commit 42c044fa2e4f878d7e2f92cdb3fa638c1b2cd86f Author: github-merge-queue[bot] Date: Tue Oct 1 00:01:00 2024 +0000 Deploying to gh-pages from @ actix/actix-net@af00dada5c2fbbc9be4a8be0c14572d2835476e6 ๐Ÿš€ diff --git a/.lock b/.lock new file mode 100644 index 00000000..e69de29b diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/actix_codec/all.html b/actix_codec/all.html new file mode 100644 index 00000000..700f0ac0 --- /dev/null +++ b/actix_codec/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/actix_codec/bcodec/struct.BytesCodec.html b/actix_codec/bcodec/struct.BytesCodec.html new file mode 100644 index 00000000..617b3cac --- /dev/null +++ b/actix_codec/bcodec/struct.BytesCodec.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_codec/struct.BytesCodec.html...

+ + + \ No newline at end of file diff --git a/actix_codec/fn.poll_read_buf.html b/actix_codec/fn.poll_read_buf.html new file mode 100644 index 00000000..2bb2fc56 --- /dev/null +++ b/actix_codec/fn.poll_read_buf.html @@ -0,0 +1,35 @@ +poll_read_buf in actix_codec - Rust
actix_codec

Function poll_read_buf

pub fn poll_read_buf<T, B>(
+    io: Pin<&mut T>,
+    cx: &mut Context<'_>,
+    buf: &mut B,
+) -> Poll<Result<usize, Error>>
where + T: AsyncRead + ?Sized, + B: BufMut,
Expand description

Try to read data from an AsyncRead into an implementer of the BufMut trait.

+

ยงExample

+
use bytes::{Bytes, BytesMut};
+use tokio_stream as stream;
+use tokio::io::Result;
+use tokio_util::io::{StreamReader, poll_read_buf};
+use futures::future::poll_fn;
+use std::pin::Pin;
+
+// Create a reader from an iterator. This particular reader will always be
+// ready.
+let mut read = StreamReader::new(stream::iter(vec![Result::Ok(Bytes::from_static(&[0, 1, 2, 3]))]));
+
+let mut buf = BytesMut::new();
+let mut reads = 0;
+
+loop {
+    reads += 1;
+    let n = poll_fn(|cx| poll_read_buf(Pin::new(&mut read), cx, &mut buf)).await?;
+
+    if n == 0 {
+        break;
+    }
+}
+
+// one or more reads might be necessary.
+assert!(reads >= 1);
+assert_eq!(&buf[..], &[0, 1, 2, 3]);
+
\ No newline at end of file diff --git a/actix_codec/framed/struct.Framed.html b/actix_codec/framed/struct.Framed.html new file mode 100644 index 00000000..57d68330 --- /dev/null +++ b/actix_codec/framed/struct.Framed.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_codec/struct.Framed.html...

+ + + \ No newline at end of file diff --git a/actix_codec/framed/struct.FramedParts.html b/actix_codec/framed/struct.FramedParts.html new file mode 100644 index 00000000..5514d76b --- /dev/null +++ b/actix_codec/framed/struct.FramedParts.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_codec/struct.FramedParts.html...

+ + + \ No newline at end of file diff --git a/actix_codec/index.html b/actix_codec/index.html new file mode 100644 index 00000000..b8f7b368 --- /dev/null +++ b/actix_codec/index.html @@ -0,0 +1,6 @@ +actix_codec - Rust

Crate actix_codec

source
Expand description

Codec utilities for working with framed protocols.

+

Contains adapters to go from streams of bytes, AsyncRead and AsyncWrite, to framed +streams implementing Sink and Stream. Framed streams are also known as transports.

+

Structsยง

  • Bytes codec. Reads/writes chunks of bytes from a stream.
  • A unified Stream and Sink interface to an underlying I/O object, using the Encoder and +Decoder traits to encode and decode frames.
  • FramedParts contains an export of the data of a Framed transport.
  • Lines codec. Reads/writes line delimited strings.
  • A wrapper around a byte buffer that is incrementally filled and initialized.

Traitsยง

Functionsยง

\ No newline at end of file diff --git a/actix_codec/lines/struct.LinesCodec.html b/actix_codec/lines/struct.LinesCodec.html new file mode 100644 index 00000000..f694bbc4 --- /dev/null +++ b/actix_codec/lines/struct.LinesCodec.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_codec/struct.LinesCodec.html...

+ + + \ No newline at end of file diff --git a/actix_codec/sidebar-items.js b/actix_codec/sidebar-items.js new file mode 100644 index 00000000..ada95f74 --- /dev/null +++ b/actix_codec/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["poll_read_buf"],"struct":["BytesCodec","Framed","FramedParts","LinesCodec","ReadBuf"],"trait":["AsyncRead","AsyncWrite","Decoder","Encoder"]}; \ No newline at end of file diff --git a/actix_codec/struct.BytesCodec.html b/actix_codec/struct.BytesCodec.html new file mode 100644 index 00000000..8b5dda32 --- /dev/null +++ b/actix_codec/struct.BytesCodec.html @@ -0,0 +1,29 @@ +BytesCodec in actix_codec - Rust
actix_codec

Struct BytesCodec

source
pub struct BytesCodec;
Expand description

Bytes codec. Reads/writes chunks of bytes from a stream.

+

Trait Implementationsยง

sourceยง

impl Clone for BytesCodec

sourceยง

fn clone(&self) -> BytesCodec

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for BytesCodec

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Decoder for BytesCodec

sourceยง

type Item = BytesMut

The type of decoded frames.
sourceยง

type Error = Error

The type of unrecoverable frame decoding errors. Read more
sourceยง

fn decode( + &mut self, + src: &mut BytesMut, +) -> Result<Option<Self::Item>, Self::Error>

Attempts to decode a frame from the provided buffer of bytes. Read more
ยง

fn decode_eof( + &mut self, + buf: &mut BytesMut, +) -> Result<Option<Self::Item>, Self::Error>

A default method available to be called when there are no more bytes +available to be read from the underlying I/O. Read more
ยง

fn framed<T>(self, io: T) -> Framed<T, Self>
where + T: AsyncRead + AsyncWrite, + Self: Sized,

Provides a Stream and Sink interface for reading and writing to this +Io object, using Decode and Encode to read and write the raw data. Read more
sourceยง

impl Encoder<Bytes> for BytesCodec

sourceยง

type Error = Error

The type of encoding errors. Read more
sourceยง

fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error>

Encodes a frame into the buffer provided. Read more
sourceยง

impl Copy for BytesCodec

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_codec/struct.Framed.html b/actix_codec/struct.Framed.html new file mode 100644 index 00000000..07551d3f --- /dev/null +++ b/actix_codec/struct.Framed.html @@ -0,0 +1,117 @@ +Framed in actix_codec - Rust
actix_codec

Struct Framed

source
pub struct Framed<T, U> { /* private fields */ }
Expand description

A unified Stream and Sink interface to an underlying I/O object, using the Encoder and +Decoder traits to encode and decode frames.

+

Raw I/O objects work with byte sequences, but higher-level code usually wants to batch these +into meaningful chunks, called โ€œframesโ€. This method layers framing on top of an I/O object, +by using the Encoder/Decoder traits to handle encoding and decoding of message frames. +Note that the incoming and outgoing frame types may be distinct.

+

Implementationsยง

sourceยง

impl<T, U> Framed<T, U>
where + T: AsyncRead + AsyncWrite, + U: Decoder,

source

pub fn new(io: T, codec: U) -> Framed<T, U>

This function returns a single object that is both Stream and Sink; grouping this into +a single object is often useful for layering things like gzip or TLS, which require both +read and write access to the underlying object.

+
sourceยง

impl<T, U> Framed<T, U>

source

pub fn codec_ref(&self) -> &U

Returns a reference to the underlying codec.

+
source

pub fn codec_mut(&mut self) -> &mut U

Returns a mutable reference to the underlying codec.

+
source

pub fn io_ref(&self) -> &T

Returns a reference to the underlying I/O stream wrapped by Frame.

+

Note that care should be taken to not tamper with the underlying stream of data coming in as +it may corrupt the stream of frames otherwise being worked with.

+
source

pub fn io_mut(&mut self) -> &mut T

Returns a mutable reference to the underlying I/O stream.

+

Note that care should be taken to not tamper with the underlying stream of data coming in as +it may corrupt the stream of frames otherwise being worked with.

+
source

pub fn io_pin(self: Pin<&mut Self>) -> Pin<&mut T>

Returns a Pin of a mutable reference to the underlying I/O stream.

+
source

pub fn is_read_buf_empty(&self) -> bool

Check if read buffer is empty.

+
source

pub fn is_write_buf_empty(&self) -> bool

Check if write buffer is empty.

+
source

pub fn is_write_buf_full(&self) -> bool

Check if write buffer is full.

+
source

pub fn is_write_ready(&self) -> bool

Check if framed is able to write more data.

+

Framed object considers ready if there is free space in write buffer.

+
source

pub fn replace_codec<U2>(self, codec: U2) -> Framed<T, U2>

Consume the Frame, returning Frame with different codec.

+
source

pub fn into_map_io<F, T2>(self, f: F) -> Framed<T2, U>
where + F: Fn(T) -> T2,

Consume the Frame, returning Frame with different io.

+
source

pub fn into_map_codec<F, U2>(self, f: F) -> Framed<T, U2>
where + F: Fn(U) -> U2,

Consume the Frame, returning Frame with different codec.

+
sourceยง

impl<T, U> Framed<T, U>

source

pub fn write<I>( + self: Pin<&mut Self>, + item: I, +) -> Result<(), <U as Encoder<I>>::Error>
where + T: AsyncWrite, + U: Encoder<I>,

Serialize item and write to the inner buffer

+
source

pub fn next_item( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Option<Result<<U as Decoder>::Item, U::Error>>>
where + T: AsyncRead, + U: Decoder,

Try to read underlying I/O stream and decode item.

+
source

pub fn flush<I>( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), U::Error>>
where + T: AsyncWrite, + U: Encoder<I>,

Flush write buffer to underlying I/O stream.

+
source

pub fn close<I>( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), U::Error>>
where + T: AsyncWrite, + U: Encoder<I>,

Flush write buffer and shutdown underlying I/O stream.

+
sourceยง

impl<T, U> Framed<T, U>

source

pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U>

This function returns a single object that is both Stream and Sink; grouping this into +a single object is often useful for layering things like gzip or TLS, which require both +read and write access to the underlying object.

+

These objects take a stream, a read buffer and a write buffer. These fields can be obtained +from an existing Framed with the into_parts method.

+
source

pub fn into_parts(self) -> FramedParts<T, U>

Consumes the Frame, returning its underlying I/O stream, the buffer with unprocessed data, +and the codec.

+

Note that care should be taken to not tamper with the underlying stream of data coming in as +it may corrupt the stream of frames otherwise being worked with.

+

Trait Implementationsยง

sourceยง

impl<T, U> Debug for Framed<T, U>
where + T: Debug, + U: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<T, U, I> Sink<I> for Framed<T, U>
where + T: AsyncWrite, + U: Encoder<I>, + U::Error: From<Error>,

sourceยง

type Error = <U as Encoder<I>>::Error

The type of value produced by the sink when an error occurs.
sourceยง

fn poll_ready( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Self::Error>>

Attempts to prepare the Sink to receive a value. Read more
sourceยง

fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error>

Begin the process of sending a value to the sink. +Each call to this function must be preceded by a successful call to +poll_ready which returned Poll::Ready(Ok(())). Read more
sourceยง

fn poll_flush( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Self::Error>>

Flush any remaining output from this sink. Read more
sourceยง

fn poll_close( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Self::Error>>

Flush any remaining output and close this sink, if necessary. Read more
sourceยง

impl<T, U> Stream for Framed<T, U>
where + T: AsyncRead, + U: Decoder,

sourceยง

type Item = Result<<U as Decoder>::Item, <U as Decoder>::Error>

Values yielded by the stream.
sourceยง

fn poll_next( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Option<Self::Item>>

Attempt to pull out the next value of this stream, registering the +current task for wakeup if the value is not yet available, and returning +None if the stream is exhausted. Read more
ยง

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
sourceยง

impl<'__pin, T, U> Unpin for Framed<T, U>
where + __Origin<'__pin, T, U>: Unpin,

Auto Trait Implementationsยง

ยง

impl<T, U> Freeze for Framed<T, U>
where + T: Freeze, + U: Freeze,

ยง

impl<T, U> RefUnwindSafe for Framed<T, U>
where + T: RefUnwindSafe, + U: RefUnwindSafe,

ยง

impl<T, U> Send for Framed<T, U>
where + T: Send, + U: Send,

ยง

impl<T, U> Sync for Framed<T, U>
where + T: Sync, + U: Sync,

ยง

impl<T, U> UnwindSafe for Framed<T, U>
where + T: UnwindSafe, + U: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<S, T, E> TryStream for S
where + S: Stream<Item = Result<T, E>> + ?Sized,

ยง

type Ok = T

The type of successful values yielded by this future
ยง

type Error = E

The type of failures yielded by this future
ยง

fn try_poll_next( + self: Pin<&mut S>, + cx: &mut Context<'_>, +) -> Poll<Option<Result<<S as TryStream>::Ok, <S as TryStream>::Error>>>

Poll this TryStream as if it were a Stream. Read more
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_codec/struct.FramedParts.html b/actix_codec/struct.FramedParts.html new file mode 100644 index 00000000..2875a077 --- /dev/null +++ b/actix_codec/struct.FramedParts.html @@ -0,0 +1,43 @@ +FramedParts in actix_codec - Rust
actix_codec

Struct FramedParts

source
pub struct FramedParts<T, U> {
+    pub io: T,
+    pub codec: U,
+    pub read_buf: BytesMut,
+    pub write_buf: BytesMut,
+    /* private fields */
+}
Expand description

FramedParts contains an export of the data of a Framed transport.

+

It can be used to construct a new Framed with a different codec. It contains all current +buffers and the inner transport.

+

Fieldsยง

ยงio: T

The inner transport used to read bytes to and write bytes to.

+
ยงcodec: U

The codec object.

+
ยงread_buf: BytesMut

The buffer with read but unprocessed data.

+
ยงwrite_buf: BytesMut

A buffer with unprocessed data which are not written yet.

+

Implementationsยง

sourceยง

impl<T, U> FramedParts<T, U>

source

pub fn new(io: T, codec: U) -> FramedParts<T, U>

Creates a new default FramedParts.

+
source

pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U>

Creates a new FramedParts with read buffer.

+

Trait Implementationsยง

sourceยง

impl<T: Debug, U: Debug> Debug for FramedParts<T, U>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

ยง

impl<T, U> Freeze for FramedParts<T, U>
where + T: Freeze, + U: Freeze,

ยง

impl<T, U> RefUnwindSafe for FramedParts<T, U>
where + T: RefUnwindSafe, + U: RefUnwindSafe,

ยง

impl<T, U> Send for FramedParts<T, U>
where + T: Send, + U: Send,

ยง

impl<T, U> Sync for FramedParts<T, U>
where + T: Sync, + U: Sync,

ยง

impl<T, U> Unpin for FramedParts<T, U>
where + T: Unpin, + U: Unpin,

ยง

impl<T, U> UnwindSafe for FramedParts<T, U>
where + T: UnwindSafe, + U: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_codec/struct.LinesCodec.html b/actix_codec/struct.LinesCodec.html new file mode 100644 index 00000000..11ae9c91 --- /dev/null +++ b/actix_codec/struct.LinesCodec.html @@ -0,0 +1,31 @@ +LinesCodec in actix_codec - Rust
actix_codec

Struct LinesCodec

source
#[non_exhaustive]
pub struct LinesCodec;
Expand description

Lines codec. Reads/writes line delimited strings.

+

Will split input up by LF or CRLF delimiters. Carriage return characters at the end of lines are +not preserved.

+

Trait Implementationsยง

sourceยง

impl Clone for LinesCodec

sourceยง

fn clone(&self) -> LinesCodec

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for LinesCodec

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Decoder for LinesCodec

sourceยง

type Item = String

The type of decoded frames.
sourceยง

type Error = Error

The type of unrecoverable frame decoding errors. Read more
sourceยง

fn decode( + &mut self, + src: &mut BytesMut, +) -> Result<Option<Self::Item>, Self::Error>

Attempts to decode a frame from the provided buffer of bytes. Read more
sourceยง

fn decode_eof( + &mut self, + src: &mut BytesMut, +) -> Result<Option<Self::Item>, Self::Error>

A default method available to be called when there are no more bytes +available to be read from the underlying I/O. Read more
ยง

fn framed<T>(self, io: T) -> Framed<T, Self>
where + T: AsyncRead + AsyncWrite, + Self: Sized,

Provides a Stream and Sink interface for reading and writing to this +Io object, using Decode and Encode to read and write the raw data. Read more
sourceยง

impl Default for LinesCodec

sourceยง

fn default() -> LinesCodec

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<T: AsRef<str>> Encoder<T> for LinesCodec

sourceยง

type Error = Error

The type of encoding errors. Read more
sourceยง

fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error>

Encodes a frame into the buffer provided. Read more
sourceยง

impl Copy for LinesCodec

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_codec/struct.ReadBuf.html b/actix_codec/struct.ReadBuf.html new file mode 100644 index 00000000..a4e6b39c --- /dev/null +++ b/actix_codec/struct.ReadBuf.html @@ -0,0 +1,83 @@ +ReadBuf in actix_codec - Rust
actix_codec

Struct ReadBuf

pub struct ReadBuf<'a> { /* private fields */ }
Expand description

A wrapper around a byte buffer that is incrementally filled and initialized.

+

This type is a sort of โ€œdouble cursorโ€. It tracks three regions in the +buffer: a region at the beginning of the buffer that has been logically +filled with data, a region that has been initialized at some point but not +yet logically filled, and a region at the end that may be uninitialized. +The filled region is guaranteed to be a subset of the initialized region.

+

In summary, the contents of the buffer can be visualized as:

+
[             capacity              ]
+[ filled |         unfilled         ]
+[    initialized    | uninitialized ]
+

It is undefined behavior to de-initialize any bytes from the uninitialized +region, since it is merely unknown whether this region is uninitialized or +not, and if part of it turns out to be initialized, it must stay initialized.

+

Implementationsยง

ยง

impl<'a> ReadBuf<'a>

pub fn new(buf: &'a mut [u8]) -> ReadBuf<'a>

Creates a new ReadBuf from a fully initialized buffer.

+

pub fn uninit(buf: &'a mut [MaybeUninit<u8>]) -> ReadBuf<'a>

Creates a new ReadBuf from a fully uninitialized buffer.

+

Use assume_init if part of the buffer is known to be already initialized.

+

pub fn capacity(&self) -> usize

Returns the total capacity of the buffer.

+

pub fn filled(&self) -> &[u8] โ“˜

Returns a shared reference to the filled portion of the buffer.

+

pub fn filled_mut(&mut self) -> &mut [u8] โ“˜

Returns a mutable reference to the filled portion of the buffer.

+

pub fn take(&mut self, n: usize) -> ReadBuf<'_>

Returns a new ReadBuf comprised of the unfilled section up to n.

+

pub fn initialized(&self) -> &[u8] โ“˜

Returns a shared reference to the initialized portion of the buffer.

+

This includes the filled portion.

+

pub fn initialized_mut(&mut self) -> &mut [u8] โ“˜

Returns a mutable reference to the initialized portion of the buffer.

+

This includes the filled portion.

+

pub unsafe fn inner_mut(&mut self) -> &mut [MaybeUninit<u8>]

Returns a mutable reference to the entire buffer, without ensuring that it has been fully +initialized.

+

The elements between 0 and self.filled().len() are filled, and those between 0 and +self.initialized().len() are initialized (and so can be converted to a &mut [u8]).

+

The caller of this method must ensure that these invariants are upheld. For example, if the +caller initializes some of the uninitialized section of the buffer, it must call +assume_init with the number of bytes initialized.

+
ยงSafety
+

The caller must not de-initialize portions of the buffer that have already been initialized. +This includes any bytes in the region marked as uninitialized by ReadBuf.

+

pub unsafe fn unfilled_mut(&mut self) -> &mut [MaybeUninit<u8>]

Returns a mutable reference to the unfilled part of the buffer without ensuring that it has been fully +initialized.

+
ยงSafety
+

The caller must not de-initialize portions of the buffer that have already been initialized. +This includes any bytes in the region marked as uninitialized by ReadBuf.

+

pub fn initialize_unfilled(&mut self) -> &mut [u8] โ“˜

Returns a mutable reference to the unfilled part of the buffer, ensuring it is fully initialized.

+

Since ReadBuf tracks the region of the buffer that has been initialized, this is effectively โ€œfreeโ€ after +the first use.

+

pub fn initialize_unfilled_to(&mut self, n: usize) -> &mut [u8] โ“˜

Returns a mutable reference to the first n bytes of the unfilled part of the buffer, ensuring it is +fully initialized.

+
ยงPanics
+

Panics if self.remaining() is less than n.

+

pub fn remaining(&self) -> usize

Returns the number of bytes at the end of the slice that have not yet been filled.

+

pub fn clear(&mut self)

Clears the buffer, resetting the filled region to empty.

+

The number of initialized bytes is not changed, and the contents of the buffer are not modified.

+

pub fn advance(&mut self, n: usize)

Advances the size of the filled region of the buffer.

+

The number of initialized bytes is not changed.

+
ยงPanics
+

Panics if the filled region of the buffer would become larger than the initialized region.

+

pub fn set_filled(&mut self, n: usize)

Sets the size of the filled region of the buffer.

+

The number of initialized bytes is not changed.

+

Note that this can be used to shrink the filled region of the buffer in addition to growing it (for +example, by a AsyncRead implementation that compresses data in-place).

+
ยงPanics
+

Panics if the filled region of the buffer would become larger than the initialized region.

+

pub unsafe fn assume_init(&mut self, n: usize)

Asserts that the first n unfilled bytes of the buffer are initialized.

+

ReadBuf assumes that bytes are never de-initialized, so this method does nothing when called with fewer +bytes than are already known to be initialized.

+
ยงSafety
+

The caller must ensure that n unfilled bytes of the buffer have already been initialized.

+

pub fn put_slice(&mut self, buf: &[u8])

Appends data to the buffer, advancing the written position and possibly also the initialized position.

+
ยงPanics
+

Panics if self.remaining() is less than buf.len().

+

Trait Implementationsยง

ยง

impl Debug for ReadBuf<'_>

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

ยง

impl<'a> Freeze for ReadBuf<'a>

ยง

impl<'a> RefUnwindSafe for ReadBuf<'a>

ยง

impl<'a> Send for ReadBuf<'a>

ยง

impl<'a> Sync for ReadBuf<'a>

ยง

impl<'a> Unpin for ReadBuf<'a>

ยง

impl<'a> !UnwindSafe for ReadBuf<'a>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_codec/trait.AsyncRead.html b/actix_codec/trait.AsyncRead.html new file mode 100644 index 00000000..03c1d967 --- /dev/null +++ b/actix_codec/trait.AsyncRead.html @@ -0,0 +1,106 @@ +AsyncRead in actix_codec - Rust
actix_codec

Trait AsyncRead

pub trait AsyncRead {
+    // Required method
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<Result<(), Error>>;
+}
Expand description

Reads bytes from a source.

+

This trait is analogous to the std::io::Read trait, but integrates with +the asynchronous task system. In particular, the poll_read method, +unlike Read::read, will automatically queue the current task for wakeup +and return if data is not yet available, rather than blocking the calling +thread.

+

Specifically, this means that the poll_read function will return one of +the following:

+
    +
  • +

    Poll::Ready(Ok(())) means that data was immediately read and placed into +the output buffer. The amount of data read can be determined by the +increase in the length of the slice returned by ReadBuf::filled. If the +difference is 0, either EOF has been reached, or the output buffer had zero +capacity (i.e. buf.remaining() == 0).

    +
  • +
  • +

    Poll::Pending means that no data was read into the buffer +provided. The I/O object is not currently readable but may become readable +in the future. Most importantly, the current futureโ€™s task is scheduled +to get unparked when the object is readable. This means that like +Future::poll youโ€™ll receive a notification when the I/O object is +readable again.

    +
  • +
  • +

    Poll::Ready(Err(e)) for other errors are standard I/O errors coming from the +underlying object.

    +
  • +
+

This trait importantly means that the read method only works in the +context of a futureโ€™s task. The object may panic if used outside of a task.

+

Utilities for working with AsyncRead values are provided by +AsyncReadExt.

+

Required Methodsยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf.

+

On success, returns Poll::Ready(Ok(())) and places data in the +unfilled portion of buf. If no data was read (buf.filled().len() is +unchanged), it implies that EOF has been reached.

+

If no data is available for reading, the method returns Poll::Pending +and arranges for the current task (via cx.waker()) to receive a +notification when the object becomes readable or is closed.

+

Implementations on Foreign Typesยง

ยง

impl AsyncRead for &[u8]

ยง

fn poll_read( + self: Pin<&mut &[u8]>, + _cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<L, R> AsyncRead for Either<L, R>
where + L: AsyncRead, + R: AsyncRead,

ยง

fn poll_read( + self: Pin<&mut Either<L, R>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<P> AsyncRead for Pin<P>
where + P: DerefMut + Unpin, + <P as Deref>::Target: AsyncRead,

ยง

fn poll_read( + self: Pin<&mut Pin<P>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<R, F> AsyncRead for InspectReader<R, F>
where + R: AsyncRead, + F: FnMut(&[u8]),

ยง

fn poll_read( + self: Pin<&mut InspectReader<R, F>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<S> AsyncRead for SinkWriter<S>
where + S: AsyncRead,

ยง

fn poll_read( + self: Pin<&mut SinkWriter<S>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<S, B, E> AsyncRead for StreamReader<S, B>
where + S: Stream<Item = Result<B, E>>, + B: Buf, + E: Into<Error>,

ยง

fn poll_read( + self: Pin<&mut StreamReader<S, B>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<T> AsyncRead for &mut T
where + T: AsyncRead + Unpin + ?Sized,

ยง

fn poll_read( + self: Pin<&mut &mut T>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<T> AsyncRead for Box<T>
where + T: AsyncRead + Unpin + ?Sized,

ยง

fn poll_read( + self: Pin<&mut Box<T>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<T> AsyncRead for Cursor<T>
where + T: AsRef<[u8]> + Unpin,

ยง

fn poll_read( + self: Pin<&mut Cursor<T>>, + _cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<W, F> AsyncRead for InspectWriter<W, F>
where + W: AsyncRead,

ยง

fn poll_read( + self: Pin<&mut InspectWriter<W, F>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Implementorsยง

ยง

impl AsyncRead for OwnedReadHalf

ยง

impl AsyncRead for OwnedReadHalf

ยง

impl AsyncRead for ReadHalf<'_>

ยง

impl AsyncRead for ReadHalf<'_>

ยง

impl AsyncRead for Receiver

ยง

impl AsyncRead for TcpStream

ยง

impl AsyncRead for UnixStream

\ No newline at end of file diff --git a/actix_codec/trait.AsyncWrite.html b/actix_codec/trait.AsyncWrite.html new file mode 100644 index 00000000..47f391d5 --- /dev/null +++ b/actix_codec/trait.AsyncWrite.html @@ -0,0 +1,334 @@ +AsyncWrite in actix_codec - Rust
actix_codec

Trait AsyncWrite

pub trait AsyncWrite {
+    // Required methods
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<Result<usize, Error>>;
+    fn poll_flush(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+    ) -> Poll<Result<(), Error>>;
+    fn poll_shutdown(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+    ) -> Poll<Result<(), Error>>;
+
+    // Provided methods
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<Result<usize, Error>> { ... }
+    fn is_write_vectored(&self) -> bool { ... }
+}
Expand description

Writes bytes asynchronously.

+

The trait inherits from std::io::Write and indicates that an I/O object is +nonblocking. All non-blocking I/O objects must return an error when +bytes cannot be written instead of blocking the current thread.

+

Specifically, this means that the poll_write function will return one of +the following:

+
    +
  • +

    Poll::Ready(Ok(n)) means that n bytes of data was immediately +written.

    +
  • +
  • +

    Poll::Pending means that no data was written from the buffer +provided. The I/O object is not currently writable but may become writable +in the future. Most importantly, the current futureโ€™s task is scheduled +to get unparked when the object is writable. This means that like +Future::poll youโ€™ll receive a notification when the I/O object is +writable again.

    +
  • +
  • +

    Poll::Ready(Err(e)) for other errors are standard I/O errors coming from the +underlying object.

    +
  • +
+

This trait importantly means that the write method only works in +the context of a futureโ€™s task. The object may panic if used outside of a task.

+

Note that this trait also represents that the Write::flush method +works very similarly to the write method, notably that Ok(()) means that the +writer has successfully been flushed, a โ€œwould blockโ€ error means that the +current task is ready to receive a notification when flushing can make more +progress, and otherwise normal errors can happen as well.

+

Utilities for working with AsyncWrite values are provided by +AsyncWriteExt.

+

Required Methodsยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object.

+

On success, returns Poll::Ready(Ok(num_bytes_written)). If successful, +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.

+

If the object is not ready for writing, the method returns +Poll::Pending and arranges for the current task (via +cx.waker()) to receive a notification when the object becomes +writable or is closed.

+

fn poll_flush( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination.

+

On success, returns Poll::Ready(Ok(())).

+

If flushing cannot immediately complete, this method returns +Poll::Pending and arranges for the current task (via +cx.waker()) to receive a notification when the object can make +progress towards flushing.

+

fn poll_shutdown( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down.

+

This method is intended to be used for asynchronous shutdown of I/O +connections. For example this is suitable for implementing shutdown of a +TLS connection or calling TcpStream::shutdown on a proxied connection. +Protocols sometimes need to flush out final pieces of data or otherwise +perform a graceful shutdown handshake, reading/writing more data as +appropriate. This method is the hook for such protocols to implement the +graceful shutdown logic.

+

This shutdown method is required by implementers of the +AsyncWrite trait. Wrappers typically just want to proxy this call +through to the wrapped type, and base types will typically implement +shutdown logic here or just return Ok(().into()). Note that if youโ€™re +wrapping an underlying AsyncWrite a call to shutdown implies that +transitively the entire stream has been shut down. After your wrapperโ€™s +shutdown logic has been executed you should shut down the underlying +stream.

+

Invocation of a shutdown implies an invocation of flush. Once this +method returns Ready it implies that a flush successfully happened +before the shutdown happened. That is, callers donโ€™t need to call +flush before calling shutdown. They can rely that by calling +shutdown any pending buffered data will be written out.

+
ยงReturn value
+

This function returns a Poll<io::Result<()>> classified as such:

+
    +
  • +

    Poll::Ready(Ok(())) - indicates that the connection was +successfully shut down and is now safe to deallocate/drop/close +resources associated with it. This method means that the current task +will no longer receive any notifications due to this method and the +I/O object itself is likely no longer usable.

    +
  • +
  • +

    Poll::Pending - indicates that shutdown is initiated but could +not complete just yet. This may mean that more I/O needs to happen to +continue this shutdown operation. The current task is scheduled to +receive a notification when itโ€™s otherwise ready to continue the +shutdown operation. When woken up this method should be called again.

    +
  • +
  • +

    Poll::Ready(Err(e)) - indicates a fatal error has happened with shutdown, +indicating that the shutdown operation did not complete successfully. +This typically means that the I/O object is no longer usable.

    +
  • +
+
ยงErrors
+

This function can return normal I/O errors through Err, described +above. Additionally this method may also render the underlying +Write::write method no longer usable (e.g. will return errors in the +future). Itโ€™s recommended that once shutdown is called the +write method is no longer called.

+
ยงPanics
+

This function will panic if not called within the context of a futureโ€™s +task.

+

Provided Methodsยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers.

+

Data is copied from each buffer in order, with the final buffer +read from possibly being only partially consumed. This method must +behave as a call to write with the buffers concatenated would.

+

The default implementation calls poll_write with either the first nonempty +buffer provided, or an empty one if none exists.

+

On success, returns Poll::Ready(Ok(num_bytes_written)).

+

If the object is not ready for writing, the method returns +Poll::Pending and arranges for the current task (via +cx.waker()) to receive a notification when the object becomes +writable or is closed.

+
ยงNote
+

This should be implemented as a single โ€œatomicโ€ write action. If any +data has been partially written, it is wrong to return an error or +pending.

+

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation.

+

If a writer does not override the default poll_write_vectored +implementation, code using it may want to avoid the method all together +and coalesce writes into a single buffer for higher performance.

+

The default implementation returns false.

+

Implementations on Foreign Typesยง

ยง

impl AsyncWrite for Vec<u8>

ยง

fn poll_write( + self: Pin<&mut Vec<u8>>, + _cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Vec<u8>>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Vec<u8>>, + _cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Vec<u8>>, + _cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl AsyncWrite for Cursor<&mut Vec<u8>>

ยง

fn poll_write( + self: Pin<&mut Cursor<&mut Vec<u8>>>, + _: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Cursor<&mut Vec<u8>>>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Cursor<&mut Vec<u8>>>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Cursor<&mut Vec<u8>>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl AsyncWrite for Cursor<&mut [u8]>

ยง

fn poll_write( + self: Pin<&mut Cursor<&mut [u8]>>, + _: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Cursor<&mut [u8]>>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Cursor<&mut [u8]>>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Cursor<&mut [u8]>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl AsyncWrite for Cursor<Box<[u8]>>

ยง

fn poll_write( + self: Pin<&mut Cursor<Box<[u8]>>>, + _: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Cursor<Box<[u8]>>>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Cursor<Box<[u8]>>>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Cursor<Box<[u8]>>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl AsyncWrite for Cursor<Vec<u8>>

ยง

fn poll_write( + self: Pin<&mut Cursor<Vec<u8>>>, + _: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Cursor<Vec<u8>>>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Cursor<Vec<u8>>>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Cursor<Vec<u8>>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<L, R> AsyncWrite for Either<L, R>
where + L: AsyncWrite, + R: AsyncWrite,

ยง

fn poll_write( + self: Pin<&mut Either<L, R>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_flush( + self: Pin<&mut Either<L, R>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Either<L, R>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<P> AsyncWrite for Pin<P>
where + P: DerefMut + Unpin, + <P as Deref>::Target: AsyncWrite,

ยง

fn poll_write( + self: Pin<&mut Pin<P>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Pin<P>>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Pin<P>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Pin<P>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<R, F> AsyncWrite for InspectReader<R, F>
where + R: AsyncWrite,

ยง

fn poll_write( + self: Pin<&mut InspectReader<R, F>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_flush( + self: Pin<&mut InspectReader<R, F>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut InspectReader<R, F>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut InspectReader<R, F>>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

impl<S, E> AsyncWrite for SinkWriter<S>
where + S: for<'a> Sink<&'a [u8], Error = E>, + E: Into<Error>,

ยง

fn poll_write( + self: Pin<&mut SinkWriter<S>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_flush( + self: Pin<&mut SinkWriter<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut SinkWriter<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<T> AsyncWrite for &mut T
where + T: AsyncWrite + Unpin + ?Sized,

ยง

fn poll_write( + self: Pin<&mut &mut T>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut &mut T>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut &mut T>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut &mut T>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<T> AsyncWrite for Box<T>
where + T: AsyncWrite + Unpin + ?Sized,

ยง

fn poll_write( + self: Pin<&mut Box<T>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut Box<T>>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

ยง

fn poll_flush( + self: Pin<&mut Box<T>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut Box<T>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

impl<W, F> AsyncWrite for InspectWriter<W, F>
where + W: AsyncWrite, + F: FnMut(&[u8]),

ยง

fn poll_write( + self: Pin<&mut InspectWriter<W, F>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

ยง

fn poll_flush( + self: Pin<&mut InspectWriter<W, F>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_shutdown( + self: Pin<&mut InspectWriter<W, F>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

ยง

fn poll_write_vectored( + self: Pin<&mut InspectWriter<W, F>>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

ยง

fn is_write_vectored(&self) -> bool

Implementorsยง

ยง

impl AsyncWrite for OwnedWriteHalf

ยง

impl AsyncWrite for OwnedWriteHalf

ยง

impl AsyncWrite for Sender

ยง

impl AsyncWrite for TcpStream

ยง

impl AsyncWrite for UnixStream

ยง

impl AsyncWrite for WriteHalf<'_>

ยง

impl AsyncWrite for WriteHalf<'_>

\ No newline at end of file diff --git a/actix_codec/trait.Decoder.html b/actix_codec/trait.Decoder.html new file mode 100644 index 00000000..c6c636f2 --- /dev/null +++ b/actix_codec/trait.Decoder.html @@ -0,0 +1,130 @@ +Decoder in actix_codec - Rust
actix_codec

Trait Decoder

pub trait Decoder {
+    type Item;
+    type Error: From<Error>;
+
+    // Required method
+    fn decode(
+        &mut self,
+        src: &mut BytesMut,
+    ) -> Result<Option<Self::Item>, Self::Error>;
+
+    // Provided methods
+    fn decode_eof(
+        &mut self,
+        buf: &mut BytesMut,
+    ) -> Result<Option<Self::Item>, Self::Error> { ... }
+    fn framed<T>(self, io: T) -> Framed<T, Self>
+       where T: AsyncRead + AsyncWrite,
+             Self: Sized { ... }
+}
Expand description

Decoding of frames via buffers.

+

This trait is used when constructing an instance of Framed or +FramedRead. An implementation of Decoder takes a byte stream that has +already been buffered in src and decodes the data into a stream of +Self::Item frames.

+

Implementations are able to track state on self, which enables +implementing stateful streaming parsers. In many cases, though, this type +will simply be a unit struct (e.g. struct HttpDecoder).

+

For some underlying data-sources, namely files and FIFOs, +itโ€™s possible to temporarily read 0 bytes by reaching EOF.

+

In these cases decode_eof will be called until it signals +fulfillment of all closing frames by returning Ok(None). +After that, repeated attempts to read from the Framed or FramedRead +will not invoke decode or decode_eof again, until data can be read +during a retry.

+

It is up to the Decoder to keep track of a restart after an EOF, +and to decide how to handle such an event by, for example, +allowing frames to cross EOF boundaries, re-emitting opening frames, or +resetting the entire internal state.

+

Required Associated Typesยง

type Item

The type of decoded frames.

+

type Error: From<Error>

The type of unrecoverable frame decoding errors.

+

If an individual message is ill-formed but can be ignored without +interfering with the processing of future messages, it may be more +useful to report the failure as an Item.

+

From<io::Error> is required in the interest of making Error suitable +for returning directly from a FramedRead, and to enable the default +implementation of decode_eof to yield an io::Error when the decoder +fails to consume all available data.

+

Note that implementors of this trait can simply indicate type Error = io::Error to use I/O errors as this type.

+

Required Methodsยง

fn decode( + &mut self, + src: &mut BytesMut, +) -> Result<Option<Self::Item>, Self::Error>

Attempts to decode a frame from the provided buffer of bytes.

+

This method is called by FramedRead whenever bytes are ready to be +parsed. The provided buffer of bytes is whatโ€™s been read so far, and +this instance of Decode can determine whether an entire frame is in +the buffer and is ready to be returned.

+

If an entire frame is available, then this instance will remove those +bytes from the buffer provided and return them as a decoded +frame. Note that removing bytes from the provided buffer doesnโ€™t always +necessarily copy the bytes, so this should be an efficient operation in +most circumstances.

+

If the bytes look valid, but a frame isnโ€™t fully available yet, then +Ok(None) is returned. This indicates to the Framed instance that +it needs to read some more bytes before calling this method again.

+

Note that the bytes provided may be empty. If a previous call to +decode consumed all the bytes in the buffer then decode will be +called again until it returns Ok(None), indicating that more bytes need to +be read.

+

Finally, if the bytes in the buffer are malformed then an error is +returned indicating why. This informs Framed that the stream is now +corrupt and should be terminated.

+
ยงBuffer management
+

Before returning from the function, implementations should ensure that +the buffer has appropriate capacity in anticipation of future calls to +decode. Failing to do so leads to inefficiency.

+

For example, if frames have a fixed length, or if the length of the +current frame is known from a header, a possible buffer management +strategy is:

+ +
impl Decoder for MyCodec {
+    // ...
+
+    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
+        // ...
+
+        // Reserve enough to complete decoding of the current frame.
+        let current_frame_len: usize = 1000; // Example.
+        // And to start decoding the next frame.
+        let next_frame_header_len: usize = 10; // Example.
+        src.reserve(current_frame_len + next_frame_header_len);
+
+        return Ok(None);
+    }
+}
+

An optimal buffer management strategy minimizes reallocations and +over-allocations.

+

Provided Methodsยง

fn decode_eof( + &mut self, + buf: &mut BytesMut, +) -> Result<Option<Self::Item>, Self::Error>

A default method available to be called when there are no more bytes +available to be read from the underlying I/O.

+

This method defaults to calling decode and returns an error if +Ok(None) is returned while there is unconsumed data in buf. +Typically this doesnโ€™t need to be implemented unless the framing +protocol differs near the end of the stream, or if you need to construct +frames across eof boundaries on sources that can be resumed.

+

Note that the buf argument may be empty. If a previous call to +decode_eof consumed all the bytes in the buffer, decode_eof will be +called again until it returns None, indicating that there are no more +frames to yield. This behavior enables returning finalization frames +that may not be based on inbound data.

+

Once None has been returned, decode_eof wonโ€™t be called again until +an attempt to resume the stream has been made, where the underlying stream +actually returned more data.

+

fn framed<T>(self, io: T) -> Framed<T, Self>
where + T: AsyncRead + AsyncWrite, + Self: Sized,

Provides a Stream and Sink interface for reading and writing to this +Io object, using Decode and Encode to read and write the raw data.

+

Raw I/O objects work with byte sequences, but higher-level code usually +wants to batch these into meaningful chunks, called โ€œframesโ€. This +method layers framing on top of an I/O object, by using the Codec +traits to handle encoding and decoding of messages frames. Note that +the incoming and outgoing frame types may be distinct.

+

This function returns a single object that is both Stream and +Sink; grouping this into a single object is often useful for layering +things like gzip or TLS, which require both read and write access to the +underlying object.

+

If you want to work more directly with the streams and sink, consider +calling split on the Framed returned by this method, which will +break them into separate objects, allowing them to interact more easily.

+

Implementorsยง

sourceยง

impl Decoder for actix_codec::BytesCodec

sourceยง

impl Decoder for actix_codec::LinesCodec

ยง

impl Decoder for AnyDelimiterCodec

ยง

type Item = Bytes

ยง

type Error = AnyDelimiterCodecError

ยง

impl Decoder for BytesCodec

ยง

type Item = BytesMut

ยง

type Error = Error

ยง

impl Decoder for LengthDelimitedCodec

ยง

type Item = BytesMut

ยง

type Error = Error

ยง

impl Decoder for LinesCodec

ยง

type Item = String

ยง

type Error = LinesCodecError

\ No newline at end of file diff --git a/actix_codec/trait.Encoder.html b/actix_codec/trait.Encoder.html new file mode 100644 index 00000000..febe4c9b --- /dev/null +++ b/actix_codec/trait.Encoder.html @@ -0,0 +1,21 @@ +Encoder in actix_codec - Rust
actix_codec

Trait Encoder

pub trait Encoder<Item> {
+    type Error: From<Error>;
+
+    // Required method
+    fn encode(
+        &mut self,
+        item: Item,
+        dst: &mut BytesMut,
+    ) -> Result<(), Self::Error>;
+}
Expand description

Trait of helper objects to write out messages as bytes, for use with +FramedWrite.

+

Required Associated Typesยง

type Error: From<Error>

The type of encoding errors.

+

FramedWrite requires Encoders errors to implement From<io::Error> +in the interest of letting it return Errors directly.

+

Required Methodsยง

fn encode(&mut self, item: Item, dst: &mut BytesMut) -> Result<(), Self::Error>

Encodes a frame into the buffer provided.

+

This method will encode item into the byte buffer provided by dst. +The dst provided is an internal buffer of the FramedWrite instance and +will be written out when possible.

+

Implementorsยง

sourceยง

impl Encoder<Bytes> for actix_codec::BytesCodec

ยง

impl Encoder<Bytes> for BytesCodec

ยง

impl Encoder<Bytes> for LengthDelimitedCodec

ยง

impl Encoder<BytesMut> for BytesCodec

ยง

impl<T> Encoder<T> for AnyDelimiterCodec
where + T: AsRef<str>,

ยง

type Error = AnyDelimiterCodecError

ยง

impl<T> Encoder<T> for LinesCodec
where + T: AsRef<str>,

ยง

type Error = LinesCodecError

sourceยง

impl<T: AsRef<str>> Encoder<T> for actix_codec::LinesCodec

\ No newline at end of file diff --git a/actix_macros/all.html b/actix_macros/all.html new file mode 100644 index 00000000..04284974 --- /dev/null +++ b/actix_macros/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Attribute Macros

\ No newline at end of file diff --git a/actix_macros/attr.main.html b/actix_macros/attr.main.html new file mode 100644 index 00000000..43fcf3ad --- /dev/null +++ b/actix_macros/attr.main.html @@ -0,0 +1,7 @@ +main in actix_macros - Rust
actix_macros

Attribute Macro main

source
#[main]
Expand description

Marks async entry-point function to be executed by Actix system.

+

ยงExamples

+
#[actix_rt::main]
+async fn main() {
+    println!("Hello world");
+}
+
\ No newline at end of file diff --git a/actix_macros/attr.test.html b/actix_macros/attr.test.html new file mode 100644 index 00000000..52558261 --- /dev/null +++ b/actix_macros/attr.test.html @@ -0,0 +1,7 @@ +test in actix_macros - Rust
actix_macros

Attribute Macro test

source
#[test]
Expand description

Marks async test function to be executed in an Actix system.

+

ยงExamples

+
#[actix_rt::test]
+async fn my_test() {
+    assert!(true);
+}
+
\ No newline at end of file diff --git a/actix_macros/index.html b/actix_macros/index.html new file mode 100644 index 00000000..d7b3ece2 --- /dev/null +++ b/actix_macros/index.html @@ -0,0 +1,7 @@ +actix_macros - Rust

Crate actix_macros

source
Expand description

Macros for Actix system and runtime.

+

The actix-rt crate must be available for macro output to compile.

+

ยงEntry-point

+

See docs for the #[main] macro.

+

ยงTests

+

See docs for the #[test] macro.

+

Attribute Macrosยง

  • Marks async entry-point function to be executed by Actix system.
  • Marks async test function to be executed in an Actix system.
\ No newline at end of file diff --git a/actix_macros/sidebar-items.js b/actix_macros/sidebar-items.js new file mode 100644 index 00000000..f2a173d7 --- /dev/null +++ b/actix_macros/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"attr":["main","test"]}; \ No newline at end of file diff --git a/actix_rt/all.html b/actix_rt/all.html new file mode 100644 index 00000000..024d5c5d --- /dev/null +++ b/actix_rt/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/actix_rt/arbiter/struct.Arbiter.html b/actix_rt/arbiter/struct.Arbiter.html new file mode 100644 index 00000000..fb91428d --- /dev/null +++ b/actix_rt/arbiter/struct.Arbiter.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_rt/struct.Arbiter.html...

+ + + \ No newline at end of file diff --git a/actix_rt/arbiter/struct.ArbiterHandle.html b/actix_rt/arbiter/struct.ArbiterHandle.html new file mode 100644 index 00000000..6d9f0775 --- /dev/null +++ b/actix_rt/arbiter/struct.ArbiterHandle.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_rt/struct.ArbiterHandle.html...

+ + + \ No newline at end of file diff --git a/actix_rt/attr.main.html b/actix_rt/attr.main.html new file mode 100644 index 00000000..d8f84e6d --- /dev/null +++ b/actix_rt/attr.main.html @@ -0,0 +1,7 @@ +main in actix_rt - Rust
actix_rt

Attribute Macro main

#[main]
Expand description

Marks async entry-point function to be executed by Actix system.

+

ยงExamples

+
#[actix_rt::main]
+async fn main() {
+    println!("Hello world");
+}
+
\ No newline at end of file diff --git a/actix_rt/attr.test.html b/actix_rt/attr.test.html new file mode 100644 index 00000000..6269cb55 --- /dev/null +++ b/actix_rt/attr.test.html @@ -0,0 +1,7 @@ +test in actix_rt - Rust
actix_rt

Attribute Macro test

#[test]
Expand description

Marks async test function to be executed in an Actix system.

+

ยงExamples

+
#[actix_rt::test]
+async fn my_test() {
+    assert!(true);
+}
+
\ No newline at end of file diff --git a/actix_rt/fn.spawn.html b/actix_rt/fn.spawn.html new file mode 100644 index 00000000..8589d87e --- /dev/null +++ b/actix_rt/fn.spawn.html @@ -0,0 +1,24 @@ +spawn in actix_rt - Rust
actix_rt

Function spawn

source
pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output> โ“˜
where + Fut: Future + 'static, + Fut::Output: 'static,
Expand description

Spawns a future on the current thread as a new task.

+

If not immediately awaited, the task can be cancelled using JoinHandle::abort.

+

The provided future is spawned as a new task; therefore, panics are caught.

+

ยงPanics

+

Panics if Actix system is not running.

+

ยงExamples

+
// task resolves successfully
+assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1);
+
+// task panics
+assert!(actix_rt::spawn(async {
+    panic!("panic is caught at task boundary");
+})
+.await
+.unwrap_err()
+.is_panic());
+
+// task is cancelled before completion
+let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100)));
+handle.abort();
+assert!(handle.await.unwrap_err().is_cancelled());
+
\ No newline at end of file diff --git a/actix_rt/index.html b/actix_rt/index.html new file mode 100644 index 00000000..0e1bae19 --- /dev/null +++ b/actix_rt/index.html @@ -0,0 +1,35 @@ +actix_rt - Rust

Crate actix_rt

source
Expand description

Tokio-based single-threaded async runtime for the Actix ecosystem.

+

In most parts of the the Actix ecosystem, it has been chosen to use !Send futures. For this +reason, a single-threaded runtime is appropriate since it is guaranteed that futures will not +be moved between threads. This can result in small performance improvements over cases where +atomics would otherwise be needed.

+

To achieve similar performance to multi-threaded, work-stealing runtimes, applications +using actix-rt will create multiple, mostly disconnected, single-threaded runtimes. +This approach has good performance characteristics for workloads where the majority of tasks +have similar runtime expense.

+

The disadvantage is that idle threads will not steal work from very busy, stuck or otherwise +backlogged threads. Tasks that are disproportionately expensive should be offloaded to the +blocking task thread-pool using task::spawn_blocking.

+

ยงExamples

+
use std::sync::mpsc;
+use actix_rt::{Arbiter, System};
+
+let _ = System::new();
+
+let (tx, rx) = mpsc::channel::<u32>();
+
+let arbiter = Arbiter::new();
+arbiter.spawn_fn(move || tx.send(42).unwrap());
+
+let num = rx.recv().unwrap();
+assert_eq!(num, 42);
+
+arbiter.stop();
+arbiter.join().unwrap();
+

ยงio-uring Support

+

There is experimental support for using io-uring with this crate by enabling the +io-uring feature. For now, it is semver exempt.

+

Note that there are currently some unimplemented parts of using actix-rt with io-uring. +In particular, when running a System, only System::block_on is supported.

+

Modulesยง

  • TCP/UDP/Unix bindings (mostly Tokio re-exports).
  • Asynchronous signal handling (Tokio re-exports).
  • Task management (Tokio re-exports).
  • Utilities for tracking time (Tokio re-exports).

Macrosยง

  • Pins a value on the stack.

Structsยง

  • An Arbiter represents a thread that provides an asynchronous execution environment for futures +and functions.
  • A handle for sending spawn and stop messages to an Arbiter.
  • A Tokio-based runtime proxy.
  • A manager for a per-thread distributed async runtime.
  • Runner that keeps a Systemโ€™s event loop alive until stop message is received.

Functionsยง

  • Spawns a future on the current thread as a new task.

Attribute Macrosยง

  • Marks async entry-point function to be executed by Actix system.
  • Marks async test function to be executed in an Actix system.
\ No newline at end of file diff --git a/actix_rt/macro.pin!.html b/actix_rt/macro.pin!.html new file mode 100644 index 00000000..22b3e842 --- /dev/null +++ b/actix_rt/macro.pin!.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to macro.pin.html...

+ + + \ No newline at end of file diff --git a/actix_rt/macro.pin.html b/actix_rt/macro.pin.html new file mode 100644 index 00000000..eac19464 --- /dev/null +++ b/actix_rt/macro.pin.html @@ -0,0 +1,104 @@ +pin in actix_rt - Rust
actix_rt

Macro pin

macro_rules! pin {
+    ($($x:ident),*) => { ... };
+    ($(
+            let $x:ident = $init:expr;
+    )*) => { ... };
+}
Expand description

Pins a value on the stack.

+

Calls to async fn return anonymous Future values that are !Unpin. +These values must be pinned before they can be polled. Calling .await will +handle this, but consumes the future. If it is required to call .await on +a &mut _ reference, the caller is responsible for pinning the future.

+

Pinning may be done by allocating with Box::pin or by using the stack +with the pin! macro.

+

The following will fail to compile:

+ +
โ“˜
async fn my_async_fn() {
+    // async logic here
+}
+
+#[tokio::main]
+async fn main() {
+    let mut future = my_async_fn();
+    (&mut future).await;
+}
+

To make this work requires pinning:

+ +
use tokio::pin;
+
+async fn my_async_fn() {
+    // async logic here
+}
+
+#[tokio::main]
+async fn main() {
+    let future = my_async_fn();
+    pin!(future);
+
+    (&mut future).await;
+}
+

Pinning is useful when using select! and stream operators that require T: Stream + Unpin.

+

ยงUsage

+

The pin! macro takes identifiers as arguments. It does not work +with expressions.

+

The following does not compile as an expression is passed to pin!.

+ +
โ“˜
async fn my_async_fn() {
+    // async logic here
+}
+
+#[tokio::main]
+async fn main() {
+    let mut future = pin!(my_async_fn());
+    (&mut future).await;
+}
+

ยงExamples

+

Using with select:

+ +
use tokio::{pin, select};
+use tokio_stream::{self as stream, StreamExt};
+
+async fn my_async_fn() {
+    // async logic here
+}
+
+#[tokio::main]
+async fn main() {
+    let mut stream = stream::iter(vec![1, 2, 3, 4]);
+
+    let future = my_async_fn();
+    pin!(future);
+
+    loop {
+        select! {
+            _ = &mut future => {
+                // Stop looping `future` will be polled after completion
+                break;
+            }
+            Some(val) = stream.next() => {
+                println!("got value = {}", val);
+            }
+        }
+    }
+}
+

Because assigning to a variable followed by pinning is common, there is also +a variant of the macro that supports doing both in one go.

+ +
use tokio::{pin, select};
+
+async fn my_async_fn() {
+    // async logic here
+}
+
+#[tokio::main]
+async fn main() {
+    pin! {
+        let future1 = my_async_fn();
+        let future2 = my_async_fn();
+    }
+
+    select! {
+        _ = &mut future1 => {}
+        _ = &mut future2 => {}
+    }
+}
+
\ No newline at end of file diff --git a/actix_rt/net/index.html b/actix_rt/net/index.html new file mode 100644 index 00000000..909c9d82 --- /dev/null +++ b/actix_rt/net/index.html @@ -0,0 +1,3 @@ +actix_rt::net - Rust
actix_rt

Module net

source
Expand description

TCP/UDP/Unix bindings (mostly Tokio re-exports).

+

Structsยง

  • Describes the readiness state of an I/O resources.
  • A TCP socket server, listening for connections.
  • A TCP socket that has not yet been converted to a TcpStream or +TcpListener.
  • A TCP stream between a local and a remote socket.
  • A UDP socket.
  • An I/O object representing a Unix datagram socket.
  • A Unix socket which can accept connections from other Unix sockets.
  • A structure representing a connected Unix socket.
\ No newline at end of file diff --git a/actix_rt/net/sidebar-items.js b/actix_rt/net/sidebar-items.js new file mode 100644 index 00000000..2f29502d --- /dev/null +++ b/actix_rt/net/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Ready","TcpListener","TcpSocket","TcpStream","UdpSocket","UnixDatagram","UnixListener","UnixStream"]}; \ No newline at end of file diff --git a/actix_rt/net/struct.Ready.html b/actix_rt/net/struct.Ready.html new file mode 100644 index 00000000..94a17c7b --- /dev/null +++ b/actix_rt/net/struct.Ready.html @@ -0,0 +1,80 @@ +Ready in actix_rt::net - Rust
actix_rt::net

Struct Ready

pub struct Ready(/* private fields */);
Expand description

Describes the readiness state of an I/O resources.

+

Ready tracks which operation an I/O resource is ready to perform.

+

Implementationsยง

ยง

impl Ready

pub const EMPTY: Ready = _

Returns the empty Ready set.

+

pub const READABLE: Ready = _

Returns a Ready representing readable readiness.

+

pub const WRITABLE: Ready = _

Returns a Ready representing writable readiness.

+

pub const READ_CLOSED: Ready = _

Returns a Ready representing read closed readiness.

+

pub const WRITE_CLOSED: Ready = _

Returns a Ready representing write closed readiness.

+

pub const PRIORITY: Ready = _

Returns a Ready representing priority readiness.

+

pub const ERROR: Ready = _

Returns a Ready representing error readiness.

+

pub const ALL: Ready = _

Returns a Ready representing readiness for all operations.

+

pub fn is_empty(self) -> bool

Returns true if Ready is the empty set.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(Ready::EMPTY.is_empty());
+assert!(!Ready::READABLE.is_empty());
+

pub fn is_readable(self) -> bool

Returns true if the value includes readable.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(!Ready::EMPTY.is_readable());
+assert!(Ready::READABLE.is_readable());
+assert!(Ready::READ_CLOSED.is_readable());
+assert!(!Ready::WRITABLE.is_readable());
+

pub fn is_writable(self) -> bool

Returns true if the value includes writable readiness.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(!Ready::EMPTY.is_writable());
+assert!(!Ready::READABLE.is_writable());
+assert!(Ready::WRITABLE.is_writable());
+assert!(Ready::WRITE_CLOSED.is_writable());
+

pub fn is_read_closed(self) -> bool

Returns true if the value includes read-closed readiness.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(!Ready::EMPTY.is_read_closed());
+assert!(!Ready::READABLE.is_read_closed());
+assert!(Ready::READ_CLOSED.is_read_closed());
+

pub fn is_write_closed(self) -> bool

Returns true if the value includes write-closed readiness.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(!Ready::EMPTY.is_write_closed());
+assert!(!Ready::WRITABLE.is_write_closed());
+assert!(Ready::WRITE_CLOSED.is_write_closed());
+

pub fn is_priority(self) -> bool

Returns true if the value includes priority readiness.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(!Ready::EMPTY.is_priority());
+assert!(!Ready::WRITABLE.is_priority());
+assert!(Ready::PRIORITY.is_priority());
+

pub fn is_error(self) -> bool

Returns true if the value includes error readiness.

+
ยงExamples
+
use tokio::io::Ready;
+
+assert!(!Ready::EMPTY.is_error());
+assert!(!Ready::WRITABLE.is_error());
+assert!(Ready::ERROR.is_error());
+

Trait Implementationsยง

ยง

impl BitAnd for Ready

ยง

type Output = Ready

The resulting type after applying the & operator.
ยง

fn bitand(self, other: Ready) -> Ready

Performs the & operation. Read more
ยง

impl BitOr for Ready

ยง

type Output = Ready

The resulting type after applying the | operator.
ยง

fn bitor(self, other: Ready) -> Ready

Performs the | operation. Read more
ยง

impl BitOrAssign for Ready

ยง

fn bitor_assign(&mut self, other: Ready)

Performs the |= operation. Read more
ยง

impl Clone for Ready

ยง

fn clone(&self) -> Ready

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for Ready

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl Ord for Ready

ยง

fn cmp(&self, other: &Ready) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where + Self: Sized,

Restrict a value to a certain interval. Read more
ยง

impl PartialEq for Ready

ยง

fn eq(&self, other: &Ready) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
ยง

impl PartialOrd for Ready

ยง

fn partial_cmp(&self, other: &Ready) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.6.0 ยท sourceยง

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.6.0 ยท sourceยง

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the +<= operator. Read more
1.6.0 ยท sourceยง

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > +operator. Read more
1.6.0 ยท sourceยง

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by +the >= operator. Read more
ยง

impl Sub for Ready

ยง

type Output = Ready

The resulting type after applying the - operator.
ยง

fn sub(self, other: Ready) -> Ready

Performs the - operation. Read more
ยง

impl Copy for Ready

ยง

impl Eq for Ready

ยง

impl StructuralPartialEq for Ready

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.TcpListener.html b/actix_rt/net/struct.TcpListener.html new file mode 100644 index 00000000..02748148 --- /dev/null +++ b/actix_rt/net/struct.TcpListener.html @@ -0,0 +1,198 @@ +TcpListener in actix_rt::net - Rust
actix_rt::net

Struct TcpListener

pub struct TcpListener { /* private fields */ }
Expand description

A TCP socket server, listening for connections.

+

You can accept a new connection by using the accept +method.

+

A TcpListener can be turned into a Stream with TcpListenerStream.

+

ยงErrors

+

Note that accepting a connection can lead to various errors and not all +of them are necessarily fatal โ€’ for example having too many open file +descriptors or the other side closing the connection while it waits in +an accept queue. These would terminate the stream if not handled in any +way.

+

ยงExamples

+

Using accept:

+ +
use tokio::net::TcpListener;
+
+use std::io;
+
+async fn process_socket<T>(socket: T) {
+    // do work with socket here
+}
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let listener = TcpListener::bind("127.0.0.1:8080").await?;
+
+    loop {
+        let (socket, _) = listener.accept().await?;
+        process_socket(socket).await;
+    }
+}
+

Implementationsยง

ยง

impl TcpListener

pub async fn bind<A>(addr: A) -> Result<TcpListener, Error>
where + A: ToSocketAddrs,

Creates a new TcpListener, which will be bound to the specified address.

+

The returned listener is ready for accepting connections.

+

Binding with a port number of 0 will request that the OS assigns a port +to this listener. The port allocated can be queried via the local_addr +method.

+

The address type can be any implementor of the ToSocketAddrs trait. +If addr yields multiple addresses, bind will be attempted with each of +the addresses until one succeeds and returns the listener. If none of +the addresses succeed in creating a listener, the error returned from +the last attempt (the last address) is returned.

+

This function sets the SO_REUSEADDR option on the socket.

+

To configure the socket before binding, you can use the TcpSocket +type.

+
ยงExamples
+
use tokio::net::TcpListener;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let listener = TcpListener::bind("127.0.0.1:2345").await?;
+
+    // use the listener
+
+    Ok(())
+}
+

pub async fn accept(&self) -> Result<(TcpStream, SocketAddr), Error>

Accepts a new incoming connection from this listener.

+

This function will yield once a new TCP connection is established. When +established, the corresponding TcpStream and the remote peerโ€™s +address will be returned.

+
ยงCancel safety
+

This method is cancel safe. If the method is used as the event in a +tokio::select! statement and some other branch +completes first, then it is guaranteed that no new connections were +accepted by this method.

+
ยงExamples
+
use tokio::net::TcpListener;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let listener = TcpListener::bind("127.0.0.1:8080").await?;
+
+    match listener.accept().await {
+        Ok((_socket, addr)) => println!("new client: {:?}", addr),
+        Err(e) => println!("couldn't get client: {:?}", e),
+    }
+
+    Ok(())
+}
+

pub fn poll_accept( + &self, + cx: &mut Context<'_>, +) -> Poll<Result<(TcpStream, SocketAddr), Error>>

Polls to accept a new incoming connection to this listener.

+

If there is no connection to accept, Poll::Pending is returned and the +current task will be notified by a waker. Note that on multiple calls +to poll_accept, only the Waker from the Context passed to the most +recent call is scheduled to receive a wakeup.

+

pub fn from_std(listener: TcpListener) -> Result<TcpListener, Error>

Creates new TcpListener from a std::net::TcpListener.

+

This function is intended to be used to wrap a TCP listener from the +standard library in the Tokio equivalent.

+

This API is typically paired with the socket2 crate and the Socket +type to build up and customize a listener before itโ€™s shipped off to the +backing event loop. This allows configuration of options like +SO_REUSEPORT, binding to multiple addresses, etc.

+
ยงNotes
+

The caller is responsible for ensuring that the listener is in +non-blocking mode. Otherwise all I/O operations on the listener +will block the thread, which will cause unexpected behavior. +Non-blocking mode can be set using set_nonblocking.

+
ยงExamples
+
use std::error::Error;
+use tokio::net::TcpListener;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let std_listener = std::net::TcpListener::bind("127.0.0.1:0")?;
+    std_listener.set_nonblocking(true)?;
+    let listener = TcpListener::from_std(std_listener)?;
+    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 function.

+

pub fn into_std(self) -> Result<TcpListener, Error>

Turns a tokio::net::TcpListener into a std::net::TcpListener.

+

The returned std::net::TcpListener will have nonblocking mode set as +true. Use set_nonblocking to change the blocking mode if needed.

+
ยงExamples
+
use std::error::Error;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let tokio_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+    let std_listener = tokio_listener.into_std()?;
+    std_listener.set_nonblocking(false)?;
+    Ok(())
+}
+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local address that this listener is bound to.

+

This can be useful, for example, when binding to port 0 to figure out +which port was actually bound.

+
ยงExamples
+
use tokio::net::TcpListener;
+
+use std::io;
+use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let listener = TcpListener::bind("127.0.0.1:8080").await?;
+
+    assert_eq!(listener.local_addr()?,
+               SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
+
+    Ok(())
+}
+

pub fn ttl(&self) -> Result<u32, Error>

Gets the value of the IP_TTL option for this socket.

+

For more information about this option, see set_ttl.

+
ยงExamples
+
use tokio::net::TcpListener;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+   let listener = TcpListener::bind("127.0.0.1:0").await?;
+
+   listener.set_ttl(100).expect("could not set TTL");
+   assert_eq!(listener.ttl()?, 100);
+
+   Ok(())
+}
+

pub fn set_ttl(&self, ttl: u32) -> Result<(), Error>

Sets the value for the IP_TTL option on this socket.

+

This value sets the time-to-live field that is used in every packet sent +from this socket.

+
ยงExamples
+
use tokio::net::TcpListener;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let listener = TcpListener::bind("127.0.0.1:0").await?;
+
+    listener.set_ttl(100).expect("could not set TTL");
+
+    Ok(())
+}
+

Trait Implementationsยง

ยง

impl AsFd for TcpListener

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for TcpListener

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl Debug for TcpListener

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl TryFrom<TcpListener> for TcpListener

ยง

fn try_from( + stream: TcpListener, +) -> Result<TcpListener, <TcpListener as TryFrom<TcpListener>>::Error>

Consumes stream, returning the tokio I/O object.

+

This is equivalent to +TcpListener::from_std(stream).

+
ยง

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.TcpSocket.html b/actix_rt/net/struct.TcpSocket.html new file mode 100644 index 00000000..cb62d924 --- /dev/null +++ b/actix_rt/net/struct.TcpSocket.html @@ -0,0 +1,394 @@ +TcpSocket in actix_rt::net - Rust
actix_rt::net

Struct TcpSocket

pub struct TcpSocket { /* private fields */ }
Expand description

A TCP socket that has not yet been converted to a TcpStream or +TcpListener.

+

TcpSocket wraps an operating system socket and enables the caller to +configure the socket before establishing a TCP connection or accepting +inbound connections. The caller is able to set socket option and explicitly +bind the socket with a socket address.

+

The underlying socket is closed when the TcpSocket value is dropped.

+

TcpSocket should only be used directly if the default configuration used +by TcpStream::connect and TcpListener::bind does not meet the required +use case.

+

Calling TcpStream::connect("127.0.0.1:8080") is equivalent to:

+ +
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    let stream = socket.connect(addr).await?;
+
+    Ok(())
+}
+

Calling TcpListener::bind("127.0.0.1:8080") is equivalent to:

+ +
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    // On platforms with Berkeley-derived sockets, this allows to quickly
+    // rebind a socket, without needing to wait for the OS to clean up the
+    // previous one.
+    //
+    // On Windows, this allows rebinding sockets which are actively in use,
+    // which allows โ€œsocket hijackingโ€, so we explicitly don't set it here.
+    // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
+    socket.set_reuseaddr(true)?;
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+
+    Ok(())
+}
+

Setting socket options not explicitly provided by TcpSocket may be done by +accessing the RawFd/RawSocket using AsRawFd/AsRawSocket and +setting the option with a crate like socket2.

+

Implementationsยง

ยง

impl TcpSocket

pub fn new_v4() -> Result<TcpSocket, Error>

Creates a new socket configured for IPv4.

+

Calls socket(2) with AF_INET 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 IPv4 socket and start listening.

+ +
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+    let socket = TcpSocket::new_v4()?;
+    socket.bind(addr)?;
+
+    let listener = socket.listen(128)?;
+    Ok(())
+}
+

pub fn new_v6() -> Result<TcpSocket, Error>

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.

+ +
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)?;
+    Ok(())
+}
+

pub fn set_keepalive(&self, keepalive: bool) -> Result<(), Error>

Sets value for the SO_KEEPALIVE option on this socket.

+

pub fn keepalive(&self) -> Result<bool, Error>

Gets the value of the SO_KEEPALIVE option on this socket.

+

pub fn set_reuseaddr(&self, reuseaddr: bool) -> Result<(), Error>

Allows the socket to bind to an in-use address.

+

Behavior is platform specific. Refer to the target platformโ€™s +documentation for more details.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.set_reuseaddr(true)?;
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+
+    Ok(())
+}
+

pub fn reuseaddr(&self) -> Result<bool, Error>

Retrieves the value set for SO_REUSEADDR on this socket.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.set_reuseaddr(true)?;
+    assert!(socket.reuseaddr().unwrap());
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+    Ok(())
+}
+

pub fn set_reuseport(&self, reuseport: bool) -> Result<(), Error>

Allows the socket to bind to an in-use port. Only available for unix systems +(excluding Solaris & Illumos).

+

Behavior is platform specific. Refer to the target platformโ€™s +documentation for more details.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.set_reuseport(true)?;
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+    Ok(())
+}
+

pub fn reuseport(&self) -> Result<bool, Error>

Allows the socket to bind to an in-use port. Only available for unix systems +(excluding Solaris & Illumos).

+

Behavior is platform specific. Refer to the target platformโ€™s +documentation for more details.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.set_reuseport(true)?;
+    assert!(socket.reuseport().unwrap());
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+    Ok(())
+}
+

pub fn set_send_buffer_size(&self, size: u32) -> Result<(), Error>

Sets the size of the TCP send buffer on this socket.

+

On most operating systems, this sets the SO_SNDBUF socket option.

+

pub fn send_buffer_size(&self) -> Result<u32, Error>

Returns the size of the TCP send buffer for this socket.

+

On most operating systems, this is the value of the SO_SNDBUF socket +option.

+

Note that if set_send_buffer_size has been called on this socket +previously, the value returned by this function may not be the same as +the argument provided to set_send_buffer_size. This is for the +following reasons:

+
    +
  • Most operating systems have minimum and maximum allowed sizes for the +send buffer, and will clamp the provided value if it is below the +minimum or above the maximum. The minimum and maximum buffer sizes are +OS-dependent.
  • +
  • Linux will double the buffer size to account for internal bookkeeping +data, and returns the doubled value from getsockopt(2). As per man 7 socket: +
    +

    Sets or gets the maximum socket send buffer in bytes. The +kernel doubles this value (to allow space for bookkeeping +overhead) when it is set using setsockopt(2), and this doubled +value is returned by getsockopt(2).

    +
    +
  • +
+

pub fn set_recv_buffer_size(&self, size: u32) -> Result<(), Error>

Sets the size of the TCP receive buffer on this socket.

+

On most operating systems, this sets the SO_RCVBUF socket option.

+

pub fn recv_buffer_size(&self) -> Result<u32, Error>

Returns the size of the TCP receive buffer for this socket.

+

On most operating systems, this is the value of the SO_RCVBUF socket +option.

+

Note that if set_recv_buffer_size has been called on this socket +previously, the value returned by this function may not be the same as +the argument provided to set_send_buffer_size. This is for the +following reasons:

+
    +
  • Most operating systems have minimum and maximum allowed sizes for the +receive buffer, and will clamp the provided value if it is below the +minimum or above the maximum. The minimum and maximum buffer sizes are +OS-dependent.
  • +
  • Linux will double the buffer size to account for internal bookkeeping +data, and returns the doubled value from getsockopt(2). As per man 7 socket: +
    +

    Sets or gets the maximum socket send buffer in bytes. The +kernel doubles this value (to allow space for bookkeeping +overhead) when it is set using setsockopt(2), and this doubled +value is returned by getsockopt(2).

    +
    +
  • +
+

pub fn set_linger(&self, dur: Option<Duration>) -> Result<(), Error>

Sets the linger duration of this socket by setting the SO_LINGER option.

+

This option controls the action taken when a stream has unsent messages and the stream is +closed. If SO_LINGER is set, the system shall block the process until it can transmit the +data or until the time expires.

+

If SO_LINGER is not specified, and the socket is closed, the system handles the call in a +way that allows the process to continue as quickly as possible.

+

pub fn linger(&self) -> Result<Option<Duration>, Error>

Reads the linger duration for this socket by getting the SO_LINGER +option.

+

For more information about this option, see set_linger.

+

pub fn set_nodelay(&self, nodelay: bool) -> Result<(), Error>

Sets the value of the TCP_NODELAY option on this socket.

+

If set, this option disables the Nagle algorithm. This means that segments are always +sent as soon as possible, even if there is only a small amount of data. When not set, +data is buffered until there is a sufficient amount to send out, thereby avoiding +the frequent sending of small packets.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+let socket = TcpSocket::new_v4()?;
+
+println!("{:?}", socket.nodelay()?);
+

pub fn nodelay(&self) -> Result<bool, Error>

Gets the value of the TCP_NODELAY option on this socket.

+

For more information about this option, see set_nodelay.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+let stream = TcpSocket::new_v4()?;
+
+stream.set_nodelay(true)?;
+

pub fn tos(&self) -> Result<u32, Error>

Gets the value of the IP_TOS option for this socket.

+

For more information about this option, see set_tos.

+

NOTE: On Windows, IP_TOS is only supported on Windows 8+ or +Windows Server 2012+.

+

pub fn set_tos(&self, tos: u32) -> Result<(), Error>

Sets the value for the IP_TOS option on this socket.

+

This value sets the type-of-service field that is used in every packet +sent from this socket.

+

NOTE: On Windows, IP_TOS is only supported on Windows 8+ or +Windows Server 2012+.

+

pub fn device(&self) -> Result<Option<Vec<u8>>, Error>

Gets the value for the SO_BINDTODEVICE option on this socket

+

This value gets the socket binded deviceโ€™s interface name.

+

pub fn bind_device(&self, interface: Option<&[u8]>) -> Result<(), Error>

Sets the value for the SO_BINDTODEVICE option on this socket

+

If a socket is bound to an interface, only packets received from that +particular interface are processed by the socket. Note that this only +works for some socket types, particularly AF_INET sockets.

+

If interface is None or an empty string it removes the binding.

+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Gets the local address of this socket.

+

Will fail on windows if called before bind.

+
ยงExamples
+
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.bind(addr)?;
+    assert_eq!(socket.local_addr().unwrap().to_string(), "127.0.0.1:8080");
+    let listener = socket.listen(1024)?;
+    Ok(())
+}
+

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

+

pub fn bind(&self, addr: SocketAddr) -> Result<(), Error>

Binds the socket to the given address.

+

This calls the bind(2) operating-system function. Behavior is +platform specific. Refer to the target platformโ€™s documentation for more +details.

+
ยงExamples
+

Bind a socket before listening.

+ +
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+
+    Ok(())
+}
+

pub async fn connect(self, addr: SocketAddr) -> Result<TcpStream, Error>

Establishes a TCP connection with a peer at the specified socket address.

+

The TcpSocket is consumed. Once the connection is established, a +connected TcpStream is returned. If the connection fails, the +encountered error is returned.

+

This calls the connect(2) operating-system function. Behavior is +platform specific. Refer to the target platformโ€™s documentation for more +details.

+
ยงExamples
+

Connecting to a peer.

+ +
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    let stream = socket.connect(addr).await?;
+
+    Ok(())
+}
+

pub fn listen(self, backlog: u32) -> Result<TcpListener, Error>

Converts the socket into a TcpListener.

+

backlog defines the maximum number of pending connections are queued +by the operating system at any given time. Connection are removed from +the queue with TcpListener::accept. When the queue is full, the +operating-system will start rejecting connections.

+

This calls the listen(2) operating-system function, marking the socket +as a passive socket. Behavior is platform specific. Refer to the target +platformโ€™s documentation for more details.

+
ยงExamples
+

Create a TcpListener.

+ +
use tokio::net::TcpSocket;
+
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let addr = "127.0.0.1:8080".parse().unwrap();
+
+    let socket = TcpSocket::new_v4()?;
+    socket.bind(addr)?;
+
+    let listener = socket.listen(1024)?;
+
+    Ok(())
+}
+

pub fn from_std_stream(std_stream: TcpStream) -> TcpSocket

Converts a std::net::TcpStream into a TcpSocket. The provided +socket must not have been connected prior to calling this function. This +function is typically used together with crates such as socket2 to +configure socket options that are not available on TcpSocket.

+
ยงNotes
+

The caller is responsible for ensuring that the socket 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.

+
ยงExamples
+
use tokio::net::TcpSocket;
+use socket2::{Domain, Socket, Type};
+
+#[tokio::main]
+async fn main() -> std::io::Result<()> {
+    let socket2_socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
+    socket2_socket.set_nonblocking(true)?;
+
+    let socket = TcpSocket::from_std_stream(socket2_socket.into());
+
+    Ok(())
+}
+

Trait Implementationsยง

ยง

impl AsFd for TcpSocket

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for TcpSocket

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl Debug for TcpSocket

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl FromRawFd for TcpSocket

ยง

unsafe fn from_raw_fd(fd: i32) -> TcpSocket

Converts a RawFd to a TcpSocket.

+
ยงNotes
+

The caller is responsible for ensuring that the socket is in +non-blocking mode.

+
ยง

impl IntoRawFd for TcpSocket

ยง

fn into_raw_fd(self) -> i32

Consumes this object, returning the raw underlying file descriptor. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.TcpStream.html b/actix_rt/net/struct.TcpStream.html new file mode 100644 index 00000000..a68b69c2 --- /dev/null +++ b/actix_rt/net/struct.TcpStream.html @@ -0,0 +1,718 @@ +TcpStream in actix_rt::net - Rust
actix_rt::net

Struct TcpStream

pub struct TcpStream { /* private fields */ }
Expand description

A TCP stream between a local and a remote socket.

+

A TCP stream can either be created by connecting to an endpoint, via the +connect method, or by accepting a connection from a listener. A +TCP stream can also be created via the TcpSocket type.

+

Reading and writing to a TcpStream is usually done using the +convenience methods found on the AsyncReadExt and AsyncWriteExt +traits.

+

ยงExamples

+
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.

+

To shut down the stream in the write direction, you can call the +shutdown() method. This will cause the other peer to receive a read of +length 0, indicating that no more data will be sent. This only closes +the stream in one direction.

+

Implementationsยง

ยง

impl TcpStream

pub async fn connect<A>(addr: A) -> Result<TcpStream, Error>
where + A: ToSocketAddrs,

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.

+
ยงExamples
+
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.

+

pub fn from_std(stream: TcpStream) -> Result<TcpStream, Error>

Creates new TcpStream from a std::net::TcpStream.

+

This function is intended to be used to wrap a TCP stream 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.

+
ยงExamples
+
use std::error::Error;
+use tokio::net::TcpStream;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let std_stream = std::net::TcpStream::connect("127.0.0.1:34254")?;
+    std_stream.set_nonblocking(true)?;
+    let stream = TcpStream::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 function.

+

pub fn into_std(self) -> Result<TcpStream, Error>

Turns a tokio::net::TcpStream into a std::net::TcpStream.

+

The returned std::net::TcpStream will have nonblocking mode set as true. +Use set_nonblocking to change the blocking mode if needed.

+
ยงExamples
+
use std::error::Error;
+use std::io::Read;
+use tokio::net::TcpListener;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let mut data = [0u8; 12];
+    let listener = TcpListener::bind("127.0.0.1:34254").await?;
+    let (tokio_tcp_stream, _) = listener.accept().await?;
+    let mut std_tcp_stream = tokio_tcp_stream.into_std()?;
+    std_tcp_stream.set_nonblocking(false)?;
+    std_tcp_stream.read_exact(&mut data)?;
+    Ok(())
+}
+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local address that this stream is bound to.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+println!("{:?}", stream.local_addr()?);
+

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

+

pub fn peer_addr(&self) -> Result<SocketAddr, Error>

Returns the remote address that this stream is connected to.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+println!("{:?}", stream.peer_addr()?);
+

pub fn poll_peek( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<usize, Error>>

Attempts to receive data on the socket, without removing that data from +the queue, registering the current task for wakeup if data is not yet +available.

+

Note that on multiple calls to poll_peek, poll_read or +poll_read_ready, only the Waker from the Context passed to the +most recent call is scheduled to receive a wakeup. (However, +poll_write retains a second, independent waker.)

+
ยงReturn value
+

The function returns:

+
    +
  • Poll::Pending if data is not yet available.
  • +
  • Poll::Ready(Ok(n)) if data is available. n is the number of bytes peeked.
  • +
  • Poll::Ready(Err(e)) if an error is encountered.
  • +
+
ยงErrors
+

This function may encounter any standard I/O error except WouldBlock.

+
ยงExamples
+
use tokio::io::{self, ReadBuf};
+use tokio::net::TcpStream;
+
+use futures::future::poll_fn;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let stream = TcpStream::connect("127.0.0.1:8000").await?;
+    let mut buf = [0; 10];
+    let mut buf = ReadBuf::new(&mut buf);
+
+    poll_fn(|cx| {
+        stream.poll_peek(cx, &mut buf)
+    }).await?;
+
+    Ok(())
+}
+

pub async fn ready(&self, interest: Interest) -> Result<Ready, Error>

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.

+ +
use tokio::io::Interest;
+use tokio::net::TcpStream;
+use std::error::Error;
+use std::io;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let stream = TcpStream::connect("127.0.0.1:8080").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 readable(&self) -> Result<(), Error>

Waits for the socket to become readable.

+

This function is equivalent to ready(Interest::READABLE) and is usually +paired with try_read().

+
ยง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.

+
ยงExamples
+
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 mut msg = vec![0; 1024];
+
+    loop {
+        // Wait for the socket to be readable
+        stream.readable().await?;
+
+        // Try to read data, this may still fail with `WouldBlock`
+        // if the readiness event is a false positive.
+        match stream.try_read(&mut msg) {
+            Ok(n) => {
+                msg.truncate(n);
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e.into());
+            }
+        }
+    }
+
+    println!("GOT = {:?}", msg);
+    Ok(())
+}
+

pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

Polls for read readiness.

+

If the tcp stream is not currently ready for reading, this method will +store a clone of the Waker from the provided Context. When the tcp +stream becomes ready for reading, Waker::wake will be called on the +waker.

+

Note that on multiple calls to poll_read_ready, poll_read or +poll_peek, 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 tcp stream is not ready for reading.
  • +
  • Poll::Ready(Ok(())) if the tcp 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.

+

pub fn try_read(&self, buf: &mut [u8]) -> Result<usize, Error>

Tries to read data from the stream into the provided buffer, 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() 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.

+
ยงReturn
+

If data is successfully read, Ok(n) is returned, where n is the +number of bytes read. If n is 0, then it can indicate one of two scenarios:

+
    +
  1. The streamโ€™s read half is closed and will no longer yield data.
  2. +
  3. The specified buffer was 0 bytes in length.
  4. +
+

If the stream is not ready to read data, +Err(io::ErrorKind::WouldBlock) is returned.

+
ยงExamples
+
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?;
+
+    loop {
+        // Wait for the socket to be readable
+        stream.readable().await?;
+
+        // Creating the buffer **after** the `await` prevents it from
+        // being stored in the async task.
+        let mut buf = [0; 4096];
+
+        // Try to read data, this may still fail with `WouldBlock`
+        // if the readiness event is a false positive.
+        match stream.try_read(&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_vectored( + &self, + bufs: &mut [IoSliceMut<'_>], +) -> Result<usize, Error>

Tries to read data from the stream into the provided buffers, returning +how many bytes were read.

+

Data is copied to fill each buffer in order, with the final buffer +written to possibly being only partially filled. This method behaves +equivalently to a single call to try_read() with concatenated +buffers.

+

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_vectored() 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.

+
ยง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
+
use tokio::net::TcpStream;
+use std::error::Error;
+use std::io::{self, IoSliceMut};
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+    loop {
+        // Wait for the socket to be readable
+        stream.readable().await?;
+
+        // Creating the buffer **after** the `await` prevents it from
+        // being stored in the async task.
+        let mut buf_a = [0; 512];
+        let mut buf_b = [0; 1024];
+        let mut bufs = [
+            IoSliceMut::new(&mut buf_a),
+            IoSliceMut::new(&mut buf_b),
+        ];
+
+        // Try to read data, this may still fail with `WouldBlock`
+        // if the readiness event is a false positive.
+        match stream.try_read_vectored(&mut bufs) {
+            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 async fn writable(&self) -> Result<(), Error>

Waits for the socket to become writable.

+

This function is equivalent to ready(Interest::WRITABLE) and is usually +paired with try_write().

+
ยง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
+
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?;
+
+    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(b"hello world") {
+            Ok(n) => {
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e.into());
+            }
+        }
+    }
+
+    Ok(())
+}
+

pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

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.

+

pub fn try_write(&self, buf: &[u8]) -> Result<usize, Error>

Try 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.

+
ยงExamples
+
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?;
+
+    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(b"hello world") {
+            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: &[IoSlice<'_>]) -> Result<usize, Error>

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().

+
ยง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
+
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_io<R>( + &self, + interest: Interest, + f: impl FnOnce() -> Result<R, Error>, +) -> Result<R, Error>

Tries to read or write from the socket using a user-provided IO operation.

+

If the socket is ready, the provided closure is called. The closure +should attempt to perform IO operation on the socket by manually +calling the appropriate syscall. If the operation fails because the +socket is not actually ready, then the closure should return a +WouldBlock error and the readiness flag is cleared. The return value +of the closure is then returned by try_io.

+

If the socket is not ready, then the closure is not called +and a WouldBlock error is returned.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio TcpStream type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

Usually, readable(), writable() or ready() is used with this function.

+

pub async fn async_io<R>( + &self, + interest: Interest, + f: impl FnMut() -> Result<R, Error>, +) -> Result<R, Error>

Reads or writes from the socket using a user-provided IO operation.

+

The readiness of the socket is awaited and when the socket is ready, +the provided closure is called. The closure should attempt to perform +IO operation on the socket by manually calling the appropriate syscall. +If the operation fails because the socket is not actually ready, +then the closure should return a WouldBlock error. In such case the +readiness flag is cleared and the socket readiness is awaited again. +This loop is repeated until the closure returns an Ok or an error +other than WouldBlock.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio TcpStream type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

pub async fn peek(&self, buf: &mut [u8]) -> Result<usize, Error>

Receives data on the socket from the remote address to which it is +connected, without removing that data from the queue. On success, +returns the number of bytes peeked.

+

Successive calls return the same data. This is accomplished by passing +MSG_PEEK as a flag to the underlying recv system call.

+
ยงExamples
+
use tokio::net::TcpStream;
+use tokio::io::AsyncReadExt;
+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?;
+
+    let mut b1 = [0; 10];
+    let mut b2 = [0; 10];
+
+    // Peek at the data
+    let n = stream.peek(&mut b1).await?;
+
+    // Read the data
+    assert_eq!(n, stream.read(&mut b2[..n]).await?);
+    assert_eq!(&b1[..n], &b2[..n]);
+
+    Ok(())
+}
+

The read method is defined on the AsyncReadExt trait.

+

pub fn nodelay(&self) -> Result<bool, Error>

Gets the value of the TCP_NODELAY option on this socket.

+

For more information about this option, see set_nodelay.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+println!("{:?}", stream.nodelay()?);
+

pub fn set_nodelay(&self, nodelay: bool) -> Result<(), Error>

Sets the value of the TCP_NODELAY option on this socket.

+

If set, this option disables the Nagle algorithm. This means that +segments are always sent as soon as possible, even if there is only a +small amount of data. When not set, data is buffered until there is a +sufficient amount to send out, thereby avoiding the frequent sending of +small packets.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+stream.set_nodelay(true)?;
+

pub fn linger(&self) -> Result<Option<Duration>, Error>

Reads the linger duration for this socket by getting the SO_LINGER +option.

+

For more information about this option, see set_linger.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+println!("{:?}", stream.linger()?);
+

pub fn set_linger(&self, dur: Option<Duration>) -> Result<(), Error>

Sets the linger duration of this socket by setting the SO_LINGER option.

+

This option controls the action taken when a stream has unsent messages and the stream is +closed. If SO_LINGER is set, the system shall block the process until it can transmit the +data or until the time expires.

+

If SO_LINGER is not specified, and the stream is closed, the system handles the call in a +way that allows the process to continue as quickly as possible.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+stream.set_linger(None)?;
+

pub fn ttl(&self) -> Result<u32, Error>

Gets the value of the IP_TTL option for this socket.

+

For more information about this option, see set_ttl.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+println!("{:?}", stream.ttl()?);
+

pub fn set_ttl(&self, ttl: u32) -> Result<(), Error>

Sets the value for the IP_TTL option on this socket.

+

This value sets the time-to-live field that is used in every packet sent +from this socket.

+
ยงExamples
+
use tokio::net::TcpStream;
+
+let stream = TcpStream::connect("127.0.0.1:8080").await?;
+
+stream.set_ttl(123)?;
+

pub fn split<'a>(&'a mut self) -> (ReadHalf<'a>, WriteHalf<'a>)

Splits a TcpStream into a read half and a write half, which can be used +to read and write the stream concurrently.

+

This method is more efficient than into_split, but the halves cannot be +moved into independently spawned tasks.

+

pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf)

Splits a TcpStream into a read half and a write half, which can be used +to read and write the stream concurrently.

+

Unlike split, the owned halves can be moved to separate tasks, however +this comes at the cost of a heap allocation.

+

Note: Dropping the write half will shut down the write half of the TCP +stream. This is equivalent to calling shutdown() on the TcpStream.

+

Trait Implementationsยง

ยง

impl AsFd for TcpStream

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for TcpStream

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl AsyncRead for TcpStream

ยง

fn poll_read( + self: Pin<&mut TcpStream>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl AsyncWrite for TcpStream

ยง

fn poll_write( + self: Pin<&mut TcpStream>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut TcpStream>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

fn poll_flush( + self: Pin<&mut TcpStream>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut TcpStream>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

impl Debug for TcpStream

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl TryFrom<TcpStream> for TcpStream

ยง

fn try_from( + stream: TcpStream, +) -> Result<TcpStream, <TcpStream as TryFrom<TcpStream>>::Error>

Consumes stream, returning the tokio I/O object.

+

This is equivalent to +TcpStream::from_std(stream).

+
ยง

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.UdpSocket.html b/actix_rt/net/struct.UdpSocket.html new file mode 100644 index 00000000..64bb61c2 --- /dev/null +++ b/actix_rt/net/struct.UdpSocket.html @@ -0,0 +1,1030 @@ +UdpSocket in actix_rt::net - Rust
actix_rt::net

Struct UdpSocket

pub struct UdpSocket { /* private fields */ }
Expand description

A UDP socket.

+

UDP is โ€œconnectionlessโ€, unlike TCP. Meaning, regardless of what address youโ€™ve bound to, a UdpSocket +is free to communicate with many different remotes. In tokio there are basically two main ways to use UdpSocket:

+
    +
  • one to many: bind and use send_to +and recv_from to communicate with many different addresses
  • +
  • one to one: connect and associate with a single address, using send +and recv to communicate only with that remote address
  • +
+

This type does not provide a split method, because this functionality +can be achieved by instead wrapping the socket in an Arc. Note that +you do not need a Mutex to share the UdpSocket โ€” an Arc<UdpSocket> +is enough. This is because all of the methods take &self instead of +&mut self. Once you have wrapped it in an Arc, you can call +.clone() on the Arc<UdpSocket> to get multiple shared handles to the +same socket. An example of such usage can be found further down.

+

ยงStreams

+

If you need to listen over UDP and produce a Stream, you can look +at UdpFramed.

+

ยงExample: one to many (bind)

+

Using bind we can create a simple echo server that sends and recvโ€™s with many different clients:

+ +
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let sock = UdpSocket::bind("0.0.0.0:8080").await?;
+    let mut buf = [0; 1024];
+    loop {
+        let (len, addr) = sock.recv_from(&mut buf).await?;
+        println!("{:?} bytes received from {:?}", len, addr);
+
+        let len = sock.send_to(&buf[..len], addr).await?;
+        println!("{:?} bytes sent", len);
+    }
+}
+

ยงExample: one to one (connect)

+

Or using connect we can echo with a single remote address using send and recv:

+ +
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let sock = UdpSocket::bind("0.0.0.0:8080").await?;
+
+    let remote_addr = "127.0.0.1:59611";
+    sock.connect(remote_addr).await?;
+    let mut buf = [0; 1024];
+    loop {
+        let len = sock.recv(&mut buf).await?;
+        println!("{:?} bytes received from {:?}", len, remote_addr);
+
+        let len = sock.send(&buf[..len]).await?;
+        println!("{:?} bytes sent", len);
+    }
+}
+

ยงExample: Splitting with Arc

+

Because send_to and recv_from take &self. Itโ€™s perfectly alright +to use an Arc<UdpSocket> and share the references to multiple tasks. +Here is a similar โ€œechoโ€ example that supports concurrent +sending/receiving:

+ +
use tokio::{net::UdpSocket, sync::mpsc};
+use std::{io, net::SocketAddr, sync::Arc};
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;
+    let r = Arc::new(sock);
+    let s = r.clone();
+    let (tx, mut rx) = mpsc::channel::<(Vec<u8>, SocketAddr)>(1_000);
+
+    tokio::spawn(async move {
+        while let Some((bytes, addr)) = rx.recv().await {
+            let len = s.send_to(&bytes, &addr).await.unwrap();
+            println!("{:?} bytes sent", len);
+        }
+    });
+
+    let mut buf = [0; 1024];
+    loop {
+        let (len, addr) = r.recv_from(&mut buf).await?;
+        println!("{:?} bytes received from {:?}", len, addr);
+        tx.send((buf[..len].to_vec(), addr)).await.unwrap();
+    }
+}
+

Implementationsยง

ยง

impl UdpSocket

pub async fn bind<A>(addr: A) -> Result<UdpSocket, Error>
where + A: ToSocketAddrs,

This function will create a new UDP socket and attempt to bind it to +the addr provided.

+

Binding with a port number of 0 will request that the OS assigns a port +to this listener. The port allocated can be queried via the local_addr +method.

+
ยงExample
+
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let sock = UdpSocket::bind("0.0.0.0:8080").await?;
+    // use `sock`
+    Ok(())
+}
+

pub fn from_std(socket: UdpSocket) -> Result<UdpSocket, Error>

Creates new UdpSocket from a previously bound std::net::UdpSocket.

+

This function is intended to be used to wrap a UDP socket from the +standard library in the Tokio equivalent.

+

This can be used in conjunction with socket2โ€™s Socket interface to +configure a socket before itโ€™s handed off, such as setting options like +reuse_address or binding to multiple addresses.

+
ยงNotes
+

The caller is responsible for ensuring that the socket 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.

+
ยงPanics
+

This function panics if thread-local runtime is not set.

+

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 function.

+
ยงExample
+
use tokio::net::UdpSocket;
+
+let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
+let std_sock = std::net::UdpSocket::bind(addr)?;
+std_sock.set_nonblocking(true)?;
+let sock = UdpSocket::from_std(std_sock)?;
+// use `sock`
+

pub fn into_std(self) -> Result<UdpSocket, Error>

Turns a tokio::net::UdpSocket into a std::net::UdpSocket.

+

The returned std::net::UdpSocket will have nonblocking mode set as +true. Use set_nonblocking to change the blocking mode if needed.

+
ยงExamples
+
use std::error::Error;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let tokio_socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await?;
+    let std_socket = tokio_socket.into_std()?;
+    std_socket.set_nonblocking(false)?;
+    Ok(())
+}
+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local address that this socket is bound to.

+
ยงExample
+
use tokio::net::UdpSocket;
+
+let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
+let sock = UdpSocket::bind(addr).await?;
+// the address the socket is bound to
+let local_addr = sock.local_addr()?;
+

pub fn peer_addr(&self) -> Result<SocketAddr, Error>

Returns the socket address of the remote peer this socket was connected to.

+
ยงExample
+
use tokio::net::UdpSocket;
+
+let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
+let peer = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
+let sock = UdpSocket::bind(addr).await?;
+sock.connect(peer).await?;
+assert_eq!(peer, sock.peer_addr()?);
+

pub async fn connect<A>(&self, addr: A) -> Result<(), Error>
where + A: ToSocketAddrs,

Connects the UDP socket setting the default destination for send() and +limiting packets that are read via recv from the address specified in +addr.

+
ยงExample
+
use tokio::net::UdpSocket;
+
+let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;
+
+let remote_addr = "127.0.0.1:59600".parse::<SocketAddr>().unwrap();
+sock.connect(remote_addr).await?;
+let mut buf = [0u8; 32];
+// recv from remote_addr
+let len = sock.recv(&mut buf).await?;
+// send to remote_addr
+let _len = sock.send(&buf[..len]).await?;
+

pub async fn ready(&self, interest: Interest) -> Result<Ready, Error>

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.

+ +
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 writable(&self) -> Result<(), Error>

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
+
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 fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

Polls for write/send readiness.

+

If the udp stream is not currently ready for sending, this method will +store a clone of the Waker from the provided Context. When the udp +stream becomes ready for sending, Waker::wake will be called on the +waker.

+

Note that on multiple calls to poll_send_ready or poll_send, only +the Waker from the Context passed to the most recent call is +scheduled to receive a wakeup. (However, poll_recv_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 udp stream is not ready for writing.
  • +
  • Poll::Ready(Ok(())) if the udp 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.

+

pub async fn send(&self, buf: &[u8]) -> Result<usize, Error>

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.

+
ยงReturn
+

On success, the number of bytes sent is returned, otherwise, the +encountered error is returned.

+
ยงCancel safety
+

This method is cancel safe. If send is used as the event in a +tokio::select! statement and some other branch +completes first, then it is guaranteed that the message was not sent.

+
ยงExamples
+
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 fn poll_send( + &self, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempts to send data on the socket to the remote address to which it +was previously connected.

+

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.

+

pub fn try_send(&self, buf: &[u8]) -> Result<usize, Error>

Tries to send data on the socket to the remote address to which it is +connected.

+

When the socket buffer is full, Err(io::ErrorKind::WouldBlock) is +returned. This function is usually paired with writable().

+
ยงReturns
+

If successful, Ok(n) is returned, where n is the number of bytes +sent. If the socket is not ready to send data, +Err(ErrorKind::WouldBlock) is returned.

+
ยงExamples
+
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    // Bind a UDP socket
+    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
+
+    // Connect to a peer
+    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 readable(&self) -> Result<(), Error>

Waits for the socket to become readable.

+

This function is equivalent to ready(Interest::READABLE) and is usually +paired with try_recv().

+

The function may complete without the socket being readable. This is a +false-positive and attempting a try_recv() 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 read that fails with WouldBlock or +Poll::Pending.

+
ยงExamples
+
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    // Connect to a peer
+    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 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 poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

Polls for read/receive readiness.

+

If the udp stream is not currently ready for receiving, this method will +store a clone of the Waker from the provided Context. When the udp +socket becomes ready for reading, Waker::wake will be called on the +waker.

+

Note that on multiple calls to poll_recv_ready, poll_recv or +poll_peek, only the Waker from the Context passed to the most +recent call is scheduled to receive a wakeup. (However, +poll_send_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 udp stream is not ready for reading.
  • +
  • Poll::Ready(Ok(())) if the udp 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.

+

pub async fn recv(&self, buf: &mut [u8]) -> Result<usize, Error>

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! statement and some other branch +completes first, it is guaranteed that no messages were received on this +socket.

+ +
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 fn poll_recv( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to receive a single datagram message on the socket from the remote +address to which it is connected.

+

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.

+

pub fn try_recv(&self, buf: &mut [u8]) -> Result<usize, Error>

Tries to receive a single datagram message on the socket from the remote +address to which it is connected. On success, returns the number of +bytes read.

+

This method 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.

+

When there is no pending data, Err(io::ErrorKind::WouldBlock) is +returned. This function is usually paired with readable().

+
ยงExamples
+
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    // Connect to a peer
+    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 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 async fn send_to<A>(&self, buf: &[u8], target: A) -> Result<usize, Error>
where + A: ToSocketAddrs,

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.

+
ยงCancel safety
+

This method is cancel safe. If send_to is used as the event in a +tokio::select! statement and some other branch +completes first, then it is guaranteed that the message was not sent.

+
ยงExample
+
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 fn poll_send_to( + &self, + cx: &mut Context<'_>, + buf: &[u8], + target: SocketAddr, +) -> Poll<Result<usize, Error>>

Attempts to send data on the socket to a given 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 try_send_to( + &self, + buf: &[u8], + target: SocketAddr, +) -> Result<usize, Error>

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.

+
ยงExample
+
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 async fn recv_from( + &self, + buf: &mut [u8], +) -> Result<(usize, SocketAddr), Error>

Receives a single datagram message on the socket. On success, returns +the number of bytes read and the origin.

+

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.

+
ยงCancel safety
+

This method is cancel safe. If recv_from is used as the event in a +tokio::select! statement and some other branch +completes first, it is guaranteed that no messages were received on this +socket.

+
ยงExample
+
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.recv_from(&mut buf).await?;
+
+    println!("received {:?} bytes from {:?}", len, addr);
+
+    Ok(())
+}
+
ยง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.

+

pub fn poll_recv_from( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<SocketAddr, 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.

+

pub fn try_recv_from( + &self, + buf: &mut [u8], +) -> Result<(usize, SocketAddr), Error>

Tries to receive a single datagram message on the socket. On success, +returns the number of bytes read and the origin.

+

This method 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.

+

When there is no pending data, Err(io::ErrorKind::WouldBlock) is +returned. This function is usually paired with readable().

+
ยง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.

+
ยงExamples
+
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    // Connect to a peer
+    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
+
+    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_from(&mut buf) {
+            Ok((n, _addr)) => {
+                println!("GOT {:?}", &buf[..n]);
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e);
+            }
+        }
+    }
+
+    Ok(())
+}
+

pub fn try_io<R>( + &self, + interest: Interest, + f: impl FnOnce() -> Result<R, Error>, +) -> Result<R, Error>

Tries to read or write from the socket using a user-provided IO operation.

+

If the socket is ready, the provided closure is called. The closure +should attempt to perform IO operation on the socket by manually +calling the appropriate syscall. If the operation fails because the +socket is not actually ready, then the closure should return a +WouldBlock error and the readiness flag is cleared. The return value +of the closure is then returned by try_io.

+

If the socket is not ready, then the closure is not called +and a WouldBlock error is returned.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio UdpSocket type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

Usually, readable(), writable() or ready() is used with this function.

+

pub async fn async_io<R>( + &self, + interest: Interest, + f: impl FnMut() -> Result<R, Error>, +) -> Result<R, Error>

Reads or writes from the socket using a user-provided IO operation.

+

The readiness of the socket is awaited and when the socket is ready, +the provided closure is called. The closure should attempt to perform +IO operation on the socket by manually calling the appropriate syscall. +If the operation fails because the socket is not actually ready, +then the closure should return a WouldBlock error. In such case the +readiness flag is cleared and the socket readiness is awaited again. +This loop is repeated until the closure returns an Ok or an error +other than WouldBlock.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio UdpSocket type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

pub async fn peek_from( + &self, + buf: &mut [u8], +) -> Result<(usize, SocketAddr), Error>

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
+
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(())
+}
+

pub fn poll_peek_from( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<SocketAddr, Error>>

Receives data from the socket, without removing it from the input queue. +On success, returns the sending address of the datagram.

+
ยง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

+

On Windows, if the data is larger than the buffer specified, the buffer +is filled with the first part of the data, and peek 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 poll_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.

+
ยง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.

+

pub fn try_peek_from( + &self, + buf: &mut [u8], +) -> Result<(usize, SocketAddr), Error>

Tries to receive data on the socket without removing it from the input queue. +On success, returns the number of bytes read and the sending address of the +datagram.

+

When there is no pending data, Err(io::ErrorKind::WouldBlock) is +returned. This function is usually paired with readable().

+
ยง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 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 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.

+

pub async fn peek_sender(&self) -> Result<SocketAddr, Error>

Retrieve the sender of the data at the head of the input queue, waiting if empty.

+

This is equivalent to calling peek_from with a zero-sized buffer, +but suppresses the WSAEMSGSIZE error on Windows and the โ€œinvalid argumentโ€ error on macOS.

+

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.

+

pub fn poll_peek_sender( + &self, + cx: &mut Context<'_>, +) -> Poll<Result<SocketAddr, Error>>

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.

+

pub fn try_peek_sender(&self) -> Result<SocketAddr, Error>

Try to retrieve the sender of the data at the head of the input queue.

+

When there is no pending data, Err(io::ErrorKind::WouldBlock) is +returned. This function is usually paired with readable().

+

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.

+

pub fn broadcast(&self) -> Result<bool, Error>

Gets the value of the SO_BROADCAST option for this socket.

+

For more information about this option, see set_broadcast.

+

pub fn set_broadcast(&self, on: bool) -> Result<(), Error>

Sets the value of the SO_BROADCAST option for this socket.

+

When enabled, this socket is allowed to send packets to a broadcast +address.

+

pub fn multicast_loop_v4(&self) -> Result<bool, Error>

Gets the value of the IP_MULTICAST_LOOP option for this socket.

+

For more information about this option, see set_multicast_loop_v4.

+

pub fn set_multicast_loop_v4(&self, on: bool) -> Result<(), Error>

Sets the value of the IP_MULTICAST_LOOP option for this socket.

+

If enabled, multicast packets will be looped back to the local socket.

+
ยงNote
+

This may not have any affect on IPv6 sockets.

+

pub fn multicast_ttl_v4(&self) -> Result<u32, Error>

Gets the value of the IP_MULTICAST_TTL option for this socket.

+

For more information about this option, see set_multicast_ttl_v4.

+

pub fn set_multicast_ttl_v4(&self, ttl: u32) -> Result<(), Error>

Sets the value of the IP_MULTICAST_TTL option for this socket.

+

Indicates the time-to-live value of outgoing multicast packets for +this socket. The default value is 1 which means that multicast packets +donโ€™t leave the local network unless explicitly requested.

+
ยงNote
+

This may not have any affect on IPv6 sockets.

+

pub fn multicast_loop_v6(&self) -> Result<bool, Error>

Gets the value of the IPV6_MULTICAST_LOOP option for this socket.

+

For more information about this option, see set_multicast_loop_v6.

+

pub fn set_multicast_loop_v6(&self, on: bool) -> Result<(), Error>

Sets the value of the IPV6_MULTICAST_LOOP option for this socket.

+

Controls whether this socket sees the multicast packets it sends itself.

+
ยงNote
+

This may not have any affect on IPv4 sockets.

+

pub fn ttl(&self) -> Result<u32, Error>

Gets the value of the IP_TTL option for this socket.

+

For more information about this option, see set_ttl.

+
ยงExamples
+
use tokio::net::UdpSocket;
+
+let sock = UdpSocket::bind("127.0.0.1:8080").await?;
+
+println!("{:?}", sock.ttl()?);
+

pub fn set_ttl(&self, ttl: u32) -> Result<(), Error>

Sets the value for the IP_TTL option on this socket.

+

This value sets the time-to-live field that is used in every packet sent +from this socket.

+
ยงExamples
+
use tokio::net::UdpSocket;
+
+let sock = UdpSocket::bind("127.0.0.1:8080").await?;
+sock.set_ttl(60)?;
+
+

pub fn tos(&self) -> Result<u32, Error>

Gets the value of the IP_TOS option for this socket.

+

For more information about this option, see set_tos.

+

NOTE: On Windows, IP_TOS is only supported on Windows 8+ or +Windows Server 2012+.

+

pub fn set_tos(&self, tos: u32) -> Result<(), Error>

Sets the value for the IP_TOS option on this socket.

+

This value sets the type-of-service field that is used in every packet +sent from this socket.

+

NOTE: On Windows, IP_TOS is only supported on Windows 8+ or +Windows Server 2012+.

+

pub fn device(&self) -> Result<Option<Vec<u8>>, Error>

Gets the value for the SO_BINDTODEVICE option on this socket

+

This value gets the socket-bound deviceโ€™s interface name.

+

pub fn bind_device(&self, interface: Option<&[u8]>) -> Result<(), Error>

Sets the value for the SO_BINDTODEVICE option on this socket

+

If a socket is bound to an interface, only packets received from that +particular interface are processed by the socket. Note that this only +works for some socket types, particularly AF_INET sockets.

+

If interface is None or an empty string it removes the binding.

+

pub fn join_multicast_v4( + &self, + multiaddr: Ipv4Addr, + interface: Ipv4Addr, +) -> Result<(), Error>

Executes an operation of the IP_ADD_MEMBERSHIP type.

+

This function specifies a new multicast group for this socket to join. +The address must be a valid multicast address, and interface is the +address of the local interface with which the system should join the +multicast group. If itโ€™s equal to INADDR_ANY then an appropriate +interface is chosen by the system.

+

pub fn join_multicast_v6( + &self, + multiaddr: &Ipv6Addr, + interface: u32, +) -> Result<(), Error>

Executes an operation of the IPV6_ADD_MEMBERSHIP type.

+

This function specifies a new multicast group for this socket to join. +The address must be a valid multicast address, and interface is the +index of the interface to join/leave (or 0 to indicate any interface).

+

pub fn leave_multicast_v4( + &self, + multiaddr: Ipv4Addr, + interface: Ipv4Addr, +) -> Result<(), Error>

Executes an operation of the IP_DROP_MEMBERSHIP type.

+

For more information about this option, see join_multicast_v4.

+

pub fn leave_multicast_v6( + &self, + multiaddr: &Ipv6Addr, + interface: u32, +) -> Result<(), Error>

Executes an operation of the IPV6_DROP_MEMBERSHIP type.

+

For more information about this option, see join_multicast_v6.

+

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

+
ยงExamples
+
use tokio::net::UdpSocket;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    // Create a socket
+    let socket = UdpSocket::bind("0.0.0.0:8080").await?;
+
+    if let Ok(Some(err)) = socket.take_error() {
+        println!("Got error: {:?}", err);
+    }
+
+    Ok(())
+}
+

Trait Implementationsยง

ยง

impl AsFd for UdpSocket

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for UdpSocket

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl Debug for UdpSocket

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl TryFrom<UdpSocket> for UdpSocket

ยง

fn try_from( + stream: UdpSocket, +) -> Result<UdpSocket, <UdpSocket as TryFrom<UdpSocket>>::Error>

Consumes stream, returning the tokio I/O object.

+

This is equivalent to +UdpSocket::from_std(stream).

+
ยง

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.UnixDatagram.html b/actix_rt/net/struct.UnixDatagram.html new file mode 100644 index 00000000..465180b2 --- /dev/null +++ b/actix_rt/net/struct.UnixDatagram.html @@ -0,0 +1,868 @@ +UnixDatagram in actix_rt::net - Rust
actix_rt::net

Struct UnixDatagram

pub struct UnixDatagram { /* private fields */ }
Expand description

An I/O object representing a Unix datagram socket.

+

A socket can be either named (associated with a filesystem path) or +unnamed.

+

This type does not provide a split method, because this functionality +can be achieved by wrapping the socket in an Arc. Note that you do +not need a Mutex to share the UnixDatagram โ€” an Arc<UnixDatagram> +is enough. This is because all of the methods take &self instead of +&mut self.

+

Note: named sockets are persisted even after the object is dropped +and the program has exited, and cannot be reconnected. It is advised +that you either check for and unlink the existing socket if it exists, +or use a temporary file that is guaranteed to not already exist.

+

ยงExamples

+

Using named sockets, associated with a filesystem path:

+ +
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);
+
+

Using unnamed sockets, created as a pair

+ +
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);
+
+

Implementationsยง

ยง

impl UnixDatagram

pub async fn ready(&self, interest: Interest) -> Result<Ready, Error>

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.

+ +
use tokio::io::Interest;
+use tokio::net::UnixDatagram;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    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 {
+        let ready = socket.ready(Interest::READABLE | Interest::WRITABLE).await?;
+
+        if ready.is_readable() {
+            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 writable(&self) -> Result<(), Error>

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
+
use tokio::net::UnixDatagram;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    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 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 fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

Polls for write/send readiness.

+

If the socket is not currently ready for sending, this method will +store a clone of the Waker from the provided Context. When the socket +becomes ready for sending, Waker::wake will be called on the +waker.

+

Note that on multiple calls to poll_send_ready or poll_send, only +the Waker from the Context passed to the most recent call is +scheduled to receive a wakeup. (However, poll_recv_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 socket is not ready for writing.
  • +
  • Poll::Ready(Ok(())) if the socket 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.

+

pub async fn readable(&self) -> Result<(), Error>

Waits for the socket to become readable.

+

This function is equivalent to ready(Interest::READABLE) and is usually +paired with try_recv().

+

The function may complete without the socket being readable. This is a +false-positive and attempting a try_recv() 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 read that fails with WouldBlock or +Poll::Pending.

+
ยงExamples
+
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 poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

Polls for read/receive readiness.

+

If the socket is not currently ready for receiving, this method will +store a clone of the Waker from the provided Context. When the +socket becomes ready for reading, Waker::wake will be called on the +waker.

+

Note that on multiple calls to poll_recv_ready, poll_recv or +poll_peek, only the Waker from the Context passed to the most +recent call is scheduled to receive a wakeup. (However, +poll_send_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 socket is not ready for reading.
  • +
  • Poll::Ready(Ok(())) if the socket 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.

+

pub fn bind<P>(path: P) -> Result<UnixDatagram, Error>
where + P: AsRef<Path>,

Creates a new UnixDatagram bound to the specified path.

+
ยงExamples
+
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 the socket to a filesystem path
+let socket_path = tmp.path().join("socket");
+let socket = UnixDatagram::bind(&socket_path)?;
+
+

pub fn pair() -> Result<(UnixDatagram, UnixDatagram), Error>

Creates an unnamed pair of connected sockets.

+

This function will create a pair of interconnected Unix sockets for +communicating back and forth between one another.

+
ยงExamples
+
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"hail eris";
+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);
+
+

pub fn from_std(datagram: UnixDatagram) -> Result<UnixDatagram, Error>

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 socket 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.

+
ยง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 function.

+
ยงExamples
+
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)?;
+
+

pub fn into_std(self) -> Result<UnixDatagram, Error>

Turns a tokio::net::UnixDatagram into a std::os::unix::net::UnixDatagram.

+

The returned std::os::unix::net::UnixDatagram will have nonblocking +mode set as true. Use set_nonblocking to change the blocking mode +if needed.

+
ยงExamples
+
let tokio_socket = tokio::net::UnixDatagram::bind("/path/to/the/socket")?;
+let std_socket = tokio_socket.into_std()?;
+std_socket.set_nonblocking(false)?;
+

pub fn unbound() -> Result<UnixDatagram, Error>

Creates a new UnixDatagram which is not bound to any address.

+
ยงExamples
+
use tokio::net::UnixDatagram;
+use tempfile::tempdir;
+
+// Create an unbound socket
+let tx = UnixDatagram::unbound()?;
+
+// Create another, bound socket
+let tmp = tempdir()?;
+let rx_path = tmp.path().join("rx");
+let rx = UnixDatagram::bind(&rx_path)?;
+
+// Send to the bound socket
+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);
+
+

pub fn connect<P>(&self, path: P) -> Result<(), Error>
where + P: AsRef<Path>,

Connects the socket to the specified address.

+

The send method may be used to send data to the specified address. +recv and recv_from will only receive data from that address.

+
ยงExamples
+
use tokio::net::UnixDatagram;
+use tempfile::tempdir;
+
+// Create an unbound socket
+let tx = UnixDatagram::unbound()?;
+
+// Create another, bound socket
+let tmp = tempdir()?;
+let rx_path = tmp.path().join("rx");
+let rx = UnixDatagram::bind(&rx_path)?;
+
+// Connect to the bound socket
+tx.connect(&rx_path)?;
+
+// Send to the bound socket
+let bytes = b"hello world";
+tx.send(bytes).await?;
+
+let mut buf = vec![0u8; 24];
+let (size, addr) = rx.recv_from(&mut buf).await?;
+
+let dgram = &buf[..size];
+assert_eq!(dgram, bytes);
+
+

pub async fn send(&self, buf: &[u8]) -> Result<usize, Error>

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! statement and some other branch +completes first, then it is guaranteed that the message was not sent.

+
ยงExamples
+
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);
+
+

pub fn try_send(&self, buf: &[u8]) -> Result<usize, Error>

Tries to send a datagram to the peer without waiting.

+
ยงExamples
+
use tokio::net::UnixDatagram;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    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 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 fn try_send_to<P>(&self, buf: &[u8], target: P) -> Result<usize, Error>
where + P: AsRef<Path>,

Tries to send a datagram to the peer without waiting.

+
ยงExamples
+
use tokio::net::UnixDatagram;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    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)?;
+
+    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_to(b"hello world", &server_path) {
+            Ok(n) => {
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e);
+            }
+        }
+    }
+
+    Ok(())
+}
+

pub async fn recv(&self, buf: &mut [u8]) -> Result<usize, Error>

Receives data from the socket.

+
ยงCancel safety
+

This method is cancel safe. If recv is used as the event in a +tokio::select! statement and some other branch +completes first, it is guaranteed that no messages were received on this +socket.

+
ยงExamples
+
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);
+
+

pub fn try_recv(&self, buf: &mut [u8]) -> Result<usize, Error>

Tries to receive a datagram from the peer without waiting.

+
ยงExamples
+
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 async fn send_to<P>(&self, buf: &[u8], target: P) -> Result<usize, Error>
where + P: AsRef<Path>,

Sends data on the socket to the specified address.

+
ยงCancel safety
+

This method is cancel safe. If send_to is used as the event in a +tokio::select! statement and some other branch +completes first, then it is guaranteed that the message was not sent.

+
ยงExamples
+
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);
+
+

pub async fn recv_from( + &self, + buf: &mut [u8], +) -> Result<(usize, SocketAddr), Error>

Receives data from the socket.

+
ยงCancel safety
+

This method is cancel safe. If recv_from is used as the event in a +tokio::select! statement and some other branch +completes first, it is guaranteed that no messages were received on this +socket.

+
ยงExamples
+
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);
+
+

pub fn poll_recv_from( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<SocketAddr, Error>>

Attempts to receive a single datagram on the specified address.

+

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.

+

pub fn poll_send_to<P>( + &self, + cx: &mut Context<'_>, + buf: &[u8], + target: P, +) -> Poll<Result<usize, Error>>
where + P: AsRef<Path>,

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( + &self, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempts to send data on the socket to the remote address to which it +was previously connected.

+

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.

+

pub fn poll_recv( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to receive a single datagram message on the socket from the remote +address to which it is connected.

+

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.

+

pub fn try_recv_from( + &self, + buf: &mut [u8], +) -> Result<(usize, SocketAddr), Error>

Tries to receive data from the socket without waiting.

+
ยงExamples
+
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)?;
+
+    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_from(&mut buf) {
+            Ok((n, _addr)) => {
+                println!("GOT {:?}", &buf[..n]);
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e);
+            }
+        }
+    }
+
+    Ok(())
+}
+

pub fn try_io<R>( + &self, + interest: Interest, + f: impl FnOnce() -> Result<R, Error>, +) -> Result<R, Error>

Tries to read or write from the socket using a user-provided IO operation.

+

If the socket is ready, the provided closure is called. The closure +should attempt to perform IO operation on the socket by manually +calling the appropriate syscall. If the operation fails because the +socket is not actually ready, then the closure should return a +WouldBlock error and the readiness flag is cleared. The return value +of the closure is then returned by try_io.

+

If the socket is not ready, then the closure is not called +and a WouldBlock error is returned.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio UnixDatagram type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

Usually, readable(), writable() or ready() is used with this function.

+

pub async fn async_io<R>( + &self, + interest: Interest, + f: impl FnMut() -> Result<R, Error>, +) -> Result<R, Error>

Reads or writes from the socket using a user-provided IO operation.

+

The readiness of the socket is awaited and when the socket is ready, +the provided closure is called. The closure should attempt to perform +IO operation on the socket by manually calling the appropriate syscall. +If the operation fails because the socket is not actually ready, +then the closure should return a WouldBlock error. In such case the +readiness flag is cleared and the socket readiness is awaited again. +This loop is repeated until the closure returns an Ok or an error +other than WouldBlock.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio UnixDatagram type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local address that this socket is bound to.

+
ยงExamples
+

For a socket bound to a local path

+ +
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 socket to a filesystem path
+let socket_path = tmp.path().join("socket");
+let socket = UnixDatagram::bind(&socket_path)?;
+
+assert_eq!(socket.local_addr()?.as_pathname().unwrap(), &socket_path);
+
+

For an unbound socket

+ +
use tokio::net::UnixDatagram;
+
+// Create an unbound socket
+let socket = UnixDatagram::unbound()?;
+
+assert!(socket.local_addr()?.is_unnamed());
+
+

pub fn peer_addr(&self) -> Result<SocketAddr, Error>

Returns the address of this socketโ€™s peer.

+

The connect method will connect the socket to a peer.

+
ยงExamples
+

For a peer with a local path

+ +
use tokio::net::UnixDatagram;
+use tempfile::tempdir;
+
+// Create an unbound socket
+let tx = UnixDatagram::unbound()?;
+
+// Create another, bound socket
+let tmp = tempdir()?;
+let rx_path = tmp.path().join("rx");
+let rx = UnixDatagram::bind(&rx_path)?;
+
+// Connect to the bound socket
+tx.connect(&rx_path)?;
+
+assert_eq!(tx.peer_addr()?.as_pathname().unwrap(), &rx_path);
+
+

For an unbound peer

+ +
use tokio::net::UnixDatagram;
+
+// Create the pair of sockets
+let (sock1, sock2) = UnixDatagram::pair()?;
+
+assert!(sock1.peer_addr()?.is_unnamed());
+
+

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

+
ยงExamples
+
use tokio::net::UnixDatagram;
+
+// Create an unbound socket
+let socket = UnixDatagram::unbound()?;
+
+if let Ok(Some(err)) = socket.take_error() {
+    println!("Got error: {:?}", err);
+}
+
+

pub fn shutdown(&self, how: Shutdown) -> Result<(), Error>

Shuts down the read, write, or both halves of this connection.

+

This function will cause all pending and future I/O calls on the +specified portions to immediately return with an appropriate value +(see the documentation of Shutdown).

+
ยงExamples
+
use tokio::net::UnixDatagram;
+use std::net::Shutdown;
+
+// Create an unbound socket
+let (socket, other) = UnixDatagram::pair()?;
+
+socket.shutdown(Shutdown::Both)?;
+
+// NOTE: the following commented out code does NOT work as expected.
+// Due to an underlying issue, the recv call will block indefinitely.
+// See: https://github.com/tokio-rs/tokio/issues/1679
+//let mut buff = vec![0u8; 24];
+//let size = socket.recv(&mut buff).await?;
+//assert_eq!(size, 0);
+
+let send_result = socket.send(b"hello world").await;
+assert!(send_result.is_err());
+
+

Trait Implementationsยง

ยง

impl AsFd for UnixDatagram

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for UnixDatagram

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl Debug for UnixDatagram

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl TryFrom<UnixDatagram> for UnixDatagram

ยง

fn try_from( + stream: UnixDatagram, +) -> Result<UnixDatagram, <UnixDatagram as TryFrom<UnixDatagram>>::Error>

Consumes stream, returning the Tokio I/O object.

+

This is equivalent to +UnixDatagram::from_std(stream).

+
ยง

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.UnixListener.html b/actix_rt/net/struct.UnixListener.html new file mode 100644 index 00000000..6fd738ba --- /dev/null +++ b/actix_rt/net/struct.UnixListener.html @@ -0,0 +1,90 @@ +UnixListener in actix_rt::net - Rust
actix_rt::net

Struct UnixListener

pub struct UnixListener { /* private fields */ }
Expand description

A Unix socket which can accept connections from other Unix sockets.

+

You can accept a new connection by using the accept method.

+

A UnixListener can be turned into a Stream with UnixListenerStream.

+

ยงErrors

+

Note that accepting a connection can lead to various errors and not all +of them are necessarily fatal โ€’ for example having too many open file +descriptors or the other side closing the connection while it waits in +an accept queue. These would terminate the stream if not handled in any +way.

+

ยงExamples

+
use tokio::net::UnixListener;
+
+#[tokio::main]
+async fn main() {
+    let listener = UnixListener::bind("/path/to/the/socket").unwrap();
+    loop {
+        match listener.accept().await {
+            Ok((stream, _addr)) => {
+                println!("new client!");
+            }
+            Err(e) => { /* connection failed */ }
+        }
+    }
+}
+

Implementationsยง

ยง

impl UnixListener

pub fn bind<P>(path: P) -> Result<UnixListener, Error>
where + P: AsRef<Path>,

Creates a new UnixListener bound to the specified path.

+
ยง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 function.

+

pub fn from_std(listener: UnixListener) -> Result<UnixListener, Error>

Creates new UnixListener from a std::os::unix::net::UnixListener.

+

This function is intended to be used to wrap a UnixListener from the +standard library in the Tokio equivalent.

+
ยงNotes
+

The caller is responsible for ensuring that the listener is in +non-blocking mode. Otherwise all I/O operations on the listener +will block the thread, which will cause unexpected behavior. +Non-blocking mode can be set using set_nonblocking.

+
ยงExamples
+
use tokio::net::UnixListener;
+use std::os::unix::net::UnixListener as StdUnixListener;
+
+let std_listener = StdUnixListener::bind("/path/to/the/socket")?;
+std_listener.set_nonblocking(true)?;
+let listener = UnixListener::from_std(std_listener)?;
+
ยง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 function.

+

pub fn into_std(self) -> Result<UnixListener, Error>

Turns a tokio::net::UnixListener into a std::os::unix::net::UnixListener.

+

The returned std::os::unix::net::UnixListener will have nonblocking mode +set as true. Use set_nonblocking to change the blocking mode if needed.

+
ยงExamples
+
let tokio_listener = tokio::net::UnixListener::bind("/path/to/the/socket")?;
+let std_listener = tokio_listener.into_std()?;
+std_listener.set_nonblocking(false)?;
+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the local socket address of this listener.

+

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

+

pub async fn accept(&self) -> Result<(UnixStream, SocketAddr), Error>

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! statement and some other branch +completes first, then it is guaranteed that no new connections were +accepted by this method.

+

pub fn poll_accept( + &self, + cx: &mut Context<'_>, +) -> Poll<Result<(UnixStream, SocketAddr), Error>>

Polls to accept a new incoming connection to this listener.

+

If there is no connection to accept, Poll::Pending is returned and the +current task will be notified by a waker. Note that on multiple calls +to poll_accept, only the Waker from the Context passed to the most +recent call is scheduled to receive a wakeup.

+

Trait Implementationsยง

ยง

impl AsFd for UnixListener

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for UnixListener

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl Debug for UnixListener

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl TryFrom<UnixListener> for UnixListener

ยง

fn try_from(stream: UnixListener) -> Result<UnixListener, Error>

Consumes stream, returning the tokio I/O object.

+

This is equivalent to +UnixListener::from_std(stream).

+
ยง

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/net/struct.UnixStream.html b/actix_rt/net/struct.UnixStream.html new file mode 100644 index 00000000..a4636b3a --- /dev/null +++ b/actix_rt/net/struct.UnixStream.html @@ -0,0 +1,575 @@ +UnixStream in actix_rt::net - Rust
actix_rt::net

Struct UnixStream

pub struct UnixStream { /* private fields */ }
Expand description

A structure representing a connected Unix socket.

+

This socket can be connected directly with UnixStream::connect or accepted +from a listener with UnixListener::accept. Additionally, a pair of +anonymous Unix sockets can be created with UnixStream::pair.

+

To shut down the stream in the write direction, you can call the +shutdown() method. This will cause the other peer to receive a read of +length 0, indicating that no more data will be sent. This only closes +the stream in one direction.

+

Implementationsยง

ยง

impl UnixStream

pub async fn connect<P>(path: P) -> Result<UnixStream, Error>
where + P: AsRef<Path>,

Connects to the socket named by path.

+

This function will create a new Unix socket and connect to the path +specified, associating the returned stream with the default event loopโ€™s +handle.

+

pub async fn ready(&self, interest: Interest) -> Result<Ready, Error>

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.

+ +
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 readable(&self) -> Result<(), Error>

Waits for the socket to become readable.

+

This function is equivalent to ready(Interest::READABLE) and is usually +paired with try_read().

+
ยง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.

+
ยงExamples
+
use tokio::net::UnixStream;
+use std::error::Error;
+use std::io;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+    let stream = UnixStream::connect(bind_path).await?;
+
+    let mut msg = vec![0; 1024];
+
+    loop {
+        // Wait for the socket to be readable
+        stream.readable().await?;
+
+        // Try to read data, this may still fail with `WouldBlock`
+        // if the readiness event is a false positive.
+        match stream.try_read(&mut msg) {
+            Ok(n) => {
+                msg.truncate(n);
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e.into());
+            }
+        }
+    }
+
+    println!("GOT = {:?}", msg);
+    Ok(())
+}
+

pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

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.

+

pub fn try_read(&self, buf: &mut [u8]) -> Result<usize, Error>

Try to read data from the stream into the provided buffer, 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() 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.

+
ยงReturn
+

If data is successfully read, Ok(n) is returned, where n is the +number of bytes read. If n is 0, then it can indicate one of two scenarios:

+
    +
  1. The streamโ€™s read half is closed and will no longer yield data.
  2. +
  3. The specified buffer was 0 bytes in length.
  4. +
+

If the stream is not ready to read data, +Err(io::ErrorKind::WouldBlock) is returned.

+
ยงExamples
+
use tokio::net::UnixStream;
+use std::error::Error;
+use std::io;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+    let stream = UnixStream::connect(bind_path).await?;
+
+    loop {
+        // Wait for the socket to be readable
+        stream.readable().await?;
+
+        // Creating the buffer **after** the `await` prevents it from
+        // being stored in the async task.
+        let mut buf = [0; 4096];
+
+        // Try to read data, this may still fail with `WouldBlock`
+        // if the readiness event is a false positive.
+        match stream.try_read(&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_vectored( + &self, + bufs: &mut [IoSliceMut<'_>], +) -> Result<usize, Error>

Tries to read data from the stream into the provided buffers, returning +how many bytes were read.

+

Data is copied to fill each buffer in order, with the final buffer +written to possibly being only partially filled. This method behaves +equivalently to a single call to try_read() with concatenated +buffers.

+

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_vectored() 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.

+
ยง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
+
use tokio::net::UnixStream;
+use std::error::Error;
+use std::io::{self, IoSliceMut};
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+    let stream = UnixStream::connect(bind_path).await?;
+
+    loop {
+        // Wait for the socket to be readable
+        stream.readable().await?;
+
+        // Creating the buffer **after** the `await` prevents it from
+        // being stored in the async task.
+        let mut buf_a = [0; 512];
+        let mut buf_b = [0; 1024];
+        let mut bufs = [
+            IoSliceMut::new(&mut buf_a),
+            IoSliceMut::new(&mut buf_b),
+        ];
+
+        // Try to read data, this may still fail with `WouldBlock`
+        // if the readiness event is a false positive.
+        match stream.try_read_vectored(&mut bufs) {
+            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 async fn writable(&self) -> Result<(), Error>

Waits for the socket to become writable.

+

This function is equivalent to ready(Interest::WRITABLE) and is usually +paired with try_write().

+
ยง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
+
use tokio::net::UnixStream;
+use std::error::Error;
+use std::io;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+    let stream = UnixStream::connect(bind_path).await?;
+
+    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(b"hello world") {
+            Ok(n) => {
+                break;
+            }
+            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
+                continue;
+            }
+            Err(e) => {
+                return Err(e.into());
+            }
+        }
+    }
+
+    Ok(())
+}
+

pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Error>>

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.

+

pub fn try_write(&self, buf: &[u8]) -> Result<usize, Error>

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.

+
ยงExamples
+
use tokio::net::UnixStream;
+use std::error::Error;
+use std::io;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+    let stream = UnixStream::connect(bind_path).await?;
+
+    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(b"hello world") {
+            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, buf: &[IoSlice<'_>]) -> Result<usize, Error>

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().

+
ยง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
+
use tokio::net::UnixStream;
+use std::error::Error;
+use std::io;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    // Connect to a peer
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+    let stream = UnixStream::connect(bind_path).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_io<R>( + &self, + interest: Interest, + f: impl FnOnce() -> Result<R, Error>, +) -> Result<R, Error>

Tries to read or write from the socket using a user-provided IO operation.

+

If the socket is ready, the provided closure is called. The closure +should attempt to perform IO operation on the socket by manually +calling the appropriate syscall. If the operation fails because the +socket is not actually ready, then the closure should return a +WouldBlock error and the readiness flag is cleared. The return value +of the closure is then returned by try_io.

+

If the socket is not ready, then the closure is not called +and a WouldBlock error is returned.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio UnixStream type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

Usually, readable(), writable() or ready() is used with this function.

+

pub async fn async_io<R>( + &self, + interest: Interest, + f: impl FnMut() -> Result<R, Error>, +) -> Result<R, Error>

Reads or writes from the socket using a user-provided IO operation.

+

The readiness of the socket is awaited and when the socket is ready, +the provided closure is called. The closure should attempt to perform +IO operation on the socket by manually calling the appropriate syscall. +If the operation fails because the socket is not actually ready, +then the closure should return a WouldBlock error. In such case the +readiness flag is cleared and the socket readiness is awaited again. +This loop is repeated until the closure returns an Ok or an error +other than WouldBlock.

+

The closure should only return a WouldBlock error if it has performed +an IO operation on the socket that failed due to the socket not being +ready. Returning a WouldBlock error in any other situation will +incorrectly clear the readiness flag, which can cause the socket to +behave incorrectly.

+

The closure should not perform the IO operation using any of the methods +defined on the Tokio UnixStream type, as this will mess with the +readiness flag and can cause the socket to behave incorrectly.

+

This method is not intended to be used with combined interests. +The closure should perform only one type of IO operation, so it should not +require more than one ready state. This method may panic or sleep forever +if it is called with a combined interest.

+

pub fn from_std(stream: UnixStream) -> Result<UnixStream, Error>

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.

+
ยงExamples
+
use tokio::net::UnixStream;
+use std::os::unix::net::UnixStream as StdUnixStream;
+
+let std_stream = StdUnixStream::connect("/path/to/the/socket")?;
+std_stream.set_nonblocking(true)?;
+let stream = UnixStream::from_std(std_stream)?;
+
ยง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 function.

+

pub fn into_std(self) -> Result<UnixStream, Error>

Turns a tokio::net::UnixStream into a std::os::unix::net::UnixStream.

+

The returned std::os::unix::net::UnixStream will have nonblocking +mode set as true. Use set_nonblocking to change the blocking +mode if needed.

+
ยงExamples
+
use std::error::Error;
+use std::io::Read;
+use tokio::net::UnixListener;
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
+    let dir = tempfile::tempdir().unwrap();
+    let bind_path = dir.path().join("bind_path");
+
+    let mut data = [0u8; 12];
+    let listener = UnixListener::bind(&bind_path)?;
+    let (tokio_unix_stream, _) = listener.accept().await?;
+    let mut std_unix_stream = tokio_unix_stream.into_std()?;
+    std_unix_stream.set_nonblocking(false)?;
+    std_unix_stream.read_exact(&mut data)?;
+    Ok(())
+}
+

pub fn pair() -> Result<(UnixStream, UnixStream), Error>

Creates an unnamed pair of connected sockets.

+

This function will create a pair of interconnected Unix sockets for +communicating back and forth between one another. Each socket will +be associated with the default event loopโ€™s handle.

+

pub fn local_addr(&self) -> Result<SocketAddr, Error>

Returns the socket address of the local half of this connection.

+
ยงExamples
+
use tokio::net::UnixStream;
+
+let dir = tempfile::tempdir().unwrap();
+let bind_path = dir.path().join("bind_path");
+let stream = UnixStream::connect(bind_path).await?;
+
+println!("{:?}", stream.local_addr()?);
+

pub fn peer_addr(&self) -> Result<SocketAddr, Error>

Returns the socket address of the remote half of this connection.

+
ยงExamples
+
use tokio::net::UnixStream;
+
+let dir = tempfile::tempdir().unwrap();
+let bind_path = dir.path().join("bind_path");
+let stream = UnixStream::connect(bind_path).await?;
+
+println!("{:?}", stream.peer_addr()?);
+

pub fn peer_cred(&self) -> Result<UCred, Error>

Returns effective credentials of the process which called connect or pair.

+

pub fn take_error(&self) -> Result<Option<Error>, Error>

Returns the value of the SO_ERROR option.

+

pub fn split<'a>(&'a mut self) -> (ReadHalf<'a>, WriteHalf<'a>)

Splits a UnixStream into a read half and a write half, which can be used +to read and write the stream concurrently.

+

This method is more efficient than into_split, but the halves cannot be +moved into independently spawned tasks.

+

pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf)

Splits a UnixStream into a read half and a write half, which can be used +to read and write the stream concurrently.

+

Unlike split, the owned halves can be moved to separate tasks, however +this comes at the cost of a heap allocation.

+

Note: Dropping the write half will shut down the write half of the +stream. This is equivalent to calling shutdown() on the UnixStream.

+

Trait Implementationsยง

ยง

impl AsFd for UnixStream

ยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
ยง

impl AsRawFd for UnixStream

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl AsyncRead for UnixStream

ยง

fn poll_read( + self: Pin<&mut UnixStream>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl AsyncWrite for UnixStream

ยง

fn poll_write( + self: Pin<&mut UnixStream>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut UnixStream>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

fn poll_flush( + self: Pin<&mut UnixStream>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut UnixStream>, + _: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

impl Debug for UnixStream

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl TryFrom<UnixStream> for UnixStream

ยง

fn try_from(stream: UnixStream) -> Result<UnixStream, Error>

Consumes stream, returning the tokio I/O object.

+

This is equivalent to +UnixStream::from_std(stream).

+
ยง

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/runtime/struct.Runtime.html b/actix_rt/runtime/struct.Runtime.html new file mode 100644 index 00000000..3c64fec5 --- /dev/null +++ b/actix_rt/runtime/struct.Runtime.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_rt/struct.Runtime.html...

+ + + \ No newline at end of file diff --git a/actix_rt/sidebar-items.js b/actix_rt/sidebar-items.js new file mode 100644 index 00000000..5909e6a6 --- /dev/null +++ b/actix_rt/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"attr":["main","test"],"fn":["spawn"],"macro":["pin"],"mod":["net","signal","task","time"],"struct":["Arbiter","ArbiterHandle","Runtime","System","SystemRunner"]}; \ No newline at end of file diff --git a/actix_rt/signal/fn.ctrl_c.html b/actix_rt/signal/fn.ctrl_c.html new file mode 100644 index 00000000..f71986ab --- /dev/null +++ b/actix_rt/signal/fn.ctrl_c.html @@ -0,0 +1,39 @@ +ctrl_c in actix_rt::signal - Rust
actix_rt::signal

Function ctrl_c

pub async fn ctrl_c() -> Result<(), Error>
Expand description

Completes when a โ€œctrl-cโ€ notification is sent to the process.

+

While signals are handled very differently between Unix and Windows, both +platforms support receiving a signal on โ€œctrl-cโ€. This function provides a +portable API for receiving this notification.

+

Once the returned future is polled, a listener is registered. The future +will complete on the first received ctrl-c after the initial call to +either Future::poll or .await.

+

ยงCaveats

+

On Unix platforms, the first time that a Signal instance is registered for a +particular signal kind, an OS signal-handler is installed which replaces the +default platform behavior when that signal is received, for the duration of +the entire process.

+

For example, Unix systems will terminate a process by default when it +receives a signal generated by "CTRL+C" on the terminal. But, when a +ctrl_c stream is created to listen for this signal, the time it arrives, +it will be translated to a stream event, and the process will continue to +execute. Even if this Signal instance is dropped, subsequent SIGINT +deliveries will end up captured by Tokio, and the default platform behavior +will NOT be reset.

+

Thus, applications should take care to ensure the expected signal behavior +occurs as expected after listening for specific signals.

+

ยงExamples

+
use tokio::signal;
+
+#[tokio::main]
+async fn main() {
+    println!("waiting for ctrl-c");
+
+    signal::ctrl_c().await.expect("failed to listen for event");
+
+    println!("received ctrl-c event");
+}
+

Listen in the background:

+ +
tokio::spawn(async move {
+    tokio::signal::ctrl_c().await.unwrap();
+    // Your handler here
+});
+
\ No newline at end of file diff --git a/actix_rt/signal/index.html b/actix_rt/signal/index.html new file mode 100644 index 00000000..5328388a --- /dev/null +++ b/actix_rt/signal/index.html @@ -0,0 +1,2 @@ +actix_rt::signal - Rust
actix_rt

Module signal

source
Expand description

Asynchronous signal handling (Tokio re-exports).

+

Modulesยง

  • Unix specific signals (Tokio re-exports).

Functionsยง

  • Completes when a โ€œctrl-cโ€ notification is sent to the process.
\ No newline at end of file diff --git a/actix_rt/signal/sidebar-items.js b/actix_rt/signal/sidebar-items.js new file mode 100644 index 00000000..ad5573ca --- /dev/null +++ b/actix_rt/signal/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["ctrl_c"],"mod":["unix"]}; \ No newline at end of file diff --git a/actix_rt/signal/unix/fn.signal.html b/actix_rt/signal/unix/fn.signal.html new file mode 100644 index 00000000..e9e69136 --- /dev/null +++ b/actix_rt/signal/unix/fn.signal.html @@ -0,0 +1,25 @@ +signal in actix_rt::signal::unix - Rust
actix_rt::signal::unix

Function signal

pub fn signal(kind: SignalKind) -> Result<Signal, Error>
Expand description

Creates a new listener which will receive notifications when the current +process receives the specified signal kind.

+

This function will create a new stream which binds to the default reactor. +The Signal stream is an infinite stream which will receive +notifications whenever a signal is received. More documentation can be +found on Signal itself, but to reiterate:

+
    +
  • Signals may be coalesced beyond what the kernel already does.
  • +
  • Once a signal handler is registered with the process the underlying +libc signal handler is never unregistered.
  • +
+

A Signal stream can be created for a particular signal number +multiple times. When a signal is received then all the associated +channels will receive the signal notification.

+

ยงErrors

+
    +
  • If the lower-level C functions fail for some reason.
  • +
  • If the previous initialization of this specific signal failed.
  • +
  • If the signal is one of +signal_hook::FORBIDDEN
  • +
+

ยงPanics

+

This function panics if there is no current reactor set, or if the rt +feature flag is not enabled.

+
\ No newline at end of file diff --git a/actix_rt/signal/unix/index.html b/actix_rt/signal/unix/index.html new file mode 100644 index 00000000..4880da47 --- /dev/null +++ b/actix_rt/signal/unix/index.html @@ -0,0 +1,3 @@ +actix_rt::signal::unix - Rust
actix_rt::signal

Module unix

source
Expand description

Unix specific signals (Tokio re-exports).

+

Structsยง

  • An listener for receiving a particular type of OS signal.
  • Represents the specific kind of signal to listen for.

Functionsยง

  • Creates a new listener which will receive notifications when the current +process receives the specified signal kind.
\ No newline at end of file diff --git a/actix_rt/signal/unix/sidebar-items.js b/actix_rt/signal/unix/sidebar-items.js new file mode 100644 index 00000000..344a2272 --- /dev/null +++ b/actix_rt/signal/unix/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["signal"],"struct":["Signal","SignalKind"]}; \ No newline at end of file diff --git a/actix_rt/signal/unix/struct.Signal.html b/actix_rt/signal/unix/struct.Signal.html new file mode 100644 index 00000000..ac20aa0e --- /dev/null +++ b/actix_rt/signal/unix/struct.Signal.html @@ -0,0 +1,119 @@ +Signal in actix_rt::signal::unix - Rust
actix_rt::signal::unix

Struct Signal

pub struct Signal { /* private fields */ }
Expand description

An listener for receiving a particular type of OS signal.

+

The listener can be turned into a Stream using SignalStream.

+

In general signal handling on Unix is a pretty tricky topic, and this +structure is no exception! There are some important limitations to keep in +mind when using Signal streams:

+
    +
  • +

    Signals handling in Unix already necessitates coalescing signals +together sometimes. This Signal stream is also no exception here in +that it will also coalesce signals. That is, even if the signal handler +for this process runs multiple times, the Signal stream may only return +one signal notification. Specifically, before poll is called, all +signal notifications are coalesced into one item returned from poll. +Once poll has been called, however, a further signal is guaranteed to +be yielded as an item.

    +

    Put another way, any element pulled off the returned listener corresponds to +at least one signal, but possibly more.

    +
  • +
  • +

    Signal handling in general is relatively inefficient. Although some +improvements are possible in this crate, itโ€™s recommended to not plan on +having millions of signal channels open.

    +
  • +
+

If youโ€™ve got any questions about this feel free to open an issue on the +repo! New approaches to alleviate some of these limitations are always +appreciated!

+

ยงCaveats

+

The first time that a Signal instance is registered for a particular +signal kind, an OS signal-handler is installed which replaces the default +platform behavior when that signal is received, for the duration of the +entire process.

+

For example, Unix systems will terminate a process by default when it +receives SIGINT. But, when a Signal instance is created to listen for +this signal, the next SIGINT that arrives will be translated to a stream +event, and the process will continue to execute. Even if this Signal +instance is dropped, subsequent SIGINT deliveries will end up captured by +Tokio, and the default platform behavior will NOT be reset.

+

Thus, applications should take care to ensure the expected signal behavior +occurs as expected after listening for specific signals.

+

ยงExamples

+

Wait for SIGHUP

+ +
use tokio::signal::unix::{signal, SignalKind};
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+    // An infinite stream of hangup signals.
+    let mut sig = signal(SignalKind::hangup())?;
+
+    // Print whenever a HUP signal is received
+    loop {
+        sig.recv().await;
+        println!("got signal HUP");
+    }
+}
+

Implementationsยง

ยง

impl Signal

pub async fn recv(&mut self) -> Option<()>

Receives the next signal notification event.

+

None is returned if no more events can be received by this stream.

+
ยงCancel safety
+

This method is cancel safe. If you use it as the event in a +tokio::select! statement and some other branch +completes first, then it is guaranteed that no signal is lost.

+
ยงExamples
+

Wait for SIGHUP

+ +
use tokio::signal::unix::{signal, SignalKind};
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+    // An infinite stream of hangup signals.
+    let mut stream = signal(SignalKind::hangup())?;
+
+    // Print whenever a HUP signal is received
+    loop {
+        stream.recv().await;
+        println!("got signal HUP");
+    }
+}
+

pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<()>>

Polls to receive the next signal notification event, outside of an +async context.

+

This method returns:

+
    +
  • Poll::Pending if no signals are available but the channel is not +closed.
  • +
  • Poll::Ready(Some(())) if a signal is available.
  • +
  • Poll::Ready(None) if the channel has been closed and all signals +sent before it was closed have been received.
  • +
+
ยงExamples
+

Polling from a manually implemented future

+ +
use std::pin::Pin;
+use std::future::Future;
+use std::task::{Context, Poll};
+use tokio::signal::unix::Signal;
+
+struct MyFuture {
+    signal: Signal,
+}
+
+impl Future for MyFuture {
+    type Output = Option<()>;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        println!("polling MyFuture");
+        self.signal.poll_recv(cx)
+    }
+}
+

Trait Implementationsยง

ยง

impl Debug for Signal

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/signal/unix/struct.SignalKind.html b/actix_rt/signal/unix/struct.SignalKind.html new file mode 100644 index 00000000..7d59930c --- /dev/null +++ b/actix_rt/signal/unix/struct.SignalKind.html @@ -0,0 +1,63 @@ +SignalKind in actix_rt::signal::unix - Rust
actix_rt::signal::unix

Struct SignalKind

pub struct SignalKind(/* private fields */);
Expand description

Represents the specific kind of signal to listen for.

+

Implementationsยง

ยง

impl SignalKind

pub const fn from_raw(signum: i32) -> SignalKind

Allows for listening to any valid OS signal.

+

For example, this can be used for listening for platform-specific +signals.

+ +
// let signum = libc::OS_SPECIFIC_SIGNAL;
+let kind = SignalKind::from_raw(signum);
+

pub const fn as_raw_value(&self) -> i32

Get the signalโ€™s numeric value.

+ +
let kind = SignalKind::interrupt();
+assert_eq!(kind.as_raw_value(), libc::SIGINT);
+

pub const fn alarm() -> SignalKind

Represents the SIGALRM signal.

+

On Unix systems this signal is sent when a real-time timer has expired. +By default, the process is terminated by this signal.

+

pub const fn child() -> SignalKind

Represents the SIGCHLD signal.

+

On Unix systems this signal is sent when the status of a child process +has changed. By default, this signal is ignored.

+

pub const fn hangup() -> SignalKind

Represents the SIGHUP signal.

+

On Unix systems this signal is sent when the terminal is disconnected. +By default, the process is terminated by this signal.

+

pub const fn interrupt() -> SignalKind

Represents the SIGINT signal.

+

On Unix systems this signal is sent to interrupt a program. +By default, the process is terminated by this signal.

+

pub const fn io() -> SignalKind

Represents the SIGIO signal.

+

On Unix systems this signal is sent when I/O operations are possible +on some file descriptor. By default, this signal is ignored.

+

pub const fn pipe() -> SignalKind

Represents the SIGPIPE signal.

+

On Unix systems this signal is sent when the process attempts to write +to a pipe which has no reader. By default, the process is terminated by +this signal.

+

pub const fn quit() -> SignalKind

Represents the SIGQUIT signal.

+

On Unix systems this signal is sent to issue a shutdown of the +process, after which the OS will dump the process core. +By default, the process is terminated by this signal.

+

pub const fn terminate() -> SignalKind

Represents the SIGTERM signal.

+

On Unix systems this signal is sent to issue a shutdown of the +process. By default, the process is terminated by this signal.

+

pub const fn user_defined1() -> SignalKind

Represents the SIGUSR1 signal.

+

On Unix systems this is a user defined signal. +By default, the process is terminated by this signal.

+

pub const fn user_defined2() -> SignalKind

Represents the SIGUSR2 signal.

+

On Unix systems this is a user defined signal. +By default, the process is terminated by this signal.

+

pub const fn window_change() -> SignalKind

Represents the SIGWINCH signal.

+

On Unix systems this signal is sent when the terminal window is resized. +By default, this signal is ignored.

+

Trait Implementationsยง

ยง

impl Clone for SignalKind

ยง

fn clone(&self) -> SignalKind

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for SignalKind

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl From<i32> for SignalKind

ยง

fn from(signum: i32) -> SignalKind

Converts to this type from the input type.
ยง

impl Hash for SignalKind

ยง

fn hash<__H>(&self, state: &mut __H)
where + __H: Hasher,

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
ยง

impl PartialEq for SignalKind

ยง

fn eq(&self, other: &SignalKind) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
ยง

impl Copy for SignalKind

ยง

impl Eq for SignalKind

ยง

impl StructuralPartialEq for SignalKind

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/struct.Arbiter.html b/actix_rt/struct.Arbiter.html new file mode 100644 index 00000000..eb28be9d --- /dev/null +++ b/actix_rt/struct.Arbiter.html @@ -0,0 +1,37 @@ +Arbiter in actix_rt - Rust
actix_rt

Struct Arbiter

source
pub struct Arbiter { /* private fields */ }
Expand description

An Arbiter represents a thread that provides an asynchronous execution environment for futures +and functions.

+

When an arbiter is created, it spawns a new OS thread, and hosts an event loop.

+

Implementationsยง

sourceยง

impl Arbiter

source

pub fn new() -> Arbiter

Spawn a new Arbiter thread and start its event loop with tokio-uring runtime.

+
ยงPanics
+

Panics if a System is not registered on the current thread.

+
source

pub fn handle(&self) -> ArbiterHandle

Return a handle to the this Arbiterโ€™s message sender.

+
source

pub fn current() -> ArbiterHandle

Return a handle to the current threadโ€™s Arbiterโ€™s message sender.

+
ยงPanics
+

Panics if no Arbiter is running on the current thread.

+
source

pub fn try_current() -> Option<ArbiterHandle>

Try to get current running arbiter handle.

+

Returns None if no Arbiter has been started.

+

Unlike current, this never panics.

+
source

pub fn stop(&self) -> bool

Stop Arbiter from continuing itโ€™s event loop.

+

Returns true if stop message was sent successfully and false if the Arbiter has been dropped.

+
source

pub fn spawn<Fut>(&self, future: Fut) -> bool
where + Fut: Future<Output = ()> + Send + 'static,

Send a future to the Arbiterโ€™s thread and spawn it.

+

If you require a result, include a response channel in the future.

+

Returns true if future was sent successfully and false if the Arbiter has died.

+
source

pub fn spawn_fn<F>(&self, f: F) -> bool
where + F: FnOnce() + Send + 'static,

Send a function to the Arbiterโ€™s thread and execute it.

+

Any result from the function is discarded. If you require a result, include a response +channel in the function.

+

Returns true if function was sent successfully and false if the Arbiter has died.

+
source

pub fn join(self) -> Result<()>

Wait for Arbiterโ€™s event loop to complete.

+

Joins the underlying OS thread handle. See JoinHandle::join.

+

Trait Implementationsยง

sourceยง

impl Debug for Arbiter

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/struct.ArbiterHandle.html b/actix_rt/struct.ArbiterHandle.html new file mode 100644 index 00000000..42b60cf3 --- /dev/null +++ b/actix_rt/struct.ArbiterHandle.html @@ -0,0 +1,26 @@ +ArbiterHandle in actix_rt - Rust
actix_rt

Struct ArbiterHandle

source
pub struct ArbiterHandle { /* private fields */ }
Expand description

A handle for sending spawn and stop messages to an Arbiter.

+

Implementationsยง

sourceยง

impl ArbiterHandle

source

pub fn spawn<Fut>(&self, future: Fut) -> bool
where + Fut: Future<Output = ()> + Send + 'static,

Send a future to the Arbiterโ€™s thread and spawn it.

+

If you require a result, include a response channel in the future.

+

Returns true if future was sent successfully and false if the Arbiter has died.

+
source

pub fn spawn_fn<F>(&self, f: F) -> bool
where + F: FnOnce() + Send + 'static,

Send a function to the Arbiterโ€™s thread and execute it.

+

Any result from the function is discarded. If you require a result, include a response +channel in the function.

+

Returns true if function was sent successfully and false if the Arbiter has died.

+
source

pub fn stop(&self) -> bool

Instruct Arbiter to stop processing itโ€™s event loop.

+

Returns true if stop message was sent successfully and false if the Arbiter has +been dropped.

+

Trait Implementationsยง

sourceยง

impl Clone for ArbiterHandle

sourceยง

fn clone(&self) -> ArbiterHandle

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for ArbiterHandle

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/struct.Runtime.html b/actix_rt/struct.Runtime.html new file mode 100644 index 00000000..e47e8e2e --- /dev/null +++ b/actix_rt/struct.Runtime.html @@ -0,0 +1,85 @@ +Runtime in actix_rt - Rust
actix_rt

Struct Runtime

source
pub struct Runtime { /* private fields */ }
Expand description

A Tokio-based runtime proxy.

+

All spawned futures will be executed on the current thread. Therefore, there is no Send bound +on submitted futures.

+

Implementationsยง

sourceยง

impl Runtime

source

pub fn new() -> Result<Self>

Returns a new runtime initialized with default configuration values.

+
source

pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> โ“˜
where + F: Future + 'static,

Offload a future onto the single-threaded runtime.

+

The returned join handle can be used to await the futureโ€™s result.

+

See crate root documentation for more details.

+
ยงExamples
+
let rt = actix_rt::Runtime::new().unwrap();
+
+// Spawn a future onto the runtime
+let handle = rt.spawn(async {
+    println!("running on the runtime");
+    42
+});
+
+assert_eq!(rt.block_on(handle).unwrap(), 42);
+
ยงPanics
+

This function panics if the spawn fails. Failure occurs if the executor is currently at +capacity and is unable to spawn a new future.

+
source

pub fn tokio_runtime(&self) -> &Runtime

Retrieves a reference to the underlying Tokio runtime associated with this instance.

+

The Tokio runtime is responsible for executing asynchronous tasks and managing +the event loop for an asynchronous Rust program. This method allows accessing +the runtime to interact with its features directly.

+

In a typical use case, you might need to share the same runtime between different +modules of your project. For example, a module might require a tokio::runtime::Handle +to spawn tasks on the same runtime, or the runtime itself to configure more complex +behaviours.

+
ยงExample
+
use actix_rt::Runtime;
+
+mod module_a {
+    pub fn do_something(handle: tokio::runtime::Handle) {
+        handle.spawn(async {
+            // Some asynchronous task here
+        });
+    }
+}
+
+mod module_b {
+    pub fn do_something_else(rt: &tokio::runtime::Runtime) {
+        rt.spawn(async {
+            // Another asynchronous task here
+        });
+    }
+}
+
+let actix_runtime = actix_rt::Runtime::new().unwrap();
+let tokio_runtime = actix_runtime.tokio_runtime();
+
+let handle = tokio_runtime.handle().clone();
+
+module_a::do_something(handle);
+module_b::do_something_else(tokio_runtime);
+
ยงReturns
+

An immutable reference to the tokio::runtime::Runtime instance associated with this +Runtime instance.

+
ยงNote
+

While this method provides an immutable reference to the Tokio runtime, which is safe to share across threads, +be aware that spawning blocking tasks on the Tokio runtime could potentially impact the execution +of the Actix runtime. This is because Tokio is responsible for driving the Actix system, +and blocking tasks could delay or deadlock other tasks in run loop.

+
source

pub fn block_on<F>(&self, f: F) -> F::Output
where + F: Future,

Runs the provided future, blocking the current thread until the future completes.

+

This function can be used to synchronously block the current thread until the provided +future has resolved either successfully or with an error. The result of the future is +then returned from this function call.

+

Note that this function will also execute any spawned futures on the current thread, but +will not block until these other spawned futures have completed. Once the function returns, +any uncompleted futures remain pending in the Runtime instance. These futures will not run +until block_on or run is called again.

+

The caller is responsible for ensuring that other spawned futures complete execution by +calling block_on or run.

+

Trait Implementationsยง

sourceยง

impl Debug for Runtime

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl From<Runtime> for Runtime

sourceยง

fn from(rt: Runtime) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/struct.System.html b/actix_rt/struct.System.html new file mode 100644 index 00000000..985a279f --- /dev/null +++ b/actix_rt/struct.System.html @@ -0,0 +1,29 @@ +System in actix_rt - Rust
actix_rt

Struct System

source
pub struct System { /* private fields */ }
Expand description

A manager for a per-thread distributed async runtime.

+

Implementationsยง

sourceยง

impl System

source

pub fn new() -> SystemRunner

Create a new system.

+
ยงPanics
+

Panics if underlying Tokio runtime can not be created.

+
sourceยง

impl System

source

pub fn current() -> System

Get current running system.

+
ยงPanics
+

Panics if no system is registered on the current thread.

+
source

pub fn try_current() -> Option<System>

Try to get current running system.

+

Returns None if no System has been started.

+

Unlike current, this never panics.

+
source

pub fn arbiter(&self) -> &ArbiterHandle

Get handle to a the Systemโ€™s initial Arbiter.

+
source

pub fn is_registered() -> bool

Check if there is a System registered on the current thread.

+
source

pub fn id(&self) -> usize

Numeric system identifier.

+

Useful when using multiple Systems.

+
source

pub fn stop(&self)

Stop the system (with code 0).

+
source

pub fn stop_with_code(&self, code: i32)

Stop the system with a given exit code.

+

Trait Implementationsยง

sourceยง

impl Clone for System

sourceยง

fn clone(&self) -> System

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for System

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/struct.SystemRunner.html b/actix_rt/struct.SystemRunner.html new file mode 100644 index 00000000..cda32b9e --- /dev/null +++ b/actix_rt/struct.SystemRunner.html @@ -0,0 +1,15 @@ +SystemRunner in actix_rt - Rust
actix_rt

Struct SystemRunner

source
pub struct SystemRunner;
Expand description

Runner that keeps a Systemโ€™s event loop alive until stop message is received.

+

Implementationsยง

sourceยง

impl SystemRunner

source

pub fn run(self) -> Result<()>

Starts event loop and will return once System is stopped.

+
source

pub fn run_with_code(self) -> Result<i32>

Runs the event loop until stopped, returning the exit code.

+
source

pub fn block_on<F: Future>(&self, fut: F) -> F::Output

Runs the provided future, blocking the current thread until the future completes.

+

Trait Implementationsยง

sourceยง

impl Debug for SystemRunner

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/system/struct.System.html b/actix_rt/system/struct.System.html new file mode 100644 index 00000000..aff72509 --- /dev/null +++ b/actix_rt/system/struct.System.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_rt/struct.System.html...

+ + + \ No newline at end of file diff --git a/actix_rt/system/struct.SystemRunner.html b/actix_rt/system/struct.SystemRunner.html new file mode 100644 index 00000000..3324e830 --- /dev/null +++ b/actix_rt/system/struct.SystemRunner.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_rt/struct.SystemRunner.html...

+ + + \ No newline at end of file diff --git a/actix_rt/task/fn.spawn_blocking.html b/actix_rt/task/fn.spawn_blocking.html new file mode 100644 index 00000000..05a06acf --- /dev/null +++ b/actix_rt/task/fn.spawn_blocking.html @@ -0,0 +1,86 @@ +spawn_blocking in actix_rt::task - Rust
actix_rt::task

Function spawn_blocking

pub fn spawn_blocking<F, R>(f: F) -> JoinHandle<R> โ“˜
where + F: FnOnce() -> R + Send + 'static, + R: Send + 'static,
Expand description

Runs the provided closure on a thread where blocking is acceptable.

+

In general, issuing a blocking call or performing a lot of compute in a +future without yielding is problematic, as it may prevent the executor from +driving other futures forward. This function runs the provided closure on a +thread dedicated to blocking operations. See the CPU-bound tasks and +blocking code section for more information.

+

Tokio will spawn more blocking threads when they are requested through this +function until the upper limit configured on the Builder is reached. +After reaching the upper limit, the tasks are put in a queue. +The thread limit is very large by default, because spawn_blocking is often +used for various kinds of IO operations that cannot be performed +asynchronously. When you run CPU-bound code using spawn_blocking, you +should keep this large upper limit in mind. When running many CPU-bound +computations, a semaphore or some other synchronization primitive should be +used to limit the number of computation executed in parallel. Specialized +CPU-bound executors, such as rayon, may also be a good fit.

+

This function is intended for non-async operations that eventually finish on +their own. If you want to spawn an ordinary thread, you should use +thread::spawn instead.

+

Be aware that tasks spawned using spawn_blocking cannot be aborted +because they are not async. If you call abort on a spawn_blocking +task, then this will not have any effect, and the task will continue +running normally. The exception is if the task has not started running +yet; in that case, calling abort may prevent the task from starting.

+

When you shut down the executor, it will wait indefinitely for all blocking operations to +finish. You can use shutdown_timeout to stop waiting for them after a +certain timeout. Be aware that this will still not cancel the tasks โ€” they +are simply allowed to keep running after the method returns. It is possible +for a blocking task to be cancelled if it has not yet started running, but this +is not guaranteed.

+

Note that if you are using the single threaded runtime, this function will +still spawn additional threads for blocking operations. The current-thread +schedulerโ€™s single thread is only used for asynchronous code.

+ +

In simple cases, it is sufficient to have the closure accept input +parameters at creation time and return a single value (or struct/tuple, etc.).

+

For more complex situations in which it is desirable to stream data to or from +the synchronous context, the mpsc channel has blocking_send and +blocking_recv methods for use in non-async code such as the thread created +by spawn_blocking.

+

Another option is SyncIoBridge for cases where the synchronous context +is operating on byte streams. For example, you might use an asynchronous +HTTP client such as hyper to fetch data, but perform complex parsing +of the payload body using a library written for synchronous I/O.

+

Finally, see also Bridging with sync code for discussions +around the opposite case of using Tokio as part of a larger synchronous +codebase.

+

ยงExamples

+

Pass an input value and receive result of computation:

+ +
use tokio::task;
+
+// Initial input
+let mut v = "Hello, ".to_string();
+let res = task::spawn_blocking(move || {
+    // Stand-in for compute-heavy work or using synchronous APIs
+    v.push_str("world");
+    // Pass ownership of the value back to the asynchronous context
+    v
+}).await?;
+
+// `res` is the value returned from the thread
+assert_eq!(res.as_str(), "Hello, world");
+

Use a channel:

+ +
use tokio::task;
+use tokio::sync::mpsc;
+
+let (tx, mut rx) = mpsc::channel(2);
+let start = 5;
+let worker = task::spawn_blocking(move || {
+    for x in 0..10 {
+        // Stand in for complex computation
+        tx.blocking_send(start + x).unwrap();
+    }
+});
+
+let mut acc = 0;
+while let Some(v) = rx.recv().await {
+    acc += v;
+}
+assert_eq!(acc, 95);
+worker.await.unwrap();
+
\ No newline at end of file diff --git a/actix_rt/task/fn.yield_now.html b/actix_rt/task/fn.yield_now.html new file mode 100644 index 00000000..71589fc6 --- /dev/null +++ b/actix_rt/task/fn.yield_now.html @@ -0,0 +1,24 @@ +yield_now in actix_rt::task - Rust
actix_rt::task

Function yield_now

pub async fn yield_now()
Expand description

Yields execution back to the Tokio runtime.

+

A task yields by awaiting on yield_now(), and may resume when that future +completes (with no output.) The current task will be re-added as a pending +task at the back of the pending queue. Any other pending tasks will be +scheduled. No other waking is required for the task to continue.

+

See also the usage example in the task module.

+

ยงNon-guarantees

+

This function may not yield all the way up to the executor if there are any +special combinators above it in the call stack. For example, if a +tokio::select! has another branch complete during the same poll as the +yield_now(), then the yield is not propagated all the way up to the +runtime.

+

It is generally not guaranteed that the runtime behaves like you expect it +to when deciding which task to schedule next after a call to yield_now(). +In particular, the runtime may choose to poll the task that just ran +yield_now() again immediately without polling any other tasks first. For +example, the runtime will not drive the IO driver between every poll of a +task, and this could result in the runtime polling the current task again +immediately even if there is another task that could make progress if that +other task is waiting for a notification from the IO driver.

+

In general, changes to the order in which the runtime polls tasks is not +considered a breaking change, and your program should be correct no matter +which order the runtime polls your tasks in.

+
\ No newline at end of file diff --git a/actix_rt/task/index.html b/actix_rt/task/index.html new file mode 100644 index 00000000..8f0b7323 --- /dev/null +++ b/actix_rt/task/index.html @@ -0,0 +1,2 @@ +actix_rt::task - Rust
actix_rt

Module task

source
Expand description

Task management (Tokio re-exports).

+

Structsยง

  • Task failed to execute to completion.
  • An owned permission to join on a task (await its termination).

Functionsยง

  • Runs the provided closure on a thread where blocking is acceptable.
  • Yields execution back to the Tokio runtime.
\ No newline at end of file diff --git a/actix_rt/task/sidebar-items.js b/actix_rt/task/sidebar-items.js new file mode 100644 index 00000000..e5d1fa75 --- /dev/null +++ b/actix_rt/task/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["spawn_blocking","yield_now"],"struct":["JoinError","JoinHandle"]}; \ No newline at end of file diff --git a/actix_rt/task/struct.JoinError.html b/actix_rt/task/struct.JoinError.html new file mode 100644 index 00000000..2db73c60 --- /dev/null +++ b/actix_rt/task/struct.JoinError.html @@ -0,0 +1,63 @@ +JoinError in actix_rt::task - Rust
actix_rt::task

Struct JoinError

pub struct JoinError { /* private fields */ }
Expand description

Task failed to execute to completion.

+

Implementationsยง

ยง

impl JoinError

pub fn is_cancelled(&self) -> bool

Returns true if the error was caused by the task being cancelled.

+

See the module level docs for more information on cancellation.

+

pub fn is_panic(&self) -> bool

Returns true if the error was caused by the task panicking.

+
ยงExamples
+
use std::panic;
+
+#[tokio::main]
+async fn main() {
+    let err = tokio::spawn(async {
+        panic!("boom");
+    }).await.unwrap_err();
+
+    assert!(err.is_panic());
+}
+

pub fn into_panic(self) -> Box<dyn Any + Send>

Consumes the join error, returning the object with which the task panicked.

+
ยงPanics
+

into_panic() panics if the Error does not represent the underlying +task terminating with a panic. Use is_panic to check the error reason +or try_into_panic for a variant that does not panic.

+
ยงExamples
+
โ“˜
use std::panic;
+
+#[tokio::main]
+async fn main() {
+    let err = tokio::spawn(async {
+        panic!("boom");
+    }).await.unwrap_err();
+
+    if err.is_panic() {
+        // Resume the panic on the main task
+        panic::resume_unwind(err.into_panic());
+    }
+}
+

pub fn try_into_panic(self) -> Result<Box<dyn Any + Send>, JoinError>

Consumes the join error, returning the object with which the task +panicked if the task terminated due to a panic. Otherwise, self is +returned.

+
ยงExamples
+
โ“˜
use std::panic;
+
+#[tokio::main]
+async fn main() {
+    let err = tokio::spawn(async {
+        panic!("boom");
+    }).await.unwrap_err();
+
+    if let Ok(reason) = err.try_into_panic() {
+        // Resume the panic on the main task
+        panic::resume_unwind(reason);
+    }
+}
+

Trait Implementationsยง

ยง

impl Debug for JoinError

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl Display for JoinError

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl Error for JoinError

1.81.0 ยท sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/task/struct.JoinHandle.html b/actix_rt/task/struct.JoinHandle.html new file mode 100644 index 00000000..21c838a7 --- /dev/null +++ b/actix_rt/task/struct.JoinHandle.html @@ -0,0 +1,291 @@ +JoinHandle in actix_rt::task - Rust
actix_rt::task

Struct JoinHandle

pub struct JoinHandle<T> { /* private fields */ }
Expand description

An owned permission to join on a task (await its termination).

+

This can be thought of as the equivalent of std::thread::JoinHandle +for a Tokio task rather than a thread. Note that the background task +associated with this JoinHandle started running immediately when you +called spawn, even if you have not yet awaited the JoinHandle.

+

A JoinHandle detaches the associated task when it is dropped, which +means that there is no longer any handle to the task, and no way to join +on it.

+

This struct is created by the task::spawn and task::spawn_blocking +functions.

+

ยงCancel safety

+

The &mut JoinHandle<T> type is cancel safe. If it is used as the event +in a tokio::select! statement and some other branch completes first, +then it is guaranteed that the output of the task is not lost.

+

If a JoinHandle is dropped, then the task continues running in the +background and its return value is lost.

+

ยงExamples

+

Creation from task::spawn:

+ +
use tokio::task;
+
+let join_handle: task::JoinHandle<_> = task::spawn(async {
+    // some work here
+});
+

Creation from task::spawn_blocking:

+ +
use tokio::task;
+
+let join_handle: task::JoinHandle<_> = task::spawn_blocking(|| {
+    // some blocking work here
+});
+

The generic parameter T in JoinHandle<T> is the return type of the spawned task. +If the return value is an i32, the join handle has type JoinHandle<i32>:

+ +
use tokio::task;
+
+let join_handle: task::JoinHandle<i32> = task::spawn(async {
+    5 + 3
+});
+
+

If the task does not have a return value, the join handle has type JoinHandle<()>:

+ +
use tokio::task;
+
+let join_handle: task::JoinHandle<()> = task::spawn(async {
+    println!("I return nothing.");
+});
+

Note that handle.await doesnโ€™t give you the return type directly. It is wrapped in a +Result because panics in the spawned task are caught by Tokio. The ? operator has +to be double chained to extract the returned value:

+ +
use tokio::task;
+use std::io;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let join_handle: task::JoinHandle<Result<i32, io::Error>> = tokio::spawn(async {
+        Ok(5 + 3)
+    });
+
+    let result = join_handle.await??;
+    assert_eq!(result, 8);
+    Ok(())
+}
+

If the task panics, the error is a JoinError that contains the panic:

+ +
use tokio::task;
+use std::io;
+use std::panic;
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let join_handle: task::JoinHandle<Result<i32, io::Error>> = tokio::spawn(async {
+        panic!("boom");
+    });
+
+    let err = join_handle.await.unwrap_err();
+    assert!(err.is_panic());
+    Ok(())
+}
+
+

Child being detached and outliving its parent:

+ +
use tokio::task;
+use tokio::time;
+use std::time::Duration;
+
+let original_task = task::spawn(async {
+    let _detached_task = task::spawn(async {
+        // Here we sleep to make sure that the first task returns before.
+        time::sleep(Duration::from_millis(10)).await;
+        // This will be called, even though the JoinHandle is dropped.
+        println!("โ™ซ Still alive โ™ซ");
+    });
+});
+
+original_task.await.expect("The task being joined has panicked");
+println!("Original task is joined.");
+
+// We make sure that the new task has time to run, before the main
+// task returns.
+
+time::sleep(Duration::from_millis(1000)).await;
+

Implementationsยง

ยง

impl<T> JoinHandle<T>

pub fn abort(&self)

Abort the task associated with the handle.

+

Awaiting a cancelled task might complete as usual if the task was +already completed at the time it was cancelled, but most likely it +will fail with a cancelled JoinError.

+

Be aware that tasks spawned using spawn_blocking cannot be aborted +because they are not async. If you call abort on a spawn_blocking +task, then this will not have any effect, and the task will continue +running normally. The exception is if the task has not started running +yet; in that case, calling abort may prevent the task from starting.

+

See also the module level docs for more information on cancellation.

+ +
use tokio::time;
+
+let mut handles = Vec::new();
+
+handles.push(tokio::spawn(async {
+   time::sleep(time::Duration::from_secs(10)).await;
+   true
+}));
+
+handles.push(tokio::spawn(async {
+   time::sleep(time::Duration::from_secs(10)).await;
+   false
+}));
+
+for handle in &handles {
+    handle.abort();
+}
+
+for handle in handles {
+    assert!(handle.await.unwrap_err().is_cancelled());
+}
+

pub fn is_finished(&self) -> bool

Checks if the task associated with this JoinHandle has finished.

+

Please note that this method can return false even if abort has been +called on the task. This is because the cancellation process may take +some time, and this method does not return true until it has +completed.

+ +
use tokio::time;
+
+let handle1 = tokio::spawn(async {
+    // do some stuff here
+});
+let handle2 = tokio::spawn(async {
+    // do some other stuff here
+    time::sleep(time::Duration::from_secs(10)).await;
+});
+// Wait for the task to finish
+handle2.abort();
+time::sleep(time::Duration::from_secs(1)).await;
+assert!(handle1.is_finished());
+assert!(handle2.is_finished());
+

pub fn abort_handle(&self) -> AbortHandle

Returns a new AbortHandle that can be used to remotely abort this task.

+

Awaiting a task cancelled by the AbortHandle might complete as usual if the task was +already completed at the time it was cancelled, but most likely it +will fail with a cancelled JoinError.

+ +
use tokio::{time, task};
+
+let mut handles = Vec::new();
+
+handles.push(tokio::spawn(async {
+   time::sleep(time::Duration::from_secs(10)).await;
+   true
+}));
+
+handles.push(tokio::spawn(async {
+   time::sleep(time::Duration::from_secs(10)).await;
+   false
+}));
+
+let abort_handles: Vec<task::AbortHandle> = handles.iter().map(|h| h.abort_handle()).collect();
+
+for handle in abort_handles {
+    handle.abort();
+}
+
+for handle in handles {
+    assert!(handle.await.unwrap_err().is_cancelled());
+}
+

Trait Implementationsยง

ยง

impl<T> Debug for JoinHandle<T>
where + T: Debug,

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl<T> Drop for JoinHandle<T>

ยง

fn drop(&mut self)

Executes the destructor for this type. Read more
ยง

impl<T> Future for JoinHandle<T>

ยง

type Output = Result<T, JoinError>

The type of value produced on completion.
ยง

fn poll( + self: Pin<&mut JoinHandle<T>>, + cx: &mut Context<'_>, +) -> Poll<<JoinHandle<T> as Future>::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
ยง

impl<T> RefUnwindSafe for JoinHandle<T>

ยง

impl<T> Send for JoinHandle<T>
where + T: Send,

ยง

impl<T> Sync for JoinHandle<T>
where + T: Send,

ยง

impl<T> Unpin for JoinHandle<T>

ยง

impl<T> UnwindSafe for JoinHandle<T>

Auto Trait Implementationsยง

ยง

impl<T> Freeze for JoinHandle<T>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> FutureExt for T
where + T: Future + ?Sized,

ยง

fn map<U, F>(self, f: F) -> Map<Self, F>
where + F: FnOnce(Self::Output) -> U, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn map_into<U>(self) -> MapInto<Self, U>
where + Self::Output: Into<U>, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where + F: FnOnce(Self::Output) -> Fut, + Fut: Future, + Self: Sized,

Chain on a computation for when a future finished, passing the result of +the future to the provided closure f. Read more
ยง

fn left_future<B>(self) -> Either<Self, B>
where + B: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the left-hand variant +of that Either. Read more
ยง

fn right_future<A>(self) -> Either<A, Self>
where + A: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the right-hand variant +of that Either. Read more
ยง

fn into_stream(self) -> IntoStream<Self>
where + Self: Sized,

Convert this future into a single element stream. Read more
ยง

fn flatten(self) -> Flatten<Self>
where + Self::Output: Future, + Self: Sized,

Flatten the execution of this future when the output of this +future is itself another future. Read more
ยง

fn flatten_stream(self) -> FlattenStream<Self>
where + Self::Output: Stream, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn fuse(self) -> Fuse<Self>
where + Self: Sized,

Fuse a future such that poll will never again be called once it has +completed. This method can be used to turn any Future into a +FusedFuture. Read more
ยง

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where + F: FnOnce(&Self::Output), + Self: Sized,

Do something with the output of a future before passing it on. Read more
ยง

fn catch_unwind(self) -> CatchUnwind<Self>
where + Self: Sized + UnwindSafe,

Catches unwinding panics while polling the future. Read more
ยง

fn shared(self) -> Shared<Self>
where + Self: Sized, + Self::Output: Clone,

Create a cloneable handle to this future where all handles will resolve +to the same result. Read more
ยง

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where + Self: Sized + Send + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where + Self: Sized + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn unit_error(self) -> UnitError<Self>
where + Self: Sized,

ยง

fn never_error(self) -> NeverError<Self>
where + Self: Sized,

ยง

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where + Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
ยง

fn now_or_never(self) -> Option<Self::Output>
where + Self: Sized,

Evaluates and consumes the future, returning the resulting output if +the future is ready after the first call to Future::poll. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
ยง

impl<F, T, E> TryFuture for F
where + F: Future<Output = Result<T, E>> + ?Sized,

ยง

type Ok = T

The type of successful values yielded by this future
ยง

type Error = E

The type of failures yielded by this future
ยง

fn try_poll( + self: Pin<&mut F>, + cx: &mut Context<'_>, +) -> Poll<<F as Future>::Output>

Poll this TryFuture as if it were a Future. Read more
ยง

impl<Fut> TryFutureExt for Fut
where + Fut: TryFuture + ?Sized,

ยง

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where + F: FnOnce(Self::Ok) -> T, + Self: Sized,

Maps this futureโ€™s success value to a different value. Read more
ยง

fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E>
where + F: FnOnce(Self::Ok) -> T, + E: FnOnce(Self::Error) -> T, + Self: Sized,

Maps this futureโ€™s success value to a different value, and permits for error handling resulting in the same type. Read more
ยง

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where + F: FnOnce(Self::Error) -> E, + Self: Sized,

Maps this futureโ€™s error value to a different value. Read more
ยง

fn err_into<E>(self) -> ErrInto<Self, E>
where + Self: Sized, + Self::Error: Into<E>,

Maps this futureโ€™s Error to a new error type +using the Into trait. Read more
ยง

fn ok_into<U>(self) -> OkInto<Self, U>
where + Self: Sized, + Self::Ok: Into<U>,

Maps this futureโ€™s Ok to a new type +using the Into trait.
ยง

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where + F: FnOnce(Self::Ok) -> Fut, + Fut: TryFuture<Error = Self::Error>, + Self: Sized,

Executes another future after this one resolves successfully. The +success value is passed to a closure to create this subsequent future. Read more
ยง

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where + F: FnOnce(Self::Error) -> Fut, + Fut: TryFuture<Ok = Self::Ok>, + Self: Sized,

Executes another future if this one resolves to an error. The +error value is passed to a closure to create this subsequent future. Read more
ยง

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where + F: FnOnce(&Self::Ok), + Self: Sized,

Do something with the success value of a future before passing it on. Read more
ยง

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where + F: FnOnce(&Self::Error), + Self: Sized,

Do something with the error value of a future before passing it on. Read more
ยง

fn try_flatten(self) -> TryFlatten<Self, Self::Ok>
where + Self::Ok: TryFuture<Error = Self::Error>, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is another future. Read more
ยง

fn try_flatten_stream(self) -> TryFlattenStream<Self>
where + Self::Ok: TryStream<Error = Self::Error>, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F>
where + Self: Sized, + F: FnOnce(Self::Error) -> Self::Ok,

Unwraps this futureโ€™s output, producing a future with this futureโ€™s +Ok type as its +Output type. Read more
ยง

fn into_future(self) -> IntoFuture<Self>
where + Self: Sized,

Wraps a [TryFuture] into a type that implements +Future. Read more
ยง

fn try_poll_unpin( + &mut self, + cx: &mut Context<'_>, +) -> Poll<Result<Self::Ok, Self::Error>>
where + Self: Unpin,

A convenience method for calling [TryFuture::try_poll] on Unpin +future types.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/time/fn.interval.html b/actix_rt/time/fn.interval.html new file mode 100644 index 00000000..b54dd1d2 --- /dev/null +++ b/actix_rt/time/fn.interval.html @@ -0,0 +1,48 @@ +interval in actix_rt::time - Rust
actix_rt::time

Function interval

pub fn interval(period: Duration) -> Interval
Expand description

Creates new Interval that yields with interval of period. The first +tick completes immediately. The default [MissedTickBehavior] is +Burst, but this can be configured +by calling set_missed_tick_behavior.

+

An interval will tick indefinitely. At any time, the Interval value can +be dropped. This cancels the interval.

+

This function is equivalent to +interval_at(Instant::now(), period).

+

ยงPanics

+

This function panics if period is zero.

+

ยงExamples

+
use tokio::time::{self, Duration};
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(Duration::from_millis(10));
+
+    interval.tick().await; // ticks immediately
+    interval.tick().await; // ticks after 10ms
+    interval.tick().await; // ticks after 10ms
+
+    // approximately 20ms have elapsed.
+}
+

A simple example using interval to execute a task every two seconds.

+

The difference between interval and sleep is that an Interval +measures the time since the last tick, which means that .tick().await +may wait for a shorter time than the duration specified for the interval +if some time has passed between calls to .tick().await.

+

If the tick in the example below was replaced with sleep, the task +would only be executed once every three seconds, and not every two +seconds.

+ +
use tokio::time;
+
+async fn task_that_takes_a_second() {
+    println!("hello");
+    time::sleep(time::Duration::from_secs(1)).await
+}
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(time::Duration::from_secs(2));
+    for _i in 0..5 {
+        interval.tick().await;
+        task_that_takes_a_second().await;
+    }
+}
+
\ No newline at end of file diff --git a/actix_rt/time/fn.interval_at.html b/actix_rt/time/fn.interval_at.html new file mode 100644 index 00000000..77c6355f --- /dev/null +++ b/actix_rt/time/fn.interval_at.html @@ -0,0 +1,23 @@ +interval_at in actix_rt::time - Rust
actix_rt::time

Function interval_at

pub fn interval_at(start: Instant, period: Duration) -> Interval
Expand description

Creates new Interval that yields with interval of period with the +first tick completing at start. The default [MissedTickBehavior] is +Burst, but this can be configured +by calling set_missed_tick_behavior.

+

An interval will tick indefinitely. At any time, the Interval value can +be dropped. This cancels the interval.

+

ยงPanics

+

This function panics if period is zero.

+

ยงExamples

+
use tokio::time::{interval_at, Duration, Instant};
+
+#[tokio::main]
+async fn main() {
+    let start = Instant::now() + Duration::from_millis(50);
+    let mut interval = interval_at(start, Duration::from_millis(10));
+
+    interval.tick().await; // ticks after 50ms
+    interval.tick().await; // ticks after 10ms
+    interval.tick().await; // ticks after 10ms
+
+    // approximately 70ms have elapsed.
+}
+
\ No newline at end of file diff --git a/actix_rt/time/fn.sleep.html b/actix_rt/time/fn.sleep.html new file mode 100644 index 00000000..dc591c20 --- /dev/null +++ b/actix_rt/time/fn.sleep.html @@ -0,0 +1,36 @@ +sleep in actix_rt::time - Rust
actix_rt::time

Function sleep

pub fn sleep(duration: Duration) -> Sleep โ“˜
Expand description

Waits until duration has elapsed.

+

Equivalent to sleep_until(Instant::now() + duration). An asynchronous +analog to std::thread::sleep.

+

No work is performed while awaiting on the sleep future to complete. Sleep +operates at millisecond granularity and should not be used for tasks that +require high-resolution timers. The implementation is platform specific, +and some platforms (specifically Windows) will provide timers with a +larger resolution than 1 ms.

+

To run something regularly on a schedule, see interval.

+

The maximum duration for a sleep is 68719476734 milliseconds (approximately 2.2 years).

+

ยงCancellation

+

Canceling a sleep instance is done by dropping the returned future. No additional +cleanup work is required.

+

ยงExamples

+

Wait 100ms and print โ€œ100 ms have elapsedโ€.

+ +
use tokio::time::{sleep, Duration};
+
+#[tokio::main]
+async fn main() {
+    sleep(Duration::from_millis(100)).await;
+    println!("100 ms have elapsed");
+}
+

See the documentation for the Sleep type for more examples.

+

ยงPanics

+

This function panics if there is no current timer set.

+

It can be triggered when Builder::enable_time or +Builder::enable_all are not included in the builder.

+

It can also panic whenever a timer is created outside of a +Tokio runtime. That is why rt.block_on(sleep(...)) will panic, +since the function is executed outside of the runtime. +Whereas rt.block_on(async {sleep(...).await}) doesnโ€™t panic. +And this is because wrapping the function on an async makes it lazy, +and so gets executed inside the runtime successfully without +panicking.

+
\ No newline at end of file diff --git a/actix_rt/time/fn.sleep_until.html b/actix_rt/time/fn.sleep_until.html new file mode 100644 index 00000000..0806594f --- /dev/null +++ b/actix_rt/time/fn.sleep_until.html @@ -0,0 +1,31 @@ +sleep_until in actix_rt::time - Rust
actix_rt::time

Function sleep_until

pub fn sleep_until(deadline: Instant) -> Sleep โ“˜
Expand description

Waits until deadline is reached.

+

No work is performed while awaiting on the sleep future to complete. Sleep +operates at millisecond granularity and should not be used for tasks that +require high-resolution timers.

+

To run something regularly on a schedule, see interval.

+

ยงCancellation

+

Canceling a sleep instance is done by dropping the returned future. No additional +cleanup work is required.

+

ยงExamples

+

Wait 100ms and print โ€œ100 ms have elapsedโ€.

+ +
use tokio::time::{sleep_until, Instant, Duration};
+
+#[tokio::main]
+async fn main() {
+    sleep_until(Instant::now() + Duration::from_millis(100)).await;
+    println!("100 ms have elapsed");
+}
+

See the documentation for the Sleep type for more examples.

+

ยงPanics

+

This function panics if there is no current timer set.

+

It can be triggered when Builder::enable_time or +Builder::enable_all are not included in the builder.

+

It can also panic whenever a timer is created outside of a +Tokio runtime. That is why rt.block_on(sleep(...)) will panic, +since the function is executed outside of the runtime. +Whereas rt.block_on(async {sleep(...).await}) doesnโ€™t panic. +And this is because wrapping the function on an async makes it lazy, +and so gets executed inside the runtime successfully without +panicking.

+
\ No newline at end of file diff --git a/actix_rt/time/fn.timeout.html b/actix_rt/time/fn.timeout.html new file mode 100644 index 00000000..525c042b --- /dev/null +++ b/actix_rt/time/fn.timeout.html @@ -0,0 +1,47 @@ +timeout in actix_rt::time - Rust
actix_rt::time

Function timeout

pub fn timeout<F>(
+    duration: Duration,
+    future: F,
+) -> Timeout<<F as IntoFuture>::IntoFuture> โ“˜
where + F: IntoFuture,
Expand description

Requires a Future to complete before the specified duration has elapsed.

+

If the future completes before the duration has elapsed, then the completed +value is returned. Otherwise, an error is returned and the future is +canceled.

+

Note that the timeout is checked before polling the future, so if the future +does not yield during execution then it is possible for the future to complete +and exceed the timeout without returning an error.

+

This function returns a future whose return type is Result<T,Elapsed>, where T is the +return type of the provided future.

+

If the provided future completes immediately, then the future returned from +this function is guaranteed to complete immediately with an Ok variant +no matter the provided duration.

+

ยงCancellation

+

Cancelling a timeout is done by dropping the future. No additional cleanup +or other work is required.

+

The original future may be obtained by calling Timeout::into_inner. This +consumes the Timeout.

+

ยงExamples

+

Create a new Timeout set to expire in 10 milliseconds.

+ +
use tokio::time::timeout;
+use tokio::sync::oneshot;
+
+use std::time::Duration;
+
+let (tx, rx) = oneshot::channel();
+
+// Wrap the future with a `Timeout` set to expire in 10 milliseconds.
+if let Err(_) = timeout(Duration::from_millis(10), rx).await {
+    println!("did not receive value within 10 ms");
+}
+

ยงPanics

+

This function panics if there is no current timer set.

+

It can be triggered when Builder::enable_time or +Builder::enable_all are not included in the builder.

+

It can also panic whenever a timer is created outside of a +Tokio runtime. That is why rt.block_on(sleep(...)) will panic, +since the function is executed outside of the runtime. +Whereas rt.block_on(async {sleep(...).await}) doesnโ€™t panic. +And this is because wrapping the function on an async makes it lazy, +and so gets executed inside the runtime successfully without +panicking.

+
\ No newline at end of file diff --git a/actix_rt/time/index.html b/actix_rt/time/index.html new file mode 100644 index 00000000..6aebd288 --- /dev/null +++ b/actix_rt/time/index.html @@ -0,0 +1,9 @@ +actix_rt::time - Rust
actix_rt

Module time

source
Expand description

Utilities for tracking time (Tokio re-exports).

+

Structsยง

Functionsยง

  • Creates new Interval that yields with interval of period. The first +tick completes immediately. The default [MissedTickBehavior] is +Burst, but this can be configured +by calling set_missed_tick_behavior.
  • Creates new Interval that yields with interval of period with the +first tick completing at start. The default [MissedTickBehavior] is +Burst, but this can be configured +by calling set_missed_tick_behavior.
  • Waits until duration has elapsed.
  • Waits until deadline is reached.
  • Requires a Future to complete before the specified duration has elapsed.
\ No newline at end of file diff --git a/actix_rt/time/sidebar-items.js b/actix_rt/time/sidebar-items.js new file mode 100644 index 00000000..414553ba --- /dev/null +++ b/actix_rt/time/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["interval","interval_at","sleep","sleep_until","timeout"],"struct":["Instant","Interval","Sleep","Timeout"]}; \ No newline at end of file diff --git a/actix_rt/time/struct.Instant.html b/actix_rt/time/struct.Instant.html new file mode 100644 index 00000000..415c48b5 --- /dev/null +++ b/actix_rt/time/struct.Instant.html @@ -0,0 +1,96 @@ +Instant in actix_rt::time - Rust
actix_rt::time

Struct Instant

pub struct Instant { /* private fields */ }
Expand description

A measurement of a monotonically nondecreasing clock. +Opaque and useful only with Duration.

+

Instants are always guaranteed to be no less than any previously measured +instant when created, and are often useful for tasks such as measuring +benchmarks or timing how long an operation takes.

+

Note, however, that instants are not guaranteed to be steady. In other +words, each tick of the underlying clock may not be the same length (e.g. +some seconds may be longer than others). An instant may jump forwards or +experience time dilation (slow down or speed up), but it will never go +backwards.

+

Instants are opaque types that can only be compared to one another. There is +no method to get โ€œthe number of secondsโ€ from an instant. Instead, it only +allows measuring the duration between two instants (or comparing two +instants).

+

The size of an Instant struct may vary depending on the target operating +system.

+

ยงNote

+

This type wraps the inner std variant and is used to align the Tokio +clock for uses of now(). This can be useful for testing where you can +take advantage of time::pause() and time::advance().

+

Implementationsยง

ยง

impl Instant

pub fn now() -> Instant

Returns an instant corresponding to โ€œnowโ€.

+
ยงExamples
+
use tokio::time::Instant;
+
+let now = Instant::now();
+

pub fn from_std(std: Instant) -> Instant

Create a tokio::time::Instant from a std::time::Instant.

+

pub fn into_std(self) -> Instant

Convert the value into a std::time::Instant.

+

pub fn duration_since(&self, earlier: Instant) -> Duration

Returns the amount of time elapsed from another instant to this one, or +zero duration if that instant is later than this one.

+

pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration>

Returns the amount of time elapsed from another instant to this one, or +None if that instant is later than this one.

+
ยงExamples
+
use tokio::time::{Duration, Instant, sleep};
+
+#[tokio::main]
+async fn main() {
+    let now = Instant::now();
+    sleep(Duration::new(1, 0)).await;
+    let new_now = Instant::now();
+    println!("{:?}", new_now.checked_duration_since(now));
+    println!("{:?}", now.checked_duration_since(new_now)); // None
+}
+

pub fn saturating_duration_since(&self, earlier: Instant) -> Duration

Returns the amount of time elapsed from another instant to this one, or +zero duration if that instant is later than this one.

+
ยงExamples
+
use tokio::time::{Duration, Instant, sleep};
+
+#[tokio::main]
+async fn main() {
+    let now = Instant::now();
+    sleep(Duration::new(1, 0)).await;
+    let new_now = Instant::now();
+    println!("{:?}", new_now.saturating_duration_since(now));
+    println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
+}
+

pub fn elapsed(&self) -> Duration

Returns the amount of time elapsed since this instant was created, +or zero duration if that this instant is in the future.

+
ยงExamples
+
use tokio::time::{Duration, Instant, sleep};
+
+#[tokio::main]
+async fn main() {
+    let instant = Instant::now();
+    let three_secs = Duration::from_secs(3);
+    sleep(three_secs).await;
+    assert!(instant.elapsed() >= three_secs);
+}
+

pub fn checked_add(&self, duration: Duration) -> Option<Instant>

Returns Some(t) where t is the time self + duration if t can be +represented as Instant (which means itโ€™s inside the bounds of the +underlying data structure), None otherwise.

+

pub fn checked_sub(&self, duration: Duration) -> Option<Instant>

Returns Some(t) where t is the time self - duration if t can be +represented as Instant (which means itโ€™s inside the bounds of the +underlying data structure), None otherwise.

+

Trait Implementationsยง

ยง

impl Add<Duration> for Instant

ยง

type Output = Instant

The resulting type after applying the + operator.
ยง

fn add(self, other: Duration) -> Instant

Performs the + operation. Read more
ยง

impl AddAssign<Duration> for Instant

ยง

fn add_assign(&mut self, rhs: Duration)

Performs the += operation. Read more
ยง

impl Clone for Instant

ยง

fn clone(&self) -> Instant

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for Instant

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl From<Instant> for Instant

ยง

fn from(time: Instant) -> Instant

Converts to this type from the input type.
ยง

impl Hash for Instant

ยง

fn hash<__H>(&self, state: &mut __H)
where + __H: Hasher,

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
ยง

impl Ord for Instant

ยง

fn cmp(&self, other: &Instant) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where + Self: Sized,

Restrict a value to a certain interval. Read more
ยง

impl PartialEq for Instant

ยง

fn eq(&self, other: &Instant) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
ยง

impl PartialOrd for Instant

ยง

fn partial_cmp(&self, other: &Instant) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.6.0 ยท sourceยง

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.6.0 ยท sourceยง

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the +<= operator. Read more
1.6.0 ยท sourceยง

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > +operator. Read more
1.6.0 ยท sourceยง

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by +the >= operator. Read more
ยง

impl Sub<Duration> for Instant

ยง

type Output = Instant

The resulting type after applying the - operator.
ยง

fn sub(self, rhs: Duration) -> Instant

Performs the - operation. Read more
ยง

impl Sub for Instant

ยง

type Output = Duration

The resulting type after applying the - operator.
ยง

fn sub(self, rhs: Instant) -> Duration

Performs the - operation. Read more
ยง

impl SubAssign<Duration> for Instant

ยง

fn sub_assign(&mut self, rhs: Duration)

Performs the -= operation. Read more
ยง

impl Copy for Instant

ยง

impl Eq for Instant

ยง

impl StructuralPartialEq for Instant

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/time/struct.Interval.html b/actix_rt/time/struct.Interval.html new file mode 100644 index 00000000..16e27f24 --- /dev/null +++ b/actix_rt/time/struct.Interval.html @@ -0,0 +1,144 @@ +Interval in actix_rt::time - Rust
actix_rt::time

Struct Interval

pub struct Interval { /* private fields */ }
Expand description

Interval returned by interval and interval_at.

+

This type allows you to wait on a sequence of instants with a certain +duration between each instant. Unlike calling sleep in a loop, this lets +you count the time spent between the calls to sleep as well.

+

An Interval can be turned into a Stream with IntervalStream.

+

Implementationsยง

ยง

impl Interval

pub async fn tick(&mut self) -> Instant

Completes when the next instant in the interval has been reached.

+
ยงCancel safety
+

This method is cancellation safe. If tick is used as the branch in a tokio::select! and +another branch completes first, then no tick has been consumed.

+
ยงExamples
+
use tokio::time;
+
+use std::time::Duration;
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(Duration::from_millis(10));
+
+    interval.tick().await;
+    // approximately 0ms have elapsed. The first tick completes immediately.
+    interval.tick().await;
+    interval.tick().await;
+
+    // approximately 20ms have elapsed.
+}
+

pub fn poll_tick(&mut self, cx: &mut Context<'_>) -> Poll<Instant>

Polls for the next instant in the interval to be reached.

+

This method can return the following values:

+
    +
  • Poll::Pending if the next instant has not yet been reached.
  • +
  • Poll::Ready(instant) if the next instant has been reached.
  • +
+

When this method returns Poll::Pending, the current task is scheduled +to receive a wakeup when the instant has elapsed. Note that on multiple +calls to poll_tick, only the Waker from the +Context passed to the most recent call is scheduled to receive a +wakeup.

+

pub fn reset(&mut self)

Resets the interval to complete one period after the current time.

+

This method ignores [MissedTickBehavior] strategy.

+

This is equivalent to calling reset_at(Instant::now() + period).

+
ยงExamples
+
use tokio::time;
+
+use std::time::Duration;
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(Duration::from_millis(100));
+
+    interval.tick().await;
+
+    time::sleep(Duration::from_millis(50)).await;
+    interval.reset();
+
+    interval.tick().await;
+    interval.tick().await;
+
+    // approximately 250ms have elapsed.
+}
+

pub fn reset_immediately(&mut self)

Resets the interval immediately.

+

This method ignores [MissedTickBehavior] strategy.

+

This is equivalent to calling reset_at(Instant::now()).

+
ยงExamples
+
use tokio::time;
+
+use std::time::Duration;
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(Duration::from_millis(100));
+
+    interval.tick().await;
+
+    time::sleep(Duration::from_millis(50)).await;
+    interval.reset_immediately();
+
+    interval.tick().await;
+    interval.tick().await;
+
+    // approximately 150ms have elapsed.
+}
+

pub fn reset_after(&mut self, after: Duration)

Resets the interval after the specified std::time::Duration.

+

This method ignores [MissedTickBehavior] strategy.

+

This is equivalent to calling reset_at(Instant::now() + after).

+
ยงExamples
+
use tokio::time;
+
+use std::time::Duration;
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(Duration::from_millis(100));
+    interval.tick().await;
+
+    time::sleep(Duration::from_millis(50)).await;
+
+    let after = Duration::from_millis(20);
+    interval.reset_after(after);
+
+    interval.tick().await;
+    interval.tick().await;
+
+    // approximately 170ms have elapsed.
+}
+

pub fn reset_at(&mut self, deadline: Instant)

Resets the interval to a crate::time::Instant deadline.

+

Sets the next tick to expire at the given instant. If the instant is in +the past, then the [MissedTickBehavior] strategy will be used to +catch up. If the instant is in the future, then the next tick will +complete at the given instant, even if that means that it will sleep for +longer than the duration of this Interval. If the Interval had +any missed ticks before calling this method, then those are discarded.

+
ยงExamples
+
use tokio::time::{self, Instant};
+
+use std::time::Duration;
+
+#[tokio::main]
+async fn main() {
+    let mut interval = time::interval(Duration::from_millis(100));
+    interval.tick().await;
+
+    time::sleep(Duration::from_millis(50)).await;
+
+    let deadline = Instant::now() + Duration::from_millis(30);
+    interval.reset_at(deadline);
+
+    interval.tick().await;
+    interval.tick().await;
+
+    // approximately 180ms have elapsed.
+}
+

pub fn missed_tick_behavior(&self) -> MissedTickBehavior

Returns the [MissedTickBehavior] strategy currently being used.

+

pub fn set_missed_tick_behavior(&mut self, behavior: MissedTickBehavior)

Sets the [MissedTickBehavior] strategy that should be used.

+

pub fn period(&self) -> Duration

Returns the period of the interval.

+

Trait Implementationsยง

ยง

impl Debug for Interval

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/time/struct.Sleep.html b/actix_rt/time/struct.Sleep.html new file mode 100644 index 00000000..49a921c0 --- /dev/null +++ b/actix_rt/time/struct.Sleep.html @@ -0,0 +1,152 @@ +Sleep in actix_rt::time - Rust
actix_rt::time

Struct Sleep

pub struct Sleep { /* private fields */ }
Expand description

Future returned by sleep and sleep_until.

+

This type does not implement the Unpin trait, which means that if you +use it with select! or by calling poll, you have to pin it first. +If you use it with .await, this does not apply.

+

ยงExamples

+

Wait 100ms and print โ€œ100 ms have elapsedโ€.

+ +
use tokio::time::{sleep, Duration};
+
+#[tokio::main]
+async fn main() {
+    sleep(Duration::from_millis(100)).await;
+    println!("100 ms have elapsed");
+}
+

Use with select!. Pinning the Sleep with tokio::pin! is +necessary when the same Sleep is selected on multiple times.

+ +
use tokio::time::{self, Duration, Instant};
+
+#[tokio::main]
+async fn main() {
+    let sleep = time::sleep(Duration::from_millis(10));
+    tokio::pin!(sleep);
+
+    loop {
+        tokio::select! {
+            () = &mut sleep => {
+                println!("timer elapsed");
+                sleep.as_mut().reset(Instant::now() + Duration::from_millis(50));
+            },
+        }
+    }
+}
+

Use in a struct with boxing. By pinning the Sleep with a Box, the +HasSleep struct implements Unpin, even though Sleep does not.

+ +
use std::future::Future;
+use std::pin::Pin;
+use std::task::{Context, Poll};
+use tokio::time::Sleep;
+
+struct HasSleep {
+    sleep: Pin<Box<Sleep>>,
+}
+
+impl Future for HasSleep {
+    type Output = ();
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
+        self.sleep.as_mut().poll(cx)
+    }
+}
+

Use in a struct with pin projection. This method avoids the Box, but +the HasSleep struct will not be Unpin as a consequence.

+ +
use std::future::Future;
+use std::pin::Pin;
+use std::task::{Context, Poll};
+use tokio::time::Sleep;
+use pin_project_lite::pin_project;
+
+pin_project! {
+    struct HasSleep {
+        #[pin]
+        sleep: Sleep,
+    }
+}
+
+impl Future for HasSleep {
+    type Output = ();
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
+        self.project().sleep.poll(cx)
+    }
+}
+

Implementationsยง

ยง

impl Sleep

pub fn deadline(&self) -> Instant

Returns the instant at which the future will complete.

+

pub fn is_elapsed(&self) -> bool

Returns true if Sleep has elapsed.

+

A Sleep instance is elapsed when the requested duration has elapsed.

+

pub fn reset(self: Pin<&mut Sleep>, deadline: Instant)

Resets the Sleep instance to a new deadline.

+

Calling this function allows changing the instant at which the Sleep +future completes without having to create new associated state.

+

This function can be called both before and after the future has +completed.

+

To call this method, you will usually combine the call with +Pin::as_mut, which lets you call the method without consuming the +Sleep itself.

+
ยงExample
+
use tokio::time::{Duration, Instant};
+
+let sleep = tokio::time::sleep(Duration::from_millis(10));
+tokio::pin!(sleep);
+
+sleep.as_mut().reset(Instant::now() + Duration::from_millis(20));
+

See also the top-level examples.

+

Trait Implementationsยง

ยง

impl Debug for Sleep

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl Future for Sleep

ยง

type Output = ()

The type of value produced on completion.
ยง

fn poll( + self: Pin<&mut Sleep>, + cx: &mut Context<'_>, +) -> Poll<<Sleep as Future>::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> FutureExt for T
where + T: Future + ?Sized,

ยง

fn map<U, F>(self, f: F) -> Map<Self, F>
where + F: FnOnce(Self::Output) -> U, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn map_into<U>(self) -> MapInto<Self, U>
where + Self::Output: Into<U>, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where + F: FnOnce(Self::Output) -> Fut, + Fut: Future, + Self: Sized,

Chain on a computation for when a future finished, passing the result of +the future to the provided closure f. Read more
ยง

fn left_future<B>(self) -> Either<Self, B>
where + B: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the left-hand variant +of that Either. Read more
ยง

fn right_future<A>(self) -> Either<A, Self>
where + A: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the right-hand variant +of that Either. Read more
ยง

fn into_stream(self) -> IntoStream<Self>
where + Self: Sized,

Convert this future into a single element stream. Read more
ยง

fn flatten(self) -> Flatten<Self>
where + Self::Output: Future, + Self: Sized,

Flatten the execution of this future when the output of this +future is itself another future. Read more
ยง

fn flatten_stream(self) -> FlattenStream<Self>
where + Self::Output: Stream, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn fuse(self) -> Fuse<Self>
where + Self: Sized,

Fuse a future such that poll will never again be called once it has +completed. This method can be used to turn any Future into a +FusedFuture. Read more
ยง

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where + F: FnOnce(&Self::Output), + Self: Sized,

Do something with the output of a future before passing it on. Read more
ยง

fn catch_unwind(self) -> CatchUnwind<Self>
where + Self: Sized + UnwindSafe,

Catches unwinding panics while polling the future. Read more
ยง

fn shared(self) -> Shared<Self>
where + Self: Sized, + Self::Output: Clone,

Create a cloneable handle to this future where all handles will resolve +to the same result. Read more
ยง

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where + Self: Sized + Send + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where + Self: Sized + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn unit_error(self) -> UnitError<Self>
where + Self: Sized,

ยง

fn never_error(self) -> NeverError<Self>
where + Self: Sized,

ยง

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where + Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
ยง

fn now_or_never(self) -> Option<Self::Output>
where + Self: Sized,

Evaluates and consumes the future, returning the resulting output if +the future is ready after the first call to Future::poll. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_rt/time/struct.Timeout.html b/actix_rt/time/struct.Timeout.html new file mode 100644 index 00000000..79a7fe7f --- /dev/null +++ b/actix_rt/time/struct.Timeout.html @@ -0,0 +1,114 @@ +Timeout in actix_rt::time - Rust
actix_rt::time

Struct Timeout

pub struct Timeout<T> { /* private fields */ }
Expand description

Future returned by timeout and timeout_at.

+

Implementationsยง

ยง

impl<T> Timeout<T>

pub fn get_ref(&self) -> &T

Gets a reference to the underlying value in this timeout.

+

pub fn get_mut(&mut self) -> &mut T

Gets a mutable reference to the underlying value in this timeout.

+

pub fn into_inner(self) -> T

Consumes this timeout, returning the underlying value.

+

Trait Implementationsยง

ยง

impl<T> Debug for Timeout<T>
where + T: Debug,

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl<T> Future for Timeout<T>
where + T: Future,

ยง

type Output = Result<<T as Future>::Output, Elapsed>

The type of value produced on completion.
ยง

fn poll( + self: Pin<&mut Timeout<T>>, + cx: &mut Context<'_>, +) -> Poll<<Timeout<T> as Future>::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
ยง

impl<'__pin, T> Unpin for Timeout<T>
where + __Origin<'__pin, T>: Unpin,

Auto Trait Implementationsยง

ยง

impl<T> !Freeze for Timeout<T>

ยง

impl<T> !RefUnwindSafe for Timeout<T>

ยง

impl<T> Send for Timeout<T>
where + T: Send,

ยง

impl<T> Sync for Timeout<T>
where + T: Sync,

ยง

impl<T> !UnwindSafe for Timeout<T>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> FutureExt for T
where + T: Future + ?Sized,

ยง

fn map<U, F>(self, f: F) -> Map<Self, F>
where + F: FnOnce(Self::Output) -> U, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn map_into<U>(self) -> MapInto<Self, U>
where + Self::Output: Into<U>, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where + F: FnOnce(Self::Output) -> Fut, + Fut: Future, + Self: Sized,

Chain on a computation for when a future finished, passing the result of +the future to the provided closure f. Read more
ยง

fn left_future<B>(self) -> Either<Self, B>
where + B: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the left-hand variant +of that Either. Read more
ยง

fn right_future<A>(self) -> Either<A, Self>
where + A: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the right-hand variant +of that Either. Read more
ยง

fn into_stream(self) -> IntoStream<Self>
where + Self: Sized,

Convert this future into a single element stream. Read more
ยง

fn flatten(self) -> Flatten<Self>
where + Self::Output: Future, + Self: Sized,

Flatten the execution of this future when the output of this +future is itself another future. Read more
ยง

fn flatten_stream(self) -> FlattenStream<Self>
where + Self::Output: Stream, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn fuse(self) -> Fuse<Self>
where + Self: Sized,

Fuse a future such that poll will never again be called once it has +completed. This method can be used to turn any Future into a +FusedFuture. Read more
ยง

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where + F: FnOnce(&Self::Output), + Self: Sized,

Do something with the output of a future before passing it on. Read more
ยง

fn catch_unwind(self) -> CatchUnwind<Self>
where + Self: Sized + UnwindSafe,

Catches unwinding panics while polling the future. Read more
ยง

fn shared(self) -> Shared<Self>
where + Self: Sized, + Self::Output: Clone,

Create a cloneable handle to this future where all handles will resolve +to the same result. Read more
ยง

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where + Self: Sized + Send + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where + Self: Sized + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn unit_error(self) -> UnitError<Self>
where + Self: Sized,

ยง

fn never_error(self) -> NeverError<Self>
where + Self: Sized,

ยง

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where + Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
ยง

fn now_or_never(self) -> Option<Self::Output>
where + Self: Sized,

Evaluates and consumes the future, returning the resulting output if +the future is ready after the first call to Future::poll. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
ยง

impl<F, T, E> TryFuture for F
where + F: Future<Output = Result<T, E>> + ?Sized,

ยง

type Ok = T

The type of successful values yielded by this future
ยง

type Error = E

The type of failures yielded by this future
ยง

fn try_poll( + self: Pin<&mut F>, + cx: &mut Context<'_>, +) -> Poll<<F as Future>::Output>

Poll this TryFuture as if it were a Future. Read more
ยง

impl<Fut> TryFutureExt for Fut
where + Fut: TryFuture + ?Sized,

ยง

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where + F: FnOnce(Self::Ok) -> T, + Self: Sized,

Maps this futureโ€™s success value to a different value. Read more
ยง

fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E>
where + F: FnOnce(Self::Ok) -> T, + E: FnOnce(Self::Error) -> T, + Self: Sized,

Maps this futureโ€™s success value to a different value, and permits for error handling resulting in the same type. Read more
ยง

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where + F: FnOnce(Self::Error) -> E, + Self: Sized,

Maps this futureโ€™s error value to a different value. Read more
ยง

fn err_into<E>(self) -> ErrInto<Self, E>
where + Self: Sized, + Self::Error: Into<E>,

Maps this futureโ€™s Error to a new error type +using the Into trait. Read more
ยง

fn ok_into<U>(self) -> OkInto<Self, U>
where + Self: Sized, + Self::Ok: Into<U>,

Maps this futureโ€™s Ok to a new type +using the Into trait.
ยง

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where + F: FnOnce(Self::Ok) -> Fut, + Fut: TryFuture<Error = Self::Error>, + Self: Sized,

Executes another future after this one resolves successfully. The +success value is passed to a closure to create this subsequent future. Read more
ยง

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where + F: FnOnce(Self::Error) -> Fut, + Fut: TryFuture<Ok = Self::Ok>, + Self: Sized,

Executes another future if this one resolves to an error. The +error value is passed to a closure to create this subsequent future. Read more
ยง

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where + F: FnOnce(&Self::Ok), + Self: Sized,

Do something with the success value of a future before passing it on. Read more
ยง

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where + F: FnOnce(&Self::Error), + Self: Sized,

Do something with the error value of a future before passing it on. Read more
ยง

fn try_flatten(self) -> TryFlatten<Self, Self::Ok>
where + Self::Ok: TryFuture<Error = Self::Error>, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is another future. Read more
ยง

fn try_flatten_stream(self) -> TryFlattenStream<Self>
where + Self::Ok: TryStream<Error = Self::Error>, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F>
where + Self: Sized, + F: FnOnce(Self::Error) -> Self::Ok,

Unwraps this futureโ€™s output, producing a future with this futureโ€™s +Ok type as its +Output type. Read more
ยง

fn into_future(self) -> IntoFuture<Self>
where + Self: Sized,

Wraps a [TryFuture] into a type that implements +Future. Read more
ยง

fn try_poll_unpin( + &mut self, + cx: &mut Context<'_>, +) -> Poll<Result<Self::Ok, Self::Error>>
where + Self: Unpin,

A convenience method for calling [TryFuture::try_poll] on Unpin +future types.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_server/all.html b/actix_server/all.html new file mode 100644 index 00000000..898ca72e --- /dev/null +++ b/actix_server/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/actix_server/builder/enum.MpTcp.html b/actix_server/builder/enum.MpTcp.html new file mode 100644 index 00000000..517d5f33 --- /dev/null +++ b/actix_server/builder/enum.MpTcp.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_server/enum.MpTcp.html...

+ + + \ No newline at end of file diff --git a/actix_server/builder/struct.ServerBuilder.html b/actix_server/builder/struct.ServerBuilder.html new file mode 100644 index 00000000..177f40ba --- /dev/null +++ b/actix_server/builder/struct.ServerBuilder.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_server/struct.ServerBuilder.html...

+ + + \ No newline at end of file diff --git a/actix_server/enum.MpTcp.html b/actix_server/enum.MpTcp.html new file mode 100644 index 00000000..cdc28d71 --- /dev/null +++ b/actix_server/enum.MpTcp.html @@ -0,0 +1,29 @@ +MpTcp in actix_server - Rust
actix_server

Enum MpTcp

source
pub enum MpTcp {
+    Disabled,
+    TcpFallback,
+    NoFallback,
+}
Expand description

Multipath TCP (MPTCP) preference.

+

Currently only useful on Linux.

+

Also see ServerBuilder::mptcp().

+

Variantsยง

ยง

Disabled

MPTCP will not be used when binding sockets.

+
ยง

TcpFallback

MPTCP will be attempted when binding sockets. If errors occur, regular TCP will be +attempted, too.

+
ยง

NoFallback

MPTCP will be used when binding sockets (with no fallback).

+

Trait Implementationsยง

sourceยง

impl Clone for MpTcp

sourceยง

fn clone(&self) -> MpTcp

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for MpTcp

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_server/handle/struct.ServerHandle.html b/actix_server/handle/struct.ServerHandle.html new file mode 100644 index 00000000..e5732d0e --- /dev/null +++ b/actix_server/handle/struct.ServerHandle.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_server/struct.ServerHandle.html...

+ + + \ No newline at end of file diff --git a/actix_server/index.html b/actix_server/index.html new file mode 100644 index 00000000..f5ea0493 --- /dev/null +++ b/actix_server/index.html @@ -0,0 +1,2 @@ +actix_server - Rust

Crate actix_server

source
Expand description

General purpose TCP server.

+

Re-exportsยง

  • pub use self::service::ServerServiceFactory;

Structsยง

Enumsยง

  • Multipath TCP (MPTCP) preference.
\ No newline at end of file diff --git a/actix_server/server/struct.Server.html b/actix_server/server/struct.Server.html new file mode 100644 index 00000000..05a75685 --- /dev/null +++ b/actix_server/server/struct.Server.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_server/struct.Server.html...

+ + + \ No newline at end of file diff --git a/actix_server/sidebar-items.js b/actix_server/sidebar-items.js new file mode 100644 index 00000000..9e69b2e9 --- /dev/null +++ b/actix_server/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["MpTcp"],"struct":["Server","ServerBuilder","ServerHandle","TestServer"]}; \ No newline at end of file diff --git a/actix_server/struct.Server.html b/actix_server/struct.Server.html new file mode 100644 index 00000000..da62a72e --- /dev/null +++ b/actix_server/struct.Server.html @@ -0,0 +1,169 @@ +Server in actix_server - Rust
actix_server

Struct Server

source
pub struct Server { /* private fields */ }
Expand description

General purpose TCP server that runs services receiving Tokio TcpStreams.

+

Handles creating worker threads, restarting faulted workers, connection accepting, and +back-pressure logic.

+

Creates a worker per CPU core (or the number specified in ServerBuilder::workers) and +distributes connections with a round-robin strategy.

+

The Server must be awaited or polled in order to start running. It will resolve when the +server has fully shut down.

+

ยงShutdown Signals

+

On UNIX systems, SIGTERM will start a graceful shutdown and SIGQUIT or SIGINT will start a +forced shutdown. On Windows, a Ctrl-C signal will start a forced shutdown.

+

A graceful shutdown will wait for all workers to stop first.

+

ยงExamples

+

The following is a TCP echo server. Test using telnet 127.0.0.1 8080.

+ +
use std::io;
+
+use actix_rt::net::TcpStream;
+use actix_server::Server;
+use actix_service::{fn_service, ServiceFactoryExt as _};
+use bytes::BytesMut;
+use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+#[actix_rt::main]
+async fn main() -> io::Result<()> {
+    let bind_addr = ("127.0.0.1", 8080);
+
+    Server::build()
+        .bind("echo", bind_addr, move || {
+            fn_service(move |mut stream: TcpStream| {
+                async move {
+                    let mut size = 0;
+                    let mut buf = BytesMut::new();
+
+                    loop {
+                        match stream.read_buf(&mut buf).await {
+                            // end of stream; bail from loop
+                            Ok(0) => break,
+
+                            // write bytes back to stream
+                            Ok(bytes_read) => {
+                                stream.write_all(&buf[size..]).await.unwrap();
+                                size += bytes_read;
+                            }
+
+                            Err(err) => {
+                                eprintln!("Stream Error: {:?}", err);
+                                return Err(());
+                            }
+                        }
+                    }
+
+                    Ok(())
+                }
+            })
+            .map_err(|err| eprintln!("Service Error: {:?}", err))
+        })?
+        .run()
+        .await
+}
+

Implementationsยง

sourceยง

impl Server

source

pub fn build() -> ServerBuilder

Create server build.

+
source

pub fn handle(&self) -> ServerHandle

Get a Server handle that can be used issue commands and change itโ€™s state.

+

See ServerHandle for usage.

+

Trait Implementationsยง

sourceยง

impl Future for Server

sourceยง

type Output = Result<(), Error>

The type of value produced on completion.
sourceยง

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> FutureExt for T
where + T: Future + ?Sized,

ยง

fn map<U, F>(self, f: F) -> Map<Self, F>
where + F: FnOnce(Self::Output) -> U, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn map_into<U>(self) -> MapInto<Self, U>
where + Self::Output: Into<U>, + Self: Sized,

Map this futureโ€™s output to a different type, returning a new future of +the resulting type. Read more
ยง

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where + F: FnOnce(Self::Output) -> Fut, + Fut: Future, + Self: Sized,

Chain on a computation for when a future finished, passing the result of +the future to the provided closure f. Read more
ยง

fn left_future<B>(self) -> Either<Self, B>
where + B: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the left-hand variant +of that Either. Read more
ยง

fn right_future<A>(self) -> Either<A, Self>
where + A: Future<Output = Self::Output>, + Self: Sized,

Wrap this future in an Either future, making it the right-hand variant +of that Either. Read more
ยง

fn into_stream(self) -> IntoStream<Self>
where + Self: Sized,

Convert this future into a single element stream. Read more
ยง

fn flatten(self) -> Flatten<Self>
where + Self::Output: Future, + Self: Sized,

Flatten the execution of this future when the output of this +future is itself another future. Read more
ยง

fn flatten_stream(self) -> FlattenStream<Self>
where + Self::Output: Stream, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn fuse(self) -> Fuse<Self>
where + Self: Sized,

Fuse a future such that poll will never again be called once it has +completed. This method can be used to turn any Future into a +FusedFuture. Read more
ยง

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where + F: FnOnce(&Self::Output), + Self: Sized,

Do something with the output of a future before passing it on. Read more
ยง

fn catch_unwind(self) -> CatchUnwind<Self>
where + Self: Sized + UnwindSafe,

Catches unwinding panics while polling the future. Read more
ยง

fn shared(self) -> Shared<Self>
where + Self: Sized, + Self::Output: Clone,

Create a cloneable handle to this future where all handles will resolve +to the same result. Read more
ยง

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where + Self: Sized + Send + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where + Self: Sized + 'a,

Wrap the future in a Box, pinning it. Read more
ยง

fn unit_error(self) -> UnitError<Self>
where + Self: Sized,

ยง

fn never_error(self) -> NeverError<Self>
where + Self: Sized,

ยง

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where + Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
ยง

fn now_or_never(self) -> Option<Self::Output>
where + Self: Sized,

Evaluates and consumes the future, returning the resulting output if +the future is ready after the first call to Future::poll. Read more
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
ยง

impl<F, T, E> TryFuture for F
where + F: Future<Output = Result<T, E>> + ?Sized,

ยง

type Ok = T

The type of successful values yielded by this future
ยง

type Error = E

The type of failures yielded by this future
ยง

fn try_poll( + self: Pin<&mut F>, + cx: &mut Context<'_>, +) -> Poll<<F as Future>::Output>

Poll this TryFuture as if it were a Future. Read more
ยง

impl<Fut> TryFutureExt for Fut
where + Fut: TryFuture + ?Sized,

ยง

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where + F: FnOnce(Self::Ok) -> T, + Self: Sized,

Maps this futureโ€™s success value to a different value. Read more
ยง

fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E>
where + F: FnOnce(Self::Ok) -> T, + E: FnOnce(Self::Error) -> T, + Self: Sized,

Maps this futureโ€™s success value to a different value, and permits for error handling resulting in the same type. Read more
ยง

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where + F: FnOnce(Self::Error) -> E, + Self: Sized,

Maps this futureโ€™s error value to a different value. Read more
ยง

fn err_into<E>(self) -> ErrInto<Self, E>
where + Self: Sized, + Self::Error: Into<E>,

Maps this futureโ€™s Error to a new error type +using the Into trait. Read more
ยง

fn ok_into<U>(self) -> OkInto<Self, U>
where + Self: Sized, + Self::Ok: Into<U>,

Maps this futureโ€™s Ok to a new type +using the Into trait.
ยง

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where + F: FnOnce(Self::Ok) -> Fut, + Fut: TryFuture<Error = Self::Error>, + Self: Sized,

Executes another future after this one resolves successfully. The +success value is passed to a closure to create this subsequent future. Read more
ยง

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where + F: FnOnce(Self::Error) -> Fut, + Fut: TryFuture<Ok = Self::Ok>, + Self: Sized,

Executes another future if this one resolves to an error. The +error value is passed to a closure to create this subsequent future. Read more
ยง

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where + F: FnOnce(&Self::Ok), + Self: Sized,

Do something with the success value of a future before passing it on. Read more
ยง

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where + F: FnOnce(&Self::Error), + Self: Sized,

Do something with the error value of a future before passing it on. Read more
ยง

fn try_flatten(self) -> TryFlatten<Self, Self::Ok>
where + Self::Ok: TryFuture<Error = Self::Error>, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is another future. Read more
ยง

fn try_flatten_stream(self) -> TryFlattenStream<Self>
where + Self::Ok: TryStream<Error = Self::Error>, + Self: Sized,

Flatten the execution of this future when the successful result of this +future is a stream. Read more
ยง

fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F>
where + Self: Sized, + F: FnOnce(Self::Error) -> Self::Ok,

Unwraps this futureโ€™s output, producing a future with this futureโ€™s +Ok type as its +Output type. Read more
ยง

fn into_future(self) -> IntoFuture<Self>
where + Self: Sized,

Wraps a [TryFuture] into a type that implements +Future. Read more
ยง

fn try_poll_unpin( + &mut self, + cx: &mut Context<'_>, +) -> Poll<Result<Self::Ok, Self::Error>>
where + Self: Unpin,

A convenience method for calling [TryFuture::try_poll] on Unpin +future types.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_server/struct.ServerBuilder.html b/actix_server/struct.ServerBuilder.html new file mode 100644 index 00000000..13a180ff --- /dev/null +++ b/actix_server/struct.ServerBuilder.html @@ -0,0 +1,107 @@ +ServerBuilder in actix_server - Rust
actix_server

Struct ServerBuilder

source
pub struct ServerBuilder { /* private fields */ }
Expand description

Server builder.

+

Implementationsยง

sourceยง

impl ServerBuilder

source

pub fn new() -> ServerBuilder

Create new Server builder instance

+
source

pub fn workers(self, num: usize) -> Self

Sets number of workers to start.

+

See bind() for more details on how worker count affects the number of +server factory instantiations.

+

The default worker count is the determined by std::thread::available_parallelism(). See +its documentation to determine what behavior you should expect when server is run.

+

num must be greater than 0.

+
ยงPanics
+

Panics if num is 0.

+
source

pub fn worker_max_blocking_threads(self, num: usize) -> Self

Set max number of threads for each workerโ€™s blocking task thread pool.

+

One thread pool is set up per worker; not shared across workers.

+
ยงExamples:
+
let builder = ServerBuilder::new()
+    .workers(4) // server has 4 worker thread.
+    .worker_max_blocking_threads(4); // every worker has 4 max blocking threads.
+

See [tokio::runtime::Builder::max_blocking_threads] for behavior reference.

+
source

pub fn backlog(self, num: u32) -> Self

Set the maximum number of pending connections.

+

This refers to the number of clients that can be waiting to be served. Exceeding this number +results in the client getting an error when attempting to connect. It should only affect +servers under significant load.

+

Generally set in the 64-2048 range. Default value is 2048.

+

This method should be called before bind() method call.

+
source

pub fn mptcp(self, mptcp_enabled: MpTcp) -> Self

Sets MultiPath TCP (MPTCP) preference on bound sockets.

+

Multipath TCP (MPTCP) builds on top of TCP to improve connection redundancy and performance +by sharing a network data stream across multiple underlying TCP sessions. See mptcp.dev +for more info about MPTCP itself.

+

MPTCP is available on Linux kernel version 5.6 and higher. In addition, youโ€™ll also need to +ensure the kernel option is enabled using sysctl net.mptcp.enabled=1.

+

This method will have no effect if called after a bind().

+
source

pub fn max_concurrent_connections(self, num: usize) -> Self

Sets the maximum per-worker number of concurrent connections.

+

All socket listeners will stop accepting connections when this limit is reached for +each worker.

+

By default max connections is set to a 25k per worker.

+
source

pub fn system_exit(self) -> Self

Sets flag to stop Actix System after server shutdown.

+

This has no effect when server is running in a Tokio-only runtime.

+
source

pub fn disable_signals(self) -> Self

Disables OS signal handling.

+
source

pub fn shutdown_timeout(self, sec: u64) -> Self

Timeout for graceful workers shutdown in seconds.

+

After receiving a stop signal, workers have this much time to finish serving requests. +Workers still alive after the timeout are force dropped.

+

By default shutdown timeout sets to 30 seconds.

+
source

pub fn bind<F, U, N>(self, name: N, addrs: U, factory: F) -> Result<Self>
where + F: ServerServiceFactory<TcpStream>, + U: ToSocketAddrs, + N: AsRef<str>,

Adds new service to the server.

+

Note that, if a DNS lookup is required, resolving hostnames is a blocking operation.

+
ยงWorker Count
+

The factory will be instantiated multiple times in most scenarios. The number of +instantiations is number of workers ร— number of sockets resolved by +addrs.

+

For example, if youโ€™ve manually set workers to 2, and use 127.0.0.1 +as the bind addrs, then factory will be instantiated twice. However, using localhost +as the bind addrs can often resolve to both 127.0.0.1 (IPv4) and ::1 (IPv6), causing +the factory to be instantiated 4 times (2 workers ร— 2 bind addresses).

+

Using a bind address of 0.0.0.0, which signals to use all interfaces, may also multiple +the number of instantiations in a similar way.

+
ยงErrors
+

Returns an io::Error if:

+
    +
  • addrs cannot be resolved into one or more socket addresses;
  • +
  • all the resolved socket addresses are already bound.
  • +
+
source

pub fn listen<F, N: AsRef<str>>( + self, + name: N, + lst: StdTcpListener, + factory: F, +) -> Result<Self>
where + F: ServerServiceFactory<TcpStream>,

Adds service to the server using a socket listener already bound.

+
ยงWorker Count
+

The factory will be instantiated multiple times in most scenarios. The number of +instantiations is: number of workers.

+
source

pub fn run(self) -> Server โ“˜

Starts processing incoming connections and return server controller.

+
sourceยง

impl ServerBuilder

source

pub fn bind_uds<F, U, N>(self, name: N, addr: U, factory: F) -> Result<Self>
where + F: ServerServiceFactory<UnixStream>, + N: AsRef<str>, + U: AsRef<Path>,

Adds new service to the server using a UDS (unix domain socket) address.

+
ยงWorker Count
+

The factory will be instantiated multiple times in most scenarios. The number of +instantiations is: number of workers.

+
source

pub fn listen_uds<F, N: AsRef<str>>( + self, + name: N, + lst: UnixListener, + factory: F, +) -> Result<Self>
where + F: ServerServiceFactory<UnixStream>,

Adds new service to the server using a UDS (unix domain socket) listener already bound.

+

Useful when running as a systemd service and a socket FD is acquired externally.

+
ยงWorker Count
+

The factory will be instantiated multiple times in most scenarios. The number of +instantiations is: number of workers.

+

Trait Implementationsยง

sourceยง

impl Default for ServerBuilder

sourceยง

fn default() -> Self

Returns the โ€œdefault valueโ€ for a type. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_server/struct.ServerHandle.html b/actix_server/struct.ServerHandle.html new file mode 100644 index 00000000..97e20441 --- /dev/null +++ b/actix_server/struct.ServerHandle.html @@ -0,0 +1,23 @@ +ServerHandle in actix_server - Rust
actix_server

Struct ServerHandle

source
pub struct ServerHandle { /* private fields */ }
Expand description

Server handle.

+

Implementationsยง

sourceยง

impl ServerHandle

source

pub fn pause(&self) -> impl Future<Output = ()>

Pause accepting incoming connections.

+

May drop socket pending connection. All open connections remain active.

+
source

pub fn resume(&self) -> impl Future<Output = ()>

Resume accepting incoming connections.

+
source

pub fn stop(&self, graceful: bool) -> impl Future<Output = ()>

Stop incoming connection processing, stop all workers and exit.

+

Trait Implementationsยง

sourceยง

impl Clone for ServerHandle

sourceยง

fn clone(&self) -> ServerHandle

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for ServerHandle

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_server/struct.TestServer.html b/actix_server/struct.TestServer.html new file mode 100644 index 00000000..d96f975f --- /dev/null +++ b/actix_server/struct.TestServer.html @@ -0,0 +1,40 @@ +TestServer in actix_server - Rust
actix_server

Struct TestServer

source
pub struct TestServer;
Expand description

A testing server.

+

TestServer is very simple test server that simplify process of writing integration tests for +network applications.

+

ยงExamples

+
use actix_service::fn_service;
+use actix_server::TestServer;
+
+#[actix_rt::main]
+async fn main() {
+    let srv = TestServer::start(|| fn_service(
+        |sock| async move {
+            println!("New connection: {:?}", sock);
+            Ok::<_, ()>(())
+        }
+    ));
+
+    println!("SOCKET: {:?}", srv.connect());
+}
+

Implementationsยง

sourceยง

impl TestServer

source

pub fn start(factory: impl ServerServiceFactory<TcpStream>) -> TestServerHandle

Start new TestServer using application factory and default server config.

+
source

pub fn start_with_builder( + server_builder: ServerBuilder, + factory: impl ServerServiceFactory<TcpStream>, +) -> TestServerHandle

Start new TestServer using application factory and server builder.

+
source

pub fn unused_addr() -> SocketAddr

Get first available unused local address.

+

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_server/test_server/struct.TestServer.html b/actix_server/test_server/struct.TestServer.html new file mode 100644 index 00000000..08933b41 --- /dev/null +++ b/actix_server/test_server/struct.TestServer.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_server/struct.TestServer.html...

+ + + \ No newline at end of file diff --git a/actix_service/all.html b/actix_service/all.html new file mode 100644 index 00000000..78d293d8 --- /dev/null +++ b/actix_service/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/actix_service/apply/fn.apply_fn.html b/actix_service/apply/fn.apply_fn.html new file mode 100644 index 00000000..b2fdf29f --- /dev/null +++ b/actix_service/apply/fn.apply_fn.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.apply_fn.html...

+ + + \ No newline at end of file diff --git a/actix_service/apply/fn.apply_fn_factory.html b/actix_service/apply/fn.apply_fn_factory.html new file mode 100644 index 00000000..19abc6a5 --- /dev/null +++ b/actix_service/apply/fn.apply_fn_factory.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.apply_fn_factory.html...

+ + + \ No newline at end of file diff --git a/actix_service/apply_cfg/fn.apply_cfg.html b/actix_service/apply_cfg/fn.apply_cfg.html new file mode 100644 index 00000000..8844f540 --- /dev/null +++ b/actix_service/apply_cfg/fn.apply_cfg.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.apply_cfg.html...

+ + + \ No newline at end of file diff --git a/actix_service/apply_cfg/fn.apply_cfg_factory.html b/actix_service/apply_cfg/fn.apply_cfg_factory.html new file mode 100644 index 00000000..cf958335 --- /dev/null +++ b/actix_service/apply_cfg/fn.apply_cfg_factory.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.apply_cfg_factory.html...

+ + + \ No newline at end of file diff --git a/actix_service/boxed/fn.factory.html b/actix_service/boxed/fn.factory.html new file mode 100644 index 00000000..7f679365 --- /dev/null +++ b/actix_service/boxed/fn.factory.html @@ -0,0 +1,11 @@ +factory in actix_service::boxed - Rust
actix_service::boxed

Function factory

source
pub fn factory<SF, Req>(
+    factory: SF,
+) -> BoxServiceFactory<SF::Config, Req, SF::Response, SF::Error, SF::InitError>
where + SF: ServiceFactory<Req> + 'static, + Req: 'static, + SF::Response: 'static, + SF::Service: 'static, + SF::Future: 'static, + SF::Error: 'static, + SF::InitError: 'static,
Expand description

Wraps a service factory that returns service trait objects.

+
\ No newline at end of file diff --git a/actix_service/boxed/fn.rc_service.html b/actix_service/boxed/fn.rc_service.html new file mode 100644 index 00000000..8e5291b1 --- /dev/null +++ b/actix_service/boxed/fn.rc_service.html @@ -0,0 +1,5 @@ +rc_service in actix_service::boxed - Rust
actix_service::boxed

Function rc_service

source
pub fn rc_service<S, Req>(service: S) -> RcService<Req, S::Response, S::Error>
where + S: Service<Req> + 'static, + Req: 'static, + S::Future: 'static,
Expand description

Wraps service as a trait object using RcService.

+
\ No newline at end of file diff --git a/actix_service/boxed/fn.service.html b/actix_service/boxed/fn.service.html new file mode 100644 index 00000000..ac291d2c --- /dev/null +++ b/actix_service/boxed/fn.service.html @@ -0,0 +1,5 @@ +service in actix_service::boxed - Rust
actix_service::boxed

Function service

source
pub fn service<S, Req>(service: S) -> BoxService<Req, S::Response, S::Error>
where + S: Service<Req> + 'static, + Req: 'static, + S::Future: 'static,
Expand description

Wraps service as a trait object using BoxService.

+
\ No newline at end of file diff --git a/actix_service/boxed/index.html b/actix_service/boxed/index.html new file mode 100644 index 00000000..04a9601b --- /dev/null +++ b/actix_service/boxed/index.html @@ -0,0 +1,2 @@ +actix_service::boxed - Rust
actix_service

Module boxed

source
Expand description

Trait object forms of services and service factories.

+

Structsยง

  • Wrapper for a service factory that will map itโ€™s services to boxed trait object services.

Functionsยง

Type Aliasesยง

  • A boxed future with no send bound or lifetime parameters.
  • Type alias for service trait object using Box.
  • Type alias for service trait object using Rc.
\ No newline at end of file diff --git a/actix_service/boxed/sidebar-items.js b/actix_service/boxed/sidebar-items.js new file mode 100644 index 00000000..bec42849 --- /dev/null +++ b/actix_service/boxed/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["factory","rc_service","service"],"struct":["BoxServiceFactory"],"type":["BoxFuture","BoxService","RcService"]}; \ No newline at end of file diff --git a/actix_service/boxed/struct.BoxServiceFactory.html b/actix_service/boxed/struct.BoxServiceFactory.html new file mode 100644 index 00000000..30a8b60d --- /dev/null +++ b/actix_service/boxed/struct.BoxServiceFactory.html @@ -0,0 +1,29 @@ +BoxServiceFactory in actix_service::boxed - Rust
actix_service::boxed

Struct BoxServiceFactory

source
pub struct BoxServiceFactory<Cfg, Req, Res, Err, InitErr>(/* private fields */);
Expand description

Wrapper for a service factory that will map itโ€™s services to boxed trait object services.

+

Trait Implementationsยง

sourceยง

impl<C, Req, Res, Err, InitErr> ServiceFactory<Req> for BoxServiceFactory<C, Req, Res, Err, InitErr>
where + Req: 'static, + Res: 'static, + Err: 'static, + InitErr: 'static,

sourceยง

type Response = Res

Responses given by the created services.
sourceยง

type Error = Err

Errors produced by the created services.
sourceยง

type Config = C

Service factory configuration.
sourceยง

type Service = Box<dyn Service<Req, Error = Err, Response = Res, Future = Pin<Box<dyn Future<Output = Result<Res, Err>>>>>>

The kind of Service created by this factory.
sourceยง

type InitError = InitErr

Errors potentially raised while building a service.
sourceยง

type Future = Pin<Box<dyn Future<Output = Result<<BoxServiceFactory<C, Req, Res, Err, InitErr> as ServiceFactory<Req>>::Service, InitErr>>>>

The future of the Service instance.g
sourceยง

fn new_service(&self, cfg: C) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

ยง

impl<Cfg, Req, Res, Err, InitErr> Freeze for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>

ยง

impl<Cfg, Req, Res, Err, InitErr> !RefUnwindSafe for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>

ยง

impl<Cfg, Req, Res, Err, InitErr> !Send for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>

ยง

impl<Cfg, Req, Res, Err, InitErr> !Sync for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>

ยง

impl<Cfg, Req, Res, Err, InitErr> Unpin for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>

ยง

impl<Cfg, Req, Res, Err, InitErr> !UnwindSafe for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

sourceยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
sourceยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

sourceยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
sourceยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
sourceยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
sourceยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_service/boxed/type.BoxFuture.html b/actix_service/boxed/type.BoxFuture.html new file mode 100644 index 00000000..d232bc19 --- /dev/null +++ b/actix_service/boxed/type.BoxFuture.html @@ -0,0 +1,2 @@ +BoxFuture in actix_service::boxed - Rust
actix_service::boxed

Type Alias BoxFuture

source
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
Expand description

A boxed future with no send bound or lifetime parameters.

+

Aliased Typeยง

struct BoxFuture<T> {}
\ No newline at end of file diff --git a/actix_service/boxed/type.BoxService.html b/actix_service/boxed/type.BoxService.html new file mode 100644 index 00000000..8087330e --- /dev/null +++ b/actix_service/boxed/type.BoxService.html @@ -0,0 +1,2 @@ +BoxService in actix_service::boxed - Rust
actix_service::boxed

Type Alias BoxService

source
pub type BoxService<Req, Res, Err> = Box<dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>>;
Expand description

Type alias for service trait object using Box.

+

Aliased Typeยง

struct BoxService<Req, Res, Err>(/* private fields */);
\ No newline at end of file diff --git a/actix_service/boxed/type.RcService.html b/actix_service/boxed/type.RcService.html new file mode 100644 index 00000000..47528c9d --- /dev/null +++ b/actix_service/boxed/type.RcService.html @@ -0,0 +1,2 @@ +RcService in actix_service::boxed - Rust
actix_service::boxed

Type Alias RcService

source
pub type RcService<Req, Res, Err> = Rc<dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>>;
Expand description

Type alias for service trait object using Rc.

+

Aliased Typeยง

struct RcService<Req, Res, Err> { /* private fields */ }
\ No newline at end of file diff --git a/actix_service/ext/trait.ServiceExt.html b/actix_service/ext/trait.ServiceExt.html new file mode 100644 index 00000000..c214803a --- /dev/null +++ b/actix_service/ext/trait.ServiceExt.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/trait.ServiceExt.html...

+ + + \ No newline at end of file diff --git a/actix_service/ext/trait.ServiceFactoryExt.html b/actix_service/ext/trait.ServiceFactoryExt.html new file mode 100644 index 00000000..84e5329c --- /dev/null +++ b/actix_service/ext/trait.ServiceFactoryExt.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/trait.ServiceFactoryExt.html...

+ + + \ No newline at end of file diff --git a/actix_service/ext/trait.TransformExt.html b/actix_service/ext/trait.TransformExt.html new file mode 100644 index 00000000..a50c50ec --- /dev/null +++ b/actix_service/ext/trait.TransformExt.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/trait.TransformExt.html...

+ + + \ No newline at end of file diff --git a/actix_service/fn.apply.html b/actix_service/fn.apply.html new file mode 100644 index 00000000..bb2dcf4f --- /dev/null +++ b/actix_service/fn.apply.html @@ -0,0 +1,5 @@ +apply in actix_service - Rust
actix_service

Function apply

source
pub fn apply<T, S, I, Req>(t: T, factory: I) -> ApplyTransform<T, S, Req>
where + I: IntoServiceFactory<S, Req>, + S: ServiceFactory<Req>, + T: Transform<S::Service, Req, InitError = S::InitError>,
Expand description

Apply a Transform to a Service.

+
\ No newline at end of file diff --git a/actix_service/fn.apply_cfg.html b/actix_service/fn.apply_cfg.html new file mode 100644 index 00000000..de5c6c29 --- /dev/null +++ b/actix_service/fn.apply_cfg.html @@ -0,0 +1,9 @@ +apply_cfg in actix_service - Rust
actix_service

Function apply_cfg

source
pub fn apply_cfg<S1, Req, F, Cfg, Fut, S2, Err>(
+    srv: S1,
+    f: F,
+) -> impl ServiceFactory<Req, Config = Cfg, Response = S2::Response, Error = S2::Error, Service = S2, InitError = Err, Future = Fut> + Clone
where + S1: Service<Req>, + F: Fn(Cfg, &S1) -> Fut, + Fut: Future<Output = Result<S2, Err>>, + S2: Service<Req>,
Expand description

Convert Fn(Config, &Service1) -> Future<Service2> fn to a service factory.

+
\ No newline at end of file diff --git a/actix_service/fn.apply_cfg_factory.html b/actix_service/fn.apply_cfg_factory.html new file mode 100644 index 00000000..8d928500 --- /dev/null +++ b/actix_service/fn.apply_cfg_factory.html @@ -0,0 +1,11 @@ +apply_cfg_factory in actix_service - Rust
actix_service

Function apply_cfg_factory

source
pub fn apply_cfg_factory<SF, Req, F, Cfg, Fut, S>(
+    factory: SF,
+    f: F,
+) -> impl ServiceFactory<Req, Config = Cfg, Response = S::Response, Error = S::Error, Service = S, InitError = SF::InitError> + Clone
where + SF: ServiceFactory<Req, Config = ()>, + F: Fn(Cfg, &SF::Service) -> Fut, + SF::InitError: From<SF::Error>, + Fut: Future<Output = Result<S, SF::InitError>>, + S: Service<Req>,
Expand description

Convert Fn(Config, &ServiceFactory1) -> Future<ServiceFactory2> fn to a service factory.

+

Service1 get constructed from T factory.

+
\ No newline at end of file diff --git a/actix_service/fn.apply_fn.html b/actix_service/fn.apply_fn.html new file mode 100644 index 00000000..fd045636 --- /dev/null +++ b/actix_service/fn.apply_fn.html @@ -0,0 +1,10 @@ +apply_fn in actix_service - Rust
actix_service

Function apply_fn

source
pub fn apply_fn<I, S, F, Fut, Req, In, Res, Err>(
+    service: I,
+    wrap_fn: F,
+) -> Apply<S, F, Req, In, Res, Err>
where + I: IntoService<S, In>, + S: Service<In, Error = Err>, + F: Fn(Req, &S) -> Fut, + Fut: Future<Output = Result<Res, Err>>,
Expand description

Apply transform function to a service.

+

The In and Out type params refer to the request and response types for the wrapped service.

+
\ No newline at end of file diff --git a/actix_service/fn.apply_fn_factory.html b/actix_service/fn.apply_fn_factory.html new file mode 100644 index 00000000..70bc8d61 --- /dev/null +++ b/actix_service/fn.apply_fn_factory.html @@ -0,0 +1,10 @@ +apply_fn_factory in actix_service - Rust
actix_service

Function apply_fn_factory

source
pub fn apply_fn_factory<I, SF, F, Fut, Req, In, Res, Err>(
+    service: I,
+    f: F,
+) -> ApplyFactory<SF, F, Req, In, Res, Err>
where + I: IntoServiceFactory<SF, In>, + SF: ServiceFactory<In, Error = Err>, + F: Fn(Req, &SF::Service) -> Fut + Clone, + Fut: Future<Output = Result<Res, Err>>,
Expand description

Service factory that produces apply_fn service.

+

The In and Out type params refer to the request and response types for the wrapped service.

+
\ No newline at end of file diff --git a/actix_service/fn.fn_factory.html b/actix_service/fn.fn_factory.html new file mode 100644 index 00000000..3189b093 --- /dev/null +++ b/actix_service/fn.fn_factory.html @@ -0,0 +1,38 @@ +fn_factory in actix_service - Rust
actix_service

Function fn_factory

source
pub fn fn_factory<F, Cfg, Srv, Req, Fut, Err>(
+    f: F,
+) -> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
where + F: Fn() -> Fut, + Fut: Future<Output = Result<Srv, Err>>, + Srv: Service<Req>,
Expand description

Create ServiceFactory for function that can produce services

+

ยงExamples

+
use std::io;
+use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
+use futures_util::future::ok;
+
+/// Service that divides two usize values.
+async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> {
+    if y == 0 {
+        Err(io::Error::new(io::ErrorKind::Other, "divide by zero"))
+    } else {
+        Ok(x / y)
+    }
+}
+
+#[actix_rt::main]
+async fn main() -> io::Result<()> {
+    // Create service factory that produces `div` services
+    let factory = fn_factory(|| {
+        ok::<_, io::Error>(fn_service(div))
+    });
+
+    // construct new service
+    let srv = factory.new_service(()).await?;
+
+    // now we can use `div` service
+    let result = srv.call((10, 20)).await?;
+
+    println!("10 / 20 = {}", result);
+
+    Ok(())
+}
+
\ No newline at end of file diff --git a/actix_service/fn.fn_factory_with_config.html b/actix_service/fn.fn_factory_with_config.html new file mode 100644 index 00000000..2c5a196b --- /dev/null +++ b/actix_service/fn.fn_factory_with_config.html @@ -0,0 +1,31 @@ +fn_factory_with_config in actix_service - Rust
actix_service

Function fn_factory_with_config

source
pub fn fn_factory_with_config<F, Fut, Cfg, Srv, Req, Err>(
+    f: F,
+) -> FnServiceConfig<F, Fut, Cfg, Srv, Req, Err>
where + F: Fn(Cfg) -> Fut, + Fut: Future<Output = Result<Srv, Err>>, + Srv: Service<Req>,
Expand description

Create ServiceFactory for function that accepts config argument and can produce services

+

Any function that has following form Fn(Config) -> Future<Output = Service> could act as +a ServiceFactory.

+

ยงExamples

+
use std::io;
+use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
+use futures_util::future::ok;
+
+#[actix_rt::main]
+async fn main() -> io::Result<()> {
+    // Create service factory. factory uses config argument for
+    // services it generates.
+    let factory = fn_factory_with_config(|y: usize| {
+        ok::<_, io::Error>(fn_service(move |x: usize| ok::<_, io::Error>(x * y)))
+    });
+
+    // construct new service with config argument
+    let srv = factory.new_service(10).await?;
+
+    let result = srv.call(10).await?;
+    assert_eq!(result, 100);
+
+    println!("10 * 10 = {}", result);
+    Ok(())
+}
+
\ No newline at end of file diff --git a/actix_service/fn.fn_service.html b/actix_service/fn.fn_service.html new file mode 100644 index 00000000..8a612809 --- /dev/null +++ b/actix_service/fn.fn_service.html @@ -0,0 +1,6 @@ +fn_service in actix_service - Rust
actix_service

Function fn_service

source
pub fn fn_service<F, Fut, Req, Res, Err, Cfg>(
+    f: F,
+) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
where + F: Fn(Req) -> Fut + Clone, + Fut: Future<Output = Result<Res, Err>>,
Expand description

Create ServiceFactory for function that can act as a Service

+
\ No newline at end of file diff --git a/actix_service/fn.into_service.html b/actix_service/fn.into_service.html new file mode 100644 index 00000000..95a6009a --- /dev/null +++ b/actix_service/fn.into_service.html @@ -0,0 +1,4 @@ +into_service in actix_service - Rust
actix_service

Function into_service

source
pub fn into_service<I, S, Req>(tp: I) -> S
where + I: IntoService<S, Req>, + S: Service<Req>,
Expand description

Convert object of type U to a service S

+
\ No newline at end of file diff --git a/actix_service/fn.map_config.html b/actix_service/fn.map_config.html new file mode 100644 index 00000000..dc62caf8 --- /dev/null +++ b/actix_service/fn.map_config.html @@ -0,0 +1,10 @@ +map_config in actix_service - Rust
actix_service

Function map_config

source
pub fn map_config<I, SF, Req, F, Cfg>(
+    factory: I,
+    f: F,
+) -> MapConfig<SF, Req, F, Cfg>
where + I: IntoServiceFactory<SF, Req>, + SF: ServiceFactory<Req>, + F: Fn(Cfg) -> SF::Config,
Expand description

Adapt external config argument to a config for provided service factory

+

Note that this function consumes the receiving service factory and returns +a wrapped version of it.

+
\ No newline at end of file diff --git a/actix_service/fn.unit_config.html b/actix_service/fn.unit_config.html new file mode 100644 index 00000000..68516d94 --- /dev/null +++ b/actix_service/fn.unit_config.html @@ -0,0 +1,4 @@ +unit_config in actix_service - Rust
actix_service

Function unit_config

source
pub fn unit_config<I, SF, Cfg, Req>(factory: I) -> UnitConfig<SF, Cfg, Req>
where + I: IntoServiceFactory<SF, Req>, + SF: ServiceFactory<Req, Config = ()>,
Expand description

Replace config with unit.

+
\ No newline at end of file diff --git a/actix_service/fn_service/fn.fn_factory.html b/actix_service/fn_service/fn.fn_factory.html new file mode 100644 index 00000000..d6973ed8 --- /dev/null +++ b/actix_service/fn_service/fn.fn_factory.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.fn_factory.html...

+ + + \ No newline at end of file diff --git a/actix_service/fn_service/fn.fn_factory_with_config.html b/actix_service/fn_service/fn.fn_factory_with_config.html new file mode 100644 index 00000000..e828658a --- /dev/null +++ b/actix_service/fn_service/fn.fn_factory_with_config.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.fn_factory_with_config.html...

+ + + \ No newline at end of file diff --git a/actix_service/fn_service/fn.fn_service.html b/actix_service/fn_service/fn.fn_service.html new file mode 100644 index 00000000..64dfab95 --- /dev/null +++ b/actix_service/fn_service/fn.fn_service.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.fn_service.html...

+ + + \ No newline at end of file diff --git a/actix_service/index.html b/actix_service/index.html new file mode 100644 index 00000000..bffcc68c --- /dev/null +++ b/actix_service/index.html @@ -0,0 +1,3 @@ +actix_service - Rust

Crate actix_service

source
Expand description

See Service docs for information on this crateโ€™s foundational trait.

+

Modulesยง

  • Trait object forms of services and service factories.

Macrosยง

Structsยง

Traitsยง

Functionsยง

  • Apply a Transform to a Service.
  • Convert Fn(Config, &Service1) -> Future<Service2> fn to a service factory.
  • Convert Fn(Config, &ServiceFactory1) -> Future<ServiceFactory2> fn to a service factory.
  • Apply transform function to a service.
  • Service factory that produces apply_fn service.
  • Create ServiceFactory for function that can produce services
  • Create ServiceFactory for function that accepts config argument and can produce services
  • Create ServiceFactory for function that can act as a Service
  • Convert object of type U to a service S
  • Adapt external config argument to a config for provided service factory
  • Replace config with unit.
\ No newline at end of file diff --git a/actix_service/macro.always_ready!.html b/actix_service/macro.always_ready!.html new file mode 100644 index 00000000..115b940a --- /dev/null +++ b/actix_service/macro.always_ready!.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to macro.always_ready.html...

+ + + \ No newline at end of file diff --git a/actix_service/macro.always_ready.html b/actix_service/macro.always_ready.html new file mode 100644 index 00000000..d9811daf --- /dev/null +++ b/actix_service/macro.always_ready.html @@ -0,0 +1,24 @@ +always_ready in actix_service - Rust
actix_service

Macro always_ready

source
macro_rules! always_ready {
+    () => { ... };
+}
Expand description

An implementation of poll_ready that always signals readiness.

+

This should only be used for basic leaf services that have no concept of un-readiness. +For wrapper or other service types, use forward_ready! for simple cases or write a bespoke +poll_ready implementation.

+

ยงExamples

+
use actix_service::Service;
+use futures_util::future::{ready, Ready};
+
+struct IdentityService;
+
+impl Service<u32> for IdentityService {
+    type Response = u32;
+    type Error = ();
+    type Future = Ready<Result<Self::Response, Self::Error>>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, req: u32) -> Self::Future {
+        ready(Ok(req))
+    }
+}
+
\ No newline at end of file diff --git a/actix_service/macro.forward_ready!.html b/actix_service/macro.forward_ready!.html new file mode 100644 index 00000000..e4ff6141 --- /dev/null +++ b/actix_service/macro.forward_ready!.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to macro.forward_ready.html...

+ + + \ No newline at end of file diff --git a/actix_service/macro.forward_ready.html b/actix_service/macro.forward_ready.html new file mode 100644 index 00000000..e91cad6c --- /dev/null +++ b/actix_service/macro.forward_ready.html @@ -0,0 +1,28 @@ +forward_ready in actix_service - Rust
actix_service

Macro forward_ready

source
macro_rules! forward_ready {
+    ($field:ident) => { ... };
+}
Expand description

An implementation of poll_ready that forwards readiness checks to a +named struct field.

+

Tuple structs are not supported.

+

ยงExamples

+
use actix_service::Service;
+use futures_util::future::{ready, Ready};
+
+struct WrapperService<S> {
+    inner: S,
+}
+
+impl<S> Service<()> for WrapperService<S>
+where
+    S: Service<()>,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    actix_service::forward_ready!(inner);
+
+    fn call(&self, req: ()) -> Self::Future {
+        self.inner.call(req)
+    }
+}
+
\ No newline at end of file diff --git a/actix_service/map_config/fn.map_config.html b/actix_service/map_config/fn.map_config.html new file mode 100644 index 00000000..dfc7e1f3 --- /dev/null +++ b/actix_service/map_config/fn.map_config.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.map_config.html...

+ + + \ No newline at end of file diff --git a/actix_service/map_config/fn.unit_config.html b/actix_service/map_config/fn.unit_config.html new file mode 100644 index 00000000..5e35d658 --- /dev/null +++ b/actix_service/map_config/fn.unit_config.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.unit_config.html...

+ + + \ No newline at end of file diff --git a/actix_service/sidebar-items.js b/actix_service/sidebar-items.js new file mode 100644 index 00000000..668241bb --- /dev/null +++ b/actix_service/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["apply","apply_cfg","apply_cfg_factory","apply_fn","apply_fn_factory","fn_factory","fn_factory_with_config","fn_service","into_service","map_config","unit_config"],"macro":["always_ready","forward_ready"],"mod":["boxed"],"struct":["ApplyTransform"],"trait":["IntoService","IntoServiceFactory","Service","ServiceExt","ServiceFactory","ServiceFactoryExt","Transform","TransformExt"]}; \ No newline at end of file diff --git a/actix_service/struct.ApplyTransform.html b/actix_service/struct.ApplyTransform.html new file mode 100644 index 00000000..45f785ff --- /dev/null +++ b/actix_service/struct.ApplyTransform.html @@ -0,0 +1,36 @@ +ApplyTransform in actix_service - Rust
actix_service

Struct ApplyTransform

source
pub struct ApplyTransform<T, S, Req>(/* private fields */);
Expand description

Apply a Transform to a Service.

+

Trait Implementationsยง

sourceยง

impl<T, S, Req> Clone for ApplyTransform<T, S, Req>

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<T, S, Req> ServiceFactory<Req> for ApplyTransform<T, S, Req>
where + S: ServiceFactory<Req>, + T: Transform<S::Service, Req, InitError = S::InitError>,

sourceยง

type Response = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::Response

Responses given by the created services.
sourceยง

type Error = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::Error

Errors produced by the created services.
sourceยง

type Config = <S as ServiceFactory<Req>>::Config

Service factory configuration.
sourceยง

type Service = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::Transform

The kind of Service created by this factory.
sourceยง

type InitError = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::InitError

Errors potentially raised while building a service.
sourceยง

type Future = ApplyTransformFuture<T, S, Req>

The future of the Service instance.g
sourceยง

fn new_service(&self, cfg: S::Config) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

ยง

impl<T, S, Req> Freeze for ApplyTransform<T, S, Req>

ยง

impl<T, S, Req> RefUnwindSafe for ApplyTransform<T, S, Req>
where + Req: RefUnwindSafe, + T: RefUnwindSafe, + S: RefUnwindSafe,

ยง

impl<T, S, Req> !Send for ApplyTransform<T, S, Req>

ยง

impl<T, S, Req> !Sync for ApplyTransform<T, S, Req>

ยง

impl<T, S, Req> Unpin for ApplyTransform<T, S, Req>
where + Req: Unpin,

ยง

impl<T, S, Req> UnwindSafe for ApplyTransform<T, S, Req>
where + Req: UnwindSafe, + T: RefUnwindSafe, + S: RefUnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

sourceยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
sourceยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

sourceยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
sourceยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
sourceยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
sourceยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_service/trait.IntoService.html b/actix_service/trait.IntoService.html new file mode 100644 index 00000000..79661b75 --- /dev/null +++ b/actix_service/trait.IntoService.html @@ -0,0 +1,8 @@ +IntoService in actix_service - Rust
actix_service

Trait IntoService

source
pub trait IntoService<S, Req>
where + S: Service<Req>,
{ + // Required method + fn into_service(self) -> S; +}
Expand description

Trait for types that can be converted to a Service

+

Required Methodsยง

source

fn into_service(self) -> S

Convert to a Service

+

Implementorsยง

sourceยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

\ No newline at end of file diff --git a/actix_service/trait.IntoServiceFactory.html b/actix_service/trait.IntoServiceFactory.html new file mode 100644 index 00000000..4ff1e067 --- /dev/null +++ b/actix_service/trait.IntoServiceFactory.html @@ -0,0 +1,8 @@ +IntoServiceFactory in actix_service - Rust
actix_service

Trait IntoServiceFactory

source
pub trait IntoServiceFactory<SF, Req>
where + SF: ServiceFactory<Req>,
{ + // Required method + fn into_factory(self) -> SF; +}
Expand description

Trait for types that can be converted to a ServiceFactory

+

Required Methodsยง

source

fn into_factory(self) -> SF

Convert Self to a ServiceFactory

+

Implementorsยง

sourceยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

\ No newline at end of file diff --git a/actix_service/trait.Service.html b/actix_service/trait.Service.html new file mode 100644 index 00000000..1f3b80d5 --- /dev/null +++ b/actix_service/trait.Service.html @@ -0,0 +1,71 @@ +Service in actix_service - Rust
actix_service

Trait Service

source
pub trait Service<Req> {
+    type Response;
+    type Error;
+    type Future: Future<Output = Result<Self::Response, Self::Error>>;
+
+    // Required methods
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
+    fn call(&self, req: Req) -> Self::Future;
+}
Expand description

An asynchronous operation from Request to a Response.

+

The Service trait models a request/response interaction, receiving requests and returning +replies. You can think about a service as a function with one argument that returns some result +asynchronously. Conceptually, the operation looks like this:

+ +
โ“˜
async fn(Request) -> Result<Response, Err>
+

The Service trait just generalizes this form. Requests are defined as a generic type parameter +and responses and other details are defined as associated types on the trait impl. Notice that +this design means that services can receive many request types and converge them to a single +response type.

+

Services can also have mutable state that influence computation by using a Cell, RefCell +or Mutex. Services intentionally do not take &mut self to reduce overhead in the +common cases.

+

Service provides a symmetric and uniform API; the same abstractions can be used to represent +both clients and servers. Services describe only transformation operations which encourage +simple API surfaces. This leads to simpler design of each service, improves test-ability and +makes composition easier.

+ +
โ“˜
struct MyService;
+
+impl Service<u8> for MyService {
+     type Response = u64;
+     type Error = MyError;
+     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
+
+     fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
+
+     fn call(&self, req: u8) -> Self::Future { ... }
+}
+

Sometimes it is not necessary to implement the Service trait. For example, the above service +could be rewritten as a simple function and passed to fn_service.

+ +
โ“˜
async fn my_service(req: u8) -> Result<u64, MyError>;
+
+let svc = fn_service(my_service)
+svc.call(123)
+

Required Associated Typesยง

source

type Response

Responses given by the service.

+
source

type Error

Errors produced by the service when polling readiness or executing call.

+
source

type Future: Future<Output = Result<Self::Response, Self::Error>>

The future response value.

+

Required Methodsยง

source

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests.

+

If the service is at capacity, then Pending is returned and the task is notified when the +service becomes ready again. This function is expected to be called while on a task.

+

This is a best effort implementation. False positives are permitted. It is permitted for +the service to return Ready from a poll_ready call and the next invocation of call +results in an error.

+
ยงNotes
+
    +
  1. poll_ready might be called on a different task to call.
  2. +
  3. In cases of chained services, .poll_ready() is called for all services at once.
  4. +
+
source

fn call(&self, req: Req) -> Self::Future

Process the request and return the response asynchronously.

+

This function is expected to be callable off-task. As such, implementations of call should +take care to not call poll_ready. If the service is at capacity and the request is unable +to be handled, the returned Future should resolve to an error.

+

Invoking call without first invoking poll_ready is permitted. Implementations must be +resilient to this fact.

+

Implementations on Foreign Typesยง

sourceยง

impl<'a, S, Req> Service<Req> for &'a S
where + S: Service<Req> + 'a,

sourceยง

type Response = <S as Service<Req>>::Response

sourceยง

type Error = <S as Service<Req>>::Error

sourceยง

type Future = <S as Service<Req>>::Future

sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

sourceยง

fn call(&self, request: Req) -> S::Future

sourceยง

impl<'a, S, Req> Service<Req> for &'a mut S
where + S: Service<Req> + 'a,

sourceยง

type Response = <S as Service<Req>>::Response

sourceยง

type Error = <S as Service<Req>>::Error

sourceยง

type Future = <S as Service<Req>>::Future

sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

sourceยง

fn call(&self, request: Req) -> S::Future

sourceยง

impl<S, Req> Service<Req> for Box<S>
where + S: Service<Req> + ?Sized,

sourceยง

type Response = <S as Service<Req>>::Response

sourceยง

type Error = <S as Service<Req>>::Error

sourceยง

type Future = <S as Service<Req>>::Future

sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), S::Error>>

sourceยง

fn call(&self, request: Req) -> S::Future

sourceยง

impl<S, Req> Service<Req> for Rc<S>
where + S: Service<Req> + ?Sized,

sourceยง

type Response = <S as Service<Req>>::Response

sourceยง

type Error = <S as Service<Req>>::Error

sourceยง

type Future = <S as Service<Req>>::Future

sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

sourceยง

fn call(&self, request: Req) -> S::Future

sourceยง

impl<S, Req> Service<Req> for RefCell<S>
where + S: Service<Req>,

This impl is deprecated since v2 because the Service trait now receives shared reference.

+
sourceยง

type Response = <S as Service<Req>>::Response

sourceยง

type Error = <S as Service<Req>>::Error

sourceยง

type Future = <S as Service<Req>>::Future

sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

sourceยง

fn call(&self, request: Req) -> S::Future

Implementorsยง

\ No newline at end of file diff --git a/actix_service/trait.ServiceExt.html b/actix_service/trait.ServiceExt.html new file mode 100644 index 00000000..34c1dafb --- /dev/null +++ b/actix_service/trait.ServiceExt.html @@ -0,0 +1,40 @@ +ServiceExt in actix_service - Rust
actix_service

Trait ServiceExt

source
pub trait ServiceExt<Req>: Service<Req> {
+    // Provided methods
+    fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
+       where Self: Sized,
+             F: FnMut(Self::Response) -> R { ... }
+    fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
+       where Self: Sized,
+             F: Fn(Self::Error) -> E { ... }
+    fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
+       where Self: Sized,
+             I: IntoService<S1, Self::Response>,
+             S1: Service<Self::Response, Error = Self::Error> { ... }
+}
Expand description

An extension trait for Services that provides a variety of convenient adapters.

+

Provided Methodsยง

source

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.

+

This function is similar to the Option::map or Iterator::map where +it will change the type of the underlying service.

+

Note that this function consumes the receiving service and returns a +wrapped version of it, similar to the existing map methods in the +standard library.

+
source

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service.

+

This function is similar to the Result::map_err where it will change +the error type of the underlying service. For example, this can be useful to +ensure that services have the same error type.

+

Note that this function consumes the receiving service and returns a +wrapped version of it.

+
source

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully.

+

This function can be used to chain two services together and ensure that the second service +isnโ€™t called until call to the first service have finished. Result of the call to the first +service is used as an input parameter for the second serviceโ€™s call.

+

Note that this function consumes the receiving service and returns a wrapped version of it.

+

Implementorsยง

sourceยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

\ No newline at end of file diff --git a/actix_service/trait.ServiceFactory.html b/actix_service/trait.ServiceFactory.html new file mode 100644 index 00000000..4fcc0818 --- /dev/null +++ b/actix_service/trait.ServiceFactory.html @@ -0,0 +1,34 @@ +ServiceFactory in actix_service - Rust
actix_service

Trait ServiceFactory

source
pub trait ServiceFactory<Req> {
+    type Response;
+    type Error;
+    type Config;
+    type Service: Service<Req, Response = Self::Response, Error = Self::Error>;
+    type InitError;
+    type Future: Future<Output = Result<Self::Service, Self::InitError>>;
+
+    // Required method
+    fn new_service(&self, cfg: Self::Config) -> Self::Future;
+}
Expand description

Factory for creating Services.

+

This is useful for cases where new Services must be produced. One case is a TCP +server listener: a listener accepts new connections, constructs a new Service for each using +the ServiceFactory trait, and uses the new Service to process inbound requests on that new +connection.

+

Config is a service factory configuration type.

+

Simple factories may be able to use fn_factory or fn_factory_with_config to +reduce boilerplate.

+

Required Associated Typesยง

source

type Response

Responses given by the created services.

+
source

type Error

Errors produced by the created services.

+
source

type Config

Service factory configuration.

+
source

type Service: Service<Req, Response = Self::Response, Error = Self::Error>

The kind of Service created by this factory.

+
source

type InitError

Errors potentially raised while building a service.

+
source

type Future: Future<Output = Result<Self::Service, Self::InitError>>

The future of the Service instance.g

+

Required Methodsยง

source

fn new_service(&self, cfg: Self::Config) -> Self::Future

Create and return a new service asynchronously.

+

Implementations on Foreign Typesยง

sourceยง

impl<S, Req> ServiceFactory<Req> for Rc<S>
where + S: ServiceFactory<Req>,

sourceยง

impl<S, Req> ServiceFactory<Req> for Arc<S>
where + S: ServiceFactory<Req>,

Implementorsยง

sourceยง

impl<C, Req, Res, Err, InitErr> ServiceFactory<Req> for BoxServiceFactory<C, Req, Res, Err, InitErr>
where + Req: 'static, + Res: 'static, + Err: 'static, + InitErr: 'static,

sourceยง

type Response = Res

sourceยง

type Error = Err

sourceยง

type Config = C

sourceยง

type Service = Box<dyn Service<Req, Error = Err, Response = Res, Future = Pin<Box<dyn Future<Output = Result<Res, Err>>>>>>

sourceยง

type InitError = InitErr

sourceยง

type Future = Pin<Box<dyn Future<Output = Result<<BoxServiceFactory<C, Req, Res, Err, InitErr> as ServiceFactory<Req>>::Service, InitErr>>>>

sourceยง

impl<T, S, Req> ServiceFactory<Req> for ApplyTransform<T, S, Req>
where + S: ServiceFactory<Req>, + T: Transform<S::Service, Req, InitError = S::InitError>,

sourceยง

type Response = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::Response

sourceยง

type Error = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::Error

sourceยง

type Config = <S as ServiceFactory<Req>>::Config

sourceยง

type Service = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::Transform

sourceยง

type InitError = <T as Transform<<S as ServiceFactory<Req>>::Service, Req>>::InitError

sourceยง

type Future = ApplyTransformFuture<T, S, Req>

\ No newline at end of file diff --git a/actix_service/trait.ServiceFactoryExt.html b/actix_service/trait.ServiceFactoryExt.html new file mode 100644 index 00000000..4d14be4a --- /dev/null +++ b/actix_service/trait.ServiceFactoryExt.html @@ -0,0 +1,37 @@ +ServiceFactoryExt in actix_service - Rust
actix_service

Trait ServiceFactoryExt

source
pub trait ServiceFactoryExt<Req>: ServiceFactory<Req> {
+    // Provided methods
+    fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
+       where Self: Sized,
+             F: FnMut(Self::Response) -> R + Clone { ... }
+    fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
+       where Self: Sized,
+             F: Fn(Self::Error) -> E + Clone { ... }
+    fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
+       where Self: Sized,
+             F: Fn(Self::InitError) -> E + Clone { ... }
+    fn and_then<I, SF1>(
+        self,
+        factory: I,
+    ) -> AndThenServiceFactory<Self, SF1, Req>
+       where Self: Sized,
+             Self::Config: Clone,
+             I: IntoServiceFactory<SF1, Self::Response>,
+             SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError> { ... }
+}
Expand description

An extension trait for ServiceFactorys that provides a variety of convenient adapters.

+

Provided Methodsยง

source

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.

+
source

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.

+
source

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.

+
source

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.

+

Implementorsยง

sourceยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

\ No newline at end of file diff --git a/actix_service/trait.Transform.html b/actix_service/trait.Transform.html new file mode 100644 index 00000000..9eda089d --- /dev/null +++ b/actix_service/trait.Transform.html @@ -0,0 +1,68 @@ +Transform in actix_service - Rust
actix_service

Trait Transform

source
pub trait Transform<S, Req> {
+    type Response;
+    type Error;
+    type Transform: Service<Req, Response = Self::Response, Error = Self::Error>;
+    type InitError;
+    type Future: Future<Output = Result<Self::Transform, Self::InitError>>;
+
+    // Required method
+    fn new_transform(&self, service: S) -> Self::Future;
+}
Expand description

Defines the interface of a service factory that wraps inner service during construction.

+

Transformers wrap an inner service and runs during inbound and/or outbound processing in the +service lifecycle. It may modify request and/or response.

+

For example, a timeout service wrapper:

+ +
โ“˜
pub struct Timeout<S> {
+    service: S,
+    timeout: Duration,
+}
+
+impl<S: Service<Req>, Req> Service<Req> for Timeout<S> {
+    type Response = S::Response;
+    type Error = TimeoutError<S::Error>;
+    type Future = TimeoutServiceResponse<S>;
+
+    actix_service::forward_ready!(service);
+
+    fn call(&self, req: Req) -> Self::Future {
+        TimeoutServiceResponse {
+            fut: self.service.call(req),
+            sleep: Sleep::new(clock::now() + self.timeout),
+        }
+    }
+}
+

This wrapper service is decoupled from the underlying service implementation and could be +applied to any service.

+

The Transform trait defines the interface of a service wrapper. Transform is often +implemented for middleware, defining how to construct a middleware Service. A Service that is +constructed by the factory takes the Service that follows it during execution as a parameter, +assuming ownership of the next Service.

+

A transform for the Timeout middleware could look like this:

+ +
โ“˜
pub struct TimeoutTransform {
+    timeout: Duration,
+}
+
+impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform {
+    type Response = S::Response;
+    type Error = TimeoutError<S::Error>;
+    type InitError = S::Error;
+    type Transform = Timeout<S>;
+    type Future = Ready<Result<Self::Transform, Self::InitError>>;
+
+    fn new_transform(&self, service: S) -> Self::Future {
+        ready(Ok(Timeout {
+            service,
+            timeout: self.timeout,
+        }))
+    }
+}
+

Required Associated Typesยง

source

type Response

Responses produced by the service.

+
source

type Error

Errors produced by the service.

+
source

type Transform: Service<Req, Response = Self::Response, Error = Self::Error>

The TransformService value created by this factory

+
source

type InitError

Errors produced while building a transform service.

+
source

type Future: Future<Output = Result<Self::Transform, Self::InitError>>

The future response value.

+

Required Methodsยง

source

fn new_transform(&self, service: S) -> Self::Future

Creates and returns a new Transform component, asynchronously

+

Implementations on Foreign Typesยง

sourceยง

impl<T, S, Req> Transform<S, Req> for Rc<T>
where + T: Transform<S, Req>,

sourceยง

type Response = <T as Transform<S, Req>>::Response

sourceยง

type Error = <T as Transform<S, Req>>::Error

sourceยง

type Transform = <T as Transform<S, Req>>::Transform

sourceยง

type InitError = <T as Transform<S, Req>>::InitError

sourceยง

type Future = <T as Transform<S, Req>>::Future

sourceยง

fn new_transform(&self, service: S) -> T::Future

sourceยง

impl<T, S, Req> Transform<S, Req> for Arc<T>
where + T: Transform<S, Req>,

sourceยง

type Response = <T as Transform<S, Req>>::Response

sourceยง

type Error = <T as Transform<S, Req>>::Error

sourceยง

type Transform = <T as Transform<S, Req>>::Transform

sourceยง

type InitError = <T as Transform<S, Req>>::InitError

sourceยง

type Future = <T as Transform<S, Req>>::Future

sourceยง

fn new_transform(&self, service: S) -> T::Future

Implementorsยง

\ No newline at end of file diff --git a/actix_service/trait.TransformExt.html b/actix_service/trait.TransformExt.html new file mode 100644 index 00000000..36fbd6af --- /dev/null +++ b/actix_service/trait.TransformExt.html @@ -0,0 +1,11 @@ +TransformExt in actix_service - Rust
actix_service

Trait TransformExt

source
pub trait TransformExt<S, Req>: Transform<S, Req> {
+    // Provided method
+    fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, Req, F, E>
+       where Self: Sized,
+             F: Fn(Self::InitError) -> E + Clone { ... }
+}
Expand description

An extension trait for Transforms that provides a variety of convenient adapters.

+

Provided Methodsยง

source

fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, Req, F, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Return a new Transform whose init error is mapped to to a different type.

+

Implementorsยง

sourceยง

impl<T, Req> TransformExt<T, Req> for T
where + T: Transform<T, Req>,

\ No newline at end of file diff --git a/actix_service/transform/fn.apply.html b/actix_service/transform/fn.apply.html new file mode 100644 index 00000000..d2820902 --- /dev/null +++ b/actix_service/transform/fn.apply.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/fn.apply.html...

+ + + \ No newline at end of file diff --git a/actix_service/transform/struct.ApplyTransform.html b/actix_service/transform/struct.ApplyTransform.html new file mode 100644 index 00000000..0b77d7d5 --- /dev/null +++ b/actix_service/transform/struct.ApplyTransform.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/struct.ApplyTransform.html...

+ + + \ No newline at end of file diff --git a/actix_service/transform/trait.Transform.html b/actix_service/transform/trait.Transform.html new file mode 100644 index 00000000..e5457e69 --- /dev/null +++ b/actix_service/transform/trait.Transform.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../actix_service/trait.Transform.html...

+ + + \ No newline at end of file diff --git a/actix_tls/accept/enum.TlsError.html b/actix_tls/accept/enum.TlsError.html new file mode 100644 index 00000000..71b11172 --- /dev/null +++ b/actix_tls/accept/enum.TlsError.html @@ -0,0 +1,45 @@ +TlsError in actix_tls::accept - Rust
actix_tls::accept

Enum TlsError

source
pub enum TlsError<TlsErr, SvcErr> {
+    Timeout,
+    Tls(TlsErr),
+    Service(SvcErr),
+}
Expand description

TLS handshake error, TLS timeout, or inner service error.

+

All TLS acceptors from this crate will return the SvcErr type parameter as Infallible, +which can be cast to your own service type, inferred or otherwise, using into_service_error.

+

Variantsยง

ยง

Timeout

TLS handshake has timed-out.

+
ยง

Tls(TlsErr)

Wraps TLS service errors.

+
ยง

Service(SvcErr)

Wraps service errors.

+

Implementationsยง

sourceยง

impl<TlsErr> TlsError<TlsErr, Infallible>

source

pub fn into_service_error<SvcErr>(self) -> TlsError<TlsErr, SvcErr>

Casts the infallible service error type returned from acceptors into callerโ€™s type.

+
ยงExamples
+
let a: TlsError<u32, Infallible> = TlsError::Tls(42);
+let _b: TlsError<u32, u64> = a.into_service_error();
+

Trait Implementationsยง

sourceยง

impl<TlsErr: Debug, SvcErr: Debug> Debug for TlsError<TlsErr, SvcErr>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<TlsErr, SvcErr> Display for TlsError<TlsErr, SvcErr>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<TlsErr, SvcErr> Error for TlsError<TlsErr, SvcErr>
where + TlsErr: Error + 'static, + SvcErr: Error + 'static,

sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementationsยง

ยง

impl<TlsErr, SvcErr> Freeze for TlsError<TlsErr, SvcErr>
where + TlsErr: Freeze, + SvcErr: Freeze,

ยง

impl<TlsErr, SvcErr> RefUnwindSafe for TlsError<TlsErr, SvcErr>
where + TlsErr: RefUnwindSafe, + SvcErr: RefUnwindSafe,

ยง

impl<TlsErr, SvcErr> Send for TlsError<TlsErr, SvcErr>
where + TlsErr: Send, + SvcErr: Send,

ยง

impl<TlsErr, SvcErr> Sync for TlsError<TlsErr, SvcErr>
where + TlsErr: Sync, + SvcErr: Sync,

ยง

impl<TlsErr, SvcErr> Unpin for TlsError<TlsErr, SvcErr>
where + TlsErr: Unpin, + SvcErr: Unpin,

ยง

impl<TlsErr, SvcErr> UnwindSafe for TlsError<TlsErr, SvcErr>
where + TlsErr: UnwindSafe, + SvcErr: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/fn.max_concurrent_tls_connect.html b/actix_tls/accept/fn.max_concurrent_tls_connect.html new file mode 100644 index 00000000..74644a2f --- /dev/null +++ b/actix_tls/accept/fn.max_concurrent_tls_connect.html @@ -0,0 +1,5 @@ +max_concurrent_tls_connect in actix_tls::accept - Rust
actix_tls::accept

Function max_concurrent_tls_connect

source
pub fn max_concurrent_tls_connect(num: usize)
Expand description

Sets the maximum per-worker concurrent TLS connection limit.

+

All listeners will stop accepting connections when this limit is reached. +It can be used to regulate the global TLS CPU usage.

+

By default, the connection limit is 256.

+
\ No newline at end of file diff --git a/actix_tls/accept/index.html b/actix_tls/accept/index.html new file mode 100644 index 00000000..ce2ae63e --- /dev/null +++ b/actix_tls/accept/index.html @@ -0,0 +1,2 @@ +actix_tls::accept - Rust
actix_tls

Module accept

source
Expand description

TLS connection acceptor services.

+

Modulesยง

  • native-tls based TLS connection acceptor service.
  • openssl based TLS acceptor service.
  • rustls v0.20 based TLS connection acceptor service.
  • rustls v0.21 based TLS connection acceptor service.
  • rustls v0.22 based TLS connection acceptor service.
  • rustls v0.23 based TLS connection acceptor service.

Enumsยง

  • TLS handshake error, TLS timeout, or inner service error.

Functionsยง

\ No newline at end of file diff --git a/actix_tls/accept/native_tls/index.html b/actix_tls/accept/native_tls/index.html new file mode 100644 index 00000000..0d13c452 --- /dev/null +++ b/actix_tls/accept/native_tls/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::native_tls - Rust
actix_tls::accept

Module native_tls

source
Expand description

native-tls based TLS connection acceptor service.

+

See Acceptor for main service factory docs.

+

Modulesยง

  • Re-exports from native-tls that are useful for acceptors.

Structsยง

  • Accept TLS connections via the native-tls crate.
  • Native-TLS based acceptor service.
  • Wraps a native-tls based async TLS stream in order to implement [ActixStream].
\ No newline at end of file diff --git a/actix_tls/accept/native_tls/reexports/index.html b/actix_tls/accept/native_tls/reexports/index.html new file mode 100644 index 00000000..7b600917 --- /dev/null +++ b/actix_tls/accept/native_tls/reexports/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::native_tls::reexports - Rust
actix_tls::accept::native_tls

Module reexports

source
Expand description

Re-exports from native-tls that are useful for acceptors.

+

Structsยง

  • An error returned from the TLS implementation.
  • A wrapper around a native_tls::TlsAcceptor, providing an async accept +method.
\ No newline at end of file diff --git a/actix_tls/accept/native_tls/reexports/sidebar-items.js b/actix_tls/accept/native_tls/reexports/sidebar-items.js new file mode 100644 index 00000000..f27cc92a --- /dev/null +++ b/actix_tls/accept/native_tls/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Error","TlsAcceptor"]}; \ No newline at end of file diff --git a/actix_tls/accept/native_tls/reexports/struct.Error.html b/actix_tls/accept/native_tls/reexports/struct.Error.html new file mode 100644 index 00000000..c30763b9 --- /dev/null +++ b/actix_tls/accept/native_tls/reexports/struct.Error.html @@ -0,0 +1,18 @@ +Error in actix_tls::accept::native_tls::reexports - Rust
actix_tls::accept::native_tls::reexports

Struct Error

pub struct Error(/* private fields */);
Expand description

An error returned from the TLS implementation.

+

Trait Implementationsยง

ยง

impl Debug for Error

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl Display for Error

ยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl Error for Error

ยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
ยง

impl From<Error> for Error

ยง

fn from(err: Error) -> Error

Converts to this type from the input type.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/native_tls/reexports/struct.TlsAcceptor.html b/actix_tls/accept/native_tls/reexports/struct.TlsAcceptor.html new file mode 100644 index 00000000..14ddc3aa --- /dev/null +++ b/actix_tls/accept/native_tls/reexports/struct.TlsAcceptor.html @@ -0,0 +1,29 @@ +TlsAcceptor in actix_tls::accept::native_tls::reexports - Rust
actix_tls::accept::native_tls::reexports

Struct TlsAcceptor

source
pub struct TlsAcceptor(/* private fields */);
Expand description

A wrapper around a native_tls::TlsAcceptor, providing an async accept +method.

+

Implementationsยง

sourceยง

impl TlsAcceptor

source

pub async fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, Error>
where + S: AsyncRead + AsyncWrite + Unpin,

Accepts a new client connection with the provided stream.

+

This function will internally call TlsAcceptor::accept to connect +the stream and returns a future representing the resolution of the +connection operation. The returned future will resolve to either +TlsStream<S> or Error depending if itโ€™s successful or not.

+

This is typically used after a new socket has been accepted from a +TcpListener. That socket is then passed to this function to perform +the server half of accepting a client connection.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsAcceptor

sourceยง

fn clone(&self) -> TlsAcceptor

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for TlsAcceptor

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl From<TlsAcceptor> for TlsAcceptor

sourceยง

fn from(inner: TlsAcceptor) -> TlsAcceptor

Converts to this type from the input type.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/native_tls/sidebar-items.js b/actix_tls/accept/native_tls/sidebar-items.js new file mode 100644 index 00000000..609abc9a --- /dev/null +++ b/actix_tls/accept/native_tls/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["Acceptor","AcceptorService","TlsStream"]}; \ No newline at end of file diff --git a/actix_tls/accept/native_tls/struct.Acceptor.html b/actix_tls/accept/native_tls/struct.Acceptor.html new file mode 100644 index 00000000..6b6aec10 --- /dev/null +++ b/actix_tls/accept/native_tls/struct.Acceptor.html @@ -0,0 +1,38 @@ +Acceptor in actix_tls::accept::native_tls - Rust
actix_tls::accept::native_tls

Struct Acceptor

source
pub struct Acceptor { /* private fields */ }
Expand description

Accept TLS connections via the native-tls crate.

+

Implementationsยง

sourceยง

impl Acceptor

source

pub fn new(acceptor: TlsAcceptor) -> Self

Constructs native-tls based acceptor service factory.

+
source

pub fn set_handshake_timeout( + &mut self, + handshake_timeout: Duration, +) -> &mut Self

Limit the amount of time that the acceptor will wait for a TLS handshake to complete.

+

Default timeout is 3 seconds.

+

Trait Implementationsยง

sourceยง

impl Clone for Acceptor

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<IO: ActixStream + 'static> ServiceFactory<IO> for Acceptor

sourceยง

type Response = TlsStream<IO>

Responses given by the created services.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = AcceptorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Acceptor as ServiceFactory<IO>>::Service, <Acceptor as ServiceFactory<IO>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/native_tls/struct.AcceptorService.html b/actix_tls/accept/native_tls/struct.AcceptorService.html new file mode 100644 index 00000000..55182088 --- /dev/null +++ b/actix_tls/accept/native_tls/struct.AcceptorService.html @@ -0,0 +1,27 @@ +AcceptorService in actix_tls::accept::native_tls - Rust
actix_tls::accept::native_tls

Struct AcceptorService

source
pub struct AcceptorService { /* private fields */ }
Expand description

Native-TLS based acceptor service.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream + 'static> Service<IO> for AcceptorService

sourceยง

type Response = TlsStream<IO>

Responses given by the service.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = Pin<Box<dyn Future<Output = Result<<AcceptorService as Service<IO>>::Response, <AcceptorService as Service<IO>>::Error>>>>

The future response value.
sourceยง

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, io: IO) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/native_tls/struct.TlsStream.html b/actix_tls/accept/native_tls/struct.TlsStream.html new file mode 100644 index 00000000..b5ee666f --- /dev/null +++ b/actix_tls/accept/native_tls/struct.TlsStream.html @@ -0,0 +1,39 @@ +TlsStream in actix_tls::accept::native_tls - Rust
actix_tls::accept::native_tls

Struct TlsStream

source
pub struct TlsStream<IO>(/* private fields */);
Expand description

Wraps a native-tls based async TLS stream in order to implement [ActixStream].

+

Methods from Deref<Target = TlsStream<IO>>ยง

source

pub fn get_ref(&self) -> &TlsStream<AllowStd<S>>

Returns a shared reference to the inner stream.

+
source

pub fn get_mut(&mut self) -> &mut TlsStream<AllowStd<S>>

Returns a mutable reference to the inner stream.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> AsyncRead for TlsStream<IO>

sourceยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<IO: ActixStream> AsyncWrite for TlsStream<IO>

sourceยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
sourceยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize>>

Like poll_write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<IO> Deref for TlsStream<IO>

sourceยง

type Target = TlsStream<IO>

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<IO> DerefMut for TlsStream<IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<IO> From<TlsStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: TlsStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>

ยง

impl<IO> RefUnwindSafe for TlsStream<IO>
where + IO: RefUnwindSafe,

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> UnwindSafe for TlsStream<IO>
where + IO: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/index.html b/actix_tls/accept/openssl/index.html new file mode 100644 index 00000000..f8b3a22e --- /dev/null +++ b/actix_tls/accept/openssl/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::openssl - Rust
actix_tls::accept

Module openssl

source
Expand description

openssl based TLS acceptor service.

+

See Acceptor for main service factory docs.

+

Modulesยง

  • Re-exports from openssl that are useful for acceptors.

Structsยง

  • Accept TLS connections via the openssl crate.
  • OpenSSL based acceptor service.
  • Wraps an openssl based async TLS stream in order to implement [ActixStream].
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/enum.HandshakeError.html b/actix_tls/accept/openssl/reexports/enum.HandshakeError.html new file mode 100644 index 00000000..f655b2df --- /dev/null +++ b/actix_tls/accept/openssl/reexports/enum.HandshakeError.html @@ -0,0 +1,32 @@ +HandshakeError in actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl::reexports

Enum HandshakeError

source
pub enum HandshakeError<S> {
+    SetupFailure(ErrorStack),
+    Failure(MidHandshakeSslStream<S>),
+    WouldBlock(MidHandshakeSslStream<S>),
+}
Expand description

An error or intermediate state after a TLS handshake attempt.

+

Variantsยง

ยง

SetupFailure(ErrorStack)

Setup failed.

+
ยง

Failure(MidHandshakeSslStream<S>)

The handshake failed.

+
ยง

WouldBlock(MidHandshakeSslStream<S>)

The handshake encountered a WouldBlock error midway through.

+

This error will never be returned for blocking streams.

+

Trait Implementationsยง

sourceยง

impl<S> Debug for HandshakeError<S>
where + S: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<S> Display for HandshakeError<S>
where + S: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<S> Error for HandshakeError<S>
where + S: Debug,

sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
sourceยง

impl<S> From<ErrorStack> for HandshakeError<S>

sourceยง

fn from(e: ErrorStack) -> HandshakeError<S>

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<S> Freeze for HandshakeError<S>

ยง

impl<S> !RefUnwindSafe for HandshakeError<S>

ยง

impl<S> Send for HandshakeError<S>
where + S: Send,

ยง

impl<S> Sync for HandshakeError<S>
where + S: Sync,

ยง

impl<S> Unpin for HandshakeError<S>
where + S: Unpin,

ยง

impl<S> !UnwindSafe for HandshakeError<S>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/index.html b/actix_tls/accept/openssl/reexports/index.html new file mode 100644 index 00000000..d4e28d0c --- /dev/null +++ b/actix_tls/accept/openssl/reexports/index.html @@ -0,0 +1,2 @@ +actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl

Module reexports

source
Expand description

Re-exports from openssl that are useful for acceptors.

+

Structsยง

Enumsยง

  • An error or intermediate state after a TLS handshake attempt.
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/sidebar-items.js b/actix_tls/accept/openssl/reexports/sidebar-items.js new file mode 100644 index 00000000..319753a1 --- /dev/null +++ b/actix_tls/accept/openssl/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["HandshakeError"],"struct":["AlpnError","Error","Ssl","SslAcceptor","SslAcceptorBuilder"]}; \ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/struct.AlpnError.html b/actix_tls/accept/openssl/reexports/struct.AlpnError.html new file mode 100644 index 00000000..defe142f --- /dev/null +++ b/actix_tls/accept/openssl/reexports/struct.AlpnError.html @@ -0,0 +1,24 @@ +AlpnError in actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl::reexports

Struct AlpnError

source
pub struct AlpnError(/* private fields */);
Expand description

An error returned from an ALPN selection callback.

+

Requires OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

Implementationsยง

sourceยง

impl AlpnError

source

pub const ALERT_FATAL: AlpnError = _

Terminate the handshake with a fatal alert.

+

Requires OpenSSL 1.1.0 or newer.

+
source

pub const NOACK: AlpnError = _

Do not select a protocol, but continue the handshake.

+

Trait Implementationsยง

sourceยง

impl Clone for AlpnError

sourceยง

fn clone(&self) -> AlpnError

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for AlpnError

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl PartialEq for AlpnError

sourceยง

fn eq(&self, other: &AlpnError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
sourceยง

impl Copy for AlpnError

sourceยง

impl Eq for AlpnError

sourceยง

impl StructuralPartialEq for AlpnError

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/struct.Error.html b/actix_tls/accept/openssl/reexports/struct.Error.html new file mode 100644 index 00000000..a90f029d --- /dev/null +++ b/actix_tls/accept/openssl/reexports/struct.Error.html @@ -0,0 +1,18 @@ +Error in actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl::reexports

Struct Error

source
pub struct Error { /* private fields */ }
Expand description

An SSL error.

+

Implementationsยง

sourceยง

impl Error

source

pub fn code(&self) -> ErrorCode

source

pub fn io_error(&self) -> Option<&Error>

source

pub fn into_io_error(self) -> Result<Error, Error>

source

pub fn ssl_error(&self) -> Option<&ErrorStack>

Trait Implementationsยง

sourceยง

impl Debug for Error

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl Display for Error

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl Error for Error

sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
sourceยง

impl From<ErrorStack> for Error

sourceยง

fn from(e: ErrorStack) -> Error

Converts to this type from the input type.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/struct.Ssl.html b/actix_tls/accept/openssl/reexports/struct.Ssl.html new file mode 100644 index 00000000..1f26d809 --- /dev/null +++ b/actix_tls/accept/openssl/reexports/struct.Ssl.html @@ -0,0 +1,330 @@ +Ssl in actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl::reexports

Struct Ssl

source
pub struct Ssl(/* private fields */);
Expand description

The state of an SSL/TLS session.

+

Ssl objects are created from an SslContext, which provides configuration defaults. +These defaults can be overridden on a per-Ssl basis, however.

+

Implementationsยง

sourceยง

impl Ssl

source

pub fn new_ex_index<T>() -> Result<Index<Ssl, T>, ErrorStack>
where + T: 'static + Sync + Send,

Returns a new extra data index.

+

Each invocation of this function is guaranteed to return a distinct index. These can be used +to store data in the context that can be retrieved later by callbacks, for example.

+

This corresponds to SSL_get_ex_new_index.

+
source

pub fn new(ctx: &SslContextRef) -> Result<Ssl, ErrorStack>

Creates a new Ssl.

+

This corresponds to SSL_new.

+

This corresponds to SSL_new.

+
source

pub fn connect<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
where + S: Read + Write,

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.

+

This corresponds to SSL_connect.

+
source

pub fn accept<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
where + S: Read + Write,

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.

+

This corresponds to SSL_accept.

+

Methods from Deref<Target = SslRef>ยง

source

pub fn set_connect_state(&mut self)

Configure as an outgoing stream from a client.

+

This corresponds to SSL_set_connect_state.

+
source

pub fn set_accept_state(&mut self)

Configure as an incoming stream to a server.

+

This corresponds to SSL_set_accept_state.

+
source

pub fn set_verify(&mut self, mode: SslVerifyMode)

Like SslContextBuilder::set_verify.

+

This corresponds to SSL_set_verify.

+
source

pub fn verify_mode(&self) -> SslVerifyMode

Returns the verify mode that was set using set_verify.

+

This corresponds to SSL_set_verify_mode.

+
source

pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,

source

pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack>

Like SslContextBuilder::set_tmp_dh.

+

This corresponds to SSL_set_tmp_dh.

+
source

pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,

source

pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack>

source

pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack>

Like SslContextBuilder::set_alpn_protos.

+

Requires BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_set_alpn_protos.

+
source

pub fn current_cipher(&self) -> Option<&SslCipherRef>

Returns the current cipher if the session is active.

+

This corresponds to SSL_get_current_cipher.

+
source

pub fn state_string(&self) -> &'static str

Returns a short string describing the state of the session.

+

This corresponds to SSL_state_string.

+
source

pub fn state_string_long(&self) -> &'static str

Returns a longer string describing the state of the session.

+

This corresponds to SSL_state_string_long.

+
source

pub fn set_hostname(&mut self, hostname: &str) -> Result<(), ErrorStack>

Sets the host name to be sent to the server for Server Name Indication (SNI).

+

It has no effect for a server-side connection.

+

This corresponds to SSL_set_tlsext_host_name.

+
source

pub fn peer_certificate(&self) -> Option<X509>

Returns the peerโ€™s certificate, if present.

+

This corresponds to SSL_get_peer_certificate.

+
source

pub fn peer_cert_chain(&self) -> Option<&StackRef<X509>>

Returns the certificate chain of the peer, if present.

+

On the client side, the chain includes the leaf certificate, but on the server side it does +not. Fun!

+

This corresponds to SSL_get_peer_cert_chain.

+
source

pub fn verified_chain(&self) -> Option<&StackRef<X509>>

Returns the verified certificate chain of the peer, including the leaf certificate.

+

If verification was not successful (i.e. verify_result does not return +X509VerifyResult::OK), this chain may be incomplete or invalid.

+

Requires OpenSSL 1.1.0 or newer.

+

This corresponds to SSL_get0_verified_chain.

+
source

pub fn certificate(&self) -> Option<&X509Ref>

Like [SslContext::certificate].

+

This corresponds to SSL_get_certificate.

+
source

pub fn private_key(&self) -> Option<&PKeyRef<Private>>

Like SslContext::private_key.

+

This corresponds to SSL_get_privatekey.

+
source

pub fn version(&self) -> &str

๐Ÿ‘ŽDeprecated since 0.10.5: renamed to version_str
source

pub fn version2(&self) -> Option<SslVersion>

Returns the protocol version of the session.

+

This corresponds to SSL_version.

+
source

pub fn version_str(&self) -> &'static str

Returns a string describing the protocol version of the session.

+

This corresponds to SSL_get_version.

+
source

pub fn selected_alpn_protocol(&self) -> Option<&[u8]>

Returns the protocol selected via Application Layer Protocol Negotiation (ALPN).

+

The protocolโ€™s name is returned is an opaque sequence of bytes. It is up to the client +to interpret it.

+

Requires BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_get0_alpn_selected.

+
source

pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack>

Enables the DTLS extension โ€œuse_srtpโ€ as defined in RFC5764.

+

This corresponds to SSL_set_tlsext_use_srtp.

+

This corresponds to SSL_set_tlsext_use_srtp.

+
source

pub fn srtp_profiles(&self) -> Option<&StackRef<SrtpProtectionProfile>>

Gets all SRTP profiles that are enabled for handshake via set_tlsext_use_srtp

+

DTLS extension โ€œuse_srtpโ€ as defined in RFC5764 has to be enabled.

+

This corresponds to SSL_get_srtp_profiles.

+

This corresponds to SSL_get_srtp_profiles.

+
source

pub fn selected_srtp_profile(&self) -> Option<&SrtpProtectionProfileRef>

Gets the SRTP profile selected by handshake.

+

DTLS extension โ€œuse_srtpโ€ as defined in RFC5764 has to be enabled.

+

This corresponds to SSL_get_selected_srtp_profile.

+
source

pub fn pending(&self) -> usize

Returns the number of bytes remaining in the currently processed TLS record.

+

If this is greater than 0, the next call to read will not call down to the underlying +stream.

+

This corresponds to SSL_pending.

+
source

pub fn servername(&self, type_: NameType) -> Option<&str>

Returns the servername sent by the client via Server Name Indication (SNI).

+

It is only useful on the server side.

+
ยงNote
+

While the SNI specification requires that servernames be valid domain names (and therefore +ASCII), OpenSSL does not enforce this restriction. If the servername provided by the client +is not valid UTF-8, this function will return None. The servername_raw method returns +the raw bytes and does not have this restriction.

+

This corresponds to SSL_get_servername.

+
source

pub fn servername_raw(&self, type_: NameType) -> Option<&[u8]>

Returns the servername sent by the client via Server Name Indication (SNI).

+

It is only useful on the server side.

+
ยงNote
+

Unlike servername, this method does not require the name be valid UTF-8.

+

This corresponds to SSL_get_servername.

+
source

pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack>

Changes the context corresponding to the current connection.

+

It is most commonly used in the Server Name Indication (SNI) callback.

+

This corresponds to SSL_set_SSL_CTX.

+
source

pub fn ssl_context(&self) -> &SslContextRef

Returns the context corresponding to the current connection.

+

This corresponds to SSL_get_SSL_CTX.

+
source

pub fn param_mut(&mut self) -> &mut X509VerifyParamRef

Returns a mutable reference to the X509 verification configuration.

+

Requires BoringSSL or OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_get0_param.

+
source

pub fn verify_result(&self) -> X509VerifyResult

Returns the certificate verification result.

+

This corresponds to SSL_get_verify_result.

+
source

pub fn session(&self) -> Option<&SslSessionRef>

Returns a shared reference to the SSL session.

+

This corresponds to SSL_get_session.

+
source

pub fn client_random(&self, buf: &mut [u8]) -> usize

Copies the client_random value sent by the client in the TLS handshake into a buffer.

+

Returns the number of bytes copied, or if the buffer is empty, the size of the client_random +value.

+

Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.

+

This corresponds to SSL_get_client_random.

+
source

pub fn server_random(&self, buf: &mut [u8]) -> usize

Copies the server_random value sent by the server in the TLS handshake into a buffer.

+

Returns the number of bytes copied, or if the buffer is empty, the size of the server_random +value.

+

Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.

+

This corresponds to SSL_get_server_random.

+
source

pub fn export_keying_material( + &self, + out: &mut [u8], + label: &str, + context: Option<&[u8]>, +) -> Result<(), ErrorStack>

Derives keying material for application use in accordance to RFC 5705.

+

This corresponds to SSL_export_keying_material.

+
source

pub fn export_keying_material_early( + &self, + out: &mut [u8], + label: &str, + context: &[u8], +) -> Result<(), ErrorStack>

Derives keying material for application use in accordance to RFC 5705.

+

This function is only usable with TLSv1.3, wherein there is no distinction between an empty context and no +context. Therefore, unlike export_keying_material, context must always be supplied.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_export_keying_material_early.

+
source

pub unsafe fn set_session( + &mut self, + session: &SslSessionRef, +) -> Result<(), ErrorStack>

Sets the session to be used.

+

This should be called before the handshake to attempt to reuse a previously established +session. If the server is not willing to reuse the session, a new one will be transparently +negotiated.

+
ยงSafety
+

The caller of this method is responsible for ensuring that the session is associated +with the same SslContext as this Ssl.

+

This corresponds to SSL_set_session.

+
source

pub fn session_reused(&self) -> bool

Determines if the session provided to set_session was successfully reused.

+

This corresponds to SSL_session_reused.

+
source

pub fn set_status_type(&mut self, type_: StatusType) -> Result<(), ErrorStack>

Sets the status response a client wishes the server to reply with.

+

This corresponds to SSL_set_tlsext_status_type.

+
source

pub fn extms_support(&self) -> Option<bool>

Determines if current session used Extended Master Secret

+

Returns None if the handshake is still in-progress.

+

This corresponds to SSL_get_extms_support.

+
source

pub fn ocsp_status(&self) -> Option<&[u8]>

Returns the serverโ€™s OCSP response, if present.

+

This corresponds to SSL_get_tlsext_status_ocsp_resp.

+
source

pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack>

Sets the OCSP response to be returned to the client.

+

This corresponds to SSL_set_tlsext_status_oscp_resp.

+
source

pub fn is_server(&self) -> bool

Determines if this Ssl is configured for server-side or client-side use.

+

This corresponds to SSL_is_server.

+
source

pub fn set_ex_data<T>(&mut self, index: Index<Ssl, T>, data: T)

Sets the extra data at the specified index.

+

This can be used to provide data to callbacks registered with the context. Use the +Ssl::new_ex_index method to create an Index.

+

This corresponds to SSL_set_ex_data.

+
source

pub fn ex_data<T>(&self, index: Index<Ssl, T>) -> Option<&T>

Returns a reference to the extra data at the specified index.

+

This corresponds to SSL_get_ex_data.

+
source

pub fn ex_data_mut<T>(&mut self, index: Index<Ssl, T>) -> Option<&mut T>

Returns a mutable reference to the extra data at the specified index.

+

This corresponds to SSL_get_ex_data.

+
source

pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack>

Sets the maximum amount of early data that will be accepted on this connection.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_set_max_early_data.

+
source

pub fn max_early_data(&self) -> u32

Gets the maximum amount of early data that can be sent on this connection.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_get_max_early_data.

+
source

pub fn finished(&self, buf: &mut [u8]) -> usize

Copies the contents of the last Finished message sent to the peer into the provided buffer.

+

The total size of the message is returned, so this can be used to determine the size of the +buffer required.

+

This corresponds to SSL_get_finished.

+
source

pub fn peer_finished(&self, buf: &mut [u8]) -> usize

Copies the contents of the last Finished message received from the peer into the provided +buffer.

+

The total size of the message is returned, so this can be used to determine the size of the +buffer required.

+

This corresponds to SSL_get_peer_finished.

+
source

pub fn is_init_finished(&self) -> bool

Determines if the initial handshake has been completed.

+

This corresponds to SSL_is_init_finished.

+
source

pub fn client_hello_isv2(&self) -> bool

Determines if the clientโ€™s hello message is in the SSLv2 format.

+

This can only be used inside of the client hello callback. Otherwise, false is returned.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_client_hello_isv2.

+
source

pub fn client_hello_legacy_version(&self) -> Option<SslVersion>

Returns the legacy version field of the clientโ€™s hello message.

+

This can only be used inside of the client hello callback. Otherwise, None is returned.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_client_hello_get0_legacy_version.

+
source

pub fn client_hello_random(&self) -> Option<&[u8]>

Returns the random field of the clientโ€™s hello message.

+

This can only be used inside of the client hello callback. Otherwise, None is returned.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_client_hello_get0_random.

+
source

pub fn client_hello_session_id(&self) -> Option<&[u8]>

Returns the session ID field of the clientโ€™s hello message.

+

This can only be used inside of the client hello callback. Otherwise, None is returned.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_client_hello_get0_session_id.

+
source

pub fn client_hello_ciphers(&self) -> Option<&[u8]>

Returns the ciphers field of the clientโ€™s hello message.

+

This can only be used inside of the client hello callback. Otherwise, None is returned.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_client_hello_get0_ciphers.

+
source

pub fn bytes_to_cipher_list( + &self, + bytes: &[u8], + isv2format: bool, +) -> Result<CipherLists, ErrorStack>

Decodes a slice of wire-format cipher suite specification bytes. Unsupported cipher suites +are ignored.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_bytes_to_cipher_list.

+
source

pub fn client_hello_compression_methods(&self) -> Option<&[u8]>

Returns the compression methods field of the clientโ€™s hello message.

+

This can only be used inside of the client hello callback. Otherwise, None is returned.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_client_hello_get0_compression_methods.

+
source

pub fn set_mtu(&mut self, mtu: u32) -> Result<(), ErrorStack>

Sets the MTU used for DTLS connections.

+

This corresponds to SSL_set_mtu.

+
source

pub fn psk_identity_hint(&self) -> Option<&[u8]>

Returns the PSK identity hint used during connection setup.

+

May return None if no PSK identity hint was used during the connection setup.

+

This corresponds to SSL_get_psk_identity_hint.

+
source

pub fn psk_identity(&self) -> Option<&[u8]>

Returns the PSK identity used during connection setup.

+

This corresponds to SSL_get_psk_identity.

+
source

pub fn add_chain_cert(&mut self, chain: X509) -> Result<(), ErrorStack>

This corresponds to SSL_add0_chain_cert.

+
source

pub fn set_method(&mut self, method: SslMethod) -> Result<(), ErrorStack>

Sets a new default TLS/SSL method for SSL objects

+
source

pub fn set_private_key_file<P>( + &mut self, + path: P, + ssl_file_type: SslFiletype, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads the private key from a file.

+

This corresponds to SSL_use_Private_Key_file.

+
source

pub fn set_private_key( + &mut self, + pkey: &PKeyRef<Private>, +) -> Result<(), ErrorStack>

Sets the private key.

+

This corresponds to SSL_use_PrivateKey.

+
source

pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack>

Sets the certificate

+

This corresponds to SSL_use_certificate.

+
source

pub fn set_certificate_chain_file<P>( + &mut self, + path: P, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads a certificate chain from a file.

+

The file should contain a sequence of PEM-formatted certificates, the first being the leaf +certificate, and the remainder forming the chain of certificates up to and including the +trusted root certificate.

+

This corresponds to SSL_use_certificate_chain_file.

+
source

pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack>

Sets ca certificate that client trusted

+

This corresponds to SSL_add_client_CA.

+
source

pub fn set_client_ca_list(&mut self, list: Stack<X509Name>)

This corresponds to SSL_set_client_CA_list.

+
source

pub fn set_min_proto_version( + &mut self, + version: Option<SslVersion>, +) -> Result<(), ErrorStack>

Sets the minimum supported protocol version.

+

A value of None will enable protocol versions down to the lowest version supported by +OpenSSL.

+

Requires BoringSSL or OpenSSL 1.1.0 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_set_min_proto_version.

+
source

pub fn set_max_proto_version( + &mut self, + version: Option<SslVersion>, +) -> Result<(), ErrorStack>

Sets the maximum supported protocol version.

+

A value of None will enable protocol versions up to the highest version supported by +OpenSSL.

+

Requires BoringSSL or OpenSSL 1.1.0 or or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_set_max_proto_version.

+
source

pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack>

Sets the list of supported ciphers for the TLSv1.3 protocol.

+

The set_cipher_list method controls the cipher suites for protocols before TLSv1.3.

+

The format consists of TLSv1.3 cipher suite names separated by : characters in order of +preference.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_set_ciphersuites.

+
source

pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack>

Sets the list of supported ciphers for protocols before TLSv1.3.

+

The set_ciphersuites method controls the cipher suites for TLSv1.3.

+

See ciphers for details on the format.

+

This corresponds to SSL_set_cipher_list.

+
source

pub fn set_verify_cert_store( + &mut self, + cert_store: X509Store, +) -> Result<(), ErrorStack>

Set the certificate store used for certificate verification

+

This corresponds to SSL_set_cert_store.

+
source

pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack>

Sets the number of TLS 1.3 session tickets that will be sent to a client after a full +handshake.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_set_num_tickets.

+
source

pub fn num_tickets(&self) -> usize

Gets the number of TLS 1.3 session tickets that will be sent to a client after a full +handshake.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_get_num_tickets.

+
source

pub fn set_security_level(&mut self, level: u32)

Set the contextโ€™s security level to a value between 0 and 5, inclusive. +A security value of 0 allows allows all parameters and algorithms.

+

Requires OpenSSL 1.1.0 or newer.

+

This corresponds to SSL_set_security_level.

+
source

pub fn security_level(&self) -> u32

Get the connectionโ€™s security level, which controls the allowed parameters +and algorithms.

+

Requires OpenSSL 1.1.0 or newer.

+

This corresponds to SSL_get_security_level.

+
source

pub fn peer_tmp_key(&self) -> Result<PKey<Public>, ErrorStack>

Get the temporary key provided by the peer that is used during key +exchange.

+

This corresponds to SSL_get_peer_tmp_key.

+
source

pub fn tmp_key(&self) -> Result<PKey<Private>, ErrorStack>

Returns the temporary key from the local end of the connection that is +used during key exchange.

+

This corresponds to SSL_get_tmp_key.

+

Trait Implementationsยง

sourceยง

impl AsRef<SslRef> for Ssl

sourceยง

fn as_ref(&self) -> &SslRef

Converts this type into a shared reference of the (usually inferred) input type.
sourceยง

impl Borrow<SslRef> for Ssl

sourceยง

fn borrow(&self) -> &SslRef

Immutably borrows from an owned value. Read more
sourceยง

impl Debug for Ssl

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl Deref for Ssl

sourceยง

type Target = SslRef

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &SslRef

Dereferences the value.
sourceยง

impl DerefMut for Ssl

sourceยง

fn deref_mut(&mut self) -> &mut SslRef

Mutably dereferences the value.
sourceยง

impl Drop for Ssl

sourceยง

fn drop(&mut self)

Executes the destructor for this type. Read more
sourceยง

impl ForeignType for Ssl

sourceยง

type CType = SSL

The raw C type.
sourceยง

type Ref = SslRef

The type representing a reference to this type.
sourceยง

unsafe fn from_ptr(ptr: *mut SSL) -> Ssl

Constructs an instance of this type from its raw type.
sourceยง

fn as_ptr(&self) -> *mut SSL

Returns a raw pointer to the wrapped value.
sourceยง

impl Send for Ssl

sourceยง

impl Sync for Ssl

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/struct.SslAcceptor.html b/actix_tls/accept/openssl/reexports/struct.SslAcceptor.html new file mode 100644 index 00000000..09c1f45e --- /dev/null +++ b/actix_tls/accept/openssl/reexports/struct.SslAcceptor.html @@ -0,0 +1,48 @@ +SslAcceptor in actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl::reexports

Struct SslAcceptor

source
pub struct SslAcceptor(/* private fields */);
Expand description

A type which wraps server-side streams in a TLS session.

+

OpenSSLโ€™s default configuration is highly insecure. This connector manages the OpenSSL +structures, configuring cipher suites, session options, and more.

+

Implementationsยง

sourceยง

impl SslAcceptor

source

pub fn mozilla_intermediate_v5( + method: SslMethod, +) -> Result<SslAcceptorBuilder, ErrorStack>

Creates a new builder configured to connect to non-legacy clients. This should generally be +considered a reasonable default choice.

+

This corresponds to the intermediate configuration of version 5 of Mozillaโ€™s server side TLS +recommendations. See its documentation for more details on specifics.

+
source

pub fn mozilla_modern_v5( + method: SslMethod, +) -> Result<SslAcceptorBuilder, ErrorStack>

Creates a new builder configured to connect to modern clients.

+

This corresponds to the modern configuration of version 5 of Mozillaโ€™s server side TLS recommendations. +See its documentation for more details on specifics.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+
source

pub fn mozilla_intermediate( + method: SslMethod, +) -> Result<SslAcceptorBuilder, ErrorStack>

Creates a new builder configured to connect to non-legacy clients. This should generally be +considered a reasonable default choice.

+

This corresponds to the intermediate configuration of version 4 of Mozillaโ€™s server side TLS +recommendations. See its documentation for more details on specifics.

+
source

pub fn mozilla_modern( + method: SslMethod, +) -> Result<SslAcceptorBuilder, ErrorStack>

Creates a new builder configured to connect to modern clients.

+

This corresponds to the modern configuration of version 4 of Mozillaโ€™s server side TLS recommendations. +See its documentation for more details on specifics.

+
source

pub fn accept<S>(&self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
where + S: Read + Write,

Initiates a server-side TLS session on a stream.

+
source

pub fn into_context(self) -> SslContext

Consumes the SslAcceptor, returning the inner raw SslContext.

+
source

pub fn context(&self) -> &SslContextRef

Returns a shared reference to the inner raw SslContext.

+

Trait Implementationsยง

sourceยง

impl Clone for SslAcceptor

sourceยง

fn clone(&self) -> SslAcceptor

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/reexports/struct.SslAcceptorBuilder.html b/actix_tls/accept/openssl/reexports/struct.SslAcceptorBuilder.html new file mode 100644 index 00000000..ab72d0af --- /dev/null +++ b/actix_tls/accept/openssl/reexports/struct.SslAcceptorBuilder.html @@ -0,0 +1,326 @@ +SslAcceptorBuilder in actix_tls::accept::openssl::reexports - Rust
actix_tls::accept::openssl::reexports

Struct SslAcceptorBuilder

source
pub struct SslAcceptorBuilder(/* private fields */);
Expand description

A builder for SslAcceptors.

+

Implementationsยง

sourceยง

impl SslAcceptorBuilder

source

pub fn build(self) -> SslAcceptor

Consumes the builder, returning a SslAcceptor.

+

Methods from Deref<Target = SslContextBuilder>ยง

source

pub fn as_ptr(&self) -> *mut SSL_CTX

Returns a pointer to the raw OpenSSL value.

+
source

pub fn set_verify(&mut self, mode: SslVerifyMode)

Configures the certificate verification method for new connections.

+

This corresponds to SSL_CTX_set_verify.

+
source

pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,

Configures the certificate verification method for new connections and +registers a verification callback.

+

The callback is passed a boolean indicating if OpenSSLโ€™s internal verification succeeded as +well as a reference to the X509StoreContext which can be used to examine the certificate +chain. It should return a boolean indicating if verification succeeded.

+

This corresponds to SSL_CTX_set_verify.

+
source

pub fn set_servername_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,

Configures the server name indication (SNI) callback for new connections.

+

SNI is used to allow a single server to handle requests for multiple domains, each of which +has its own certificate chain and configuration.

+

Obtain the server name with the servername method and then set the corresponding context +with set_ssl_context

+

This corresponds to SSL_CTX_set_tlsext_servername_callback.

+
source

pub fn set_verify_depth(&mut self, depth: u32)

Sets the certificate verification depth.

+

If the peerโ€™s certificate chain is longer than this value, verification will fail.

+

This corresponds to SSL_CTX_set_verify_depth.

+
source

pub fn set_verify_cert_store( + &mut self, + cert_store: X509Store, +) -> Result<(), ErrorStack>

Sets a custom certificate store for verifying peer certificates.

+

Requires OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_set0_verify_cert_store.

+
source

pub fn set_cert_store(&mut self, cert_store: X509Store)

Replaces the contextโ€™s certificate store.

+

This corresponds to SSL_CTX_set_cert_store.

+
source

pub fn set_read_ahead(&mut self, read_ahead: bool)

Controls read ahead behavior.

+

If enabled, OpenSSL will read as much data as is available from the underlying stream, +instead of a single record at a time.

+

It has no effect when used with DTLS.

+

This corresponds to SSL_CTX_set_read_ahead.

+
source

pub fn set_mode(&mut self, mode: SslMode) -> SslMode

Sets the mode used by the context, returning the previous mode.

+

This corresponds to SSL_CTX_set_mode.

+
source

pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack>

Sets the parameters to be used during ephemeral Diffie-Hellman key exchange.

+

This corresponds to SSL_CTX_set_tmp_dh.

+
source

pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,

Sets the callback which will generate parameters to be used during ephemeral Diffie-Hellman +key exchange.

+

The callback is provided with a reference to the Ssl for the session, as well as a boolean +indicating if the selected cipher is export-grade, and the key length. The export and key +length options are archaic and should be ignored in almost all cases.

+

This corresponds to SSL_CTX_set_tmp_dh_callback.

+
source

pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack>

Sets the parameters to be used during ephemeral elliptic curve Diffie-Hellman key exchange.

+

This corresponds to SSL_CTX_set_tmp_ecdh.

+
source

pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack>

Use the default locations of trusted certificates for verification.

+

These locations are read from the SSL_CERT_FILE and SSL_CERT_DIR environment variables +if present, or defaults specified at OpenSSL build time otherwise.

+

This corresponds to SSL_CTX_set_default_verify_paths.

+
source

pub fn set_ca_file<P>(&mut self, file: P) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads trusted root certificates from a file.

+

The file should contain a sequence of PEM-formatted CA certificates.

+

This corresponds to SSL_CTX_load_verify_locations.

+
source

pub fn set_client_ca_list(&mut self, list: Stack<X509Name>)

Sets the list of CA names sent to the client.

+

The CA certificates must still be added to the trust root - they are not automatically set +as trusted by this method.

+

This corresponds to SSL_CTX_set_client_CA_list.

+
source

pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack>

Add the provided CA certificate to the list sent by the server to the client when +requesting client-side TLS authentication.

+

This corresponds to SSL_CTX_add_client_CA.

+
source

pub fn set_session_id_context( + &mut self, + sid_ctx: &[u8], +) -> Result<(), ErrorStack>

Set the context identifier for sessions.

+

This value identifies the serverโ€™s session cache to clients, telling them when theyโ€™re +able to reuse sessions. It should be set to a unique value per server, unless multiple +servers share a session cache.

+

This value should be set when using client certificates, or each request will fail its +handshake and need to be restarted.

+

This corresponds to SSL_CTX_set_session_id_context.

+
source

pub fn set_certificate_file<P>( + &mut self, + file: P, + file_type: SslFiletype, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads a leaf certificate from a file.

+

Only a single certificate will be loaded - use add_extra_chain_cert to add the remainder +of the certificate chain, or set_certificate_chain_file to load the entire chain from a +single file.

+

This corresponds to SSL_CTX_use_certificate_file.

+
source

pub fn set_certificate_chain_file<P>( + &mut self, + file: P, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads a certificate chain from a file.

+

The file should contain a sequence of PEM-formatted certificates, the first being the leaf +certificate, and the remainder forming the chain of certificates up to and including the +trusted root certificate.

+

This corresponds to SSL_CTX_use_certificate_chain_file.

+
source

pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack>

Sets the leaf certificate.

+

Use add_extra_chain_cert to add the remainder of the certificate chain.

+

This corresponds to SSL_CTX_use_certificate.

+
source

pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack>

Appends a certificate to the certificate chain.

+

This chain should contain all certificates necessary to go from the certificate specified by +set_certificate to a trusted root.

+

This corresponds to SSL_CTX_add_extra_chain_cert.

+
source

pub fn set_private_key_file<P>( + &mut self, + file: P, + file_type: SslFiletype, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads the private key from a file.

+

This corresponds to SSL_CTX_use_PrivateKey_file.

+
source

pub fn set_private_key<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
where + T: HasPrivate,

Sets the private key.

+

This corresponds to SSL_CTX_use_PrivateKey.

+
source

pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack>

Sets the list of supported ciphers for protocols before TLSv1.3.

+

The set_ciphersuites method controls the cipher suites for TLSv1.3.

+

See ciphers for details on the format.

+

This corresponds to SSL_CTX_set_cipher_list.

+
source

pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack>

Sets the list of supported ciphers for the TLSv1.3 protocol.

+

The set_cipher_list method controls the cipher suites for protocols before TLSv1.3.

+

The format consists of TLSv1.3 cipher suite names separated by : characters in order of +preference.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_CTX_set_ciphersuites.

+
source

pub fn set_options(&mut self, option: SslOptions) -> SslOptions

Sets the options used by the context, returning the old set.

+
ยงNote
+

This enables the specified options, but does not disable unspecified options. Use +clear_options for that.

+

This corresponds to SSL_CTX_set_options.

+
source

pub fn options(&self) -> SslOptions

Returns the options used by the context.

+

This corresponds to SSL_CTX_get_options.

+
source

pub fn clear_options(&mut self, option: SslOptions) -> SslOptions

Clears the options used by the context, returning the old set.

+

This corresponds to SSL_CTX_clear_options.

+
source

pub fn set_min_proto_version( + &mut self, + version: Option<SslVersion>, +) -> Result<(), ErrorStack>

Sets the minimum supported protocol version.

+

A value of None will enable protocol versions down to the lowest version supported by +OpenSSL.

+

Requires BoringSSL or OpenSSL 1.1.0 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_min_proto_version.

+
source

pub fn set_max_proto_version( + &mut self, + version: Option<SslVersion>, +) -> Result<(), ErrorStack>

Sets the maximum supported protocol version.

+

A value of None will enable protocol versions up to the highest version supported by +OpenSSL.

+

Requires BoringSSL or OpenSSL 1.1.0 or or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_max_proto_version.

+
source

pub fn min_proto_version(&mut self) -> Option<SslVersion>

Gets the minimum supported protocol version.

+

A value of None indicates that all versions down to the lowest version supported by +OpenSSL are enabled.

+

Requires OpenSSL 1.1.0g or LibreSSL 2.7.0 or newer.

+

This corresponds to SSL_CTX_get_min_proto_version.

+
source

pub fn max_proto_version(&mut self) -> Option<SslVersion>

Gets the maximum supported protocol version.

+

A value of None indicates that all versions up to the highest version supported by +OpenSSL are enabled.

+

Requires OpenSSL 1.1.0g or LibreSSL 2.7.0 or newer.

+

This corresponds to SSL_CTX_get_max_proto_version.

+
source

pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack>

Sets the protocols to sent to the server for Application Layer Protocol Negotiation (ALPN).

+

The input must be in ALPN โ€œwire formatโ€. It consists of a sequence of supported protocol +names prefixed by their byte length. For example, the protocol list consisting of spdy/1 +and http/1.1 is encoded as b"\x06spdy/1\x08http/1.1". The protocols are ordered by +preference.

+

Requires BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_alpn_protos.

+
source

pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack>

Enables the DTLS extension โ€œuse_srtpโ€ as defined in RFC5764.

+

This corresponds to SSL_CTX_set_tlsext_use_srtp.

+
source

pub fn set_alpn_select_callback<F>(&mut self, callback: F)
where + F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,

Sets the callback used by a server to select a protocol for Application Layer Protocol +Negotiation (ALPN).

+

The callback is provided with the clientโ€™s protocol list in ALPN wire format. See the +documentation for SslContextBuilder::set_alpn_protos for details. It should return one +of those protocols on success. The select_next_proto function implements the standard +protocol selection algorithm.

+

Requires OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_alpn_select_cb.

+
source

pub fn check_private_key(&self) -> Result<(), ErrorStack>

Checks for consistency between the private key and certificate.

+

This corresponds to SSL_CTX_check_private_key.

+
source

pub fn cert_store(&self) -> &X509StoreBuilderRef

Returns a shared reference to the contextโ€™s certificate store.

+

This corresponds to SSL_CTX_get_cert_store.

+
source

pub fn cert_store_mut(&mut self) -> &mut X509StoreBuilderRef

Returns a mutable reference to the contextโ€™s certificate store.

+

This corresponds to SSL_CTX_get_cert_store.

+
source

pub fn verify_param(&self) -> &X509VerifyParamRef

Returns a reference to the X509 verification configuration.

+

Requires BoringSSL or OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_get0_param.

+
source

pub fn verify_param_mut(&mut self) -> &mut X509VerifyParamRef

Returns a mutable reference to the X509 verification configuration.

+

Requires BoringSSL or OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_get0_param.

+
source

pub fn set_status_callback<F>(&mut self, callback: F) -> Result<(), ErrorStack>
where + F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,

Sets the callback dealing with OCSP stapling.

+

On the client side, this callback is responsible for validating the OCSP status response +returned by the server. The status may be retrieved with the SslRef::ocsp_status method. +A response of Ok(true) indicates that the OCSP status is valid, and a response of +Ok(false) indicates that the OCSP status is invalid and the handshake should be +terminated.

+

On the server side, this callback is responsible for setting the OCSP status response to be +returned to clients. The status may be set with the SslRef::set_ocsp_status method. A +response of Ok(true) indicates that the OCSP status should be returned to the client, and +Ok(false) indicates that the status should not be returned to the client.

+

This corresponds to SSL_CTX_set_tlsext_status_cb.

+
source

pub fn set_psk_client_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,

Sets the callback for providing an identity and pre-shared key for a TLS-PSK client.

+

The callback will be called with the SSL context, an identity hint if one was provided +by the server, a mutable slice for each of the identity and pre-shared key bytes. The +identity must be written as a null-terminated C string.

+

This corresponds to SSL_CTX_set_psk_client_callback.

+
source

pub fn set_psk_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,

๐Ÿ‘ŽDeprecated since 0.10.10: renamed to set_psk_client_callback
source

pub fn set_psk_server_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,

Sets the callback for providing an identity and pre-shared key for a TLS-PSK server.

+

The callback will be called with the SSL context, an identity provided by the client, +and, a mutable slice for the pre-shared key bytes. The callback returns the number of +bytes in the pre-shared key.

+

This corresponds to SSL_CTX_set_psk_server_callback.

+
source

pub fn set_new_session_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,

Sets the callback which is called when new sessions are negotiated.

+

This can be used by clients to implement session caching. While in TLSv1.2 the session is +available to access via SslRef::session immediately after the handshake completes, this +is not the case for TLSv1.3. There, a session is not generally available immediately, and +the server may provide multiple session tokens to the client over a single session. The new +session callback is a portable way to deal with both cases.

+

Note that session caching must be enabled for the callback to be invoked, and it defaults +off for clients. set_session_cache_mode controls that behavior.

+

This corresponds to SSL_CTX_sess_set_new_cb.

+
source

pub fn set_remove_session_callback<F>(&mut self, callback: F)
where + F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,

Sets the callback which is called when sessions are removed from the context.

+

Sessions can be removed because they have timed out or because they are considered faulty.

+

This corresponds to SSL_CTX_sess_set_remove_cb.

+
source

pub unsafe fn set_get_session_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,

Sets the callback which is called when a client proposed to resume a session but it was not +found in the internal cache.

+

The callback is passed a reference to the session ID provided by the client. It should +return the session corresponding to that ID if available. This is only used for servers, not +clients.

+
ยงSafety
+

The returned SslSession must not be associated with a different SslContext.

+

This corresponds to SSL_CTX_sess_set_get_cb.

+
source

pub fn set_keylog_callback<F>(&mut self, callback: F)
where + F: Fn(&SslRef, &str) + 'static + Sync + Send,

Sets the TLS key logging callback.

+

The callback is invoked whenever TLS key material is generated, and is passed a line of NSS +SSLKEYLOGFILE-formatted text. This can be used by tools like Wireshark to decrypt message +traffic. The line does not contain a trailing newline.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_set_keylog_callback.

+
source

pub fn set_session_cache_mode( + &mut self, + mode: SslSessionCacheMode, +) -> SslSessionCacheMode

Sets the session caching mode use for connections made with the context.

+

Returns the previous session caching mode.

+

This corresponds to SSL_CTX_set_session_cache_mode.

+

Sets the callback for generating an application cookie for TLS1.3 +stateless handshakes.

+

The callback will be called with the SSL context and a slice into which the cookie +should be written. The callback should return the number of bytes written.

+

This corresponds to SSL_CTX_set_stateless_cookie_generate_cb.

+

Sets the callback for verifying an application cookie for TLS1.3 +stateless handshakes.

+

The callback will be called with the SSL context and the cookie supplied by the +client. It should return true if and only if the cookie is valid.

+

Note that the OpenSSL implementation independently verifies the integrity of +application cookies using an HMAC before invoking the supplied callback.

+

This corresponds to SSL_CTX_set_stateless_cookie_verify_cb.

+

Sets the callback for generating a DTLSv1 cookie

+

The callback will be called with the SSL context and a slice into which the cookie +should be written. The callback should return the number of bytes written.

+

This corresponds to SSL_CTX_set_cookie_generate_cb.

+

Sets the callback for verifying a DTLSv1 cookie

+

The callback will be called with the SSL context and the cookie supplied by the +client. It should return true if and only if the cookie is valid.

+

This corresponds to SSL_CTX_set_cookie_verify_cb.

+
source

pub fn set_ex_data<T>(&mut self, index: Index<SslContext, T>, data: T)

Sets the extra data at the specified index.

+

This can be used to provide data to callbacks registered with the context. Use the +SslContext::new_ex_index method to create an Index.

+

This corresponds to SSL_CTX_set_ex_data.

+
source

pub fn add_custom_ext<AddFn, ParseFn, T>( + &mut self, + ext_type: u16, + context: ExtensionContext, + add_cb: AddFn, + parse_cb: ParseFn, +) -> Result<(), ErrorStack>
where + AddFn: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result<Option<T>, SslAlert> + 'static + Sync + Send, + T: AsRef<[u8]> + 'static + Sync + Send, + ParseFn: Fn(&mut SslRef, ExtensionContext, &[u8], Option<(usize, &X509Ref)>) -> Result<(), SslAlert> + 'static + Sync + Send,

Adds a custom extension for a TLS/DTLS client or server for all supported protocol versions.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_add_custom_ext.

+
source

pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack>

Sets the maximum amount of early data that will be accepted on incoming connections.

+

Defaults to 0.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_CTX_set_max_early_data.

+
source

pub fn set_client_hello_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, &mut SslAlert) -> Result<ClientHelloResponse, ErrorStack> + 'static + Sync + Send,

Sets a callback which will be invoked just after the clientโ€™s hello message is received.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_set_client_hello_cb.

+
source

pub fn set_session_cache_size(&mut self, size: i32) -> i64

Sets the contextโ€™s session cache size limit, returning the previous limit.

+

A value of 0 means that the cache size is unbounded.

+

This corresponds to SSL_CTX_sess_set_cache_size.

+
source

pub fn set_sigalgs_list(&mut self, sigalgs: &str) -> Result<(), ErrorStack>

Sets the contextโ€™s supported signature algorithms.

+

Requires OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_set1_sigalgs_list.

+
source

pub fn set_groups_list(&mut self, groups: &str) -> Result<(), ErrorStack>

Sets the contextโ€™s supported elliptic curve groups.

+

Requires BoringSSL or OpenSSL 1.1.1 or LibreSSL 2.5.1 or newer.

+

This corresponds to SSL_CTX_set1_groups_list.

+
source

pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack>

Sets the number of TLS 1.3 session tickets that will be sent to a client after a full +handshake.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_set_num_tickets.

+
source

pub fn set_security_level(&mut self, level: u32)

Set the contextโ€™s security level to a value between 0 and 5, inclusive. +A security value of 0 allows allows all parameters and algorithms.

+

Requires OpenSSL 1.1.0 or newer.

+

This corresponds to SSL_CTX_set_security_level.

+

Trait Implementationsยง

sourceยง

impl Deref for SslAcceptorBuilder

sourceยง

type Target = SslContextBuilder

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &SslContextBuilder

Dereferences the value.
sourceยง

impl DerefMut for SslAcceptorBuilder

sourceยง

fn deref_mut(&mut self) -> &mut SslContextBuilder

Mutably dereferences the value.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/sidebar-items.js b/actix_tls/accept/openssl/sidebar-items.js new file mode 100644 index 00000000..609abc9a --- /dev/null +++ b/actix_tls/accept/openssl/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["Acceptor","AcceptorService","TlsStream"]}; \ No newline at end of file diff --git a/actix_tls/accept/openssl/struct.Acceptor.html b/actix_tls/accept/openssl/struct.Acceptor.html new file mode 100644 index 00000000..6ccb2872 --- /dev/null +++ b/actix_tls/accept/openssl/struct.Acceptor.html @@ -0,0 +1,38 @@ +Acceptor in actix_tls::accept::openssl - Rust
actix_tls::accept::openssl

Struct Acceptor

source
pub struct Acceptor { /* private fields */ }
Expand description

Accept TLS connections via the openssl crate.

+

Implementationsยง

sourceยง

impl Acceptor

source

pub fn new(acceptor: SslAcceptor) -> Self

Create openssl based acceptor service factory.

+
source

pub fn set_handshake_timeout( + &mut self, + handshake_timeout: Duration, +) -> &mut Self

Limit the amount of time that the acceptor will wait for a TLS handshake to complete.

+

Default timeout is 3 seconds.

+

Trait Implementationsยง

sourceยง

impl Clone for Acceptor

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<IO: ActixStream> ServiceFactory<IO> for Acceptor

sourceยง

type Response = TlsStream<IO>

Responses given by the created services.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = AcceptorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Acceptor as ServiceFactory<IO>>::Service, <Acceptor as ServiceFactory<IO>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/struct.AcceptorService.html b/actix_tls/accept/openssl/struct.AcceptorService.html new file mode 100644 index 00000000..34367e5a --- /dev/null +++ b/actix_tls/accept/openssl/struct.AcceptorService.html @@ -0,0 +1,27 @@ +AcceptorService in actix_tls::accept::openssl - Rust
actix_tls::accept::openssl

Struct AcceptorService

source
pub struct AcceptorService { /* private fields */ }
Expand description

OpenSSL based acceptor service.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> Service<IO> for AcceptorService

sourceยง

type Response = TlsStream<IO>

Responses given by the service.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = AcceptFut<IO>

The future response value.
sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, io: IO) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/openssl/struct.TlsStream.html b/actix_tls/accept/openssl/struct.TlsStream.html new file mode 100644 index 00000000..b2d18506 --- /dev/null +++ b/actix_tls/accept/openssl/struct.TlsStream.html @@ -0,0 +1,83 @@ +TlsStream in actix_tls::accept::openssl - Rust
actix_tls::accept::openssl

Struct TlsStream

source
pub struct TlsStream<IO>(/* private fields */);
Expand description

Wraps an openssl based async TLS stream in order to implement [ActixStream].

+

Methods from Deref<Target = SslStream<IO>>ยง

pub fn poll_connect( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

pub async fn connect(self: Pin<&mut SslStream<S>>) -> Result<(), Error>

A convenience method wrapping poll_connect.

+

pub fn poll_accept( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

pub async fn accept(self: Pin<&mut SslStream<S>>) -> Result<(), Error>

A convenience method wrapping poll_accept.

+

pub fn poll_do_handshake( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

pub async fn do_handshake(self: Pin<&mut SslStream<S>>) -> Result<(), Error>

A convenience method wrapping poll_do_handshake.

+

pub fn poll_peek( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, + buf: &mut [u8], +) -> Poll<Result<usize, Error>>

pub async fn peek( + self: Pin<&mut SslStream<S>>, + buf: &mut [u8], +) -> Result<usize, Error>

A convenience method wrapping poll_peek.

+

pub fn poll_read_early_data( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, + buf: &mut [u8], +) -> Poll<Result<usize, Error>>

pub async fn read_early_data( + self: Pin<&mut SslStream<S>>, + buf: &mut [u8], +) -> Result<usize, Error>

A convenience method wrapping poll_read_early_data.

+

pub fn poll_write_early_data( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

pub async fn write_early_data( + self: Pin<&mut SslStream<S>>, + buf: &[u8], +) -> Result<usize, Error>

A convenience method wrapping poll_write_early_data.

+

pub fn ssl(&self) -> &SslRef

Returns a shared reference to the Ssl object associated with this stream.

+

pub fn get_ref(&self) -> &S

Returns a shared reference to the underlying stream.

+

pub fn get_mut(&mut self) -> &mut S

Returns a mutable reference to the underlying stream.

+

pub fn get_pin_mut(self: Pin<&mut SslStream<S>>) -> Pin<&mut S>

Returns a pinned mutable reference to the underlying stream.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> AsyncRead for TlsStream<IO>

sourceยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<IO: ActixStream> AsyncWrite for TlsStream<IO>

sourceยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
sourceยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize>>

Like poll_write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<IO> Deref for TlsStream<IO>

sourceยง

type Target = SslStream<IO>

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<IO> DerefMut for TlsStream<IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<IO> From<SslStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: SslStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>

ยง

impl<IO> RefUnwindSafe for TlsStream<IO>
where + IO: RefUnwindSafe,

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> UnwindSafe for TlsStream<IO>
where + IO: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/index.html b/actix_tls/accept/rustls_0_20/index.html new file mode 100644 index 00000000..2ece8553 --- /dev/null +++ b/actix_tls/accept/rustls_0_20/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::rustls_0_20 - Rust
actix_tls::accept

Module rustls_0_20

source
Expand description

rustls v0.20 based TLS connection acceptor service.

+

See Acceptor for main service factory docs.

+

Modulesยง

  • Re-exports from rustls that are useful for acceptors.

Structsยง

  • Accept TLS connections via the rustls crate.
  • Rustls based acceptor service.
  • Wraps a rustls based async TLS stream in order to implement [ActixStream].
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/reexports/index.html b/actix_tls/accept/rustls_0_20/reexports/index.html new file mode 100644 index 00000000..f061b746 --- /dev/null +++ b/actix_tls/accept/rustls_0_20/reexports/index.html @@ -0,0 +1,2 @@ +actix_tls::accept::rustls_0_20::reexports - Rust
actix_tls::accept::rustls_0_20

Module reexports

source
Expand description

Re-exports from rustls that are useful for acceptors.

+

Structsยง

  • Common configuration for a set of server sessions.
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/reexports/sidebar-items.js b/actix_tls/accept/rustls_0_20/reexports/sidebar-items.js new file mode 100644 index 00000000..78a9f205 --- /dev/null +++ b/actix_tls/accept/rustls_0_20/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["ServerConfig"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/reexports/struct.ServerConfig.html b/actix_tls/accept/rustls_0_20/reexports/struct.ServerConfig.html new file mode 100644 index 00000000..3899d13a --- /dev/null +++ b/actix_tls/accept/rustls_0_20/reexports/struct.ServerConfig.html @@ -0,0 +1,82 @@ +ServerConfig in actix_tls::accept::rustls_0_20::reexports - Rust
actix_tls::accept::rustls_0_20::reexports

Struct ServerConfig

pub struct ServerConfig {
+    pub ignore_client_order: bool,
+    pub max_fragment_size: Option<usize>,
+    pub session_storage: Arc<dyn StoresServerSessions + Sync + Send>,
+    pub ticketer: Arc<dyn ProducesTickets>,
+    pub cert_resolver: Arc<dyn ResolvesServerCert>,
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub key_log: Arc<dyn KeyLog>,
+    pub max_early_data_size: u32,
+    pub send_half_rtt_data: bool,
+    /* private fields */
+}
Expand description

Common configuration for a set of server sessions.

+

Making one of these can be expensive, and should be +once per process rather than once per connection.

+

These must be created via the ServerConfig::builder() function.

+

ยงDefaults

+ +

Fieldsยง

ยงignore_client_order: bool

Ignore the clientโ€™s ciphersuite order. Instead, +choose the top ciphersuite in the server list +which is supported by the client.

+
ยงmax_fragment_size: Option<usize>

The maximum size of TLS message weโ€™ll emit. If None, we donโ€™t limit TLS +message lengths except to the 2**16 limit specified in the standard.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ServerConnection::new.

+

Setting this value to the TCP MSS may improve latency for stream-y workloads.

+
ยงsession_storage: Arc<dyn StoresServerSessions + Sync + Send>

How to store client sessions.

+
ยงticketer: Arc<dyn ProducesTickets>

How to produce tickets.

+
ยงcert_resolver: Arc<dyn ResolvesServerCert>

How to choose a server cert and key.

+
ยงalpn_protocols: Vec<Vec<u8>>

Protocol names we support, most preferred first. +If empty we donโ€™t do ALPN at all.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงmax_early_data_size: u32

Amount of early data to accept for sessions created by +this config. Specify 0 to disable early data. The +default is 0.

+

Read the early data via [ServerConnection::early_data].

+

The units for this are both plaintext bytes, and ciphertext +bytes, depending on whether the server accepts a clientโ€™s early_data +or not. It is therefore recommended to include some slop in +this value to account for the unknown amount of ciphertext +expansion in the latter case.

+
ยงsend_half_rtt_data: bool

Whether the server should send โ€œ0.5RTTโ€ data. This means the server +sends data after its first flight of handshake messages, without +waiting for the client to complete the handshake.

+

This can improve TTFB latency for either server-speaks-first protocols, +or client-speaks-first protocols when paired with โ€œ0RTTโ€ data. This +comes at the cost of a subtle weakening of the normal handshake +integrity guarantees that TLS provides. Note that the initial +ClientHello is indirectly authenticated because it is included +in the transcript used to derive the keys used to encrypt the data.

+

This only applies to TLS1.3 connections. TLS1.2 connections cannot +do this optimisation and this setting is ignored for them. It is +also ignored for TLS1.3 connections that even attempt client +authentication.

+

This defaults to false. This means the first application data +sent by the server comes after receiving and validating the clientโ€™s +handshake up to the Finished message. This is the safest option.

+

Implementationsยง

ยง

impl ServerConfig

pub fn builder() -> ConfigBuilder<ServerConfig, WantsCipherSuites>

Create builder to build up the server configuration.

+

For more information, see the [ConfigBuilder] documentation.

+

Trait Implementationsยง

ยง

impl Clone for ServerConfig

ยง

fn clone(&self) -> ServerConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ServerConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ServerConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/sidebar-items.js b/actix_tls/accept/rustls_0_20/sidebar-items.js new file mode 100644 index 00000000..609abc9a --- /dev/null +++ b/actix_tls/accept/rustls_0_20/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["Acceptor","AcceptorService","TlsStream"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/struct.Acceptor.html b/actix_tls/accept/rustls_0_20/struct.Acceptor.html new file mode 100644 index 00000000..557750ce --- /dev/null +++ b/actix_tls/accept/rustls_0_20/struct.Acceptor.html @@ -0,0 +1,38 @@ +Acceptor in actix_tls::accept::rustls_0_20 - Rust
actix_tls::accept::rustls_0_20

Struct Acceptor

source
pub struct Acceptor { /* private fields */ }
Expand description

Accept TLS connections via the rustls crate.

+

Implementationsยง

sourceยง

impl Acceptor

source

pub fn new(config: ServerConfig) -> Self

Constructs rustls based acceptor service factory.

+
source

pub fn set_handshake_timeout( + &mut self, + handshake_timeout: Duration, +) -> &mut Self

Limit the amount of time that the acceptor will wait for a TLS handshake to complete.

+

Default timeout is 3 seconds.

+

Trait Implementationsยง

sourceยง

impl Clone for Acceptor

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<IO: ActixStream> ServiceFactory<IO> for Acceptor

sourceยง

type Response = TlsStream<IO>

Responses given by the created services.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = AcceptorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Acceptor as ServiceFactory<IO>>::Service, <Acceptor as ServiceFactory<IO>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/struct.AcceptorService.html b/actix_tls/accept/rustls_0_20/struct.AcceptorService.html new file mode 100644 index 00000000..1f9e99aa --- /dev/null +++ b/actix_tls/accept/rustls_0_20/struct.AcceptorService.html @@ -0,0 +1,27 @@ +AcceptorService in actix_tls::accept::rustls_0_20 - Rust
actix_tls::accept::rustls_0_20

Struct AcceptorService

source
pub struct AcceptorService { /* private fields */ }
Expand description

Rustls based acceptor service.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> Service<IO> for AcceptorService

sourceยง

type Response = TlsStream<IO>

Responses given by the service.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = AcceptFut<IO>

The future response value.
sourceยง

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: IO) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_20/struct.TlsStream.html b/actix_tls/accept/rustls_0_20/struct.TlsStream.html new file mode 100644 index 00000000..9a88d86f --- /dev/null +++ b/actix_tls/accept/rustls_0_20/struct.TlsStream.html @@ -0,0 +1,36 @@ +TlsStream in actix_tls::accept::rustls_0_20 - Rust
actix_tls::accept::rustls_0_20

Struct TlsStream

source
pub struct TlsStream<IO>(/* private fields */);
Expand description

Wraps a rustls based async TLS stream in order to implement [ActixStream].

+

Methods from Deref<Target = TlsStream<IO>>ยง

pub fn get_ref(&self) -> (&IO, &ServerConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ServerConnection)

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> AsyncRead for TlsStream<IO>

sourceยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<IO: ActixStream> AsyncWrite for TlsStream<IO>

sourceยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
sourceยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize>>

Like poll_write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<IO> Deref for TlsStream<IO>

sourceยง

type Target = TlsStream<IO>

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<IO> DerefMut for TlsStream<IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<IO> From<TlsStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: TlsStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/index.html b/actix_tls/accept/rustls_0_21/index.html new file mode 100644 index 00000000..4387a220 --- /dev/null +++ b/actix_tls/accept/rustls_0_21/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::rustls_0_21 - Rust
actix_tls::accept

Module rustls_0_21

source
Expand description

rustls v0.21 based TLS connection acceptor service.

+

See Acceptor for main service factory docs.

+

Modulesยง

  • Re-exports from rustls that are useful for acceptors.

Structsยง

  • Accept TLS connections via the rustls crate.
  • Rustls based acceptor service.
  • Wraps a rustls based async TLS stream in order to implement [ActixStream].
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/reexports/index.html b/actix_tls/accept/rustls_0_21/reexports/index.html new file mode 100644 index 00000000..fb0eaf6e --- /dev/null +++ b/actix_tls/accept/rustls_0_21/reexports/index.html @@ -0,0 +1,2 @@ +actix_tls::accept::rustls_0_21::reexports - Rust
actix_tls::accept::rustls_0_21

Module reexports

source
Expand description

Re-exports from rustls that are useful for acceptors.

+

Structsยง

  • Common configuration for a set of server sessions.
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/reexports/sidebar-items.js b/actix_tls/accept/rustls_0_21/reexports/sidebar-items.js new file mode 100644 index 00000000..78a9f205 --- /dev/null +++ b/actix_tls/accept/rustls_0_21/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["ServerConfig"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/reexports/struct.ServerConfig.html b/actix_tls/accept/rustls_0_21/reexports/struct.ServerConfig.html new file mode 100644 index 00000000..76b861dc --- /dev/null +++ b/actix_tls/accept/rustls_0_21/reexports/struct.ServerConfig.html @@ -0,0 +1,92 @@ +ServerConfig in actix_tls::accept::rustls_0_21::reexports - Rust
actix_tls::accept::rustls_0_21::reexports

Struct ServerConfig

pub struct ServerConfig {
+    pub ignore_client_order: bool,
+    pub max_fragment_size: Option<usize>,
+    pub session_storage: Arc<dyn StoresServerSessions + Sync + Send>,
+    pub ticketer: Arc<dyn ProducesTickets>,
+    pub cert_resolver: Arc<dyn ResolvesServerCert>,
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub key_log: Arc<dyn KeyLog>,
+    pub max_early_data_size: u32,
+    pub send_half_rtt_data: bool,
+    pub send_tls13_tickets: usize,
+    /* private fields */
+}
Expand description

Common configuration for a set of server sessions.

+

Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots +from the operating system to add to the RootCertStore passed to a ClientCertVerifier +builder may take on the order of a few hundred milliseconds.

+

These must be created via the ServerConfig::builder() function.

+

ยงDefaults

+ +

Fieldsยง

ยงignore_client_order: bool

Ignore the clientโ€™s ciphersuite order. Instead, +choose the top ciphersuite in the server list +which is supported by the client.

+
ยงmax_fragment_size: Option<usize>

The maximum size of TLS message weโ€™ll emit. If None, we donโ€™t limit TLS +message lengths except to the 2**16 limit specified in the standard.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ServerConnection::new.

+

Setting this value to the TCP MSS may improve latency for stream-y workloads.

+
ยงsession_storage: Arc<dyn StoresServerSessions + Sync + Send>

How to store client sessions.

+
ยงticketer: Arc<dyn ProducesTickets>

How to produce tickets.

+
ยงcert_resolver: Arc<dyn ResolvesServerCert>

How to choose a server cert and key.

+
ยงalpn_protocols: Vec<Vec<u8>>

Protocol names we support, most preferred first. +If empty we donโ€™t do ALPN at all.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงmax_early_data_size: u32

Amount of early data to accept for sessions created by +this config. Specify 0 to disable early data. The +default is 0.

+

Read the early data via [ServerConnection::early_data].

+

The units for this are both plaintext bytes, and ciphertext +bytes, depending on whether the server accepts a clientโ€™s early_data +or not. It is therefore recommended to include some slop in +this value to account for the unknown amount of ciphertext +expansion in the latter case.

+
ยงsend_half_rtt_data: bool

Whether the server should send โ€œ0.5RTTโ€ data. This means the server +sends data after its first flight of handshake messages, without +waiting for the client to complete the handshake.

+

This can improve TTFB latency for either server-speaks-first protocols, +or client-speaks-first protocols when paired with โ€œ0RTTโ€ data. This +comes at the cost of a subtle weakening of the normal handshake +integrity guarantees that TLS provides. Note that the initial +ClientHello is indirectly authenticated because it is included +in the transcript used to derive the keys used to encrypt the data.

+

This only applies to TLS1.3 connections. TLS1.2 connections cannot +do this optimisation and this setting is ignored for them. It is +also ignored for TLS1.3 connections that even attempt client +authentication.

+

This defaults to false. This means the first application data +sent by the server comes after receiving and validating the clientโ€™s +handshake up to the Finished message. This is the safest option.

+
ยงsend_tls13_tickets: usize

How many TLS1.3 tickets to send immediately after a successful +handshake.

+

Because TLS1.3 tickets are single-use, this allows +a client to perform multiple resumptions.

+

The default is 4.

+

If this is 0, no tickets are sent and clients will not be able to +do any resumption.

+

Implementationsยง

ยง

impl ServerConfig

pub fn builder() -> ConfigBuilder<ServerConfig, WantsCipherSuites>

Create builder to build up the server configuration.

+

For more information, see the [ConfigBuilder] documentation.

+

Trait Implementationsยง

ยง

impl Clone for ServerConfig

ยง

fn clone(&self) -> ServerConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ServerConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ServerConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/sidebar-items.js b/actix_tls/accept/rustls_0_21/sidebar-items.js new file mode 100644 index 00000000..609abc9a --- /dev/null +++ b/actix_tls/accept/rustls_0_21/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["Acceptor","AcceptorService","TlsStream"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/struct.Acceptor.html b/actix_tls/accept/rustls_0_21/struct.Acceptor.html new file mode 100644 index 00000000..8664004c --- /dev/null +++ b/actix_tls/accept/rustls_0_21/struct.Acceptor.html @@ -0,0 +1,38 @@ +Acceptor in actix_tls::accept::rustls_0_21 - Rust
actix_tls::accept::rustls_0_21

Struct Acceptor

source
pub struct Acceptor { /* private fields */ }
Expand description

Accept TLS connections via the rustls crate.

+

Implementationsยง

sourceยง

impl Acceptor

source

pub fn new(config: ServerConfig) -> Self

Constructs rustls based acceptor service factory.

+
source

pub fn set_handshake_timeout( + &mut self, + handshake_timeout: Duration, +) -> &mut Self

Limit the amount of time that the acceptor will wait for a TLS handshake to complete.

+

Default timeout is 3 seconds.

+

Trait Implementationsยง

sourceยง

impl Clone for Acceptor

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<IO: ActixStream> ServiceFactory<IO> for Acceptor

sourceยง

type Response = TlsStream<IO>

Responses given by the created services.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = AcceptorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Acceptor as ServiceFactory<IO>>::Service, <Acceptor as ServiceFactory<IO>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/struct.AcceptorService.html b/actix_tls/accept/rustls_0_21/struct.AcceptorService.html new file mode 100644 index 00000000..be726287 --- /dev/null +++ b/actix_tls/accept/rustls_0_21/struct.AcceptorService.html @@ -0,0 +1,27 @@ +AcceptorService in actix_tls::accept::rustls_0_21 - Rust
actix_tls::accept::rustls_0_21

Struct AcceptorService

source
pub struct AcceptorService { /* private fields */ }
Expand description

Rustls based acceptor service.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> Service<IO> for AcceptorService

sourceยง

type Response = TlsStream<IO>

Responses given by the service.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = AcceptFut<IO>

The future response value.
sourceยง

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: IO) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_21/struct.TlsStream.html b/actix_tls/accept/rustls_0_21/struct.TlsStream.html new file mode 100644 index 00000000..d42b0c07 --- /dev/null +++ b/actix_tls/accept/rustls_0_21/struct.TlsStream.html @@ -0,0 +1,36 @@ +TlsStream in actix_tls::accept::rustls_0_21 - Rust
actix_tls::accept::rustls_0_21

Struct TlsStream

source
pub struct TlsStream<IO>(/* private fields */);
Expand description

Wraps a rustls based async TLS stream in order to implement [ActixStream].

+

Methods from Deref<Target = TlsStream<IO>>ยง

pub fn get_ref(&self) -> (&IO, &ServerConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ServerConnection)

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> AsyncRead for TlsStream<IO>

sourceยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<IO: ActixStream> AsyncWrite for TlsStream<IO>

sourceยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
sourceยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize>>

Like poll_write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<IO> Deref for TlsStream<IO>

sourceยง

type Target = TlsStream<IO>

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<IO> DerefMut for TlsStream<IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<IO> From<TlsStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: TlsStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/index.html b/actix_tls/accept/rustls_0_22/index.html new file mode 100644 index 00000000..4836e57d --- /dev/null +++ b/actix_tls/accept/rustls_0_22/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::rustls_0_22 - Rust
actix_tls::accept

Module rustls_0_22

source
Expand description

rustls v0.22 based TLS connection acceptor service.

+

See Acceptor for main service factory docs.

+

Modulesยง

  • Re-exports from rustls that are useful for acceptors.

Structsยง

  • Accept TLS connections via the rustls crate.
  • Rustls based acceptor service.
  • Wraps a rustls based async TLS stream in order to implement [ActixStream].
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/reexports/index.html b/actix_tls/accept/rustls_0_22/reexports/index.html new file mode 100644 index 00000000..84b51d54 --- /dev/null +++ b/actix_tls/accept/rustls_0_22/reexports/index.html @@ -0,0 +1,2 @@ +actix_tls::accept::rustls_0_22::reexports - Rust
actix_tls::accept::rustls_0_22

Module reexports

source
Expand description

Re-exports from rustls that are useful for acceptors.

+

Structsยง

  • Common configuration for a set of server sessions.
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/reexports/sidebar-items.js b/actix_tls/accept/rustls_0_22/reexports/sidebar-items.js new file mode 100644 index 00000000..78a9f205 --- /dev/null +++ b/actix_tls/accept/rustls_0_22/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["ServerConfig"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/reexports/struct.ServerConfig.html b/actix_tls/accept/rustls_0_22/reexports/struct.ServerConfig.html new file mode 100644 index 00000000..7cdb7647 --- /dev/null +++ b/actix_tls/accept/rustls_0_22/reexports/struct.ServerConfig.html @@ -0,0 +1,116 @@ +ServerConfig in actix_tls::accept::rustls_0_22::reexports - Rust
actix_tls::accept::rustls_0_22::reexports

Struct ServerConfig

pub struct ServerConfig {
+    pub ignore_client_order: bool,
+    pub max_fragment_size: Option<usize>,
+    pub session_storage: Arc<dyn StoresServerSessions + Sync + Send>,
+    pub ticketer: Arc<dyn ProducesTickets>,
+    pub cert_resolver: Arc<dyn ResolvesServerCert>,
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub key_log: Arc<dyn KeyLog>,
+    pub enable_secret_extraction: bool,
+    pub max_early_data_size: u32,
+    pub send_half_rtt_data: bool,
+    pub send_tls13_tickets: usize,
+    /* private fields */
+}
Expand description

Common configuration for a set of server sessions.

+

Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots +from the operating system to add to the RootCertStore passed to a ClientCertVerifier +builder may take on the order of a few hundred milliseconds.

+

These must be created via the ServerConfig::builder() or ServerConfig::builder_with_provider() +function.

+

ยงDefaults

+ +

Fieldsยง

ยงignore_client_order: bool

Ignore the clientโ€™s ciphersuite order. Instead, +choose the top ciphersuite in the server list +which is supported by the client.

+
ยงmax_fragment_size: Option<usize>

The maximum size of plaintext input to be emitted in a single TLS record. +A value of None is equivalent to the TLS maximum of 16 kB.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ServerConnection::new.

+

Setting this value to a little less than the TCP MSS may improve latency +for stream-y workloads.

+
ยงsession_storage: Arc<dyn StoresServerSessions + Sync + Send>

How to store client sessions.

+
ยงticketer: Arc<dyn ProducesTickets>

How to produce tickets.

+
ยงcert_resolver: Arc<dyn ResolvesServerCert>

How to choose a server cert and key. This is usually set by +[ConfigBuilder::with_single_cert] or [ConfigBuilder::with_cert_resolver]. +For async applications, see also [Acceptor].

+
ยงalpn_protocols: Vec<Vec<u8>>

Protocol names we support, most preferred first. +If empty we donโ€™t do ALPN at all.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงenable_secret_extraction: bool

Allows traffic secrets to be extracted after the handshake, +e.g. for kTLS setup.

+
ยงmax_early_data_size: u32

Amount of early data to accept for sessions created by +this config. Specify 0 to disable early data. The +default is 0.

+

Read the early data via [ServerConnection::early_data].

+

The units for this are both plaintext bytes, and ciphertext +bytes, depending on whether the server accepts a clientโ€™s early_data +or not. It is therefore recommended to include some slop in +this value to account for the unknown amount of ciphertext +expansion in the latter case.

+
ยงsend_half_rtt_data: bool

Whether the server should send โ€œ0.5RTTโ€ data. This means the server +sends data after its first flight of handshake messages, without +waiting for the client to complete the handshake.

+

This can improve TTFB latency for either server-speaks-first protocols, +or client-speaks-first protocols when paired with โ€œ0RTTโ€ data. This +comes at the cost of a subtle weakening of the normal handshake +integrity guarantees that TLS provides. Note that the initial +ClientHello is indirectly authenticated because it is included +in the transcript used to derive the keys used to encrypt the data.

+

This only applies to TLS1.3 connections. TLS1.2 connections cannot +do this optimisation and this setting is ignored for them. It is +also ignored for TLS1.3 connections that even attempt client +authentication.

+

This defaults to false. This means the first application data +sent by the server comes after receiving and validating the clientโ€™s +handshake up to the Finished message. This is the safest option.

+
ยงsend_tls13_tickets: usize

How many TLS1.3 tickets to send immediately after a successful +handshake.

+

Because TLS1.3 tickets are single-use, this allows +a client to perform multiple resumptions.

+

The default is 4.

+

If this is 0, no tickets are sent and clients will not be able to +do any resumption.

+

Implementationsยง

ยง

impl ServerConfig

pub fn builder() -> ConfigBuilder<ServerConfig, WantsVerifier>

Create a builder for a server configuration with the default +[CryptoProvider]: [crypto::ring::default_provider] and safe ciphersuite and protocol +defaults.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_protocol_versions( + versions: &[&'static SupportedProtocolVersion], +) -> ConfigBuilder<ServerConfig, WantsVerifier>

Create a builder for a server configuration with the default +[CryptoProvider]: [crypto::ring::default_provider], safe ciphersuite defaults and +the provided protocol versions.

+

Panics if provided an empty slice of supported versions.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_provider( + provider: Arc<CryptoProvider>, +) -> ConfigBuilder<ServerConfig, WantsVersions>

Create a builder for a server configuration with a specific [CryptoProvider].

+

This will use the providerโ€™s configured ciphersuites. You must additionally choose +which protocol versions to enable, using with_protocol_versions or +with_safe_default_protocol_versions and handling the Result in case a protocol +version is not supported by the providerโ€™s ciphersuites.

+

For more information, see the [ConfigBuilder] documentation.

+

Trait Implementationsยง

ยง

impl Clone for ServerConfig

ยง

fn clone(&self) -> ServerConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ServerConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ServerConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/sidebar-items.js b/actix_tls/accept/rustls_0_22/sidebar-items.js new file mode 100644 index 00000000..609abc9a --- /dev/null +++ b/actix_tls/accept/rustls_0_22/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["Acceptor","AcceptorService","TlsStream"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/struct.Acceptor.html b/actix_tls/accept/rustls_0_22/struct.Acceptor.html new file mode 100644 index 00000000..1c3c65dc --- /dev/null +++ b/actix_tls/accept/rustls_0_22/struct.Acceptor.html @@ -0,0 +1,38 @@ +Acceptor in actix_tls::accept::rustls_0_22 - Rust
actix_tls::accept::rustls_0_22

Struct Acceptor

source
pub struct Acceptor { /* private fields */ }
Expand description

Accept TLS connections via the rustls crate.

+

Implementationsยง

sourceยง

impl Acceptor

source

pub fn new(config: ServerConfig) -> Self

Constructs rustls based acceptor service factory.

+
source

pub fn set_handshake_timeout( + &mut self, + handshake_timeout: Duration, +) -> &mut Self

Limit the amount of time that the acceptor will wait for a TLS handshake to complete.

+

Default timeout is 3 seconds.

+

Trait Implementationsยง

sourceยง

impl Clone for Acceptor

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<IO: ActixStream> ServiceFactory<IO> for Acceptor

sourceยง

type Response = TlsStream<IO>

Responses given by the created services.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = AcceptorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Acceptor as ServiceFactory<IO>>::Service, <Acceptor as ServiceFactory<IO>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/struct.AcceptorService.html b/actix_tls/accept/rustls_0_22/struct.AcceptorService.html new file mode 100644 index 00000000..8fc3e67b --- /dev/null +++ b/actix_tls/accept/rustls_0_22/struct.AcceptorService.html @@ -0,0 +1,27 @@ +AcceptorService in actix_tls::accept::rustls_0_22 - Rust
actix_tls::accept::rustls_0_22

Struct AcceptorService

source
pub struct AcceptorService { /* private fields */ }
Expand description

Rustls based acceptor service.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> Service<IO> for AcceptorService

sourceยง

type Response = TlsStream<IO>

Responses given by the service.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = AcceptFut<IO>

The future response value.
sourceยง

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: IO) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_22/struct.TlsStream.html b/actix_tls/accept/rustls_0_22/struct.TlsStream.html new file mode 100644 index 00000000..5a39a32b --- /dev/null +++ b/actix_tls/accept/rustls_0_22/struct.TlsStream.html @@ -0,0 +1,36 @@ +TlsStream in actix_tls::accept::rustls_0_22 - Rust
actix_tls::accept::rustls_0_22

Struct TlsStream

source
pub struct TlsStream<IO>(/* private fields */);
Expand description

Wraps a rustls based async TLS stream in order to implement [ActixStream].

+

Methods from Deref<Target = TlsStream<IO>>ยง

pub fn get_ref(&self) -> (&IO, &ServerConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ServerConnection)

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> AsyncRead for TlsStream<IO>

sourceยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<IO: ActixStream> AsyncWrite for TlsStream<IO>

sourceยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
sourceยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize>>

Like poll_write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<IO> Deref for TlsStream<IO>

sourceยง

type Target = TlsStream<IO>

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<IO> DerefMut for TlsStream<IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<IO> From<TlsStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: TlsStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/index.html b/actix_tls/accept/rustls_0_23/index.html new file mode 100644 index 00000000..cec45f13 --- /dev/null +++ b/actix_tls/accept/rustls_0_23/index.html @@ -0,0 +1,3 @@ +actix_tls::accept::rustls_0_23 - Rust
actix_tls::accept

Module rustls_0_23

source
Expand description

rustls v0.23 based TLS connection acceptor service.

+

See Acceptor for main service factory docs.

+

Modulesยง

  • Re-exports from rustls that are useful for acceptors.

Structsยง

  • Accept TLS connections via the rustls crate.
  • Rustls based acceptor service.
  • Wraps a rustls based async TLS stream in order to implement [ActixStream].
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/reexports/index.html b/actix_tls/accept/rustls_0_23/reexports/index.html new file mode 100644 index 00000000..8f451706 --- /dev/null +++ b/actix_tls/accept/rustls_0_23/reexports/index.html @@ -0,0 +1,2 @@ +actix_tls::accept::rustls_0_23::reexports - Rust
actix_tls::accept::rustls_0_23

Module reexports

source
Expand description

Re-exports from rustls that are useful for acceptors.

+

Structsยง

  • Common configuration for a set of server sessions.
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/reexports/sidebar-items.js b/actix_tls/accept/rustls_0_23/reexports/sidebar-items.js new file mode 100644 index 00000000..78a9f205 --- /dev/null +++ b/actix_tls/accept/rustls_0_23/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["ServerConfig"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/reexports/struct.ServerConfig.html b/actix_tls/accept/rustls_0_23/reexports/struct.ServerConfig.html new file mode 100644 index 00000000..375dd457 --- /dev/null +++ b/actix_tls/accept/rustls_0_23/reexports/struct.ServerConfig.html @@ -0,0 +1,169 @@ +ServerConfig in actix_tls::accept::rustls_0_23::reexports - Rust
actix_tls::accept::rustls_0_23::reexports

Struct ServerConfig

pub struct ServerConfig {
Show 15 fields + pub ignore_client_order: bool, + pub max_fragment_size: Option<usize>, + pub session_storage: Arc<dyn StoresServerSessions>, + pub ticketer: Arc<dyn ProducesTickets>, + pub cert_resolver: Arc<dyn ResolvesServerCert>, + pub alpn_protocols: Vec<Vec<u8>>, + pub key_log: Arc<dyn KeyLog>, + pub enable_secret_extraction: bool, + pub max_early_data_size: u32, + pub send_half_rtt_data: bool, + pub send_tls13_tickets: usize, + pub time_provider: Arc<dyn TimeProvider>, + pub cert_compressors: Vec<&'static dyn CertCompressor>, + pub cert_compression_cache: Arc<CompressionCache>, + pub cert_decompressors: Vec<&'static dyn CertDecompressor>, + /* private fields */ +
}
Expand description

Common configuration for a set of server sessions.

+

Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots +from the operating system to add to the RootCertStore passed to a ClientCertVerifier +builder may take on the order of a few hundred milliseconds.

+

These must be created via the ServerConfig::builder() or ServerConfig::builder_with_provider() +function.

+

ยงDefaults

+ +

Fieldsยง

ยงignore_client_order: bool

Ignore the clientโ€™s ciphersuite order. Instead, +choose the top ciphersuite in the server list +which is supported by the client.

+
ยงmax_fragment_size: Option<usize>

The maximum size of plaintext input to be emitted in a single TLS record. +A value of None is equivalent to the TLS maximum of 16 kB.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ServerConnection::new.

+

Setting this value to a little less than the TCP MSS may improve latency +for stream-y workloads.

+
ยงsession_storage: Arc<dyn StoresServerSessions>

How to store client sessions.

+
ยงticketer: Arc<dyn ProducesTickets>

How to produce tickets.

+
ยงcert_resolver: Arc<dyn ResolvesServerCert>

How to choose a server cert and key. This is usually set by +[ConfigBuilder::with_single_cert] or [ConfigBuilder::with_cert_resolver]. +For async applications, see also [Acceptor].

+
ยงalpn_protocols: Vec<Vec<u8>>

Protocol names we support, most preferred first. +If empty we donโ€™t do ALPN at all.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงenable_secret_extraction: bool

Allows traffic secrets to be extracted after the handshake, +e.g. for kTLS setup.

+
ยงmax_early_data_size: u32

Amount of early data to accept for sessions created by +this config. Specify 0 to disable early data. The +default is 0.

+

Read the early data via [ServerConnection::early_data].

+

The units for this are both plaintext bytes, and ciphertext +bytes, depending on whether the server accepts a clientโ€™s early_data +or not. It is therefore recommended to include some slop in +this value to account for the unknown amount of ciphertext +expansion in the latter case.

+
ยงsend_half_rtt_data: bool

Whether the server should send โ€œ0.5RTTโ€ data. This means the server +sends data after its first flight of handshake messages, without +waiting for the client to complete the handshake.

+

This can improve TTFB latency for either server-speaks-first protocols, +or client-speaks-first protocols when paired with โ€œ0RTTโ€ data. This +comes at the cost of a subtle weakening of the normal handshake +integrity guarantees that TLS provides. Note that the initial +ClientHello is indirectly authenticated because it is included +in the transcript used to derive the keys used to encrypt the data.

+

This only applies to TLS1.3 connections. TLS1.2 connections cannot +do this optimisation and this setting is ignored for them. It is +also ignored for TLS1.3 connections that even attempt client +authentication.

+

This defaults to false. This means the first application data +sent by the server comes after receiving and validating the clientโ€™s +handshake up to the Finished message. This is the safest option.

+
ยงsend_tls13_tickets: usize

How many TLS1.3 tickets to send immediately after a successful +handshake.

+

Because TLS1.3 tickets are single-use, this allows +a client to perform multiple resumptions.

+

The default is 4.

+

If this is 0, no tickets are sent and clients will not be able to +do any resumption.

+
ยงtime_provider: Arc<dyn TimeProvider>

Provides the current system time

+
ยงcert_compressors: Vec<&'static dyn CertCompressor>

How to compress the serverโ€™s certificate chain.

+

If a client supports this extension, and advertises support +for one of the compression algorithms included here, the +server certificate will be compressed according to RFC8779.

+

This only applies to TLS1.3 connections. It is ignored for +TLS1.2 connections.

+
ยงcert_compression_cache: Arc<CompressionCache>

Caching for compressed certificates.

+

This is optional: [compress::CompressionCache::Disabled] gives +a cache that does no caching.

+
ยงcert_decompressors: Vec<&'static dyn CertDecompressor>

How to decompress the clientsโ€™s certificate chain.

+

If this is non-empty, the RFC8779 certificate compression +extension is offered when requesting client authentication, +and any compressed certificates are transparently decompressed +during the handshake.

+

This only applies to TLS1.3 connections. It is ignored for +TLS1.2 connections.

+

Implementationsยง

ยง

impl ServerConfig

pub fn builder() -> ConfigBuilder<ServerConfig, WantsVerifier>

Create a builder for a server configuration with +[the process-default CryptoProvider][CryptoProvider#using-the-per-process-default-cryptoprovider] +and safe protocol version defaults.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_protocol_versions( + versions: &[&'static SupportedProtocolVersion], +) -> ConfigBuilder<ServerConfig, WantsVerifier>

Create a builder for a server configuration with +[the process-default CryptoProvider][CryptoProvider#using-the-per-process-default-cryptoprovider] +and the provided protocol versions.

+

Panics if

+
    +
  • the supported versions are not compatible with the provider (eg. +the combination of ciphersuites supported by the provider and supported +versions lead to zero cipher suites being usable),
  • +
  • if a CryptoProvider cannot be resolved using a combination of +the crate features and process default.
  • +
+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_provider( + provider: Arc<CryptoProvider>, +) -> ConfigBuilder<ServerConfig, WantsVersions>

Create a builder for a server configuration with a specific [CryptoProvider].

+

This will use the providerโ€™s configured ciphersuites. You must additionally choose +which protocol versions to enable, using with_protocol_versions or +with_safe_default_protocol_versions and handling the Result in case a protocol +version is not supported by the providerโ€™s ciphersuites.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_details( + provider: Arc<CryptoProvider>, + time_provider: Arc<dyn TimeProvider>, +) -> ConfigBuilder<ServerConfig, WantsVersions>

Create a builder for a server configuration with no default implementation details.

+

This API must be used by no_std users.

+

You must provide a specific [TimeProvider].

+

You must provide a specific [CryptoProvider].

+

This will use the providerโ€™s configured ciphersuites. You must additionally choose +which protocol versions to enable, using with_protocol_versions or +with_safe_default_protocol_versions and handling the Result in case a protocol +version is not supported by the providerโ€™s ciphersuites.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn fips(&self) -> bool

Return true if connections made with this ServerConfig will +operate in FIPS mode.

+

This is different from [CryptoProvider::fips()]: [CryptoProvider::fips()] +is concerned only with cryptography, whereas this also covers TLS-level +configuration that NIST recommends.

+

pub fn crypto_provider(&self) -> &Arc<CryptoProvider>

Return the crypto provider used to construct this client configuration.

+

Trait Implementationsยง

ยง

impl Clone for ServerConfig

ยง

fn clone(&self) -> ServerConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ServerConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ServerConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/sidebar-items.js b/actix_tls/accept/rustls_0_23/sidebar-items.js new file mode 100644 index 00000000..609abc9a --- /dev/null +++ b/actix_tls/accept/rustls_0_23/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["Acceptor","AcceptorService","TlsStream"]}; \ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/struct.Acceptor.html b/actix_tls/accept/rustls_0_23/struct.Acceptor.html new file mode 100644 index 00000000..d8f56161 --- /dev/null +++ b/actix_tls/accept/rustls_0_23/struct.Acceptor.html @@ -0,0 +1,38 @@ +Acceptor in actix_tls::accept::rustls_0_23 - Rust
actix_tls::accept::rustls_0_23

Struct Acceptor

source
pub struct Acceptor { /* private fields */ }
Expand description

Accept TLS connections via the rustls crate.

+

Implementationsยง

sourceยง

impl Acceptor

source

pub fn new(config: ServerConfig) -> Self

Constructs rustls based acceptor service factory.

+
source

pub fn set_handshake_timeout( + &mut self, + handshake_timeout: Duration, +) -> &mut Self

Limit the amount of time that the acceptor will wait for a TLS handshake to complete.

+

Default timeout is 3 seconds.

+

Trait Implementationsยง

sourceยง

impl Clone for Acceptor

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<IO: ActixStream> ServiceFactory<IO> for Acceptor

sourceยง

type Response = TlsStream<IO>

Responses given by the created services.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = AcceptorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Acceptor as ServiceFactory<IO>>::Service, <Acceptor as ServiceFactory<IO>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/struct.AcceptorService.html b/actix_tls/accept/rustls_0_23/struct.AcceptorService.html new file mode 100644 index 00000000..70451f90 --- /dev/null +++ b/actix_tls/accept/rustls_0_23/struct.AcceptorService.html @@ -0,0 +1,27 @@ +AcceptorService in actix_tls::accept::rustls_0_23 - Rust
actix_tls::accept::rustls_0_23

Struct AcceptorService

source
pub struct AcceptorService { /* private fields */ }
Expand description

Rustls based acceptor service.

+

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> Service<IO> for AcceptorService

sourceยง

type Response = TlsStream<IO>

Responses given by the service.
sourceยง

type Error = TlsError<Error, Infallible>

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = AcceptFut<IO>

The future response value.
sourceยง

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: IO) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/rustls_0_23/struct.TlsStream.html b/actix_tls/accept/rustls_0_23/struct.TlsStream.html new file mode 100644 index 00000000..a29ec06f --- /dev/null +++ b/actix_tls/accept/rustls_0_23/struct.TlsStream.html @@ -0,0 +1,36 @@ +TlsStream in actix_tls::accept::rustls_0_23 - Rust
actix_tls::accept::rustls_0_23

Struct TlsStream

source
pub struct TlsStream<IO>(/* private fields */);
Expand description

Wraps a rustls based async TLS stream in order to implement [ActixStream].

+

Methods from Deref<Target = TlsStream<IO>>ยง

pub fn get_ref(&self) -> (&IO, &ServerConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ServerConnection)

Trait Implementationsยง

sourceยง

impl<IO: ActixStream> AsyncRead for TlsStream<IO>

sourceยง

fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<IO: ActixStream> AsyncWrite for TlsStream<IO>

sourceยง

fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
sourceยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize>>

Like poll_write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<IO> Deref for TlsStream<IO>

sourceยง

type Target = TlsStream<IO>

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<IO> DerefMut for TlsStream<IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<IO> From<TlsStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: TlsStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/accept/sidebar-items.js b/actix_tls/accept/sidebar-items.js new file mode 100644 index 00000000..b946eaf8 --- /dev/null +++ b/actix_tls/accept/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["TlsError"],"fn":["max_concurrent_tls_connect"],"mod":["native_tls","openssl","rustls_0_20","rustls_0_21","rustls_0_22","rustls_0_23"]}; \ No newline at end of file diff --git a/actix_tls/all.html b/actix_tls/all.html new file mode 100644 index 00000000..8c9c3e15 --- /dev/null +++ b/actix_tls/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

Enums

Traits

Functions

Statics

Constants

\ No newline at end of file diff --git a/actix_tls/connect/connection/struct.Connection.html b/actix_tls/connect/connection/struct.Connection.html new file mode 100644 index 00000000..1fca3fcc --- /dev/null +++ b/actix_tls/connect/connection/struct.Connection.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/struct.Connection.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/connector/struct.Connector.html b/actix_tls/connect/connector/struct.Connector.html new file mode 100644 index 00000000..7ed48d92 --- /dev/null +++ b/actix_tls/connect/connector/struct.Connector.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/struct.Connector.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/connector/struct.ConnectorService.html b/actix_tls/connect/connector/struct.ConnectorService.html new file mode 100644 index 00000000..022ca935 --- /dev/null +++ b/actix_tls/connect/connector/struct.ConnectorService.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/struct.ConnectorService.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/enum.ConnectError.html b/actix_tls/connect/enum.ConnectError.html new file mode 100644 index 00000000..8de8dd8f --- /dev/null +++ b/actix_tls/connect/enum.ConnectError.html @@ -0,0 +1,29 @@ +ConnectError in actix_tls::connect - Rust
actix_tls::connect

Enum ConnectError

source
pub enum ConnectError {
+    Resolver(Box<dyn Error>),
+    NoRecords,
+    InvalidInput,
+    Unresolved,
+    Io(Error),
+}
Expand description

Errors that can result from using a connector service.

+

Variantsยง

ยง

Resolver(Box<dyn Error>)

Failed to resolve the hostname.

+
ยง

NoRecords

No DNS records.

+
ยง

InvalidInput

Invalid input.

+
ยง

Unresolved

Unresolved host name.

+
ยง

Io(Error)

Connection IO error.

+

Trait Implementationsยง

sourceยง

impl Debug for ConnectError

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Display for ConnectError

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Error for ConnectError

sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/error/enum.ConnectError.html b/actix_tls/connect/error/enum.ConnectError.html new file mode 100644 index 00000000..392e34ff --- /dev/null +++ b/actix_tls/connect/error/enum.ConnectError.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/enum.ConnectError.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/host/trait.Host.html b/actix_tls/connect/host/trait.Host.html new file mode 100644 index 00000000..d28ee925 --- /dev/null +++ b/actix_tls/connect/host/trait.Host.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/trait.Host.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/index.html b/actix_tls/connect/index.html new file mode 100644 index 00000000..92a67e8a --- /dev/null +++ b/actix_tls/connect/index.html @@ -0,0 +1,13 @@ +actix_tls::connect - Rust
actix_tls

Module connect

source
Expand description

TCP and TLS connector services.

+

ยงStages of the TCP connector service:

+
    +
  1. Resolve Host (if needed) with given Resolver and collect list of socket addresses.
  2. +
  3. Establish TCP connection and return TcpStream.
  4. +
+

ยงStages of TLS connector services:

+
    +
  1. Resolve DNS and establish a TcpStream with the TCP connector service.
  2. +
  3. Wrap the stream and perform connect handshake with remote peer.
  4. +
  5. Return wrapped stream type that implements AsyncRead and AsyncWrite.
  6. +
+

Modulesยง

Structsยง

Enumsยง

  • Errors that can result from using a connector service.

Traitsยง

  • An interface for types where host parts (hostname and port) can be derived.
  • Custom async DNS resolvers.
\ No newline at end of file diff --git a/actix_tls/connect/info/struct.ConnectInfo.html b/actix_tls/connect/info/struct.ConnectInfo.html new file mode 100644 index 00000000..e507967c --- /dev/null +++ b/actix_tls/connect/info/struct.ConnectInfo.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/struct.ConnectInfo.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/native_tls/index.html b/actix_tls/connect/native_tls/index.html new file mode 100644 index 00000000..1889dacf --- /dev/null +++ b/actix_tls/connect/native_tls/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::native_tls - Rust
actix_tls::connect

Module native_tls

source
Expand description

Native-TLS based connector service.

+

See TlsConnector for main connector service factory docs.

+

Modulesยง

  • Re-exports from native-tls and tokio-native-tls that are useful for connectors.

Structsยง

\ No newline at end of file diff --git a/actix_tls/connect/native_tls/reexports/index.html b/actix_tls/connect/native_tls/reexports/index.html new file mode 100644 index 00000000..c1191278 --- /dev/null +++ b/actix_tls/connect/native_tls/reexports/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::native_tls::reexports - Rust
actix_tls::connect::native_tls

Module reexports

source
Expand description

Re-exports from native-tls and tokio-native-tls that are useful for connectors.

+

Structsยง

  • A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.
  • A builder for client-side TLS connections.
\ No newline at end of file diff --git a/actix_tls/connect/native_tls/reexports/sidebar-items.js b/actix_tls/connect/native_tls/reexports/sidebar-items.js new file mode 100644 index 00000000..aa9182e1 --- /dev/null +++ b/actix_tls/connect/native_tls/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["AsyncTlsStream","TlsConnector"]}; \ No newline at end of file diff --git a/actix_tls/connect/native_tls/reexports/struct.AsyncTlsStream.html b/actix_tls/connect/native_tls/reexports/struct.AsyncTlsStream.html new file mode 100644 index 00000000..3988eef9 --- /dev/null +++ b/actix_tls/connect/native_tls/reexports/struct.AsyncTlsStream.html @@ -0,0 +1,54 @@ +AsyncTlsStream in actix_tls::connect::native_tls::reexports - Rust
actix_tls::connect::native_tls::reexports

Struct AsyncTlsStream

source
pub struct AsyncTlsStream<S>(/* private fields */);
Expand description

A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.

+

A TlsStream<S> represents a handshake that has been completed successfully +and both the server and the client are ready for receiving and sending +data. Bytes read from a TlsStream are decrypted from S and bytes written +to a TlsStream are encrypted when passing through to S.

+

Implementationsยง

sourceยง

impl<S> TlsStream<S>

source

pub fn get_ref(&self) -> &TlsStream<AllowStd<S>>

Returns a shared reference to the inner stream.

+
source

pub fn get_mut(&mut self) -> &mut TlsStream<AllowStd<S>>

Returns a mutable reference to the inner stream.

+

Trait Implementationsยง

sourceยง

impl<S> AsRawFd for TlsStream<S>
where + S: AsRawFd,

sourceยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
sourceยง

impl<S> AsyncRead for TlsStream<S>
where + S: AsyncRead + AsyncWrite + Unpin,

sourceยง

fn poll_read( + self: Pin<&mut TlsStream<S>>, + ctx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
sourceยง

impl<S> AsyncWrite for TlsStream<S>
where + S: AsyncRead + AsyncWrite + Unpin,

sourceยง

fn poll_write( + self: Pin<&mut TlsStream<S>>, + ctx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
sourceยง

fn poll_flush( + self: Pin<&mut TlsStream<S>>, + ctx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
sourceยง

fn poll_shutdown( + self: Pin<&mut TlsStream<S>>, + ctx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
sourceยง

impl<S> Debug for TlsStream<S>
where + S: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<IO> From<TlsStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: TlsStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<S> Freeze for TlsStream<S>

ยง

impl<S> RefUnwindSafe for TlsStream<S>
where + S: RefUnwindSafe,

ยง

impl<S> Send for TlsStream<S>
where + S: Send,

ยง

impl<S> Sync for TlsStream<S>
where + S: Sync,

ยง

impl<S> Unpin for TlsStream<S>
where + S: Unpin,

ยง

impl<S> UnwindSafe for TlsStream<S>
where + S: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/native_tls/reexports/struct.TlsConnector.html b/actix_tls/connect/native_tls/reexports/struct.TlsConnector.html new file mode 100644 index 00000000..c9b574c6 --- /dev/null +++ b/actix_tls/connect/native_tls/reexports/struct.TlsConnector.html @@ -0,0 +1,49 @@ +TlsConnector in actix_tls::connect::native_tls::reexports - Rust
actix_tls::connect::native_tls::reexports

Struct TlsConnector

pub struct TlsConnector(/* private fields */);
Expand description

A builder for client-side TLS connections.

+

ยงExamples

+
use native_tls::TlsConnector;
+use std::io::{Read, Write};
+use std::net::TcpStream;
+
+let connector = TlsConnector::new().unwrap();
+
+let stream = TcpStream::connect("google.com:443").unwrap();
+let mut stream = connector.connect("google.com", stream).unwrap();
+
+stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
+let mut res = vec![];
+stream.read_to_end(&mut res).unwrap();
+println!("{}", String::from_utf8_lossy(&res));
+

Implementationsยง

ยง

impl TlsConnector

pub fn new() -> Result<TlsConnector, Error>

Returns a new connector with default settings.

+

pub fn builder() -> TlsConnectorBuilder

Returns a new builder for a TlsConnector.

+

pub fn connect<S>( + &self, + domain: &str, + stream: S, +) -> Result<TlsStream<S>, HandshakeError<S>>
where + S: Read + Write,

Initiates a TLS handshake.

+

The provided domain will be used for both SNI and certificate hostname +validation.

+

If the socket is nonblocking and a WouldBlock error is returned during +the handshake, a HandshakeError::WouldBlock error will be returned +which can be used to restart the handshake when the socket is ready +again.

+

The domain is ignored if both SNI and hostname verification are +disabled.

+

Trait Implementationsยง

ยง

impl Clone for TlsConnector

ยง

fn clone(&self) -> TlsConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for TlsConnector

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/native_tls/sidebar-items.js b/actix_tls/connect/native_tls/sidebar-items.js new file mode 100644 index 00000000..96ff4fde --- /dev/null +++ b/actix_tls/connect/native_tls/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["TlsConnector"]}; \ No newline at end of file diff --git a/actix_tls/connect/native_tls/struct.TlsConnector.html b/actix_tls/connect/native_tls/struct.TlsConnector.html new file mode 100644 index 00000000..cea9b949 --- /dev/null +++ b/actix_tls/connect/native_tls/struct.TlsConnector.html @@ -0,0 +1,49 @@ +TlsConnector in actix_tls::connect::native_tls - Rust
actix_tls::connect::native_tls

Struct TlsConnector

source
pub struct TlsConnector { /* private fields */ }
Expand description

Connector service and factory using native-tls.

+

Implementationsยง

sourceยง

impl TlsConnector

source

pub fn new(connector: NativeTlsConnector) -> Self

Constructs new connector service from a native-tls connector.

+

This type is itโ€™s own service factory, so it can be used in that setting, too.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnector

sourceยง

fn clone(&self) -> TlsConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

The native-tls connector is both itโ€™s ServiceFactory and Service impl type. +As the factory and service share the same type and state.

+
sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = Pin<Box<dyn Future<Output = Result<<TlsConnector as Service<Connection<R, IO>>>::Response, <TlsConnector as Service<Connection<R, IO>>>::Error>>>>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, stream: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R: Host, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnector

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/index.html b/actix_tls/connect/openssl/index.html new file mode 100644 index 00000000..3ac71ea7 --- /dev/null +++ b/actix_tls/connect/openssl/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::openssl - Rust
actix_tls::connect

Module openssl

source
Expand description

OpenSSL based connector service.

+

See TlsConnector for main connector service factory docs.

+

Modulesยง

  • Re-exports from openssl and tokio-openssl that are useful for connectors.

Structsยง

\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/enum.HandshakeError.html b/actix_tls/connect/openssl/reexports/enum.HandshakeError.html new file mode 100644 index 00000000..805ecb5c --- /dev/null +++ b/actix_tls/connect/openssl/reexports/enum.HandshakeError.html @@ -0,0 +1,32 @@ +HandshakeError in actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl::reexports

Enum HandshakeError

source
pub enum HandshakeError<S> {
+    SetupFailure(ErrorStack),
+    Failure(MidHandshakeSslStream<S>),
+    WouldBlock(MidHandshakeSslStream<S>),
+}
Expand description

An error or intermediate state after a TLS handshake attempt.

+

Variantsยง

ยง

SetupFailure(ErrorStack)

Setup failed.

+
ยง

Failure(MidHandshakeSslStream<S>)

The handshake failed.

+
ยง

WouldBlock(MidHandshakeSslStream<S>)

The handshake encountered a WouldBlock error midway through.

+

This error will never be returned for blocking streams.

+

Trait Implementationsยง

sourceยง

impl<S> Debug for HandshakeError<S>
where + S: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<S> Display for HandshakeError<S>
where + S: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<S> Error for HandshakeError<S>
where + S: Debug,

sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
sourceยง

impl<S> From<ErrorStack> for HandshakeError<S>

sourceยง

fn from(e: ErrorStack) -> HandshakeError<S>

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<S> Freeze for HandshakeError<S>

ยง

impl<S> !RefUnwindSafe for HandshakeError<S>

ยง

impl<S> Send for HandshakeError<S>
where + S: Send,

ยง

impl<S> Sync for HandshakeError<S>
where + S: Sync,

ยง

impl<S> Unpin for HandshakeError<S>
where + S: Unpin,

ยง

impl<S> !UnwindSafe for HandshakeError<S>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/index.html b/actix_tls/connect/openssl/reexports/index.html new file mode 100644 index 00000000..7d44c4e7 --- /dev/null +++ b/actix_tls/connect/openssl/reexports/index.html @@ -0,0 +1,2 @@ +actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl

Module reexports

source
Expand description

Re-exports from openssl and tokio-openssl that are useful for connectors.

+

Structsยง

Enumsยง

  • An error or intermediate state after a TLS handshake attempt.
\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/sidebar-items.js b/actix_tls/connect/openssl/reexports/sidebar-items.js new file mode 100644 index 00000000..611d6350 --- /dev/null +++ b/actix_tls/connect/openssl/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["HandshakeError"],"struct":["AsyncSslStream","Error","SslConnector","SslConnectorBuilder","SslMethod"]}; \ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/struct.AsyncSslStream.html b/actix_tls/connect/openssl/reexports/struct.AsyncSslStream.html new file mode 100644 index 00000000..abe1fa66 --- /dev/null +++ b/actix_tls/connect/openssl/reexports/struct.AsyncSslStream.html @@ -0,0 +1,94 @@ +AsyncSslStream in actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl::reexports

Struct AsyncSslStream

pub struct AsyncSslStream<S>(/* private fields */);
Expand description

An asynchronous version of openssl::ssl::SslStream.

+

Implementationsยง

ยง

impl<S> SslStream<S>
where + S: AsyncRead + AsyncWrite,

pub fn new(ssl: Ssl, stream: S) -> Result<SslStream<S>, ErrorStack>

pub fn poll_connect( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

pub async fn connect(self: Pin<&mut SslStream<S>>) -> Result<(), Error>

A convenience method wrapping poll_connect.

+

pub fn poll_accept( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

pub async fn accept(self: Pin<&mut SslStream<S>>) -> Result<(), Error>

A convenience method wrapping poll_accept.

+

pub fn poll_do_handshake( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

pub async fn do_handshake(self: Pin<&mut SslStream<S>>) -> Result<(), Error>

A convenience method wrapping poll_do_handshake.

+

pub fn poll_peek( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, + buf: &mut [u8], +) -> Poll<Result<usize, Error>>

pub async fn peek( + self: Pin<&mut SslStream<S>>, + buf: &mut [u8], +) -> Result<usize, Error>

A convenience method wrapping poll_peek.

+

pub fn poll_read_early_data( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, + buf: &mut [u8], +) -> Poll<Result<usize, Error>>

pub async fn read_early_data( + self: Pin<&mut SslStream<S>>, + buf: &mut [u8], +) -> Result<usize, Error>

A convenience method wrapping poll_read_early_data.

+

pub fn poll_write_early_data( + self: Pin<&mut SslStream<S>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

pub async fn write_early_data( + self: Pin<&mut SslStream<S>>, + buf: &[u8], +) -> Result<usize, Error>

A convenience method wrapping poll_write_early_data.

+
ยง

impl<S> SslStream<S>

pub fn ssl(&self) -> &SslRef

Returns a shared reference to the Ssl object associated with this stream.

+

pub fn get_ref(&self) -> &S

Returns a shared reference to the underlying stream.

+

pub fn get_mut(&mut self) -> &mut S

Returns a mutable reference to the underlying stream.

+

pub fn get_pin_mut(self: Pin<&mut SslStream<S>>) -> Pin<&mut S>

Returns a pinned mutable reference to the underlying stream.

+

Trait Implementationsยง

ยง

impl<S> AsyncRead for SslStream<S>
where + S: AsyncRead + AsyncWrite,

ยง

fn poll_read( + self: Pin<&mut SslStream<S>>, + ctx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl<S> AsyncWrite for SslStream<S>
where + S: AsyncRead + AsyncWrite,

ยง

fn poll_write( + self: Pin<&mut SslStream<S>>, + ctx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
ยง

fn poll_flush( + self: Pin<&mut SslStream<S>>, + ctx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut SslStream<S>>, + ctx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

impl<S> Debug for SslStream<S>
where + S: Debug,

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<IO> From<SslStream<IO>> for TlsStream<IO>

sourceยง

fn from(from: SslStream<IO>) -> Self

Converts to this type from the input type.

Auto Trait Implementationsยง

ยง

impl<S> Freeze for SslStream<S>

ยง

impl<S> RefUnwindSafe for SslStream<S>
where + S: RefUnwindSafe,

ยง

impl<S> Send for SslStream<S>
where + S: Send,

ยง

impl<S> Sync for SslStream<S>
where + S: Sync,

ยง

impl<S> Unpin for SslStream<S>
where + S: Unpin,

ยง

impl<S> UnwindSafe for SslStream<S>
where + S: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/struct.Error.html b/actix_tls/connect/openssl/reexports/struct.Error.html new file mode 100644 index 00000000..6b1e2b0b --- /dev/null +++ b/actix_tls/connect/openssl/reexports/struct.Error.html @@ -0,0 +1,18 @@ +Error in actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl::reexports

Struct Error

source
pub struct Error { /* private fields */ }
Expand description

An SSL error.

+

Implementationsยง

sourceยง

impl Error

source

pub fn code(&self) -> ErrorCode

source

pub fn io_error(&self) -> Option<&Error>

source

pub fn into_io_error(self) -> Result<Error, Error>

source

pub fn ssl_error(&self) -> Option<&ErrorStack>

Trait Implementationsยง

sourceยง

impl Debug for Error

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl Display for Error

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl Error for Error

sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
sourceยง

impl From<ErrorStack> for Error

sourceยง

fn from(e: ErrorStack) -> Error

Converts to this type from the input type.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/struct.SslConnector.html b/actix_tls/connect/openssl/reexports/struct.SslConnector.html new file mode 100644 index 00000000..8b803ccd --- /dev/null +++ b/actix_tls/connect/openssl/reexports/struct.SslConnector.html @@ -0,0 +1,35 @@ +SslConnector in actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl::reexports

Struct SslConnector

source
pub struct SslConnector(/* private fields */);
Expand description

A type which wraps client-side streams in a TLS session.

+

OpenSSLโ€™s default configuration is highly insecure. This connector manages the OpenSSL +structures, configuring cipher suites, session options, hostname verification, and more.

+

OpenSSLโ€™s built-in hostname verification is used when linking against OpenSSL 1.0.2 or 1.1.0, +and a custom implementation is used when linking against OpenSSL 1.0.1.

+

Implementationsยง

sourceยง

impl SslConnector

source

pub fn builder(method: SslMethod) -> Result<SslConnectorBuilder, ErrorStack>

Creates a new builder for TLS connections.

+

The default configuration is subject to change, and is currently derived from Python.

+
source

pub fn connect<S>( + &self, + domain: &str, + stream: S, +) -> Result<SslStream<S>, HandshakeError<S>>
where + S: Read + Write,

Initiates a client-side TLS session on a stream.

+

The domain is used for SNI and hostname verification.

+
source

pub fn configure(&self) -> Result<ConnectConfiguration, ErrorStack>

Returns a structure allowing for configuration of a single TLS session before connection.

+
source

pub fn into_context(self) -> SslContext

Consumes the SslConnector, returning the inner raw SslContext.

+
source

pub fn context(&self) -> &SslContextRef

Returns a shared reference to the inner raw SslContext.

+

Trait Implementationsยง

sourceยง

impl Clone for SslConnector

sourceยง

fn clone(&self) -> SslConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for SslConnector

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/struct.SslConnectorBuilder.html b/actix_tls/connect/openssl/reexports/struct.SslConnectorBuilder.html new file mode 100644 index 00000000..33f3ddbd --- /dev/null +++ b/actix_tls/connect/openssl/reexports/struct.SslConnectorBuilder.html @@ -0,0 +1,326 @@ +SslConnectorBuilder in actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl::reexports

Struct SslConnectorBuilder

source
pub struct SslConnectorBuilder(/* private fields */);
Expand description

A builder for SslConnectors.

+

Implementationsยง

sourceยง

impl SslConnectorBuilder

source

pub fn build(self) -> SslConnector

Consumes the builder, returning an SslConnector.

+

Methods from Deref<Target = SslContextBuilder>ยง

source

pub fn as_ptr(&self) -> *mut SSL_CTX

Returns a pointer to the raw OpenSSL value.

+
source

pub fn set_verify(&mut self, mode: SslVerifyMode)

Configures the certificate verification method for new connections.

+

This corresponds to SSL_CTX_set_verify.

+
source

pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,

Configures the certificate verification method for new connections and +registers a verification callback.

+

The callback is passed a boolean indicating if OpenSSLโ€™s internal verification succeeded as +well as a reference to the X509StoreContext which can be used to examine the certificate +chain. It should return a boolean indicating if verification succeeded.

+

This corresponds to SSL_CTX_set_verify.

+
source

pub fn set_servername_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,

Configures the server name indication (SNI) callback for new connections.

+

SNI is used to allow a single server to handle requests for multiple domains, each of which +has its own certificate chain and configuration.

+

Obtain the server name with the servername method and then set the corresponding context +with set_ssl_context

+

This corresponds to SSL_CTX_set_tlsext_servername_callback.

+
source

pub fn set_verify_depth(&mut self, depth: u32)

Sets the certificate verification depth.

+

If the peerโ€™s certificate chain is longer than this value, verification will fail.

+

This corresponds to SSL_CTX_set_verify_depth.

+
source

pub fn set_verify_cert_store( + &mut self, + cert_store: X509Store, +) -> Result<(), ErrorStack>

Sets a custom certificate store for verifying peer certificates.

+

Requires OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_set0_verify_cert_store.

+
source

pub fn set_cert_store(&mut self, cert_store: X509Store)

Replaces the contextโ€™s certificate store.

+

This corresponds to SSL_CTX_set_cert_store.

+
source

pub fn set_read_ahead(&mut self, read_ahead: bool)

Controls read ahead behavior.

+

If enabled, OpenSSL will read as much data as is available from the underlying stream, +instead of a single record at a time.

+

It has no effect when used with DTLS.

+

This corresponds to SSL_CTX_set_read_ahead.

+
source

pub fn set_mode(&mut self, mode: SslMode) -> SslMode

Sets the mode used by the context, returning the previous mode.

+

This corresponds to SSL_CTX_set_mode.

+
source

pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack>

Sets the parameters to be used during ephemeral Diffie-Hellman key exchange.

+

This corresponds to SSL_CTX_set_tmp_dh.

+
source

pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,

Sets the callback which will generate parameters to be used during ephemeral Diffie-Hellman +key exchange.

+

The callback is provided with a reference to the Ssl for the session, as well as a boolean +indicating if the selected cipher is export-grade, and the key length. The export and key +length options are archaic and should be ignored in almost all cases.

+

This corresponds to SSL_CTX_set_tmp_dh_callback.

+
source

pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef<Params>) -> Result<(), ErrorStack>

Sets the parameters to be used during ephemeral elliptic curve Diffie-Hellman key exchange.

+

This corresponds to SSL_CTX_set_tmp_ecdh.

+
source

pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack>

Use the default locations of trusted certificates for verification.

+

These locations are read from the SSL_CERT_FILE and SSL_CERT_DIR environment variables +if present, or defaults specified at OpenSSL build time otherwise.

+

This corresponds to SSL_CTX_set_default_verify_paths.

+
source

pub fn set_ca_file<P>(&mut self, file: P) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads trusted root certificates from a file.

+

The file should contain a sequence of PEM-formatted CA certificates.

+

This corresponds to SSL_CTX_load_verify_locations.

+
source

pub fn set_client_ca_list(&mut self, list: Stack<X509Name>)

Sets the list of CA names sent to the client.

+

The CA certificates must still be added to the trust root - they are not automatically set +as trusted by this method.

+

This corresponds to SSL_CTX_set_client_CA_list.

+
source

pub fn add_client_ca(&mut self, cacert: &X509Ref) -> Result<(), ErrorStack>

Add the provided CA certificate to the list sent by the server to the client when +requesting client-side TLS authentication.

+

This corresponds to SSL_CTX_add_client_CA.

+
source

pub fn set_session_id_context( + &mut self, + sid_ctx: &[u8], +) -> Result<(), ErrorStack>

Set the context identifier for sessions.

+

This value identifies the serverโ€™s session cache to clients, telling them when theyโ€™re +able to reuse sessions. It should be set to a unique value per server, unless multiple +servers share a session cache.

+

This value should be set when using client certificates, or each request will fail its +handshake and need to be restarted.

+

This corresponds to SSL_CTX_set_session_id_context.

+
source

pub fn set_certificate_file<P>( + &mut self, + file: P, + file_type: SslFiletype, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads a leaf certificate from a file.

+

Only a single certificate will be loaded - use add_extra_chain_cert to add the remainder +of the certificate chain, or set_certificate_chain_file to load the entire chain from a +single file.

+

This corresponds to SSL_CTX_use_certificate_file.

+
source

pub fn set_certificate_chain_file<P>( + &mut self, + file: P, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads a certificate chain from a file.

+

The file should contain a sequence of PEM-formatted certificates, the first being the leaf +certificate, and the remainder forming the chain of certificates up to and including the +trusted root certificate.

+

This corresponds to SSL_CTX_use_certificate_chain_file.

+
source

pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack>

Sets the leaf certificate.

+

Use add_extra_chain_cert to add the remainder of the certificate chain.

+

This corresponds to SSL_CTX_use_certificate.

+
source

pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack>

Appends a certificate to the certificate chain.

+

This chain should contain all certificates necessary to go from the certificate specified by +set_certificate to a trusted root.

+

This corresponds to SSL_CTX_add_extra_chain_cert.

+
source

pub fn set_private_key_file<P>( + &mut self, + file: P, + file_type: SslFiletype, +) -> Result<(), ErrorStack>
where + P: AsRef<Path>,

Loads the private key from a file.

+

This corresponds to SSL_CTX_use_PrivateKey_file.

+
source

pub fn set_private_key<T>(&mut self, key: &PKeyRef<T>) -> Result<(), ErrorStack>
where + T: HasPrivate,

Sets the private key.

+

This corresponds to SSL_CTX_use_PrivateKey.

+
source

pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack>

Sets the list of supported ciphers for protocols before TLSv1.3.

+

The set_ciphersuites method controls the cipher suites for TLSv1.3.

+

See ciphers for details on the format.

+

This corresponds to SSL_CTX_set_cipher_list.

+
source

pub fn set_ciphersuites(&mut self, cipher_list: &str) -> Result<(), ErrorStack>

Sets the list of supported ciphers for the TLSv1.3 protocol.

+

The set_cipher_list method controls the cipher suites for protocols before TLSv1.3.

+

The format consists of TLSv1.3 cipher suite names separated by : characters in order of +preference.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_CTX_set_ciphersuites.

+
source

pub fn set_options(&mut self, option: SslOptions) -> SslOptions

Sets the options used by the context, returning the old set.

+
ยงNote
+

This enables the specified options, but does not disable unspecified options. Use +clear_options for that.

+

This corresponds to SSL_CTX_set_options.

+
source

pub fn options(&self) -> SslOptions

Returns the options used by the context.

+

This corresponds to SSL_CTX_get_options.

+
source

pub fn clear_options(&mut self, option: SslOptions) -> SslOptions

Clears the options used by the context, returning the old set.

+

This corresponds to SSL_CTX_clear_options.

+
source

pub fn set_min_proto_version( + &mut self, + version: Option<SslVersion>, +) -> Result<(), ErrorStack>

Sets the minimum supported protocol version.

+

A value of None will enable protocol versions down to the lowest version supported by +OpenSSL.

+

Requires BoringSSL or OpenSSL 1.1.0 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_min_proto_version.

+
source

pub fn set_max_proto_version( + &mut self, + version: Option<SslVersion>, +) -> Result<(), ErrorStack>

Sets the maximum supported protocol version.

+

A value of None will enable protocol versions up to the highest version supported by +OpenSSL.

+

Requires BoringSSL or OpenSSL 1.1.0 or or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_max_proto_version.

+
source

pub fn min_proto_version(&mut self) -> Option<SslVersion>

Gets the minimum supported protocol version.

+

A value of None indicates that all versions down to the lowest version supported by +OpenSSL are enabled.

+

Requires OpenSSL 1.1.0g or LibreSSL 2.7.0 or newer.

+

This corresponds to SSL_CTX_get_min_proto_version.

+
source

pub fn max_proto_version(&mut self) -> Option<SslVersion>

Gets the maximum supported protocol version.

+

A value of None indicates that all versions up to the highest version supported by +OpenSSL are enabled.

+

Requires OpenSSL 1.1.0g or LibreSSL 2.7.0 or newer.

+

This corresponds to SSL_CTX_get_max_proto_version.

+
source

pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack>

Sets the protocols to sent to the server for Application Layer Protocol Negotiation (ALPN).

+

The input must be in ALPN โ€œwire formatโ€. It consists of a sequence of supported protocol +names prefixed by their byte length. For example, the protocol list consisting of spdy/1 +and http/1.1 is encoded as b"\x06spdy/1\x08http/1.1". The protocols are ordered by +preference.

+

Requires BoringSSL or OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_alpn_protos.

+
source

pub fn set_tlsext_use_srtp(&mut self, protocols: &str) -> Result<(), ErrorStack>

Enables the DTLS extension โ€œuse_srtpโ€ as defined in RFC5764.

+

This corresponds to SSL_CTX_set_tlsext_use_srtp.

+
source

pub fn set_alpn_select_callback<F>(&mut self, callback: F)
where + F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,

Sets the callback used by a server to select a protocol for Application Layer Protocol +Negotiation (ALPN).

+

The callback is provided with the clientโ€™s protocol list in ALPN wire format. See the +documentation for SslContextBuilder::set_alpn_protos for details. It should return one +of those protocols on success. The select_next_proto function implements the standard +protocol selection algorithm.

+

Requires OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

+

This corresponds to SSL_CTX_set_alpn_select_cb.

+
source

pub fn check_private_key(&self) -> Result<(), ErrorStack>

Checks for consistency between the private key and certificate.

+

This corresponds to SSL_CTX_check_private_key.

+
source

pub fn cert_store(&self) -> &X509StoreBuilderRef

Returns a shared reference to the contextโ€™s certificate store.

+

This corresponds to SSL_CTX_get_cert_store.

+
source

pub fn cert_store_mut(&mut self) -> &mut X509StoreBuilderRef

Returns a mutable reference to the contextโ€™s certificate store.

+

This corresponds to SSL_CTX_get_cert_store.

+
source

pub fn verify_param(&self) -> &X509VerifyParamRef

Returns a reference to the X509 verification configuration.

+

Requires BoringSSL or OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_get0_param.

+
source

pub fn verify_param_mut(&mut self) -> &mut X509VerifyParamRef

Returns a mutable reference to the X509 verification configuration.

+

Requires BoringSSL or OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_get0_param.

+
source

pub fn set_status_callback<F>(&mut self, callback: F) -> Result<(), ErrorStack>
where + F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,

Sets the callback dealing with OCSP stapling.

+

On the client side, this callback is responsible for validating the OCSP status response +returned by the server. The status may be retrieved with the SslRef::ocsp_status method. +A response of Ok(true) indicates that the OCSP status is valid, and a response of +Ok(false) indicates that the OCSP status is invalid and the handshake should be +terminated.

+

On the server side, this callback is responsible for setting the OCSP status response to be +returned to clients. The status may be set with the SslRef::set_ocsp_status method. A +response of Ok(true) indicates that the OCSP status should be returned to the client, and +Ok(false) indicates that the status should not be returned to the client.

+

This corresponds to SSL_CTX_set_tlsext_status_cb.

+
source

pub fn set_psk_client_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,

Sets the callback for providing an identity and pre-shared key for a TLS-PSK client.

+

The callback will be called with the SSL context, an identity hint if one was provided +by the server, a mutable slice for each of the identity and pre-shared key bytes. The +identity must be written as a null-terminated C string.

+

This corresponds to SSL_CTX_set_psk_client_callback.

+
source

pub fn set_psk_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,

๐Ÿ‘ŽDeprecated since 0.10.10: renamed to set_psk_client_callback
source

pub fn set_psk_server_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,

Sets the callback for providing an identity and pre-shared key for a TLS-PSK server.

+

The callback will be called with the SSL context, an identity provided by the client, +and, a mutable slice for the pre-shared key bytes. The callback returns the number of +bytes in the pre-shared key.

+

This corresponds to SSL_CTX_set_psk_server_callback.

+
source

pub fn set_new_session_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,

Sets the callback which is called when new sessions are negotiated.

+

This can be used by clients to implement session caching. While in TLSv1.2 the session is +available to access via SslRef::session immediately after the handshake completes, this +is not the case for TLSv1.3. There, a session is not generally available immediately, and +the server may provide multiple session tokens to the client over a single session. The new +session callback is a portable way to deal with both cases.

+

Note that session caching must be enabled for the callback to be invoked, and it defaults +off for clients. set_session_cache_mode controls that behavior.

+

This corresponds to SSL_CTX_sess_set_new_cb.

+
source

pub fn set_remove_session_callback<F>(&mut self, callback: F)
where + F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,

Sets the callback which is called when sessions are removed from the context.

+

Sessions can be removed because they have timed out or because they are considered faulty.

+

This corresponds to SSL_CTX_sess_set_remove_cb.

+
source

pub unsafe fn set_get_session_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,

Sets the callback which is called when a client proposed to resume a session but it was not +found in the internal cache.

+

The callback is passed a reference to the session ID provided by the client. It should +return the session corresponding to that ID if available. This is only used for servers, not +clients.

+
ยงSafety
+

The returned SslSession must not be associated with a different SslContext.

+

This corresponds to SSL_CTX_sess_set_get_cb.

+
source

pub fn set_keylog_callback<F>(&mut self, callback: F)
where + F: Fn(&SslRef, &str) + 'static + Sync + Send,

Sets the TLS key logging callback.

+

The callback is invoked whenever TLS key material is generated, and is passed a line of NSS +SSLKEYLOGFILE-formatted text. This can be used by tools like Wireshark to decrypt message +traffic. The line does not contain a trailing newline.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_set_keylog_callback.

+
source

pub fn set_session_cache_mode( + &mut self, + mode: SslSessionCacheMode, +) -> SslSessionCacheMode

Sets the session caching mode use for connections made with the context.

+

Returns the previous session caching mode.

+

This corresponds to SSL_CTX_set_session_cache_mode.

+

Sets the callback for generating an application cookie for TLS1.3 +stateless handshakes.

+

The callback will be called with the SSL context and a slice into which the cookie +should be written. The callback should return the number of bytes written.

+

This corresponds to SSL_CTX_set_stateless_cookie_generate_cb.

+

Sets the callback for verifying an application cookie for TLS1.3 +stateless handshakes.

+

The callback will be called with the SSL context and the cookie supplied by the +client. It should return true if and only if the cookie is valid.

+

Note that the OpenSSL implementation independently verifies the integrity of +application cookies using an HMAC before invoking the supplied callback.

+

This corresponds to SSL_CTX_set_stateless_cookie_verify_cb.

+

Sets the callback for generating a DTLSv1 cookie

+

The callback will be called with the SSL context and a slice into which the cookie +should be written. The callback should return the number of bytes written.

+

This corresponds to SSL_CTX_set_cookie_generate_cb.

+

Sets the callback for verifying a DTLSv1 cookie

+

The callback will be called with the SSL context and the cookie supplied by the +client. It should return true if and only if the cookie is valid.

+

This corresponds to SSL_CTX_set_cookie_verify_cb.

+
source

pub fn set_ex_data<T>(&mut self, index: Index<SslContext, T>, data: T)

Sets the extra data at the specified index.

+

This can be used to provide data to callbacks registered with the context. Use the +SslContext::new_ex_index method to create an Index.

+

This corresponds to SSL_CTX_set_ex_data.

+
source

pub fn add_custom_ext<AddFn, ParseFn, T>( + &mut self, + ext_type: u16, + context: ExtensionContext, + add_cb: AddFn, + parse_cb: ParseFn, +) -> Result<(), ErrorStack>
where + AddFn: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result<Option<T>, SslAlert> + 'static + Sync + Send, + T: AsRef<[u8]> + 'static + Sync + Send, + ParseFn: Fn(&mut SslRef, ExtensionContext, &[u8], Option<(usize, &X509Ref)>) -> Result<(), SslAlert> + 'static + Sync + Send,

Adds a custom extension for a TLS/DTLS client or server for all supported protocol versions.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_add_custom_ext.

+
source

pub fn set_max_early_data(&mut self, bytes: u32) -> Result<(), ErrorStack>

Sets the maximum amount of early data that will be accepted on incoming connections.

+

Defaults to 0.

+

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

+

This corresponds to SSL_CTX_set_max_early_data.

+
source

pub fn set_client_hello_callback<F>(&mut self, callback: F)
where + F: Fn(&mut SslRef, &mut SslAlert) -> Result<ClientHelloResponse, ErrorStack> + 'static + Sync + Send,

Sets a callback which will be invoked just after the clientโ€™s hello message is received.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_set_client_hello_cb.

+
source

pub fn set_session_cache_size(&mut self, size: i32) -> i64

Sets the contextโ€™s session cache size limit, returning the previous limit.

+

A value of 0 means that the cache size is unbounded.

+

This corresponds to SSL_CTX_sess_set_cache_size.

+
source

pub fn set_sigalgs_list(&mut self, sigalgs: &str) -> Result<(), ErrorStack>

Sets the contextโ€™s supported signature algorithms.

+

Requires OpenSSL 1.0.2 or newer.

+

This corresponds to SSL_CTX_set1_sigalgs_list.

+
source

pub fn set_groups_list(&mut self, groups: &str) -> Result<(), ErrorStack>

Sets the contextโ€™s supported elliptic curve groups.

+

Requires BoringSSL or OpenSSL 1.1.1 or LibreSSL 2.5.1 or newer.

+

This corresponds to SSL_CTX_set1_groups_list.

+
source

pub fn set_num_tickets(&mut self, num_tickets: usize) -> Result<(), ErrorStack>

Sets the number of TLS 1.3 session tickets that will be sent to a client after a full +handshake.

+

Requires OpenSSL 1.1.1 or newer.

+

This corresponds to SSL_CTX_set_num_tickets.

+
source

pub fn set_security_level(&mut self, level: u32)

Set the contextโ€™s security level to a value between 0 and 5, inclusive. +A security value of 0 allows allows all parameters and algorithms.

+

Requires OpenSSL 1.1.0 or newer.

+

This corresponds to SSL_CTX_set_security_level.

+

Trait Implementationsยง

sourceยง

impl Deref for SslConnectorBuilder

sourceยง

type Target = SslContextBuilder

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &SslContextBuilder

Dereferences the value.
sourceยง

impl DerefMut for SslConnectorBuilder

sourceยง

fn deref_mut(&mut self) -> &mut SslContextBuilder

Mutably dereferences the value.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/reexports/struct.SslMethod.html b/actix_tls/connect/openssl/reexports/struct.SslMethod.html new file mode 100644 index 00000000..642cfb88 --- /dev/null +++ b/actix_tls/connect/openssl/reexports/struct.SslMethod.html @@ -0,0 +1,31 @@ +SslMethod in actix_tls::connect::openssl::reexports - Rust
actix_tls::connect::openssl::reexports

Struct SslMethod

source
pub struct SslMethod(/* private fields */);
Expand description

A type specifying the kind of protocol an SslContext will speak.

+

Implementationsยง

sourceยง

impl SslMethod

source

pub fn tls() -> SslMethod

Support all versions of the TLS protocol.

+

This corresponds to TLS_method.

+
source

pub fn dtls() -> SslMethod

Support all versions of the DTLS protocol.

+

This corresponds to DTLS_method.

+
source

pub fn tls_client() -> SslMethod

Support all versions of the TLS protocol, explicitly as a client.

+

This corresponds to TLS_client_method.

+
source

pub fn tls_server() -> SslMethod

Support all versions of the TLS protocol, explicitly as a server.

+

This corresponds to TLS_server_method.

+
source

pub unsafe fn from_ptr(ptr: *const SSL_METHOD) -> SslMethod

Constructs an SslMethod from a pointer to the underlying OpenSSL value.

+
ยงSafety
+

The caller must ensure the pointer is valid.

+
source

pub fn as_ptr(&self) -> *const SSL_METHOD

Returns a pointer to the underlying OpenSSL value.

+

Trait Implementationsยง

sourceยง

impl Clone for SslMethod

sourceยง

fn clone(&self) -> SslMethod

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Copy for SslMethod

sourceยง

impl Send for SslMethod

sourceยง

impl Sync for SslMethod

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/sidebar-items.js b/actix_tls/connect/openssl/sidebar-items.js new file mode 100644 index 00000000..27e2fa41 --- /dev/null +++ b/actix_tls/connect/openssl/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["reexports"],"struct":["TlsConnector","TlsConnectorService"]}; \ No newline at end of file diff --git a/actix_tls/connect/openssl/struct.TlsConnector.html b/actix_tls/connect/openssl/struct.TlsConnector.html new file mode 100644 index 00000000..171eb9fb --- /dev/null +++ b/actix_tls/connect/openssl/struct.TlsConnector.html @@ -0,0 +1,36 @@ +TlsConnector in actix_tls::connect::openssl - Rust
actix_tls::connect::openssl

Struct TlsConnector

source
pub struct TlsConnector { /* private fields */ }
Expand description

Connector service factory using openssl.

+

Implementationsยง

sourceยง

impl TlsConnector

source

pub fn new(connector: SslConnector) -> Self

Constructs new connector service factory from an openssl connector.

+
source

pub fn service(connector: SslConnector) -> TlsConnectorService

Constructs new connector service from an openssl connector.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnector

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, SslStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/openssl/struct.TlsConnectorService.html b/actix_tls/connect/openssl/struct.TlsConnectorService.html new file mode 100644 index 00000000..5d386e2d --- /dev/null +++ b/actix_tls/connect/openssl/struct.TlsConnectorService.html @@ -0,0 +1,31 @@ +TlsConnectorService in actix_tls::connect::openssl - Rust
actix_tls::connect::openssl

Struct TlsConnectorService

source
pub struct TlsConnectorService { /* private fields */ }
Expand description

Connector service using openssl.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnectorService

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, SslStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, stream: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/resolve/trait.Resolve.html b/actix_tls/connect/resolve/trait.Resolve.html new file mode 100644 index 00000000..960a66f0 --- /dev/null +++ b/actix_tls/connect/resolve/trait.Resolve.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/trait.Resolve.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/resolver/struct.Resolver.html b/actix_tls/connect/resolver/struct.Resolver.html new file mode 100644 index 00000000..e3562aef --- /dev/null +++ b/actix_tls/connect/resolver/struct.Resolver.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/struct.Resolver.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/resolver/struct.ResolverService.html b/actix_tls/connect/resolver/struct.ResolverService.html new file mode 100644 index 00000000..8cfb92b9 --- /dev/null +++ b/actix_tls/connect/resolver/struct.ResolverService.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_tls/connect/struct.ResolverService.html...

+ + + \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/fn.native_roots_cert_store.html b/actix_tls/connect/rustls_0_20/fn.native_roots_cert_store.html new file mode 100644 index 00000000..9a12bd6f --- /dev/null +++ b/actix_tls/connect/rustls_0_20/fn.native_roots_cert_store.html @@ -0,0 +1,3 @@ +native_roots_cert_store in actix_tls::connect::rustls_0_20 - Rust
actix_tls::connect::rustls_0_20

Function native_roots_cert_store

source
pub fn native_roots_cert_store() -> Result<RootCertStore>
Expand description

Returns root certificates via rustls-native-certs crate as a rustls certificate store.

+

See rustls_native_certs::load_native_certs() for more info on behavior and errors.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/fn.webpki_roots_cert_store.html b/actix_tls/connect/rustls_0_20/fn.webpki_roots_cert_store.html new file mode 100644 index 00000000..62189d9e --- /dev/null +++ b/actix_tls/connect/rustls_0_20/fn.webpki_roots_cert_store.html @@ -0,0 +1,2 @@ +webpki_roots_cert_store in actix_tls::connect::rustls_0_20 - Rust
actix_tls::connect::rustls_0_20

Function webpki_roots_cert_store

source
pub fn webpki_roots_cert_store() -> RootCertStore
Expand description

Returns standard root certificates from webpki-roots crate as a rustls certificate store.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/index.html b/actix_tls/connect/rustls_0_20/index.html new file mode 100644 index 00000000..f413ebc9 --- /dev/null +++ b/actix_tls/connect/rustls_0_20/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_20 - Rust
actix_tls::connect

Module rustls_0_20

source
Expand description

Rustls based connector service.

+

See TlsConnector for main connector service factory docs.

+

Modulesยง

  • Re-exports from the rustls v0.20 ecosystem that are useful for connectors.

Structsยง

Functionsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/reexports/index.html b/actix_tls/connect/rustls_0_20/reexports/index.html new file mode 100644 index 00000000..5cd88432 --- /dev/null +++ b/actix_tls/connect/rustls_0_20/reexports/index.html @@ -0,0 +1,4 @@ +actix_tls::connect::rustls_0_20::reexports - Rust
actix_tls::connect::rustls_0_20

Module reexports

source
Expand description

Re-exports from the rustls v0.20 ecosystem that are useful for connectors.

+

Structsยง

  • A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.
  • Common configuration for (typically) all connections made by +a program.

Staticsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/reexports/sidebar-items.js b/actix_tls/connect/rustls_0_20/reexports/sidebar-items.js new file mode 100644 index 00000000..5f006fad --- /dev/null +++ b/actix_tls/connect/rustls_0_20/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"static":["TLS_SERVER_ROOTS"],"struct":["AsyncTlsStream","ClientConfig"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/reexports/static.TLS_SERVER_ROOTS.html b/actix_tls/connect/rustls_0_20/reexports/static.TLS_SERVER_ROOTS.html new file mode 100644 index 00000000..2234e58d --- /dev/null +++ b/actix_tls/connect/rustls_0_20/reexports/static.TLS_SERVER_ROOTS.html @@ -0,0 +1 @@ +TLS_SERVER_ROOTS in actix_tls::connect::rustls_0_20::reexports - Rust
actix_tls::connect::rustls_0_20::reexports

Static TLS_SERVER_ROOTS

pub static TLS_SERVER_ROOTS: TlsServerTrustAnchors<'static>
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/reexports/struct.AsyncTlsStream.html b/actix_tls/connect/rustls_0_20/reexports/struct.AsyncTlsStream.html new file mode 100644 index 00000000..af5c1744 --- /dev/null +++ b/actix_tls/connect/rustls_0_20/reexports/struct.AsyncTlsStream.html @@ -0,0 +1,49 @@ +AsyncTlsStream in actix_tls::connect::rustls_0_20::reexports - Rust
actix_tls::connect::rustls_0_20::reexports

Struct AsyncTlsStream

pub struct AsyncTlsStream<IO> { /* private fields */ }
Expand description

A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.

+

Implementationsยง

ยง

impl<IO> TlsStream<IO>

pub fn get_ref(&self) -> (&IO, &ClientConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ClientConnection)

pub fn into_inner(self) -> (IO, ClientConnection)

Trait Implementationsยง

ยง

impl<S> AsRawFd for TlsStream<S>
where + S: AsRawFd,

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl<IO> AsyncRead for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_read( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl<IO> AsyncWrite for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_write( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Note: that it does not guarantee the final data to be sent. +To be cautious, you must manually call flush.

+
ยง

fn poll_flush( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

impl<IO> Debug for TlsStream<IO>
where + IO: Debug,

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/reexports/struct.ClientConfig.html b/actix_tls/connect/rustls_0_20/reexports/struct.ClientConfig.html new file mode 100644 index 00000000..d146c27b --- /dev/null +++ b/actix_tls/connect/rustls_0_20/reexports/struct.ClientConfig.html @@ -0,0 +1,63 @@ +ClientConfig in actix_tls::connect::rustls_0_20::reexports - Rust
actix_tls::connect::rustls_0_20::reexports

Struct ClientConfig

pub struct ClientConfig {
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub session_storage: Arc<dyn StoresClientSessions>,
+    pub max_fragment_size: Option<usize>,
+    pub client_auth_cert_resolver: Arc<dyn ResolvesClientCert>,
+    pub enable_tickets: bool,
+    pub enable_sni: bool,
+    pub key_log: Arc<dyn KeyLog>,
+    pub enable_early_data: bool,
+    /* private fields */
+}
Expand description

Common configuration for (typically) all connections made by +a program.

+

Making one of these can be expensive, and should be +once per process rather than once per connection.

+

These must be created via the ClientConfig::builder() function.

+

ยงDefaults

+ +

Fieldsยง

ยงalpn_protocols: Vec<Vec<u8>>

Which ALPN protocols we include in our client hello. +If empty, no ALPN extension is sent.

+
ยงsession_storage: Arc<dyn StoresClientSessions>

How we store session data or tickets.

+
ยงmax_fragment_size: Option<usize>

The maximum size of TLS message weโ€™ll emit. If None, we donโ€™t limit TLS +message lengths except to the 2**16 limit specified in the standard.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ClientConnection::new.

+

Setting this value to the TCP MSS may improve latency for stream-y workloads.

+
ยงclient_auth_cert_resolver: Arc<dyn ResolvesClientCert>

How to decide what client auth certificate/keys to use.

+
ยงenable_tickets: bool

Whether to support RFC5077 tickets. You must provide a working +session_storage member for this to have any meaningful +effect.

+

The default is true.

+
ยงenable_sni: bool

Whether to send the Server Name Indication (SNI) extension +during the client handshake.

+

The default is true.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงenable_early_data: bool

Whether to send data on the first flight (โ€œearly dataโ€) in +TLS 1.3 handshakes.

+

The default is false.

+

Implementationsยง

ยง

impl ClientConfig

pub fn builder() -> ConfigBuilder<ClientConfig, WantsCipherSuites>

Create a builder to build up the client configuration.

+

For more information, see the [ConfigBuilder] documentation.

+

Trait Implementationsยง

ยง

impl Clone for ClientConfig

ยง

fn clone(&self) -> ClientConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ClientConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ClientConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/sidebar-items.js b/actix_tls/connect/rustls_0_20/sidebar-items.js new file mode 100644 index 00000000..5564ad8e --- /dev/null +++ b/actix_tls/connect/rustls_0_20/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["native_roots_cert_store","webpki_roots_cert_store"],"mod":["reexports"],"struct":["TlsConnector","TlsConnectorService"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/struct.TlsConnector.html b/actix_tls/connect/rustls_0_20/struct.TlsConnector.html new file mode 100644 index 00000000..59e82bad --- /dev/null +++ b/actix_tls/connect/rustls_0_20/struct.TlsConnector.html @@ -0,0 +1,36 @@ +TlsConnector in actix_tls::connect::rustls_0_20 - Rust
actix_tls::connect::rustls_0_20

Struct TlsConnector

source
pub struct TlsConnector { /* private fields */ }
Expand description

Connector service factory using rustls.

+

Implementationsยง

sourceยง

impl TlsConnector

source

pub fn new(connector: Arc<ClientConfig>) -> Self

Constructs new connector service factory from a rustls client configuration.

+
source

pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService

Constructs new connector service from a rustls client configuration.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnector

sourceยง

fn clone(&self) -> TlsConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_20/struct.TlsConnectorService.html b/actix_tls/connect/rustls_0_20/struct.TlsConnectorService.html new file mode 100644 index 00000000..5621de73 --- /dev/null +++ b/actix_tls/connect/rustls_0_20/struct.TlsConnectorService.html @@ -0,0 +1,31 @@ +TlsConnectorService in actix_tls::connect::rustls_0_20 - Rust
actix_tls::connect::rustls_0_20

Struct TlsConnectorService

source
pub struct TlsConnectorService { /* private fields */ }
Expand description

Connector service using rustls.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnectorService

sourceยง

fn clone(&self) -> TlsConnectorService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/fn.native_roots_cert_store.html b/actix_tls/connect/rustls_0_21/fn.native_roots_cert_store.html new file mode 100644 index 00000000..8f3ff515 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/fn.native_roots_cert_store.html @@ -0,0 +1,3 @@ +native_roots_cert_store in actix_tls::connect::rustls_0_21 - Rust
actix_tls::connect::rustls_0_21

Function native_roots_cert_store

source
pub fn native_roots_cert_store() -> Result<RootCertStore>
Expand description

Returns root certificates via rustls-native-certs crate as a rustls certificate store.

+

See rustls_native_certs::load_native_certs() for more info on behavior and errors.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/fn.webpki_roots_cert_store.html b/actix_tls/connect/rustls_0_21/fn.webpki_roots_cert_store.html new file mode 100644 index 00000000..76832a00 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/fn.webpki_roots_cert_store.html @@ -0,0 +1,2 @@ +webpki_roots_cert_store in actix_tls::connect::rustls_0_21 - Rust
actix_tls::connect::rustls_0_21

Function webpki_roots_cert_store

source
pub fn webpki_roots_cert_store() -> RootCertStore
Expand description

Returns standard root certificates from webpki-roots crate as a rustls certificate store.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/index.html b/actix_tls/connect/rustls_0_21/index.html new file mode 100644 index 00000000..a8774134 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_21 - Rust
actix_tls::connect

Module rustls_0_21

source
Expand description

Rustls based connector service.

+

See TlsConnector for main connector service factory docs.

+

Modulesยง

  • Re-exports from the rustls v0.21 ecosystem that are useful for connectors.

Structsยง

Functionsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/reexports/constant.TLS_SERVER_ROOTS.html b/actix_tls/connect/rustls_0_21/reexports/constant.TLS_SERVER_ROOTS.html new file mode 100644 index 00000000..14183c14 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/reexports/constant.TLS_SERVER_ROOTS.html @@ -0,0 +1 @@ +TLS_SERVER_ROOTS in actix_tls::connect::rustls_0_21::reexports - Rust
actix_tls::connect::rustls_0_21::reexports

Constant TLS_SERVER_ROOTS

pub const TLS_SERVER_ROOTS: &'static [TrustAnchor<'static>];
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/reexports/index.html b/actix_tls/connect/rustls_0_21/reexports/index.html new file mode 100644 index 00000000..d84dca9c --- /dev/null +++ b/actix_tls/connect/rustls_0_21/reexports/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_21::reexports - Rust
actix_tls::connect::rustls_0_21

Module reexports

source
Expand description

Re-exports from the rustls v0.21 ecosystem that are useful for connectors.

+

Structsยง

  • A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.
  • Common configuration for (typically) all connections made by a program.

Constantsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/reexports/sidebar-items.js b/actix_tls/connect/rustls_0_21/reexports/sidebar-items.js new file mode 100644 index 00000000..33872f1f --- /dev/null +++ b/actix_tls/connect/rustls_0_21/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["TLS_SERVER_ROOTS"],"struct":["AsyncTlsStream","ClientConfig"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/reexports/struct.AsyncTlsStream.html b/actix_tls/connect/rustls_0_21/reexports/struct.AsyncTlsStream.html new file mode 100644 index 00000000..28169f84 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/reexports/struct.AsyncTlsStream.html @@ -0,0 +1,49 @@ +AsyncTlsStream in actix_tls::connect::rustls_0_21::reexports - Rust
actix_tls::connect::rustls_0_21::reexports

Struct AsyncTlsStream

pub struct AsyncTlsStream<IO> { /* private fields */ }
Expand description

A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.

+

Implementationsยง

ยง

impl<IO> TlsStream<IO>

pub fn get_ref(&self) -> (&IO, &ClientConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ClientConnection)

pub fn into_inner(self) -> (IO, ClientConnection)

Trait Implementationsยง

ยง

impl<S> AsRawFd for TlsStream<S>
where + S: AsRawFd,

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl<IO> AsyncRead for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_read( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl<IO> AsyncWrite for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_write( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Note: that it does not guarantee the final data to be sent. +To be cautious, you must manually call flush.

+
ยง

fn poll_flush( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

impl<IO> Debug for TlsStream<IO>
where + IO: Debug,

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/reexports/struct.ClientConfig.html b/actix_tls/connect/rustls_0_21/reexports/struct.ClientConfig.html new file mode 100644 index 00000000..d1b83247 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/reexports/struct.ClientConfig.html @@ -0,0 +1,60 @@ +ClientConfig in actix_tls::connect::rustls_0_21::reexports - Rust
actix_tls::connect::rustls_0_21::reexports

Struct ClientConfig

pub struct ClientConfig {
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub resumption: Resumption,
+    pub max_fragment_size: Option<usize>,
+    pub client_auth_cert_resolver: Arc<dyn ResolvesClientCert>,
+    pub enable_sni: bool,
+    pub key_log: Arc<dyn KeyLog>,
+    pub enable_early_data: bool,
+    /* private fields */
+}
Expand description

Common configuration for (typically) all connections made by a program.

+

Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots +from the operating system to add to the RootCertStore passed to with_root_certificates() +(the rustls-native-certs crate is often used for this) may take on the order of a few hundred +milliseconds.

+

These must be created via the ClientConfig::builder() function.

+

ยงDefaults

+ +

Fieldsยง

ยงalpn_protocols: Vec<Vec<u8>>

Which ALPN protocols we include in our client hello. +If empty, no ALPN extension is sent.

+
ยงresumption: Resumption

How and when the client can resume a previous session.

+
ยงmax_fragment_size: Option<usize>

The maximum size of TLS message weโ€™ll emit. If None, we donโ€™t limit TLS +message lengths except to the 2**16 limit specified in the standard.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ClientConnection::new.

+

Setting this value to the TCP MSS may improve latency for stream-y workloads.

+
ยงclient_auth_cert_resolver: Arc<dyn ResolvesClientCert>

How to decide what client auth certificate/keys to use.

+
ยงenable_sni: bool

Whether to send the Server Name Indication (SNI) extension +during the client handshake.

+

The default is true.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงenable_early_data: bool

Whether to send data on the first flight (โ€œearly dataโ€) in +TLS 1.3 handshakes.

+

The default is false.

+

Implementationsยง

ยง

impl ClientConfig

pub fn builder() -> ConfigBuilder<ClientConfig, WantsCipherSuites>

Create a builder to build up the client configuration.

+

For more information, see the [ConfigBuilder] documentation.

+

Trait Implementationsยง

ยง

impl Clone for ClientConfig

ยง

fn clone(&self) -> ClientConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ClientConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ClientConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/sidebar-items.js b/actix_tls/connect/rustls_0_21/sidebar-items.js new file mode 100644 index 00000000..5564ad8e --- /dev/null +++ b/actix_tls/connect/rustls_0_21/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["native_roots_cert_store","webpki_roots_cert_store"],"mod":["reexports"],"struct":["TlsConnector","TlsConnectorService"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/struct.TlsConnector.html b/actix_tls/connect/rustls_0_21/struct.TlsConnector.html new file mode 100644 index 00000000..97be6037 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/struct.TlsConnector.html @@ -0,0 +1,36 @@ +TlsConnector in actix_tls::connect::rustls_0_21 - Rust
actix_tls::connect::rustls_0_21

Struct TlsConnector

source
pub struct TlsConnector { /* private fields */ }
Expand description

Connector service factory using rustls.

+

Implementationsยง

sourceยง

impl TlsConnector

source

pub fn new(connector: Arc<ClientConfig>) -> Self

Constructs new connector service factory from a rustls client configuration.

+
source

pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService

Constructs new connector service from a rustls client configuration.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnector

sourceยง

fn clone(&self) -> TlsConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_21/struct.TlsConnectorService.html b/actix_tls/connect/rustls_0_21/struct.TlsConnectorService.html new file mode 100644 index 00000000..989461a5 --- /dev/null +++ b/actix_tls/connect/rustls_0_21/struct.TlsConnectorService.html @@ -0,0 +1,31 @@ +TlsConnectorService in actix_tls::connect::rustls_0_21 - Rust
actix_tls::connect::rustls_0_21

Struct TlsConnectorService

source
pub struct TlsConnectorService { /* private fields */ }
Expand description

Connector service using rustls.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnectorService

sourceยง

fn clone(&self) -> TlsConnectorService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/fn.native_roots_cert_store.html b/actix_tls/connect/rustls_0_22/fn.native_roots_cert_store.html new file mode 100644 index 00000000..37f0100b --- /dev/null +++ b/actix_tls/connect/rustls_0_22/fn.native_roots_cert_store.html @@ -0,0 +1,3 @@ +native_roots_cert_store in actix_tls::connect::rustls_0_22 - Rust
actix_tls::connect::rustls_0_22

Function native_roots_cert_store

source
pub fn native_roots_cert_store() -> Result<RootCertStore>
Expand description

Returns root certificates via rustls-native-certs crate as a rustls certificate store.

+

See rustls_native_certs::load_native_certs() for more info on behavior and errors.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/fn.webpki_roots_cert_store.html b/actix_tls/connect/rustls_0_22/fn.webpki_roots_cert_store.html new file mode 100644 index 00000000..15e7a4d4 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/fn.webpki_roots_cert_store.html @@ -0,0 +1,2 @@ +webpki_roots_cert_store in actix_tls::connect::rustls_0_22 - Rust
actix_tls::connect::rustls_0_22

Function webpki_roots_cert_store

source
pub fn webpki_roots_cert_store() -> RootCertStore
Expand description

Returns standard root certificates from webpki-roots crate as a rustls certificate store.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/index.html b/actix_tls/connect/rustls_0_22/index.html new file mode 100644 index 00000000..d58f7be7 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_22 - Rust
actix_tls::connect

Module rustls_0_22

source
Expand description

Rustls based connector service.

+

See TlsConnector for main connector service factory docs.

+

Modulesยง

  • Re-exports from the rustls v0.22 ecosystem that are useful for connectors.

Structsยง

Functionsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/reexports/constant.TLS_SERVER_ROOTS.html b/actix_tls/connect/rustls_0_22/reexports/constant.TLS_SERVER_ROOTS.html new file mode 100644 index 00000000..4ecd45b2 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/reexports/constant.TLS_SERVER_ROOTS.html @@ -0,0 +1 @@ +TLS_SERVER_ROOTS in actix_tls::connect::rustls_0_22::reexports - Rust
actix_tls::connect::rustls_0_22::reexports

Constant TLS_SERVER_ROOTS

pub const TLS_SERVER_ROOTS: &'static [TrustAnchor<'static>];
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/reexports/index.html b/actix_tls/connect/rustls_0_22/reexports/index.html new file mode 100644 index 00000000..d433fa9d --- /dev/null +++ b/actix_tls/connect/rustls_0_22/reexports/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_22::reexports - Rust
actix_tls::connect::rustls_0_22

Module reexports

source
Expand description

Re-exports from the rustls v0.22 ecosystem that are useful for connectors.

+

Structsยง

  • A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.
  • Common configuration for (typically) all connections made by a program.

Constantsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/reexports/sidebar-items.js b/actix_tls/connect/rustls_0_22/reexports/sidebar-items.js new file mode 100644 index 00000000..33872f1f --- /dev/null +++ b/actix_tls/connect/rustls_0_22/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["TLS_SERVER_ROOTS"],"struct":["AsyncTlsStream","ClientConfig"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/reexports/struct.AsyncTlsStream.html b/actix_tls/connect/rustls_0_22/reexports/struct.AsyncTlsStream.html new file mode 100644 index 00000000..35081987 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/reexports/struct.AsyncTlsStream.html @@ -0,0 +1,49 @@ +AsyncTlsStream in actix_tls::connect::rustls_0_22::reexports - Rust
actix_tls::connect::rustls_0_22::reexports

Struct AsyncTlsStream

pub struct AsyncTlsStream<IO> { /* private fields */ }
Expand description

A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.

+

Implementationsยง

ยง

impl<IO> TlsStream<IO>

pub fn get_ref(&self) -> (&IO, &ClientConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ClientConnection)

pub fn into_inner(self) -> (IO, ClientConnection)

Trait Implementationsยง

ยง

impl<S> AsRawFd for TlsStream<S>
where + S: AsRawFd,

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl<IO> AsyncRead for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_read( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl<IO> AsyncWrite for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_write( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Note: that it does not guarantee the final data to be sent. +To be cautious, you must manually call flush.

+
ยง

fn poll_flush( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Like poll_write, except that it writes from a slice of buffers. Read more
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

impl<IO> Debug for TlsStream<IO>
where + IO: Debug,

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/reexports/struct.ClientConfig.html b/actix_tls/connect/rustls_0_22/reexports/struct.ClientConfig.html new file mode 100644 index 00000000..c1630095 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/reexports/struct.ClientConfig.html @@ -0,0 +1,84 @@ +ClientConfig in actix_tls::connect::rustls_0_22::reexports - Rust
actix_tls::connect::rustls_0_22::reexports

Struct ClientConfig

pub struct ClientConfig {
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub resumption: Resumption,
+    pub max_fragment_size: Option<usize>,
+    pub client_auth_cert_resolver: Arc<dyn ResolvesClientCert>,
+    pub enable_sni: bool,
+    pub key_log: Arc<dyn KeyLog>,
+    pub enable_secret_extraction: bool,
+    pub enable_early_data: bool,
+    /* private fields */
+}
Expand description

Common configuration for (typically) all connections made by a program.

+

Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots +from the operating system to add to the RootCertStore passed to with_root_certificates() +(the rustls-native-certs crate is often used for this) may take on the order of a few hundred +milliseconds.

+

These must be created via the ClientConfig::builder() or ClientConfig::builder_with_provider() +function.

+

ยงDefaults

+ +

Fieldsยง

ยงalpn_protocols: Vec<Vec<u8>>

Which ALPN protocols we include in our client hello. +If empty, no ALPN extension is sent.

+
ยงresumption: Resumption

How and when the client can resume a previous session.

+
ยงmax_fragment_size: Option<usize>

The maximum size of plaintext input to be emitted in a single TLS record. +A value of None is equivalent to the TLS maximum of 16 kB.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ClientConnection::new.

+

Setting this value to a little less than the TCP MSS may improve latency +for stream-y workloads.

+
ยงclient_auth_cert_resolver: Arc<dyn ResolvesClientCert>

How to decide what client auth certificate/keys to use.

+
ยงenable_sni: bool

Whether to send the Server Name Indication (SNI) extension +during the client handshake.

+

The default is true.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงenable_secret_extraction: bool

Allows traffic secrets to be extracted after the handshake, +e.g. for kTLS setup.

+
ยงenable_early_data: bool

Whether to send data on the first flight (โ€œearly dataโ€) in +TLS 1.3 handshakes.

+

The default is false.

+

Implementationsยง

ยง

impl ClientConfig

pub fn builder() -> ConfigBuilder<ClientConfig, WantsVerifier>

Create a builder for a client configuration with the default +[CryptoProvider]: [crypto::ring::default_provider] and safe ciphersuite and +protocol defaults.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_protocol_versions( + versions: &[&'static SupportedProtocolVersion], +) -> ConfigBuilder<ClientConfig, WantsVerifier>

Create a builder for a client configuration with the default +[CryptoProvider]: [crypto::ring::default_provider], safe ciphersuite defaults and +the provided protocol versions.

+

Panics if provided an empty slice of supported versions.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_provider( + provider: Arc<CryptoProvider>, +) -> ConfigBuilder<ClientConfig, WantsVersions>

Create a builder for a client configuration with a specific [CryptoProvider].

+

This will use the providerโ€™s configured ciphersuites. You must additionally choose +which protocol versions to enable, using with_protocol_versions or +with_safe_default_protocol_versions and handling the Result in case a protocol +version is not supported by the providerโ€™s ciphersuites.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn dangerous(&mut self) -> DangerousClientConfig<'_>

Access configuration options whose use is dangerous and requires +extra care.

+

Trait Implementationsยง

ยง

impl Clone for ClientConfig

ยง

fn clone(&self) -> ClientConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ClientConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ClientConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/sidebar-items.js b/actix_tls/connect/rustls_0_22/sidebar-items.js new file mode 100644 index 00000000..5564ad8e --- /dev/null +++ b/actix_tls/connect/rustls_0_22/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["native_roots_cert_store","webpki_roots_cert_store"],"mod":["reexports"],"struct":["TlsConnector","TlsConnectorService"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/struct.TlsConnector.html b/actix_tls/connect/rustls_0_22/struct.TlsConnector.html new file mode 100644 index 00000000..934ec512 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/struct.TlsConnector.html @@ -0,0 +1,36 @@ +TlsConnector in actix_tls::connect::rustls_0_22 - Rust
actix_tls::connect::rustls_0_22

Struct TlsConnector

source
pub struct TlsConnector { /* private fields */ }
Expand description

Connector service factory using rustls.

+

Implementationsยง

sourceยง

impl TlsConnector

source

pub fn new(connector: Arc<ClientConfig>) -> Self

Constructs new connector service factory from a rustls client configuration.

+
source

pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService

Constructs new connector service from a rustls client configuration.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnector

sourceยง

fn clone(&self) -> TlsConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_22/struct.TlsConnectorService.html b/actix_tls/connect/rustls_0_22/struct.TlsConnectorService.html new file mode 100644 index 00000000..cfa09444 --- /dev/null +++ b/actix_tls/connect/rustls_0_22/struct.TlsConnectorService.html @@ -0,0 +1,31 @@ +TlsConnectorService in actix_tls::connect::rustls_0_22 - Rust
actix_tls::connect::rustls_0_22

Struct TlsConnectorService

source
pub struct TlsConnectorService { /* private fields */ }
Expand description

Connector service using rustls.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnectorService

sourceยง

fn clone(&self) -> TlsConnectorService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/fn.native_roots_cert_store.html b/actix_tls/connect/rustls_0_23/fn.native_roots_cert_store.html new file mode 100644 index 00000000..c1286901 --- /dev/null +++ b/actix_tls/connect/rustls_0_23/fn.native_roots_cert_store.html @@ -0,0 +1,3 @@ +native_roots_cert_store in actix_tls::connect::rustls_0_23 - Rust
actix_tls::connect::rustls_0_23

Function native_roots_cert_store

source
pub fn native_roots_cert_store() -> Result<RootCertStore>
Expand description

Returns root certificates via rustls-native-certs crate as a rustls certificate store.

+

See rustls_native_certs::load_native_certs() for more info on behavior and errors.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/fn.webpki_roots_cert_store.html b/actix_tls/connect/rustls_0_23/fn.webpki_roots_cert_store.html new file mode 100644 index 00000000..349fb4c4 --- /dev/null +++ b/actix_tls/connect/rustls_0_23/fn.webpki_roots_cert_store.html @@ -0,0 +1,2 @@ +webpki_roots_cert_store in actix_tls::connect::rustls_0_23 - Rust
actix_tls::connect::rustls_0_23

Function webpki_roots_cert_store

source
pub fn webpki_roots_cert_store() -> RootCertStore
Expand description

Returns standard root certificates from webpki-roots crate as a rustls certificate store.

+
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/index.html b/actix_tls/connect/rustls_0_23/index.html new file mode 100644 index 00000000..69c02157 --- /dev/null +++ b/actix_tls/connect/rustls_0_23/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_23 - Rust
actix_tls::connect

Module rustls_0_23

source
Expand description

Rustls based connector service.

+

See TlsConnector for main connector service factory docs.

+

Modulesยง

  • Re-exports from the rustls v0.23 ecosystem that are useful for connectors.

Structsยง

Functionsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/reexports/constant.TLS_SERVER_ROOTS.html b/actix_tls/connect/rustls_0_23/reexports/constant.TLS_SERVER_ROOTS.html new file mode 100644 index 00000000..ceec4b67 --- /dev/null +++ b/actix_tls/connect/rustls_0_23/reexports/constant.TLS_SERVER_ROOTS.html @@ -0,0 +1 @@ +TLS_SERVER_ROOTS in actix_tls::connect::rustls_0_23::reexports - Rust
actix_tls::connect::rustls_0_23::reexports

Constant TLS_SERVER_ROOTS

pub const TLS_SERVER_ROOTS: &'static [TrustAnchor<'static>];
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/reexports/index.html b/actix_tls/connect/rustls_0_23/reexports/index.html new file mode 100644 index 00000000..bba1d60e --- /dev/null +++ b/actix_tls/connect/rustls_0_23/reexports/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::rustls_0_23::reexports - Rust
actix_tls::connect::rustls_0_23

Module reexports

source
Expand description

Re-exports from the rustls v0.23 ecosystem that are useful for connectors.

+

Structsยง

  • A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.
  • Common configuration for (typically) all connections made by a program.

Constantsยง

\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/reexports/sidebar-items.js b/actix_tls/connect/rustls_0_23/reexports/sidebar-items.js new file mode 100644 index 00000000..33872f1f --- /dev/null +++ b/actix_tls/connect/rustls_0_23/reexports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["TLS_SERVER_ROOTS"],"struct":["AsyncTlsStream","ClientConfig"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/reexports/struct.AsyncTlsStream.html b/actix_tls/connect/rustls_0_23/reexports/struct.AsyncTlsStream.html new file mode 100644 index 00000000..a850cb40 --- /dev/null +++ b/actix_tls/connect/rustls_0_23/reexports/struct.AsyncTlsStream.html @@ -0,0 +1,51 @@ +AsyncTlsStream in actix_tls::connect::rustls_0_23::reexports - Rust
actix_tls::connect::rustls_0_23::reexports

Struct AsyncTlsStream

pub struct AsyncTlsStream<IO> { /* private fields */ }
Expand description

A wrapper around an underlying raw stream which implements the TLS or SSL +protocol.

+

Implementationsยง

ยง

impl<IO> TlsStream<IO>

pub fn get_ref(&self) -> (&IO, &ClientConnection)

pub fn get_mut(&mut self) -> (&mut IO, &mut ClientConnection)

pub fn into_inner(self) -> (IO, ClientConnection)

Trait Implementationsยง

ยง

impl<S> AsRawFd for TlsStream<S>
where + S: AsRawFd,

ยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
ยง

impl<IO> AsyncRead for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_read( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, +) -> Poll<Result<(), Error>>

Attempts to read from the AsyncRead into buf. Read more
ยง

impl<IO> AsyncWrite for TlsStream<IO>
where + IO: AsyncRead + AsyncWrite + Unpin,

ยง

fn poll_write( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + buf: &[u8], +) -> Poll<Result<usize, Error>>

Note: that it does not guarantee the final data to be sent. +To be cautious, you must manually call flush.

+
ยง

fn poll_write_vectored( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], +) -> Poll<Result<usize, Error>>

Note: that it does not guarantee the final data to be sent. +To be cautious, you must manually call flush.

+
ยง

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored +implementation. Read more
ยง

fn poll_flush( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach +their destination. Read more
ยง

fn poll_shutdown( + self: Pin<&mut TlsStream<IO>>, + cx: &mut Context<'_>, +) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when +the I/O connection has completely shut down. Read more
ยง

impl<IO> Debug for TlsStream<IO>
where + IO: Debug,

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

ยง

impl<IO> Freeze for TlsStream<IO>
where + IO: Freeze,

ยง

impl<IO> !RefUnwindSafe for TlsStream<IO>

ยง

impl<IO> Send for TlsStream<IO>
where + IO: Send,

ยง

impl<IO> Sync for TlsStream<IO>
where + IO: Sync,

ยง

impl<IO> Unpin for TlsStream<IO>
where + IO: Unpin,

ยง

impl<IO> !UnwindSafe for TlsStream<IO>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/reexports/struct.ClientConfig.html b/actix_tls/connect/rustls_0_23/reexports/struct.ClientConfig.html new file mode 100644 index 00000000..aa7c196b --- /dev/null +++ b/actix_tls/connect/rustls_0_23/reexports/struct.ClientConfig.html @@ -0,0 +1,137 @@ +ClientConfig in actix_tls::connect::rustls_0_23::reexports - Rust
actix_tls::connect::rustls_0_23::reexports

Struct ClientConfig

pub struct ClientConfig {
+    pub alpn_protocols: Vec<Vec<u8>>,
+    pub resumption: Resumption,
+    pub max_fragment_size: Option<usize>,
+    pub client_auth_cert_resolver: Arc<dyn ResolvesClientCert>,
+    pub enable_sni: bool,
+    pub key_log: Arc<dyn KeyLog>,
+    pub enable_secret_extraction: bool,
+    pub enable_early_data: bool,
+    pub time_provider: Arc<dyn TimeProvider>,
+    pub cert_decompressors: Vec<&'static dyn CertDecompressor>,
+    pub cert_compressors: Vec<&'static dyn CertCompressor>,
+    pub cert_compression_cache: Arc<CompressionCache>,
+    /* private fields */
+}
Expand description

Common configuration for (typically) all connections made by a program.

+

Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots +from the operating system to add to the RootCertStore passed to with_root_certificates() +(the rustls-native-certs crate is often used for this) may take on the order of a few hundred +milliseconds.

+

These must be created via the ClientConfig::builder() or ClientConfig::builder_with_provider() +function.

+

Note that using [ConfigBuilder<ClientConfig, WantsVersions>::with_ech()] will produce a common +configuration specific to the provided [crate::client::EchConfig] that may not be appropriate +for all connections made by the program. In this case the configuration should only be shared +by connections intended for domains that offer the provided [crate::client::EchConfig] in +their DNS zone.

+

ยงDefaults

+ +

Fieldsยง

ยงalpn_protocols: Vec<Vec<u8>>

Which ALPN protocols we include in our client hello. +If empty, no ALPN extension is sent.

+
ยงresumption: Resumption

How and when the client can resume a previous session.

+
ยงmax_fragment_size: Option<usize>

The maximum size of plaintext input to be emitted in a single TLS record. +A value of None is equivalent to the TLS maximum of 16 kB.

+

rustls enforces an arbitrary minimum of 32 bytes for this field. +Out of range values are reported as errors from ClientConnection::new.

+

Setting this value to a little less than the TCP MSS may improve latency +for stream-y workloads.

+
ยงclient_auth_cert_resolver: Arc<dyn ResolvesClientCert>

How to decide what client auth certificate/keys to use.

+
ยงenable_sni: bool

Whether to send the Server Name Indication (SNI) extension +during the client handshake.

+

The default is true.

+
ยงkey_log: Arc<dyn KeyLog>

How to output key material for debugging. The default +does nothing.

+
ยงenable_secret_extraction: bool

Allows traffic secrets to be extracted after the handshake, +e.g. for kTLS setup.

+
ยงenable_early_data: bool

Whether to send data on the first flight (โ€œearly dataโ€) in +TLS 1.3 handshakes.

+

The default is false.

+
ยงtime_provider: Arc<dyn TimeProvider>

Provides the current system time

+
ยงcert_decompressors: Vec<&'static dyn CertDecompressor>

How to decompress the serverโ€™s certificate chain.

+

If this is non-empty, the RFC8779 certificate compression +extension is offered, and any compressed certificates are +transparently decompressed during the handshake.

+

This only applies to TLS1.3 connections. It is ignored for +TLS1.2 connections.

+
ยงcert_compressors: Vec<&'static dyn CertCompressor>

How to compress the clientโ€™s certificate chain.

+

If a server supports this extension, and advertises support +for one of the compression algorithms included here, the +client certificate will be compressed according to RFC8779.

+

This only applies to TLS1.3 connections. It is ignored for +TLS1.2 connections.

+
ยงcert_compression_cache: Arc<CompressionCache>

Caching for compressed certificates.

+

This is optional: [compress::CompressionCache::Disabled] gives +a cache that does no caching.

+

Implementationsยง

ยง

impl ClientConfig

pub fn builder() -> ConfigBuilder<ClientConfig, WantsVerifier>

Create a builder for a client configuration with +[the process-default CryptoProvider][CryptoProvider#using-the-per-process-default-cryptoprovider] +and safe protocol version defaults.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_protocol_versions( + versions: &[&'static SupportedProtocolVersion], +) -> ConfigBuilder<ClientConfig, WantsVerifier>

Create a builder for a client configuration with +[the process-default CryptoProvider][CryptoProvider#using-the-per-process-default-cryptoprovider] +and the provided protocol versions.

+

Panics if

+
    +
  • the supported versions are not compatible with the provider (eg. +the combination of ciphersuites supported by the provider and supported +versions lead to zero cipher suites being usable),
  • +
  • if a CryptoProvider cannot be resolved using a combination of +the crate features and process default.
  • +
+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_provider( + provider: Arc<CryptoProvider>, +) -> ConfigBuilder<ClientConfig, WantsVersions>

Create a builder for a client configuration with a specific [CryptoProvider].

+

This will use the providerโ€™s configured ciphersuites. You must additionally choose +which protocol versions to enable, using with_protocol_versions or +with_safe_default_protocol_versions and handling the Result in case a protocol +version is not supported by the providerโ€™s ciphersuites.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn builder_with_details( + provider: Arc<CryptoProvider>, + time_provider: Arc<dyn TimeProvider>, +) -> ConfigBuilder<ClientConfig, WantsVersions>

Create a builder for a client configuration with no default implementation details.

+

This API must be used by no_std users.

+

You must provide a specific [TimeProvider].

+

You must provide a specific [CryptoProvider].

+

This will use the providerโ€™s configured ciphersuites. You must additionally choose +which protocol versions to enable, using with_protocol_versions or +with_safe_default_protocol_versions and handling the Result in case a protocol +version is not supported by the providerโ€™s ciphersuites.

+

For more information, see the [ConfigBuilder] documentation.

+

pub fn fips(&self) -> bool

Return true if connections made with this ClientConfig will +operate in FIPS mode.

+

This is different from [CryptoProvider::fips()]: [CryptoProvider::fips()] +is concerned only with cryptography, whereas this also covers TLS-level +configuration that NIST recommends, as well as ECH HPKE suites if applicable.

+

pub fn crypto_provider(&self) -> &Arc<CryptoProvider>

Return the crypto provider used to construct this client configuration.

+

pub fn dangerous(&mut self) -> DangerousClientConfig<'_>

Access configuration options whose use is dangerous and requires +extra care.

+

Trait Implementationsยง

ยง

impl Clone for ClientConfig

ยง

fn clone(&self) -> ClientConfig

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
ยง

impl Debug for ClientConfig

ยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
ยง

impl ConfigSide for ClientConfig

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/sidebar-items.js b/actix_tls/connect/rustls_0_23/sidebar-items.js new file mode 100644 index 00000000..5564ad8e --- /dev/null +++ b/actix_tls/connect/rustls_0_23/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["native_roots_cert_store","webpki_roots_cert_store"],"mod":["reexports"],"struct":["TlsConnector","TlsConnectorService"]}; \ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/struct.TlsConnector.html b/actix_tls/connect/rustls_0_23/struct.TlsConnector.html new file mode 100644 index 00000000..2c3a1e4c --- /dev/null +++ b/actix_tls/connect/rustls_0_23/struct.TlsConnector.html @@ -0,0 +1,36 @@ +TlsConnector in actix_tls::connect::rustls_0_23 - Rust
actix_tls::connect::rustls_0_23

Struct TlsConnector

source
pub struct TlsConnector { /* private fields */ }
Expand description

Connector service factory using rustls.

+

Implementationsยง

sourceยง

impl TlsConnector

source

pub fn new(connector: Arc<ClientConfig>) -> Self

Constructs new connector service factory from a rustls client configuration.

+
source

pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService

Constructs new connector service from a rustls client configuration.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnector

sourceยง

fn clone(&self) -> TlsConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/rustls_0_23/struct.TlsConnectorService.html b/actix_tls/connect/rustls_0_23/struct.TlsConnectorService.html new file mode 100644 index 00000000..23e84c87 --- /dev/null +++ b/actix_tls/connect/rustls_0_23/struct.TlsConnectorService.html @@ -0,0 +1,31 @@ +TlsConnectorService in actix_tls::connect::rustls_0_23 - Rust
actix_tls::connect::rustls_0_23

Struct TlsConnectorService

source
pub struct TlsConnectorService { /* private fields */ }
Expand description

Connector service using rustls.

+

Trait Implementationsยง

sourceยง

impl Clone for TlsConnectorService

sourceยง

fn clone(&self) -> TlsConnectorService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/sidebar-items.js b/actix_tls/connect/sidebar-items.js new file mode 100644 index 00000000..a413b4ec --- /dev/null +++ b/actix_tls/connect/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["ConnectError"],"mod":["native_tls","openssl","rustls_0_20","rustls_0_21","rustls_0_22","rustls_0_23","tcp"],"struct":["ConnectInfo","Connection","Connector","ConnectorService","Resolver","ResolverService"],"trait":["Host","Resolve"]}; \ No newline at end of file diff --git a/actix_tls/connect/struct.ConnectInfo.html b/actix_tls/connect/struct.ConnectInfo.html new file mode 100644 index 00000000..a652299b --- /dev/null +++ b/actix_tls/connect/struct.ConnectInfo.html @@ -0,0 +1,69 @@ +ConnectInfo in actix_tls::connect - Rust
actix_tls::connect

Struct ConnectInfo

source
pub struct ConnectInfo<R> { /* private fields */ }
Expand description

Connection request information.

+

May contain known/pre-resolved socket address(es) or a host that needs resolving with DNS.

+

Implementationsยง

sourceยง

impl<R: Host> ConnectInfo<R>

source

pub fn new(request: R) -> ConnectInfo<R>

Constructs new connection info using a request.

+
source

pub fn with_addr(request: R, addr: SocketAddr) -> ConnectInfo<R>

Constructs new connection info from request and known socket address.

+

Since socket address is known, Connector will skip the DNS +resolution step.

+
source

pub fn set_port(self, port: u16) -> Self

Set connection port.

+

If request provided a port, this will override it.

+
source

pub fn set_addr(self, addr: impl Into<Option<SocketAddr>>) -> Self

Set connection socket address.

+
source

pub fn set_addrs<I>(self, addrs: I) -> Self
where + I: IntoIterator<Item = SocketAddr>,

Set list of addresses.

+
source

pub fn set_local_addr(self, addr: impl Into<IpAddr>) -> Self

Set local address to connection with.

+

Useful in situations where the IP address bound to a particular network interface is known. +This would make sure the socket is opened through that interface.

+
source

pub fn request(&self) -> &R

Returns a reference to the connection request.

+
source

pub fn hostname(&self) -> &str

Returns request hostname.

+
source

pub fn port(&self) -> u16

Returns request port.

+
source

pub fn addrs( + &self, +) -> impl Iterator<Item = SocketAddr> + ExactSizeIterator + FusedIterator + Clone + Debug + '_

Get borrowed iterator of resolved request addresses.

+
ยงExamples
+
let addr = SocketAddr::from(([127, 0, 0, 1], 4242));
+
+let conn = ConnectInfo::new("localhost");
+let mut addrs = conn.addrs();
+assert!(addrs.next().is_none());
+
+let conn = ConnectInfo::with_addr("localhost", addr);
+let mut addrs = conn.addrs();
+assert_eq!(addrs.next().unwrap(), addr);
+
source

pub fn take_addrs( + &mut self, +) -> impl Iterator<Item = SocketAddr> + ExactSizeIterator + FusedIterator + Clone + Debug + 'static

Take owned iterator resolved request addresses.

+
ยงExamples
+
let addr = SocketAddr::from(([127, 0, 0, 1], 4242));
+
+let mut conn = ConnectInfo::new("localhost");
+let mut addrs = conn.take_addrs();
+assert!(addrs.next().is_none());
+
+let mut conn = ConnectInfo::with_addr("localhost", addr);
+let mut addrs = conn.take_addrs();
+assert_eq!(addrs.next().unwrap(), addr);
+

Trait Implementationsยง

sourceยง

impl<R: Debug> Debug for ConnectInfo<R>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<R: Host> Display for ConnectInfo<R>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<R: Host> From<R> for ConnectInfo<R>

sourceยง

fn from(addr: R) -> Self

Converts to this type from the input type.
sourceยง

impl<R: Hash> Hash for ConnectInfo<R>

sourceยง

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
sourceยง

impl<R: PartialEq> PartialEq for ConnectInfo<R>

sourceยง

fn eq(&self, other: &ConnectInfo<R>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
sourceยง

impl<R: Host> Service<ConnectInfo<R>> for ConnectorService

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the service.
sourceยง

type Error = ConnectError

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectServiceResponse<R>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: ConnectInfo<R>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R: Host> Service<ConnectInfo<R>> for ResolverService

sourceยง

type Response = ConnectInfo<R>

Responses given by the service.
sourceยง

type Error = ConnectError

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ResolverFut<R>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: ConnectInfo<R>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R: Host> Service<ConnectInfo<R>> for TcpConnectorService

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the service.
sourceยง

type Error = ConnectError

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = TcpConnectorFut<R>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: ConnectInfo<R>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R: Host> ServiceFactory<ConnectInfo<R>> for Connector

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the created services.
sourceยง

type Error = ConnectError

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = ConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Connector as ServiceFactory<ConnectInfo<R>>>::Service, <Connector as ServiceFactory<ConnectInfo<R>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R: Host> ServiceFactory<ConnectInfo<R>> for Resolver

sourceยง

type Response = ConnectInfo<R>

Responses given by the created services.
sourceยง

type Error = ConnectError

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = ResolverService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Resolver as ServiceFactory<ConnectInfo<R>>>::Service, <Resolver as ServiceFactory<ConnectInfo<R>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R: Host> ServiceFactory<ConnectInfo<R>> for TcpConnector

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the created services.
sourceยง

type Error = ConnectError

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TcpConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TcpConnector as ServiceFactory<ConnectInfo<R>>>::Service, <TcpConnector as ServiceFactory<ConnectInfo<R>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R: Eq> Eq for ConnectInfo<R>

sourceยง

impl<R> StructuralPartialEq for ConnectInfo<R>

Auto Trait Implementationsยง

ยง

impl<R> Freeze for ConnectInfo<R>
where + R: Freeze,

ยง

impl<R> RefUnwindSafe for ConnectInfo<R>
where + R: RefUnwindSafe,

ยง

impl<R> Send for ConnectInfo<R>
where + R: Send,

ยง

impl<R> Sync for ConnectInfo<R>
where + R: Sync,

ยง

impl<R> Unpin for ConnectInfo<R>
where + R: Unpin,

ยง

impl<R> UnwindSafe for ConnectInfo<R>
where + R: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/struct.Connection.html b/actix_tls/connect/struct.Connection.html new file mode 100644 index 00000000..92750820 --- /dev/null +++ b/actix_tls/connect/struct.Connection.html @@ -0,0 +1,61 @@ +Connection in actix_tls::connect - Rust
actix_tls::connect

Struct Connection

source
pub struct Connection<R, IO> { /* private fields */ }
Expand description

Wraps underlying I/O and the connection request that initiated it.

+

Implementationsยง

sourceยง

impl<R, IO> Connection<R, IO>

source

pub fn new(req: R, io: IO) -> Self

Construct new Connection from request and IO parts.

+
sourceยง

impl<R, IO> Connection<R, IO>

source

pub fn into_parts(self) -> (IO, R)

Deconstructs into IO and request parts.

+
source

pub fn replace_io<IO2>(self, io: IO2) -> (IO, Connection<R, IO2>)

Replaces underlying IO, returning old IO and new Connection.

+
source

pub fn io_ref(&self) -> &IO

Returns a shared reference to the underlying IO.

+
source

pub fn io_mut(&mut self) -> &mut IO

Returns a mutable reference to the underlying IO.

+
source

pub fn request(&self) -> &R

Returns a reference to the connection request.

+
sourceยง

impl<R: Host, IO> Connection<R, IO>

source

pub fn hostname(&self) -> &str

Returns hostname.

+

Trait Implementationsยง

sourceยง

impl<R: Debug, IO: Debug> Debug for Connection<R, IO>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<R, IO> Deref for Connection<R, IO>

sourceยง

type Target = IO

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &Self::Target

Dereferences the value.
sourceยง

impl<R, IO> DerefMut for Connection<R, IO>

sourceยง

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

The native-tls connector is both itโ€™s ServiceFactory and Service impl type. +As the factory and service share the same type and state.

+
sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = Pin<Box<dyn Future<Output = Result<<TlsConnector as Service<Connection<R, IO>>>::Response, <TlsConnector as Service<Connection<R, IO>>>::Error>>>>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, stream: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, SslStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, stream: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where + R: Host, + IO: ActixStream,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the service.
sourceยง

type Error = Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectFut<R, IO>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, connection: Connection<R, IO>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, SslStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + R: Host, + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl<R: Host, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where + IO: ActixStream + 'static,

sourceยง

type Response = Connection<R, TlsStream<IO>>

Responses given by the created services.
sourceยง

type Error = Error

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TlsConnector

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TlsConnector as ServiceFactory<Connection<R, IO>>>::Service, <TlsConnector as ServiceFactory<Connection<R, IO>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

ยง

impl<R, IO> Freeze for Connection<R, IO>
where + R: Freeze, + IO: Freeze,

ยง

impl<R, IO> RefUnwindSafe for Connection<R, IO>
where + R: RefUnwindSafe, + IO: RefUnwindSafe,

ยง

impl<R, IO> Send for Connection<R, IO>
where + R: Send, + IO: Send,

ยง

impl<R, IO> Sync for Connection<R, IO>
where + R: Sync, + IO: Sync,

ยง

impl<R, IO> Unpin for Connection<R, IO>
where + R: Unpin, + IO: Unpin,

ยง

impl<R, IO> UnwindSafe for Connection<R, IO>
where + R: UnwindSafe, + IO: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/struct.Connector.html b/actix_tls/connect/struct.Connector.html new file mode 100644 index 00000000..409ff158 --- /dev/null +++ b/actix_tls/connect/struct.Connector.html @@ -0,0 +1,36 @@ +Connector in actix_tls::connect - Rust
actix_tls::connect

Struct Connector

source
pub struct Connector { /* private fields */ }
Expand description

Combined resolver and TCP connector service factory.

+

Used to create ConnectorServices which receive connection information, resolve DNS if +required, and return a TCP stream.

+

Implementationsยง

sourceยง

impl Connector

source

pub fn new(resolver: Resolver) -> Self

Constructs new connector factory with the given resolver.

+
source

pub fn service(&self) -> ConnectorService

Build connector service.

+

Trait Implementationsยง

sourceยง

impl Clone for Connector

sourceยง

fn clone(&self) -> Connector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Default for Connector

sourceยง

fn default() -> Connector

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<R: Host> ServiceFactory<ConnectInfo<R>> for Connector

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the created services.
sourceยง

type Error = ConnectError

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = ConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Connector as ServiceFactory<ConnectInfo<R>>>::Service, <Connector as ServiceFactory<ConnectInfo<R>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/struct.ConnectorService.html b/actix_tls/connect/struct.ConnectorService.html new file mode 100644 index 00000000..368acf6b --- /dev/null +++ b/actix_tls/connect/struct.ConnectorService.html @@ -0,0 +1,31 @@ +ConnectorService in actix_tls::connect - Rust
actix_tls::connect

Struct ConnectorService

source
pub struct ConnectorService { /* private fields */ }
Expand description

Combined resolver and TCP connector service.

+

Service implementation receives connection information, resolves DNS if required, and returns +a TCP stream.

+

Trait Implementationsยง

sourceยง

impl Clone for ConnectorService

sourceยง

fn clone(&self) -> ConnectorService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Default for ConnectorService

sourceยง

fn default() -> ConnectorService

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<R: Host> Service<ConnectInfo<R>> for ConnectorService

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the service.
sourceยง

type Error = ConnectError

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ConnectServiceResponse<R>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: ConnectInfo<R>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/struct.Resolver.html b/actix_tls/connect/struct.Resolver.html new file mode 100644 index 00000000..4c7e486b --- /dev/null +++ b/actix_tls/connect/struct.Resolver.html @@ -0,0 +1,34 @@ +Resolver in actix_tls::connect - Rust
actix_tls::connect

Struct Resolver

source
pub struct Resolver { /* private fields */ }
Expand description

DNS resolver service factory.

+

Implementationsยง

sourceยง

impl Resolver

source

pub fn custom(resolver: impl Resolve + 'static) -> Self

Constructs a new resolver factory with a custom resolver.

+
source

pub fn service(&self) -> ResolverService

Returns a new resolver service.

+

Trait Implementationsยง

sourceยง

impl Clone for Resolver

sourceยง

fn clone(&self) -> Resolver

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Default for Resolver

sourceยง

fn default() -> Resolver

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<R: Host> ServiceFactory<ConnectInfo<R>> for Resolver

sourceยง

type Response = ConnectInfo<R>

Responses given by the created services.
sourceยง

type Error = ConnectError

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = ResolverService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<Resolver as ServiceFactory<ConnectInfo<R>>>::Service, <Resolver as ServiceFactory<ConnectInfo<R>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/struct.ResolverService.html b/actix_tls/connect/struct.ResolverService.html new file mode 100644 index 00000000..79384ab3 --- /dev/null +++ b/actix_tls/connect/struct.ResolverService.html @@ -0,0 +1,30 @@ +ResolverService in actix_tls::connect - Rust
actix_tls::connect

Struct ResolverService

source
pub struct ResolverService { /* private fields */ }
Expand description

DNS resolver service.

+

Implementationsยง

sourceยง

impl ResolverService

source

pub fn custom(resolver: impl Resolve + 'static) -> Self

Constructor for custom Resolve trait object and use it as resolver.

+

Trait Implementationsยง

sourceยง

impl Clone for ResolverService

sourceยง

fn clone(&self) -> ResolverService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Default for ResolverService

sourceยง

fn default() -> ResolverService

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<R: Host> Service<ConnectInfo<R>> for ResolverService

sourceยง

type Response = ConnectInfo<R>

Responses given by the service.
sourceยง

type Error = ConnectError

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = ResolverFut<R>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: ConnectInfo<R>) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/tcp/index.html b/actix_tls/connect/tcp/index.html new file mode 100644 index 00000000..cf3100f0 --- /dev/null +++ b/actix_tls/connect/tcp/index.html @@ -0,0 +1,3 @@ +actix_tls::connect::tcp - Rust
actix_tls::connect

Module tcp

source
Expand description

TCP connector service.

+

See TcpConnector for main connector service factory docs.

+

Structsยง

\ No newline at end of file diff --git a/actix_tls/connect/tcp/sidebar-items.js b/actix_tls/connect/tcp/sidebar-items.js new file mode 100644 index 00000000..845ac971 --- /dev/null +++ b/actix_tls/connect/tcp/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["TcpConnector","TcpConnectorService"]}; \ No newline at end of file diff --git a/actix_tls/connect/tcp/struct.TcpConnector.html b/actix_tls/connect/tcp/struct.TcpConnector.html new file mode 100644 index 00000000..acfa9d03 --- /dev/null +++ b/actix_tls/connect/tcp/struct.TcpConnector.html @@ -0,0 +1,33 @@ +TcpConnector in actix_tls::connect::tcp - Rust
actix_tls::connect::tcp

Struct TcpConnector

source
#[non_exhaustive]
pub struct TcpConnector;
Expand description

TCP connector service factory.

+

Implementationsยง

sourceยง

impl TcpConnector

source

pub fn service(&self) -> TcpConnectorService

Returns a new TCP connector service.

+

Trait Implementationsยง

sourceยง

impl Clone for TcpConnector

sourceยง

fn clone(&self) -> TcpConnector

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for TcpConnector

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Default for TcpConnector

sourceยง

fn default() -> TcpConnector

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<R: Host> ServiceFactory<ConnectInfo<R>> for TcpConnector

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the created services.
sourceยง

type Error = ConnectError

Errors produced by the created services.
sourceยง

type Config = ()

Service factory configuration.
sourceยง

type Service = TcpConnectorService

The kind of Service created by this factory.
sourceยง

type InitError = ()

Errors potentially raised while building a service.
sourceยง

type Future = Ready<Result<<TcpConnector as ServiceFactory<ConnectInfo<R>>>::Service, <TcpConnector as ServiceFactory<ConnectInfo<R>>>::InitError>>

The future of the Service instance.g
sourceยง

fn new_service(&self, _: ()) -> Self::Future

Create and return a new service asynchronously.
sourceยง

impl Copy for TcpConnector

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<SF, Req> IntoServiceFactory<SF, Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn into_factory(self) -> SF

Convert Self to a ServiceFactory
ยง

impl<SF, Req> ServiceFactoryExt<Req> for SF
where + SF: ServiceFactory<Req>,

ยง

fn map<F, R>(self, f: F) -> MapServiceFactory<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R + Clone,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type.
ยง

fn map_err<F, E>(self, f: F) -> MapErrServiceFactory<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E + Clone,

Map this serviceโ€™s error to a different error, returning a new service.
ยง

fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, Req, E>
where + Self: Sized, + F: Fn(Self::InitError) -> E + Clone,

Map this factoryโ€™s init error to a different error, returning a new service.
ยง

fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
where + Self: Sized, + Self::Config: Clone, + I: IntoServiceFactory<SF1, Self::Response>, + SF1: ServiceFactory<Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,

Call another service after call to this one has resolved successfully.
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/tcp/struct.TcpConnectorService.html b/actix_tls/connect/tcp/struct.TcpConnectorService.html new file mode 100644 index 00000000..83f992e0 --- /dev/null +++ b/actix_tls/connect/tcp/struct.TcpConnectorService.html @@ -0,0 +1,29 @@ +TcpConnectorService in actix_tls::connect::tcp - Rust
actix_tls::connect::tcp

Struct TcpConnectorService

source
#[non_exhaustive]
pub struct TcpConnectorService;
Expand description

TCP connector service.

+

Trait Implementationsยง

sourceยง

impl Clone for TcpConnectorService

sourceยง

fn clone(&self) -> TcpConnectorService

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for TcpConnectorService

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Default for TcpConnectorService

sourceยง

fn default() -> TcpConnectorService

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<R: Host> Service<ConnectInfo<R>> for TcpConnectorService

sourceยง

type Response = Connection<R, TcpStream>

Responses given by the service.
sourceยง

type Error = ConnectError

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = TcpConnectorFut<R>

The future response value.
sourceยง

fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: ConnectInfo<R>) -> Self::Future

Process the request and return the response asynchronously. Read more
sourceยง

impl Copy for TcpConnectorService

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tls/connect/trait.Host.html b/actix_tls/connect/trait.Host.html new file mode 100644 index 00000000..af8d95ba --- /dev/null +++ b/actix_tls/connect/trait.Host.html @@ -0,0 +1,17 @@ +Host in actix_tls::connect - Rust
actix_tls::connect

Trait Host

source
pub trait Host: Unpin + 'static {
+    // Required method
+    fn hostname(&self) -> &str;
+
+    // Provided method
+    fn port(&self) -> Option<u16> { ... }
+}
Expand description

An interface for types where host parts (hostname and port) can be derived.

+

The WHATWG URL Standard defines the terminology used for this trait and its methods.

+
+------------------------+
+|          host          |
++-----------------+------+
+|    hostname     | port |
+|                 |      |
+| sub.example.com : 8080 |
++-----------------+------+

Required Methodsยง

source

fn hostname(&self) -> &str

Extract hostname.

+

Provided Methodsยง

source

fn port(&self) -> Option<u16>

Extract optional port.

+

Implementations on Foreign Typesยง

sourceยง

impl Host for &'static str

sourceยง

impl Host for String

sourceยง

impl Host for Uri

sourceยง

impl Host for Uri

Implementorsยง

\ No newline at end of file diff --git a/actix_tls/connect/trait.Resolve.html b/actix_tls/connect/trait.Resolve.html new file mode 100644 index 00000000..60cce6da --- /dev/null +++ b/actix_tls/connect/trait.Resolve.html @@ -0,0 +1,58 @@ +Resolve in actix_tls::connect - Rust
actix_tls::connect

Trait Resolve

source
pub trait Resolve {
+    // Required method
+    fn lookup<'a>(
+        &'a self,
+        host: &'a str,
+        port: u16,
+    ) -> LocalBoxFuture<'a, Result<Vec<SocketAddr>, Box<dyn StdError>>>;
+}
Expand description

Custom async DNS resolvers.

+

ยงExamples

+
use std::net::SocketAddr;
+
+use actix_tls::connect::{Resolve, Resolver};
+use futures_util::future::LocalBoxFuture;
+
+// use trust-dns async tokio resolver
+use trust_dns_resolver::TokioAsyncResolver;
+
+struct MyResolver {
+    trust_dns: TokioAsyncResolver,
+};
+
+// impl Resolve trait and convert given host address str and port to SocketAddr.
+impl Resolve for MyResolver {
+    fn lookup<'a>(
+        &'a self,
+        host: &'a str,
+        port: u16,
+    ) -> LocalBoxFuture<'a, Result<Vec<SocketAddr>, Box<dyn std::error::Error>>> {
+        Box::pin(async move {
+            let res = self
+                .trust_dns
+                .lookup_ip(host)
+                .await?
+                .iter()
+                .map(|ip| SocketAddr::new(ip, port))
+                .collect();
+            Ok(res)
+        })
+    }
+}
+
+let my_resolver = MyResolver {
+    trust_dns: TokioAsyncResolver::tokio_from_system_conf().unwrap(),
+};
+
+// wrap custom resolver
+let resolver = Resolver::custom(my_resolver);
+
+// resolver can be passed to connector factory where returned service factory
+// can be used to construct new connector services for use in clients
+let factory = actix_tls::connect::Connector::new(resolver);
+let connector = factory.service();
+

Required Methodsยง

source

fn lookup<'a>( + &'a self, + host: &'a str, + port: u16, +) -> LocalBoxFuture<'a, Result<Vec<SocketAddr>, Box<dyn StdError>>>

Given DNS lookup information, returns a future that completes with socket information.

+

Implementorsยง

\ No newline at end of file diff --git a/actix_tls/index.html b/actix_tls/index.html new file mode 100644 index 00000000..f0de37b2 --- /dev/null +++ b/actix_tls/index.html @@ -0,0 +1,2 @@ +actix_tls - Rust

Crate actix_tls

source
Expand description

TLS acceptor and connector services for the Actix ecosystem.

+

Modulesยง

  • TLS connection acceptor services.
  • TCP and TLS connector services.
\ No newline at end of file diff --git a/actix_tls/sidebar-items.js b/actix_tls/sidebar-items.js new file mode 100644 index 00000000..d1b2efad --- /dev/null +++ b/actix_tls/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["accept","connect"]}; \ No newline at end of file diff --git a/actix_tracing/all.html b/actix_tracing/all.html new file mode 100644 index 00000000..e13f7a54 --- /dev/null +++ b/actix_tracing/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

Functions

\ No newline at end of file diff --git a/actix_tracing/fn.trace.html b/actix_tracing/fn.trace.html new file mode 100644 index 00000000..e704b435 --- /dev/null +++ b/actix_tracing/fn.trace.html @@ -0,0 +1,17 @@ +trace in actix_tracing - Rust
actix_tracing

Function trace

source
pub fn trace<S, Req, I, F>(
+    service_factory: I,
+    make_span: F,
+) -> ApplyTransform<TracingTransform<S::Service, S, F>, S, Req>
where + I: IntoServiceFactory<S, Req>, + S: ServiceFactory<Req>, + F: Fn(&Req) -> Option<Span> + Clone,
Expand description

Wraps the provided service factory with a transform that automatically +enters/exits the given span.

+

The span to be entered/exited can be provided via a closure. The closure +is passed in a reference to the request being handled by the service.

+

For example:

+ +
โ“˜
let traced_service = trace(
+    web_service,
+    |req: &Request| Some(span!(Level::INFO, "request", req.id))
+);
+
\ No newline at end of file diff --git a/actix_tracing/index.html b/actix_tracing/index.html new file mode 100644 index 00000000..7f42edb4 --- /dev/null +++ b/actix_tracing/index.html @@ -0,0 +1,4 @@ +actix_tracing - Rust

Crate actix_tracing

source
Expand description

Actix tracing - support for tokio tracing with Actix services.

+

Structsยง

Functionsยง

  • Wraps the provided service factory with a transform that automatically +enters/exits the given span.
\ No newline at end of file diff --git a/actix_tracing/sidebar-items.js b/actix_tracing/sidebar-items.js new file mode 100644 index 00000000..e9c74c73 --- /dev/null +++ b/actix_tracing/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["trace"],"struct":["TracingService","TracingTransform"]}; \ No newline at end of file diff --git a/actix_tracing/struct.TracingService.html b/actix_tracing/struct.TracingService.html new file mode 100644 index 00000000..afe1a59a --- /dev/null +++ b/actix_tracing/struct.TracingService.html @@ -0,0 +1,49 @@ +TracingService in actix_tracing - Rust
actix_tracing

Struct TracingService

source
pub struct TracingService<S, F> { /* private fields */ }
Expand description

A Service implementation that automatically enters/exits tracing spans +for the wrapped inner service.

+

Implementationsยง

sourceยง

impl<S, F> TracingService<S, F>

source

pub fn new(inner: S, make_span: F) -> Self

Trait Implementationsยง

sourceยง

impl<S: Clone, F: Clone> Clone for TracingService<S, F>

sourceยง

fn clone(&self) -> TracingService<S, F>

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<S, Req, F> Service<Req> for TracingService<S, F>
where + S: Service<Req>, + F: Fn(&Req) -> Option<Span>,

sourceยง

type Response = <S as Service<Req>>::Response

Responses given by the service.
sourceยง

type Error = <S as Service<Req>>::Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = Either<<S as Service<Req>>::Future, Instrumented<<S as Service<Req>>::Future>>

The future response value.
sourceยง

fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, req: Req) -> Self::Future

Process the request and return the response asynchronously. Read more

Auto Trait Implementationsยง

ยง

impl<S, F> Freeze for TracingService<S, F>
where + S: Freeze, + F: Freeze,

ยง

impl<S, F> RefUnwindSafe for TracingService<S, F>
where + S: RefUnwindSafe, + F: RefUnwindSafe,

ยง

impl<S, F> Send for TracingService<S, F>
where + S: Send, + F: Send,

ยง

impl<S, F> Sync for TracingService<S, F>
where + S: Sync, + F: Sync,

ยง

impl<S, F> Unpin for TracingService<S, F>
where + S: Unpin, + F: Unpin,

ยง

impl<S, F> UnwindSafe for TracingService<S, F>
where + S: UnwindSafe, + F: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T> Instrument for T

sourceยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an +Instrumented wrapper. Read more
sourceยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
ยง

impl<S, Req> IntoService<S, Req> for S
where + S: Service<Req>,

ยง

fn into_service(self) -> S

Convert to a Service
ยง

impl<S, Req> ServiceExt<Req> for S
where + S: Service<Req>,

ยง

fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
where + Self: Sized, + F: FnMut(Self::Response) -> R,

Map this serviceโ€™s output to a different type, returning a new service +of the resulting type. Read more
ยง

fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
where + Self: Sized, + F: Fn(Self::Error) -> E,

Map this serviceโ€™s error to a different error, returning a new service. Read more
ยง

fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
where + Self: Sized, + I: IntoService<S1, Self::Response>, + S1: Service<Self::Response, Error = Self::Error>,

Call another service after call to this one has resolved successfully. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
sourceยง

impl<T> WithSubscriber for T

sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +WithDispatch wrapper. Read more
sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +WithDispatch wrapper. Read more
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_tracing/struct.TracingTransform.html b/actix_tracing/struct.TracingTransform.html new file mode 100644 index 00000000..536db88d --- /dev/null +++ b/actix_tracing/struct.TracingTransform.html @@ -0,0 +1,31 @@ +TracingTransform in actix_tracing - Rust
actix_tracing

Struct TracingTransform

source
pub struct TracingTransform<S, U, F> { /* private fields */ }
Expand description

A Transform implementation that wraps services with a TracingService.

+

Implementationsยง

sourceยง

impl<S, U, F> TracingTransform<S, U, F>

source

pub fn new(make_span: F) -> Self

Trait Implementationsยง

sourceยง

impl<S, Req, U, F> Transform<S, Req> for TracingTransform<S, U, F>
where + S: Service<Req>, + U: ServiceFactory<Req, Response = S::Response, Error = S::Error, Service = S>, + F: Fn(&Req) -> Option<Span> + Clone,

sourceยง

type Response = <S as Service<Req>>::Response

Responses produced by the service.
sourceยง

type Error = <S as Service<Req>>::Error

Errors produced by the service.
sourceยง

type Transform = TracingService<S, F>

The TransformService value created by this factory
sourceยง

type InitError = <U as ServiceFactory<Req>>::InitError

Errors produced while building a transform service.
sourceยง

type Future = Ready<Result<<TracingTransform<S, U, F> as Transform<S, Req>>::Transform, <TracingTransform<S, U, F> as Transform<S, Req>>::InitError>>

The future response value.
sourceยง

fn new_transform(&self, service: S) -> Self::Future

Creates and returns a new Transform component, asynchronously

Auto Trait Implementationsยง

ยง

impl<S, U, F> Freeze for TracingTransform<S, U, F>
where + F: Freeze,

ยง

impl<S, U, F> RefUnwindSafe for TracingTransform<S, U, F>
where + F: RefUnwindSafe,

ยง

impl<S, U, F> Send for TracingTransform<S, U, F>
where + F: Send,

ยง

impl<S, U, F> Sync for TracingTransform<S, U, F>
where + F: Sync,

ยง

impl<S, U, F> Unpin for TracingTransform<S, U, F>
where + F: Unpin,

ยง

impl<S, U, F> UnwindSafe for TracingTransform<S, U, F>
where + F: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T> Instrument for T

sourceยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an +Instrumented wrapper. Read more
sourceยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
ยง

impl<T> Instrument for T

ยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
ยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
sourceยง

impl<T> WithSubscriber for T

sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +WithDispatch wrapper. Read more
sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +WithDispatch wrapper. Read more
ยง

impl<T> WithSubscriber for T

ยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
ยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/actix_utils/all.html b/actix_utils/all.html new file mode 100644 index 00000000..1707a5a2 --- /dev/null +++ b/actix_utils/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/actix_utils/counter/index.html b/actix_utils/counter/index.html new file mode 100644 index 00000000..0b5164e9 --- /dev/null +++ b/actix_utils/counter/index.html @@ -0,0 +1,2 @@ +actix_utils::counter - Rust
actix_utils

Module counter

source
Expand description

Task-notifying counter.

+

Structsยง

  • Simple counter with ability to notify task on reaching specific number
  • An RAII structure that keeps the underlying counter incremented until this guard is dropped.
\ No newline at end of file diff --git a/actix_utils/counter/sidebar-items.js b/actix_utils/counter/sidebar-items.js new file mode 100644 index 00000000..1d8e4e9f --- /dev/null +++ b/actix_utils/counter/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Counter","CounterGuard"]}; \ No newline at end of file diff --git a/actix_utils/counter/struct.Counter.html b/actix_utils/counter/struct.Counter.html new file mode 100644 index 00000000..e8e7bd3a --- /dev/null +++ b/actix_utils/counter/struct.Counter.html @@ -0,0 +1,19 @@ +Counter in actix_utils::counter - Rust
actix_utils::counter

Struct Counter

source
pub struct Counter(/* private fields */);
Expand description

Simple counter with ability to notify task on reaching specific number

+

Counter could be cloned, total n-count is shared across all clones.

+

Implementationsยง

sourceยง

impl Counter

source

pub fn new(capacity: usize) -> Self

Create Counter instance with max value.

+
source

pub fn get(&self) -> CounterGuard

Create new counter guard, incrementing the counter.

+
source

pub fn available(&self, cx: &Context<'_>) -> bool

Returns true if counter is below capacity. Otherwise, register to wake task when it is.

+
source

pub fn total(&self) -> usize

Get total number of acquired guards.

+

Trait Implementationsยง

sourceยง

impl Clone for Counter

sourceยง

fn clone(&self) -> Counter

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for Counter

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_utils/counter/struct.CounterGuard.html b/actix_utils/counter/struct.CounterGuard.html new file mode 100644 index 00000000..08a8528d --- /dev/null +++ b/actix_utils/counter/struct.CounterGuard.html @@ -0,0 +1,12 @@ +CounterGuard in actix_utils::counter - Rust
actix_utils::counter

Struct CounterGuard

source
pub struct CounterGuard(/* private fields */);
Expand description

An RAII structure that keeps the underlying counter incremented until this guard is dropped.

+

Trait Implementationsยง

sourceยง

impl Debug for CounterGuard

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Drop for CounterGuard

sourceยง

fn drop(&mut self)

Executes the destructor for this type. Read more
sourceยง

impl Unpin for CounterGuard

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_utils/future/either/enum.Either.html b/actix_utils/future/either/enum.Either.html new file mode 100644 index 00000000..7d566b61 --- /dev/null +++ b/actix_utils/future/either/enum.Either.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/enum.Either.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/enum.Either.html b/actix_utils/future/enum.Either.html new file mode 100644 index 00000000..9c047706 --- /dev/null +++ b/actix_utils/future/enum.Either.html @@ -0,0 +1,50 @@ +Either in actix_utils::future - Rust
actix_utils::future

Enum Either

source
pub enum Either<L, R> {
+    Left {
+        value: L,
+    },
+    Right {
+        value: R,
+    },
+}
Expand description

Combines two different futures that have the same output type.

+

Construct variants with Either::left and Either::right.

+

ยงExamples

+
use actix_utils::future::{ready, Ready, Either};
+
+let res = Either::<_, Ready<usize>>::left(ready(42));
+assert_eq!(res.await, 42);
+
+let res = Either::<Ready<usize>, _>::right(ready(43));
+assert_eq!(res.await, 43);
+

Variantsยง

ยง

Left

A value of type L.

+

Fields

ยงvalue: L
ยง

Right

A value of type R.

+

Fields

ยงvalue: R

Implementationsยง

sourceยง

impl<L, R> Either<L, R>

source

pub fn left(value: L) -> Either<L, R> โ“˜

Creates new Either using left variant.

+
source

pub fn right(value: R) -> Either<L, R> โ“˜

Creates new Either using right variant.

+
sourceยง

impl<T> Either<T, T>

source

pub fn into_inner(self) -> T

Unwraps into inner value when left and right have a common type.

+

Trait Implementationsยง

sourceยง

impl<L: Clone, R: Clone> Clone for Either<L, R>

sourceยง

fn clone(&self) -> Either<L, R> โ“˜

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<L: Debug, R: Debug> Debug for Either<L, R>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<L, R> Future for Either<L, R>
where + L: Future, + R: Future<Output = L::Output>,

sourceยง

type Output = <L as Future>::Output

The type of value produced on completion.
sourceยง

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
sourceยง

impl<'__pin, L, R> Unpin for Either<L, R>
where + __Origin<'__pin, L, R>: Unpin,

Auto Trait Implementationsยง

ยง

impl<L, R> Freeze for Either<L, R>
where + L: Freeze, + R: Freeze,

ยง

impl<L, R> RefUnwindSafe for Either<L, R>
where + L: RefUnwindSafe, + R: RefUnwindSafe,

ยง

impl<L, R> Send for Either<L, R>
where + L: Send, + R: Send,

ยง

impl<L, R> Sync for Either<L, R>
where + L: Sync, + R: Sync,

ยง

impl<L, R> UnwindSafe for Either<L, R>
where + L: UnwindSafe, + R: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_utils/future/fn.err.html b/actix_utils/future/fn.err.html new file mode 100644 index 00000000..e5e99d6b --- /dev/null +++ b/actix_utils/future/fn.err.html @@ -0,0 +1,7 @@ +err in actix_utils::future - Rust
actix_utils::future

Function err

source
pub fn err<T, E>(err: E) -> Ready<Result<T, E>> โ“˜
Expand description

Creates a future that is immediately ready with an error value.

+

ยงExamples

+
use actix_utils::future::err;
+
+let a = err::<(), _>(1);
+assert_eq!(a.await, Err(1));
+
\ No newline at end of file diff --git a/actix_utils/future/fn.ok.html b/actix_utils/future/fn.ok.html new file mode 100644 index 00000000..a3bc1482 --- /dev/null +++ b/actix_utils/future/fn.ok.html @@ -0,0 +1,7 @@ +ok in actix_utils::future - Rust
actix_utils::future

Function ok

source
pub fn ok<T, E>(val: T) -> Ready<Result<T, E>> โ“˜
Expand description

Creates a future that is immediately ready with a success value.

+

ยงExamples

+
use actix_utils::future::ok;
+
+let a = ok::<_, ()>(1);
+assert_eq!(a.await, Ok(1));
+
\ No newline at end of file diff --git a/actix_utils/future/fn.poll_fn.html b/actix_utils/future/fn.poll_fn.html new file mode 100644 index 00000000..0c3aead6 --- /dev/null +++ b/actix_utils/future/fn.poll_fn.html @@ -0,0 +1,20 @@ +poll_fn in actix_utils::future - Rust
actix_utils::future

Function poll_fn

source
pub fn poll_fn<F, T>(f: F) -> PollFn<F> โ“˜
where + F: FnMut(&mut Context<'_>) -> Poll<T>,
Expand description

Creates a future driven by the provided function that receives a task context.

+

ยงExamples

+
let res = poll_fn(|_| Poll::Ready(42)).await;
+assert_eq!(res, 42);
+
+let mut i = 5;
+let res = poll_fn(|cx| {
+    i -= 1;
+
+    if i > 0 {
+        cx.waker().wake_by_ref();
+        Poll::Pending
+    } else {
+        Poll::Ready(42)
+    }
+})
+.await;
+assert_eq!(res, 42);
+
\ No newline at end of file diff --git a/actix_utils/future/fn.ready.html b/actix_utils/future/fn.ready.html new file mode 100644 index 00000000..2807c4cf --- /dev/null +++ b/actix_utils/future/fn.ready.html @@ -0,0 +1,11 @@ +ready in actix_utils::future - Rust
actix_utils::future

Function ready

source
pub fn ready<T>(val: T) -> Ready<T> โ“˜
Expand description

Creates a future that is immediately ready with a value.

+

ยงExamples

+
use actix_utils::future::ready;
+
+let a = ready(1);
+assert_eq!(a.await, 1);
+
+// sync
+let a = ready(1);
+assert_eq!(a.into_inner(), 1);
+
\ No newline at end of file diff --git a/actix_utils/future/index.html b/actix_utils/future/index.html new file mode 100644 index 00000000..0c5b99a2 --- /dev/null +++ b/actix_utils/future/index.html @@ -0,0 +1,2 @@ +actix_utils::future - Rust
actix_utils

Module future

source
Expand description

Helpers for constructing futures.

+

Structsยง

Enumsยง

  • Combines two different futures that have the same output type.

Functionsยง

  • Creates a future that is immediately ready with an error value.
  • Creates a future that is immediately ready with a success value.
  • Creates a future driven by the provided function that receives a task context.
  • Creates a future that is immediately ready with a value.
\ No newline at end of file diff --git a/actix_utils/future/poll_fn/fn.poll_fn.html b/actix_utils/future/poll_fn/fn.poll_fn.html new file mode 100644 index 00000000..237fed57 --- /dev/null +++ b/actix_utils/future/poll_fn/fn.poll_fn.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/fn.poll_fn.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/poll_fn/struct.PollFn.html b/actix_utils/future/poll_fn/struct.PollFn.html new file mode 100644 index 00000000..04123051 --- /dev/null +++ b/actix_utils/future/poll_fn/struct.PollFn.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/struct.PollFn.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/ready/fn.err.html b/actix_utils/future/ready/fn.err.html new file mode 100644 index 00000000..0a788ef2 --- /dev/null +++ b/actix_utils/future/ready/fn.err.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/fn.err.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/ready/fn.ok.html b/actix_utils/future/ready/fn.ok.html new file mode 100644 index 00000000..fa6909c7 --- /dev/null +++ b/actix_utils/future/ready/fn.ok.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/fn.ok.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/ready/fn.ready.html b/actix_utils/future/ready/fn.ready.html new file mode 100644 index 00000000..1d4d8e94 --- /dev/null +++ b/actix_utils/future/ready/fn.ready.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/fn.ready.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/ready/struct.Ready.html b/actix_utils/future/ready/struct.Ready.html new file mode 100644 index 00000000..05abbb02 --- /dev/null +++ b/actix_utils/future/ready/struct.Ready.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../../actix_utils/future/struct.Ready.html...

+ + + \ No newline at end of file diff --git a/actix_utils/future/sidebar-items.js b/actix_utils/future/sidebar-items.js new file mode 100644 index 00000000..7c524289 --- /dev/null +++ b/actix_utils/future/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Either"],"fn":["err","ok","poll_fn","ready"],"struct":["PollFn","Ready"]}; \ No newline at end of file diff --git a/actix_utils/future/struct.PollFn.html b/actix_utils/future/struct.PollFn.html new file mode 100644 index 00000000..9ee0f6ee --- /dev/null +++ b/actix_utils/future/struct.PollFn.html @@ -0,0 +1,21 @@ +PollFn in actix_utils::future - Rust
actix_utils::future

Struct PollFn

source
pub struct PollFn<F> { /* private fields */ }
Expand description

Future for the poll_fn function.

+

Trait Implementationsยง

sourceยง

impl<F> Debug for PollFn<F>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<F, T> Future for PollFn<F>
where + F: FnMut(&mut Context<'_>) -> Poll<T>,

sourceยง

type Output = T

The type of value produced on completion.
sourceยง

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementationsยง

ยง

impl<F> Freeze for PollFn<F>
where + F: Freeze,

ยง

impl<F> RefUnwindSafe for PollFn<F>
where + F: RefUnwindSafe,

ยง

impl<F> Send for PollFn<F>
where + F: Send,

ยง

impl<F> Sync for PollFn<F>
where + F: Sync,

ยง

impl<F> Unpin for PollFn<F>
where + F: Unpin,

ยง

impl<F> UnwindSafe for PollFn<F>
where + F: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_utils/future/struct.Ready.html b/actix_utils/future/struct.Ready.html new file mode 100644 index 00000000..2154d382 --- /dev/null +++ b/actix_utils/future/struct.Ready.html @@ -0,0 +1,33 @@ +Ready in actix_utils::future - Rust
actix_utils::future

Struct Ready

source
pub struct Ready<T> { /* private fields */ }
Expand description

Future for the ready function.

+

Panic will occur if polled more than once.

+

ยงExamples

+
use actix_utils::future::ready;
+
+// async
+let a = ready(1);
+assert_eq!(a.await, 1);
+
+// sync
+let a = ready(1);
+assert_eq!(a.into_inner(), 1);
+

Implementationsยง

sourceยง

impl<T> Ready<T>

source

pub fn into_inner(self) -> T

Unwraps the value from this immediately ready future.

+

Trait Implementationsยง

sourceยง

impl<T: Clone> Clone for Ready<T>

sourceยง

fn clone(&self) -> Ready<T> โ“˜

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<T: Debug> Debug for Ready<T>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<T> Future for Ready<T>

sourceยง

type Output = T

The type of value produced on completion.
sourceยง

fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
sourceยง

impl<T> Unpin for Ready<T>

Auto Trait Implementationsยง

ยง

impl<T> Freeze for Ready<T>
where + T: Freeze,

ยง

impl<T> RefUnwindSafe for Ready<T>
where + T: RefUnwindSafe,

ยง

impl<T> Send for Ready<T>
where + T: Send,

ยง

impl<T> Sync for Ready<T>
where + T: Sync,

ยง

impl<T> UnwindSafe for Ready<T>
where + T: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<F> IntoFuture for F
where + F: Future,

sourceยง

type Output = <F as Future>::Output

The output that the future will produce on completion.
sourceยง

type IntoFuture = F

Which kind of future are we turning this into?
sourceยง

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/actix_utils/index.html b/actix_utils/index.html new file mode 100644 index 00000000..152ea941 --- /dev/null +++ b/actix_utils/index.html @@ -0,0 +1,2 @@ +actix_utils - Rust

Crate actix_utils

source
Expand description

Various utilities used in the Actix ecosystem.

+

Modulesยง

  • Task-notifying counter.
  • Helpers for constructing futures.
\ No newline at end of file diff --git a/actix_utils/sidebar-items.js b/actix_utils/sidebar-items.js new file mode 100644 index 00000000..f6a4148c --- /dev/null +++ b/actix_utils/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["counter","future"]}; \ No newline at end of file diff --git a/bytestring/all.html b/bytestring/all.html new file mode 100644 index 00000000..8566ec23 --- /dev/null +++ b/bytestring/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

\ No newline at end of file diff --git a/bytestring/index.html b/bytestring/index.html new file mode 100644 index 00000000..64d9a408 --- /dev/null +++ b/bytestring/index.html @@ -0,0 +1,3 @@ +bytestring - Rust

Crate bytestring

source
Expand description

A UTF-8 encoded read-only string using Bytes as storage.

+

See docs for ByteString.

+

Structsยง

  • An immutable UTF-8 encoded string with [Bytes] as a storage.
\ No newline at end of file diff --git a/bytestring/sidebar-items.js b/bytestring/sidebar-items.js new file mode 100644 index 00000000..6cfaf287 --- /dev/null +++ b/bytestring/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["ByteString"]}; \ No newline at end of file diff --git a/bytestring/struct.ByteString.html b/bytestring/struct.ByteString.html new file mode 100644 index 00000000..3aebfe63 --- /dev/null +++ b/bytestring/struct.ByteString.html @@ -0,0 +1,1302 @@ +ByteString in bytestring - Rust
bytestring

Struct ByteString

source
pub struct ByteString(/* private fields */);
Expand description

An immutable UTF-8 encoded string with [Bytes] as a storage.

+

Implementationsยง

sourceยง

impl ByteString

source

pub const fn new() -> Self

Creates a new empty ByteString.

+
source

pub fn as_bytes(&self) -> &Bytes

Get a reference to the underlying Bytes object.

+
source

pub fn into_bytes(self) -> Bytes

Unwraps this ByteString into the underlying Bytes object.

+
source

pub const fn from_static(src: &'static str) -> ByteString

Creates a new ByteString from a &'static str.

+
source

pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString

Creates a new ByteString from a Bytes.

+
ยงSafety
+

This function is unsafe because it does not check 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 ByteString, as we assume that ByteStrings are valid UTF-8. However, the most likely +issue is that the data gets corrupted.

+
source

pub fn slice_ref(&self, subset: &str) -> Self

Returns a new byte string that is equivalent to the given subset.

+

When processing a ByteString buffer with other tools, one often gets a &str which is in +fact a slice of the original ByteString; i.e., a subset of it. This function turns that +&str into another ByteString, as if one had sliced the ByteString with the offsets +that correspond to subset.

+

Corresponds to [Bytes::slice_ref].

+

This operation is O(1).

+
ยงPanics
+

Panics if subset is not a sub-slice of this byte string.

+

Note that strings which are only subsets from an equality perspective do not uphold this +requirement; see examples.

+
ยงExamples
+
let string = ByteString::from_static(" foo ");
+let subset = string.trim();
+let substring = string.slice_ref(subset);
+assert_eq!(substring, "foo");
+ +
โ“˜
// panics because the given slice is not derived from the original byte string, despite
+// being a logical subset of the string
+ByteString::from_static("foo bar").slice_ref("foo");
+

Methods from Deref<Target = str>ยง

1.6.0 ยท source

pub fn len(&self) -> usize

Returns the length of self.

+

This length is in bytes, not chars or graphemes. In other words, +it might not be what a human considers the length of the string.

+
ยงExamples
+
let len = "foo".len();
+assert_eq!(3, len);
+
+assert_eq!("ฦ’oo".len(), 4); // fancy f!
+assert_eq!("ฦ’oo".chars().count(), 3);
+
1.6.0 ยท source

pub fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

+
ยงExamples
+
let s = "";
+assert!(s.is_empty());
+
+let s = "not empty";
+assert!(!s.is_empty());
+
1.9.0 ยท source

pub fn is_char_boundary(&self, index: usize) -> bool

Checks that index-th byte is the first byte in a UTF-8 code point +sequence or the end of the string.

+

The start and end of the string (when index == self.len()) are +considered to be boundaries.

+

Returns false if index is greater than self.len().

+
ยงExamples
+
let s = "Lรถwe ่€่™Ž Lรฉopard";
+assert!(s.is_char_boundary(0));
+// start of `่€`
+assert!(s.is_char_boundary(6));
+assert!(s.is_char_boundary(s.len()));
+
+// second byte of `รถ`
+assert!(!s.is_char_boundary(2));
+
+// third byte of `่€`
+assert!(!s.is_char_boundary(8));
+
source

pub fn floor_char_boundary(&self, index: usize) -> usize

๐Ÿ”ฌThis is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not exceeding index where is_char_boundary(x) is true.

+

This method can help you truncate a string so that itโ€™s still valid UTF-8, but doesnโ€™t +exceed a given number of bytes. Note that this is done purely at the character level +and can still visually split graphemes, even though the underlying characters arenโ€™t +split. For example, the emoji ๐Ÿง‘โ€๐Ÿ”ฌ (scientist) could be split so that the string only +includes ๐Ÿง‘ (person) instead.

+
ยงExamples
+
#![feature(round_char_boundary)]
+let s = "โค๏ธ๐Ÿงก๐Ÿ’›๐Ÿ’š๐Ÿ’™๐Ÿ’œ";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.floor_char_boundary(13);
+assert_eq!(closest, 10);
+assert_eq!(&s[..closest], "โค๏ธ๐Ÿงก");
+
source

pub fn ceil_char_boundary(&self, index: usize) -> usize

๐Ÿ”ฌThis is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not below index where is_char_boundary(x) is true.

+

If index is greater than the length of the string, this returns the length of the string.

+

This method is the natural complement to floor_char_boundary. See that method +for more details.

+
ยงExamples
+
#![feature(round_char_boundary)]
+let s = "โค๏ธ๐Ÿงก๐Ÿ’›๐Ÿ’š๐Ÿ’™๐Ÿ’œ";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.ceil_char_boundary(13);
+assert_eq!(closest, 14);
+assert_eq!(&s[..closest], "โค๏ธ๐Ÿงก๐Ÿ’›");
+
1.6.0 ยท source

pub fn as_bytes(&self) -> &[u8] โ“˜

Converts a string slice to a byte slice. To convert the byte slice back +into a string slice, use the from_utf8 function.

+
ยงExamples
+
let bytes = "bors".as_bytes();
+assert_eq!(b"bors", bytes);
+
1.6.0 ยท source

pub fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +u8. This pointer will be pointing to the first byte of the string +slice.

+

The caller must ensure that the returned pointer is never written to. +If you need to mutate the contents of the string slice, use as_mut_ptr.

+
ยงExamples
+
let s = "Hello";
+let ptr = s.as_ptr();
+
1.20.0 ยท source

pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>
where + I: SliceIndex<str>,

Returns a subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +None whenever equivalent indexing operation would panic.

+
ยงExamples
+
let v = String::from("๐Ÿ—ปโˆˆ๐ŸŒ");
+
+assert_eq!(Some("๐Ÿ—ป"), v.get(0..4));
+
+// indices not on UTF-8 sequence boundaries
+assert!(v.get(1..).is_none());
+assert!(v.get(..8).is_none());
+
+// out of bounds
+assert!(v.get(..42).is_none());
+
1.20.0 ยท source

pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Output
where + I: SliceIndex<str>,

Returns an unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
ยงSafety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
ยงExamples
+
let v = "๐Ÿ—ปโˆˆ๐ŸŒ";
+unsafe {
+    assert_eq!("๐Ÿ—ป", v.get_unchecked(0..4));
+    assert_eq!("โˆˆ", v.get_unchecked(4..7));
+    assert_eq!("๐ŸŒ", v.get_unchecked(7..11));
+}
+
1.6.0 ยท source

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

๐Ÿ‘ŽDeprecated since 1.29.0: use get_unchecked(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks.

+

This is generally not recommended, use with caution! For a safe +alternative see str and Index.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get a mutable string slice instead, see the +slice_mut_unchecked method.

+
ยงSafety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
ยงExamples
+
let s = "Lรถwe ่€่™Ž Lรฉopard";
+
+unsafe {
+    assert_eq!("Lรถwe ่€่™Ž Lรฉopard", s.slice_unchecked(0, 21));
+}
+
+let s = "Hello, world!";
+
+unsafe {
+    assert_eq!("world", s.slice_unchecked(7, 12));
+}
+
1.6.0 ยท source

pub fn split_at(&self, mid: usize) -> (&str, &str)

Divides one string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get mutable string slices instead, see the split_at_mut +method.

+
ยงPanics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is past +the end of the last code point of the string slice. For a non-panicking +alternative see split_at_checked.

+
ยงExamples
+
let s = "Per Martin-Lรถf";
+
+let (first, last) = s.split_at(3);
+
+assert_eq!("Per", first);
+assert_eq!(" Martin-Lรถf", last);
+
1.80.0 ยท source

pub fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)>

Divides one string slice into two at an index.

+

The argument, mid, should be a valid byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point. The +method returns None if thatโ€™s not the case.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get mutable string slices instead, see the split_at_mut_checked +method.

+
ยงExamples
+
let s = "Per Martin-Lรถf";
+
+let (first, last) = s.split_at_checked(3).unwrap();
+assert_eq!("Per", first);
+assert_eq!(" Martin-Lรถf", last);
+
+assert_eq!(None, s.split_at_checked(13));  // Inside โ€œรถโ€
+assert_eq!(None, s.split_at_checked(16));  // Beyond the string length
+
1.6.0 ยท source

pub fn chars(&self) -> Chars<'_>

Returns an iterator over the chars of a string slice.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns such an iterator.

+

Itโ€™s important to remember that char represents a Unicode Scalar +Value, and might not match your idea of what a โ€˜characterโ€™ is. Iteration +over grapheme clusters may be what you actually want. This functionality +is not provided by Rustโ€™s standard library, check crates.io instead.

+
ยงExamples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.chars().count();
+assert_eq!(7, count);
+
+let mut chars = word.chars();
+
+assert_eq!(Some('g'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('d'), chars.next());
+assert_eq!(Some('b'), chars.next());
+assert_eq!(Some('y'), chars.next());
+assert_eq!(Some('e'), chars.next());
+
+assert_eq!(None, chars.next());
+

Remember, chars might not match your intuition about characters:

+ +
let y = "yฬ†";
+
+let mut chars = y.chars();
+
+assert_eq!(Some('y'), chars.next()); // not 'yฬ†'
+assert_eq!(Some('\u{0306}'), chars.next());
+
+assert_eq!(None, chars.next());
+
1.6.0 ยท source

pub fn char_indices(&self) -> CharIndices<'_>

Returns an iterator over the chars of a string slice, and their +positions.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns an iterator of both +these chars, as well as their byte positions.

+

The iterator yields tuples. The position is first, the char is +second.

+
ยงExamples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.char_indices().count();
+assert_eq!(7, count);
+
+let mut char_indices = word.char_indices();
+
+assert_eq!(Some((0, 'g')), char_indices.next());
+assert_eq!(Some((1, 'o')), char_indices.next());
+assert_eq!(Some((2, 'o')), char_indices.next());
+assert_eq!(Some((3, 'd')), char_indices.next());
+assert_eq!(Some((4, 'b')), char_indices.next());
+assert_eq!(Some((5, 'y')), char_indices.next());
+assert_eq!(Some((6, 'e')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+

Remember, chars might not match your intuition about characters:

+ +
let yes = "yฬ†es";
+
+let mut char_indices = yes.char_indices();
+
+assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'yฬ†')
+assert_eq!(Some((1, '\u{0306}')), char_indices.next());
+
+// note the 3 here - the previous character took up two bytes
+assert_eq!(Some((3, 'e')), char_indices.next());
+assert_eq!(Some((4, 's')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+
1.6.0 ยท source

pub fn bytes(&self) -> Bytes<'_>

Returns an iterator over the bytes of a string slice.

+

As a string slice consists of a sequence of bytes, we can iterate +through a string slice by byte. This method returns such an iterator.

+
ยงExamples
+
let mut bytes = "bors".bytes();
+
+assert_eq!(Some(b'b'), bytes.next());
+assert_eq!(Some(b'o'), bytes.next());
+assert_eq!(Some(b'r'), bytes.next());
+assert_eq!(Some(b's'), bytes.next());
+
+assert_eq!(None, bytes.next());
+
1.6.0 ยท source

pub fn split_whitespace(&self) -> SplitWhitespace<'_>

Splits a string slice by whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of whitespace.

+

โ€˜Whitespaceโ€™ is defined according to the terms of the Unicode Derived +Core Property White_Space. If you only want to split on ASCII whitespace +instead, use split_ascii_whitespace.

+
ยงExamples
+

Basic usage:

+ +
let mut iter = "A few words".split_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of whitespace are considered:

+ +
let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_whitespace().next(), None);
+assert_eq!("   ".split_whitespace().next(), None);
+
1.34.0 ยท source

pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>

Splits a string slice by ASCII whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of ASCII whitespace.

+

To split by Unicode Whitespace instead, use split_whitespace.

+
ยงExamples
+

Basic usage:

+ +
let mut iter = "A few words".split_ascii_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of ASCII whitespace are considered:

+ +
let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all ASCII whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_ascii_whitespace().next(), None);
+assert_eq!("   ".split_ascii_whitespace().next(), None);
+
1.6.0 ยท source

pub fn lines(&self) -> Lines<'_>

Returns an iterator over the lines of a string, as string slices.

+

Lines are split at line endings that are either newlines (\n) or +sequences of a carriage return followed by a line feed (\r\n).

+

Line terminators are not included in the lines returned by the iterator.

+

Note that any carriage return (\r) not immediately followed by a +line feed (\n) does not split a line. These carriage returns are +thereby included in the produced lines.

+

The final line ending is optional. A string that ends with a final line +ending will return the same lines as an otherwise identical string +without a final line ending.

+
ยงExamples
+

Basic usage:

+ +
let text = "foo\r\nbar\n\nbaz\r";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+// Trailing carriage return is included in the last line
+assert_eq!(Some("baz\r"), lines.next());
+
+assert_eq!(None, lines.next());
+

The final line does not require any ending:

+ +
let text = "foo\nbar\n\r\nbaz";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+
1.6.0 ยท source

pub fn lines_any(&self) -> LinesAny<'_>

๐Ÿ‘ŽDeprecated since 1.4.0: use lines() instead now

Returns an iterator over the lines of a string.

+
1.8.0 ยท source

pub fn encode_utf16(&self) -> EncodeUtf16<'_>

Returns an iterator of u16 over the string encoded as UTF-16.

+
ยงExamples
+
let text = "Zaลผรณล‚ฤ‡ gฤ™ล›lฤ… jaลบล„";
+
+let utf8_len = text.len();
+let utf16_len = text.encode_utf16().count();
+
+assert!(utf16_len <= utf8_len);
+
1.6.0 ยท source

pub fn contains<P>(&self, pat: P) -> bool
where + P: Pattern,

Returns true if the given pattern matches a sub-slice of +this string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+
let bananas = "bananas";
+
+assert!(bananas.contains("nana"));
+assert!(!bananas.contains("apples"));
+
1.6.0 ยท source

pub fn starts_with<P>(&self, pat: P) -> bool
where + P: Pattern,

Returns true if the given pattern matches a prefix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, in which case this function will return true if +the &str is a prefix of this string slice.

+

The pattern can also be a char, a slice of chars, or a +function or closure that determines if a character matches. +These will only be checked against the first character of this string slice. +Look at the second example below regarding behavior for slices of chars.

+
ยงExamples
+
let bananas = "bananas";
+
+assert!(bananas.starts_with("bana"));
+assert!(!bananas.starts_with("nana"));
+ +
let bananas = "bananas";
+
+// Note that both of these assert successfully.
+assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
+assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
+
1.6.0 ยท source

pub fn ends_with<P>(&self, pat: P) -> bool
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns true if the given pattern matches a suffix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+
let bananas = "bananas";
+
+assert!(bananas.ends_with("anas"));
+assert!(!bananas.ends_with("nana"));
+
1.6.0 ยท source

pub fn find<P>(&self, pat: P) -> Option<usize>
where + P: Pattern,

Returns the byte index of the first character of this string slice that +matches the pattern.

+

Returns None if the pattern doesnโ€™t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+

Simple patterns:

+ +
let s = "Lรถwe ่€่™Ž Lรฉopard Gepardi";
+
+assert_eq!(s.find('L'), Some(0));
+assert_eq!(s.find('รฉ'), Some(14));
+assert_eq!(s.find("pard"), Some(17));
+

More complex patterns using point-free style and closures:

+ +
let s = "Lรถwe ่€่™Ž Lรฉopard";
+
+assert_eq!(s.find(char::is_whitespace), Some(5));
+assert_eq!(s.find(char::is_lowercase), Some(1));
+assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
+assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
+

Not finding the pattern:

+ +
let s = "Lรถwe ่€่™Ž Lรฉopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.find(x), None);
+
1.6.0 ยท source

pub fn rfind<P>(&self, pat: P) -> Option<usize>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns the byte index for the first character of the last match of the pattern in +this string slice.

+

Returns None if the pattern doesnโ€™t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+

Simple patterns:

+ +
let s = "Lรถwe ่€่™Ž Lรฉopard Gepardi";
+
+assert_eq!(s.rfind('L'), Some(13));
+assert_eq!(s.rfind('รฉ'), Some(14));
+assert_eq!(s.rfind("pard"), Some(24));
+

More complex patterns with closures:

+ +
let s = "Lรถwe ่€่™Ž Lรฉopard";
+
+assert_eq!(s.rfind(char::is_whitespace), Some(12));
+assert_eq!(s.rfind(char::is_lowercase), Some(20));
+

Not finding the pattern:

+ +
let s = "Lรถwe ่€่™Ž Lรฉopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.rfind(x), None);
+
1.6.0 ยท source

pub fn split<P>(&self, pat: P) -> Split<'_, P>
where + P: Pattern,

Returns 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 chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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:

+ +
โ“˜
assert_eq!(d, &["a", "b", "c"]);
+

Use split_whitespace for this behavior.

+
1.51.0 ยท source

pub fn split_inclusive<P>(&self, pat: P) -> SplitInclusive<'_, P>
where + P: Pattern,

Returns an iterator over substrings of this string slice, separated by +characters matched by a pattern.

+

Differs from the iterator produced by split in that split_inclusive +leaves the matched part as the terminator of the substring.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
+

If the last element of the string is matched, +that element will be considered the terminator of the preceding substring. +That substring will be the last item returned by the iterator.

+ +
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
+
1.6.0 ยท source

pub fn rsplit<P>(&self, pat: P) -> RSplit<'_, P>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns 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 chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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"]);
+
1.6.0 ยท source

pub fn split_terminator<P>(&self, pat: P) -> SplitTerminator<'_, P>
where + P: Pattern,

Returns 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 chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring +is skipped if empty.

+

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.

+
ยง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"]);
+
1.6.0 ยท source

pub fn rsplit_terminator<P>(&self, pat: P) -> RSplitTerminator<'_, P>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns 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 chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring is +skipped if empty.

+

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.

+
ยง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"]);
+
1.6.0 ยท source

pub fn splitn<P>(&self, n: usize, pat: P) -> SplitN<'_, P>
where + P: Pattern,

Returns 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 nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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"]);
+
1.6.0 ยท source

pub fn rsplitn<P>(&self, n: usize, pat: P) -> RSplitN<'_, P>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns 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 nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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"]);
+
1.52.0 ยท source

pub fn split_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
where + P: Pattern,

Splits the string on the first occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
ยงExamples
+
assert_eq!("cfg".split_once('='), None);
+assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
+assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
+
1.52.0 ยท source

pub fn rsplit_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Splits the string on the last occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
ยงExamples
+
assert_eq!("cfg".rsplit_once('='), None);
+assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
+
1.6.0 ยท source

pub fn matches<P>(&self, pat: P) -> Matches<'_, P>
where + P: Pattern,

Returns an iterator over the disjoint matches of a pattern within the +given string slice.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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"]);
+
1.6.0 ยท source

pub fn rmatches<P>(&self, pat: P) -> RMatches<'_, P>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns 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 chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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"]);
+
1.6.0 ยท source

pub fn match_indices<P>(&self, pat: P) -> MatchIndices<'_, P>
where + P: Pattern,

Returns 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 chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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`
+
1.6.0 ยท source

pub fn rmatch_indices<P>(&self, pat: P) -> RMatchIndices<'_, P>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns 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 chars, or a +function or closure that determines if a character matches.

+
ยง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.

+
ยง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`
+
1.6.0 ยท source

pub fn trim(&self) -> &str

Returns a string slice with leading and trailing whitespace removed.

+

โ€˜Whitespaceโ€™ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
ยงExamples
+
let s = "\n Hello\tworld\t\n";
+
+assert_eq!("Hello\tworld", s.trim());
+
1.30.0 ยท source

pub fn trim_start(&self) -> &str

Returns a string slice with leading whitespace removed.

+

โ€˜Whitespaceโ€™ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
ยงText directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
ยงExamples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("Hello\tworld\t\n", s.trim_start());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('E') == s.trim_start().chars().next());
+
+let s = "  ืขื‘ืจื™ืช  ";
+assert!(Some('ืข') == s.trim_start().chars().next());
+
1.30.0 ยท source

pub fn trim_end(&self) -> &str

Returns a string slice with trailing whitespace removed.

+

โ€˜Whitespaceโ€™ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
ยงText directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
ยงExamples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("\n Hello\tworld", s.trim_end());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('h') == s.trim_end().chars().rev().next());
+
+let s = "  ืขื‘ืจื™ืช  ";
+assert!(Some('ืช') == s.trim_end().chars().rev().next());
+
1.6.0 ยท source

pub fn trim_left(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.33.0: superseded by trim_start

Returns a string slice with leading whitespace removed.

+

โ€˜Whitespaceโ€™ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
ยงText directionality
+

A string is a sequence of bytes. โ€˜Leftโ€™ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are โ€˜right to leftโ€™ rather than โ€˜left to rightโ€™, this will be +the right side, not the left.

+
ยงExamples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!("Hello\tworld\t", s.trim_left());
+

Directionality:

+ +
let s = "  English";
+assert!(Some('E') == s.trim_left().chars().next());
+
+let s = "  ืขื‘ืจื™ืช";
+assert!(Some('ืข') == s.trim_left().chars().next());
+
1.6.0 ยท source

pub fn trim_right(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.33.0: superseded by trim_end

Returns a string slice with trailing whitespace removed.

+

โ€˜Whitespaceโ€™ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
ยงText directionality
+

A string is a sequence of bytes. โ€˜Rightโ€™ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are โ€˜right to leftโ€™ rather than โ€˜left to rightโ€™, this will be +the left side, not the right.

+
ยงExamples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!(" Hello\tworld", s.trim_right());
+

Directionality:

+ +
let s = "English  ";
+assert!(Some('h') == s.trim_right().chars().rev().next());
+
+let s = "ืขื‘ืจื™ืช  ";
+assert!(Some('ืช') == s.trim_right().chars().rev().next());
+
1.6.0 ยท source

pub fn trim_matches<P>(&self, pat: P) -> &str
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> DoubleEndedSearcher<'a>,

Returns a string slice with all prefixes and suffixes that match a +pattern repeatedly removed.

+

The pattern can be a char, a slice of chars, or a function +or closure that determines if a character matches.

+
ยงExamples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
+assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
+
1.30.0 ยท source

pub fn trim_start_matches<P>(&self, pat: P) -> &str
where + P: Pattern,

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงText directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
ยงExamples
+
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
+
1.45.0 ยท source

pub fn strip_prefix<P>(&self, prefix: P) -> Option<&str>
where + P: Pattern,

Returns a string slice with the prefix removed.

+

If the string starts with the pattern prefix, returns the substring after the prefix, +wrapped in Some. Unlike trim_start_matches, this method removes the prefix exactly once.

+

If the string does not start with prefix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
+assert_eq!("foo:bar".strip_prefix("bar"), None);
+assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
+
1.45.0 ยท source

pub fn strip_suffix<P>(&self, suffix: P) -> Option<&str>
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with the suffix removed.

+

If the string ends with the pattern suffix, returns the substring before the suffix, +wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.

+

If the string does not end with suffix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงExamples
+
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
+assert_eq!("bar:foo".strip_suffix("bar"), None);
+assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
+
1.30.0 ยท source

pub fn trim_end_matches<P>(&self, pat: P) -> &str
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงText directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
ยงExamples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.6.0 ยท source

pub fn trim_left_matches<P>(&self, pat: P) -> &str
where + P: Pattern,

๐Ÿ‘ŽDeprecated since 1.33.0: superseded by trim_start_matches

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงText directionality
+

A string is a sequence of bytes. โ€˜Leftโ€™ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are โ€˜right to leftโ€™ rather than โ€˜left to rightโ€™, this will be +the right side, not the left.

+
ยงExamples
+
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
+
1.6.0 ยท source

pub fn trim_right_matches<P>(&self, pat: P) -> &str
where + P: Pattern, + <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

๐Ÿ‘ŽDeprecated since 1.33.0: superseded by trim_end_matches

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
ยงText directionality
+

A string is a sequence of bytes. โ€˜Rightโ€™ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are โ€˜right to leftโ€™ rather than โ€˜left to rightโ€™, this will be +the left side, not the right.

+
ยงExamples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.6.0 ยท source

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
where + F: FromStr,

Parses this string slice into another type.

+

Because parse is so general, it can cause problems with type +inference. As such, parse is one of the few times youโ€™ll see +the syntax affectionately known as the โ€˜turbofishโ€™: ::<>. This +helps the inference algorithm understand specifically which type +youโ€™re trying to parse into.

+

parse can parse into any type that implements the FromStr trait.

+
ยงErrors
+

Will return Err if itโ€™s not possible to parse this string slice into +the desired type.

+
ยงExamples
+

Basic usage

+ +
let four: u32 = "4".parse().unwrap();
+
+assert_eq!(4, four);
+

Using the โ€˜turbofishโ€™ instead of annotating four:

+ +
let four = "4".parse::<u32>();
+
+assert_eq!(Ok(4), four);
+

Failing to parse:

+ +
let nope = "j".parse::<u32>();
+
+assert!(nope.is_err());
+
1.23.0 ยท source

pub fn is_ascii(&self) -> bool

Checks if all characters in this string are within the ASCII range.

+
ยงExamples
+
let ascii = "hello!\n";
+let non_ascii = "GrรผรŸe, Jรผrgen โค";
+
+assert!(ascii.is_ascii());
+assert!(!non_ascii.is_ascii());
+
source

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

๐Ÿ”ฌThis is a nightly-only experimental API. (ascii_char)

If this string slice is_ascii, returns it as a slice +of ASCII characters, otherwise returns None.

+
1.23.0 ยท source

pub fn eq_ignore_ascii_case(&self, other: &str) -> bool

Checks that two strings are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
ยงExamples
+
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
+assert!("Ferrรถs".eq_ignore_ascii_case("FERRรถS"));
+assert!(!"Ferrรถs".eq_ignore_ascii_case("FERRร–S"));
+
1.80.0 ยท source

pub fn trim_ascii_start(&self) -> &str

Returns a string slice with leading ASCII whitespace removed.

+

โ€˜Whitespaceโ€™ refers to the definition used by +u8::is_ascii_whitespace.

+
ยงExamples
+
assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
+assert_eq!("  ".trim_ascii_start(), "");
+assert_eq!("".trim_ascii_start(), "");
+
1.80.0 ยท source

pub fn trim_ascii_end(&self) -> &str

Returns a string slice with trailing ASCII whitespace removed.

+

โ€˜Whitespaceโ€™ refers to the definition used by +u8::is_ascii_whitespace.

+
ยงExamples
+
assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
+assert_eq!("  ".trim_ascii_end(), "");
+assert_eq!("".trim_ascii_end(), "");
+
1.80.0 ยท source

pub fn trim_ascii(&self) -> &str

Returns a string slice with leading and trailing ASCII whitespace +removed.

+

โ€˜Whitespaceโ€™ refers to the definition used by +u8::is_ascii_whitespace.

+
ยงExamples
+
assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
+assert_eq!("  ".trim_ascii(), "");
+assert_eq!("".trim_ascii(), "");
+
1.34.0 ยท source

pub fn escape_debug(&self) -> EscapeDebug<'_>

Returns an iterator that escapes each char in self with char::escape_debug.

+

Note: only extended grapheme codepoints that begin the string will be +escaped.

+
ยงExamples
+

As an iterator:

+ +
for c in "โค\n!".escape_debug() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "โค\n!".escape_debug());
+

Both are equivalent to:

+ +
println!("โค\\n!");
+

Using to_string:

+ +
assert_eq!("โค\n!".escape_debug().to_string(), "โค\\n!");
+
1.34.0 ยท source

pub fn escape_default(&self) -> EscapeDefault<'_>

Returns an iterator that escapes each char in self with char::escape_default.

+
ยงExamples
+

As an iterator:

+ +
for c in "โค\n!".escape_default() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "โค\n!".escape_default());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\n!");
+

Using to_string:

+ +
assert_eq!("โค\n!".escape_default().to_string(), "\\u{2764}\\n!");
+
1.34.0 ยท source

pub fn escape_unicode(&self) -> EscapeUnicode<'_>

Returns an iterator that escapes each char in self with char::escape_unicode.

+
ยงExamples
+

As an iterator:

+ +
for c in "โค\n!".escape_unicode() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "โค\n!".escape_unicode());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
+

Using to_string:

+ +
assert_eq!("โค\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
+
source

pub fn substr_range(&self, substr: &str) -> Option<Range<usize>>

๐Ÿ”ฌThis is a nightly-only experimental API. (substr_range)

Returns the range that a substring points to.

+

Returns None if substr does not point within self.

+

Unlike str::find, this does not search through the string. +Instead, it uses pointer arithmetic to find where in the string +substr is derived from.

+

This is useful for extending str::split and similar methods.

+

Note that this method may return false positives (typically either +Some(0..0) or Some(self.len()..self.len())) if substr is a +zero-length str that points at the beginning or end of another, +independent, str.

+
ยงExamples
+
#![feature(substr_range)]
+
+let data = "a, b, b, a";
+let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());
+
+assert_eq!(iter.next(), Some(0..1));
+assert_eq!(iter.next(), Some(3..4));
+assert_eq!(iter.next(), Some(6..7));
+assert_eq!(iter.next(), Some(9..10));
+
source

pub fn as_str(&self) -> &str

๐Ÿ”ฌThis is a nightly-only experimental API. (str_as_str)

Returns the same string as a string slice &str.

+

This method is redundant when used directly on &str, but +it helps dereferencing other string-like types to string slices, +for example references to Box<str> or Arc<str>.

+
1.36.0 ยท source

pub fn replace<P>(&self, from: P, to: &str) -> String
where + P: Pattern,

Replaces all matches of a pattern with another string.

+

replace creates a new String, and copies the data from this string slice into it. +While doing so, it attempts to find matches of a pattern. If it finds any, it +replaces them with the replacement string slice.

+
ยงExamples
+

Basic usage:

+ +
let s = "this is old";
+
+assert_eq!("this is new", s.replace("old", "new"));
+assert_eq!("than an old", s.replace("is", "an"));
+

When the pattern doesnโ€™t match, it returns this string slice as String:

+ +
let s = "this is old";
+assert_eq!(s, s.replace("cookie monster", "little lamb"));
+
1.36.0 ยท source

pub fn replacen<P>(&self, pat: P, to: &str, count: usize) -> String
where + P: Pattern,

Replaces first N matches of a pattern with another string.

+

replacen creates a new String, and copies the data from this string slice into it. +While doing so, it attempts to find matches of a pattern. If it finds any, it +replaces them with the replacement string slice at most count times.

+
ยงExamples
+

Basic usage:

+ +
let s = "foo foo 123 foo";
+assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
+assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
+assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
+

When the pattern doesnโ€™t match, it returns this string slice as String:

+ +
let s = "this is old";
+assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
+
1.36.0 ยท source

pub fn to_lowercase(&self) -> String

Returns the lowercase equivalent of this string slice, as a new String.

+

โ€˜Lowercaseโ€™ is defined according to the terms of the Unicode Derived Core Property +Lowercase.

+

Since some characters can expand into multiple characters when changing +the case, this function returns a String instead of modifying the +parameter in-place.

+
ยงExamples
+

Basic usage:

+ +
let s = "HELLO";
+
+assert_eq!("hello", s.to_lowercase());
+

A tricky example, with sigma:

+ +
let sigma = "ฮฃ";
+
+assert_eq!("ฯƒ", sigma.to_lowercase());
+
+// but at the end of a word, it's ฯ‚, not ฯƒ:
+let odysseus = "แฝˆฮ”ฮฅฮฃฮฃฮ•ฮŽฮฃ";
+
+assert_eq!("แฝ€ฮดฯ…ฯƒฯƒฮตฯฯ‚", odysseus.to_lowercase());
+

Languages without case are not changed:

+ +
let new_year = "ๅ†œๅŽ†ๆ–ฐๅนด";
+
+assert_eq!(new_year, new_year.to_lowercase());
+
1.36.0 ยท source

pub fn to_uppercase(&self) -> String

Returns the uppercase equivalent of this string slice, as a new String.

+

โ€˜Uppercaseโ€™ is defined according to the terms of the Unicode Derived Core Property +Uppercase.

+

Since some characters can expand into multiple characters when changing +the case, this function returns a String instead of modifying the +parameter in-place.

+
ยงExamples
+

Basic usage:

+ +
let s = "hello";
+
+assert_eq!("HELLO", s.to_uppercase());
+

Scripts without case are not changed:

+ +
let new_year = "ๅ†œๅŽ†ๆ–ฐๅนด";
+
+assert_eq!(new_year, new_year.to_uppercase());
+

One character can become multiple:

+ +
let s = "tschรผรŸ";
+
+assert_eq!("TSCHรœSS", s.to_uppercase());
+
1.36.0 ยท source

pub fn repeat(&self, n: usize) -> String

Creates a new String by repeating a string n times.

+
ยงPanics
+

This function will panic if the capacity would overflow.

+
ยงExamples
+

Basic usage:

+ +
assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
+

A panic upon overflow:

+ +
โ“˜
// this will panic at runtime
+let huge = "0123456789abcdef".repeat(usize::MAX);
+
1.36.0 ยท source

pub fn to_ascii_uppercase(&self) -> String

Returns a copy of this string where each character is mapped to its +ASCII upper case equivalent.

+

ASCII letters โ€˜aโ€™ to โ€˜zโ€™ are mapped to โ€˜Aโ€™ to โ€˜Zโ€™, +but non-ASCII letters are unchanged.

+

To uppercase the value in-place, use make_ascii_uppercase.

+

To uppercase ASCII characters in addition to non-ASCII characters, use +to_uppercase.

+
ยงExamples
+
let s = "GrรผรŸe, Jรผrgen โค";
+
+assert_eq!("GRรผรŸE, JรผRGEN โค", s.to_ascii_uppercase());
+
1.36.0 ยท source

pub fn to_ascii_lowercase(&self) -> String

Returns a copy of this string where each character is mapped to its +ASCII lower case equivalent.

+

ASCII letters โ€˜Aโ€™ to โ€˜Zโ€™ are mapped to โ€˜aโ€™ to โ€˜zโ€™, +but non-ASCII letters are unchanged.

+

To lowercase the value in-place, use make_ascii_lowercase.

+

To lowercase ASCII characters in addition to non-ASCII characters, use +to_lowercase.

+
ยงExamples
+
let s = "GrรผรŸe, Jรผrgen โค";
+
+assert_eq!("grรผรŸe, jรผrgen โค", s.to_ascii_lowercase());
+

Trait Implementationsยง

sourceยง

impl AsRef<[u8]> for ByteString

sourceยง

fn as_ref(&self) -> &[u8] โ“˜

Converts this type into a shared reference of the (usually inferred) input type.
sourceยง

impl AsRef<ByteString> for ByteString

sourceยง

fn as_ref(&self) -> &ByteString

Converts this type into a shared reference of the (usually inferred) input type.
sourceยง

impl AsRef<str> for ByteString

sourceยง

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
sourceยง

impl Borrow<str> for ByteString

sourceยง

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
sourceยง

impl Clone for ByteString

sourceยง

fn clone(&self) -> ByteString

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for ByteString

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Default for ByteString

sourceยง

fn default() -> ByteString

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl Deref for ByteString

sourceยง

type Target = str

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &str

Dereferences the value.
sourceยง

impl<'de> Deserialize<'de> for ByteString

sourceยง

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where + D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
sourceยง

impl Display for ByteString

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl From<&str> for ByteString

sourceยง

fn from(value: &str) -> Self

Converts to this type from the input type.
sourceยง

impl From<Box<str>> for ByteString

sourceยง

fn from(value: Box<str>) -> Self

Converts to this type from the input type.
sourceยง

impl From<ByteString> for String

sourceยง

fn from(value: ByteString) -> Self

Converts to this type from the input type.
sourceยง

impl From<String> for ByteString

sourceยง

fn from(value: String) -> Self

Converts to this type from the input type.
sourceยง

impl Hash for ByteString

sourceยง

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
sourceยง

impl Ord for ByteString

sourceยง

fn cmp(&self, other: &ByteString) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where + Self: Sized,

Restrict a value to a certain interval. Read more
sourceยง

impl<T: AsRef<str>> PartialEq<T> for ByteString

sourceยง

fn eq(&self, other: &T) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
sourceยง

impl PartialEq<str> for ByteString

sourceยง

fn eq(&self, other: &str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
sourceยง

impl PartialOrd for ByteString

sourceยง

fn partial_cmp(&self, other: &ByteString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.6.0 ยท sourceยง

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.6.0 ยท sourceยง

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the +<= operator. Read more
1.6.0 ยท sourceยง

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > +operator. Read more
1.6.0 ยท sourceยง

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by +the >= operator. Read more
sourceยง

impl Serialize for ByteString

sourceยง

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where + S: Serializer,

Serialize this value into the given Serde serializer. Read more
sourceยง

impl TryFrom<&[u8]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 0]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 0]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 1]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 1]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 10]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 10]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 11]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 11]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 12]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 12]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 13]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 13]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 14]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 14]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 15]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 15]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 16]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 16]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 17]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 17]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 18]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 18]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 19]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 19]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 2]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 2]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 20]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 20]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 21]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 21]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 22]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 22]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 23]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 23]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 24]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 24]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 25]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 25]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 26]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 26]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 27]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 27]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 28]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 28]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 29]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 29]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 3]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 3]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 30]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 30]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 31]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 31]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 32]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 32]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 4]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 4]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 5]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 5]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 6]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 6]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 7]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 7]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 8]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 8]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<&[u8; 9]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: &[u8; 9]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 0]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 0]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 1]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 1]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 10]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 10]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 11]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 11]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 12]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 12]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 13]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 13]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 14]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 14]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 15]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 15]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 16]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 16]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 17]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 17]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 18]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 18]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 19]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 19]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 2]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 2]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 20]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 20]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 21]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 21]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 22]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 22]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 23]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 23]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 24]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 24]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 25]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 25]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 26]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 26]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 27]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 27]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 28]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 28]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 29]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 29]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 3]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 3]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 30]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 30]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 31]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 31]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 32]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 32]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 4]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 4]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 5]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 5]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 6]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 6]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 7]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 7]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 8]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 8]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<[u8; 9]> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: [u8; 9]) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<Bytes> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: Bytes) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<BytesMut> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: BytesMut) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl TryFrom<Vec<u8>> for ByteString

sourceยง

type Error = Utf8Error

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: Vec<u8>) -> Result<Self, Self::Error>

Performs the conversion.
sourceยง

impl Eq for ByteString

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
sourceยง

impl<T> DeserializeOwned for T
where + T: for<'de> Deserialize<'de>,

\ No newline at end of file diff --git a/crates.js b/crates.js new file mode 100644 index 00000000..5467e626 --- /dev/null +++ b/crates.js @@ -0,0 +1,2 @@ +window.ALL_CRATES = ["actix_codec","actix_macros","actix_rt","actix_server","actix_service","actix_tls","actix_tracing","actix_utils","bytestring","local_channel","local_waker"]; +//{"start":21,"fragment_lengths":[13,15,11,15,16,12,16,14,13,16,14]} \ No newline at end of file diff --git a/help.html b/help.html new file mode 100644 index 00000000..531c35e8 --- /dev/null +++ b/help.html @@ -0,0 +1 @@ +Help

Rustdoc help

Back
\ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 00000000..76105d1f --- /dev/null +++ b/index.html @@ -0,0 +1 @@ + diff --git a/local_channel/all.html b/local_channel/all.html new file mode 100644 index 00000000..f3ff709a --- /dev/null +++ b/local_channel/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/local_channel/index.html b/local_channel/index.html new file mode 100644 index 00000000..8a2a2fc0 --- /dev/null +++ b/local_channel/index.html @@ -0,0 +1,3 @@ +local_channel - Rust

Crate local_channel

source
Expand description

Non-thread-safe channels.

+

See docs for mpsc::channel().

+

Modulesยง

  • A non-thread-safe multi-producer, single-consumer, futures-aware, FIFO queue.
\ No newline at end of file diff --git a/local_channel/mpsc/fn.channel.html b/local_channel/mpsc/fn.channel.html new file mode 100644 index 00000000..6d749886 --- /dev/null +++ b/local_channel/mpsc/fn.channel.html @@ -0,0 +1,3 @@ +channel in local_channel::mpsc - Rust
local_channel::mpsc

Function channel

source
pub fn channel<T>() -> (Sender<T>, Receiver<T>)
Expand description

Creates a unbounded in-memory channel with buffered storage.

+

Senders and Receivers are !Send.

+
\ No newline at end of file diff --git a/local_channel/mpsc/index.html b/local_channel/mpsc/index.html new file mode 100644 index 00000000..0fed2c8e --- /dev/null +++ b/local_channel/mpsc/index.html @@ -0,0 +1,2 @@ +local_channel::mpsc - Rust
local_channel

Module mpsc

source
Expand description

A non-thread-safe multi-producer, single-consumer, futures-aware, FIFO queue.

+

Structsยง

  • The receiving end of a channel which implements the Stream trait.
  • Error returned when attempting to send after the channelsโ€™ Receiver is dropped or closed.
  • The transmission end of a channel.

Functionsยง

  • Creates a unbounded in-memory channel with buffered storage.
\ No newline at end of file diff --git a/local_channel/mpsc/sidebar-items.js b/local_channel/mpsc/sidebar-items.js new file mode 100644 index 00000000..6627a3ac --- /dev/null +++ b/local_channel/mpsc/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["channel"],"struct":["Receiver","SendError","Sender"]}; \ No newline at end of file diff --git a/local_channel/mpsc/struct.Receiver.html b/local_channel/mpsc/struct.Receiver.html new file mode 100644 index 00000000..78808b16 --- /dev/null +++ b/local_channel/mpsc/struct.Receiver.html @@ -0,0 +1,27 @@ +Receiver in local_channel::mpsc - Rust
local_channel::mpsc

Struct Receiver

source
pub struct Receiver<T> { /* private fields */ }
Expand description

The receiving end of a channel which implements the Stream trait.

+

This is created by the channel function.

+

Implementationsยง

sourceยง

impl<T> Receiver<T>

source

pub async fn recv(&mut self) -> Option<T>

Receive the next value.

+

Returns None if the channel is empty and has been closed explicitly or +when all senders have been dropped and, therefore, no more values can ever be sent though +this channel.

+
source

pub fn sender(&self) -> Sender<T>

Create an associated Sender.

+

Trait Implementationsยง

sourceยง

impl<T: Debug> Debug for Receiver<T>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<T> Drop for Receiver<T>

sourceยง

fn drop(&mut self)

Executes the destructor for this type. Read more
sourceยง

impl<T> Stream for Receiver<T>

sourceยง

type Item = T

Values yielded by the stream.
sourceยง

fn poll_next( + self: Pin<&mut Self>, + cx: &mut Context<'_>, +) -> Poll<Option<Self::Item>>

Attempt to pull out the next value of this stream, registering the +current task for wakeup if the value is not yet available, and returning +None if the stream is exhausted. Read more
ยง

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
sourceยง

impl<T> Unpin for Receiver<T>

Auto Trait Implementationsยง

ยง

impl<T> Freeze for Receiver<T>

ยง

impl<T> !RefUnwindSafe for Receiver<T>

ยง

impl<T> !Send for Receiver<T>

ยง

impl<T> !Sync for Receiver<T>

ยง

impl<T> !UnwindSafe for Receiver<T>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
ยง

impl<S, T, E> TryStream for S
where + S: Stream<Item = Result<T, E>> + ?Sized,

ยง

type Ok = T

The type of successful values yielded by this future
ยง

type Error = E

The type of failures yielded by this future
ยง

fn try_poll_next( + self: Pin<&mut S>, + cx: &mut Context<'_>, +) -> Poll<Option<Result<<S as TryStream>::Ok, <S as TryStream>::Error>>>

Poll this TryStream as if it were a Stream. Read more
\ No newline at end of file diff --git a/local_channel/mpsc/struct.SendError.html b/local_channel/mpsc/struct.SendError.html new file mode 100644 index 00000000..79ee6eb6 --- /dev/null +++ b/local_channel/mpsc/struct.SendError.html @@ -0,0 +1,21 @@ +SendError in local_channel::mpsc - Rust
local_channel::mpsc

Struct SendError

source
pub struct SendError<T>(pub T);
Expand description

Error returned when attempting to send after the channelsโ€™ Receiver is dropped or closed.

+

Allows access to message that failed to send with into_inner.

+

Tuple Fieldsยง

ยง0: T

Implementationsยง

sourceยง

impl<T> SendError<T>

source

pub fn into_inner(self) -> T

Returns the message that was attempted to be sent but failed.

+

Trait Implementationsยง

sourceยง

impl<T> Debug for SendError<T>

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<T> Display for SendError<T>

sourceยง

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<T> Error for SendError<T>

1.81.0 ยท sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.81.0 ยท sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
1.81.0 ยท sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn provide<'a>(&'a self, request: &mut Request<'a>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementationsยง

ยง

impl<T> Freeze for SendError<T>
where + T: Freeze,

ยง

impl<T> RefUnwindSafe for SendError<T>
where + T: RefUnwindSafe,

ยง

impl<T> Send for SendError<T>
where + T: Send,

ยง

impl<T> Sync for SendError<T>
where + T: Sync,

ยง

impl<T> Unpin for SendError<T>
where + T: Unpin,

ยง

impl<T> UnwindSafe for SendError<T>
where + T: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToString for T
where + T: Display + ?Sized,

sourceยง

default fn to_string(&self) -> String

Converts the given value to a String. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/local_channel/mpsc/struct.Sender.html b/local_channel/mpsc/struct.Sender.html new file mode 100644 index 00000000..8def5609 --- /dev/null +++ b/local_channel/mpsc/struct.Sender.html @@ -0,0 +1,30 @@ +Sender in local_channel::mpsc - Rust
local_channel::mpsc

Struct Sender

source
pub struct Sender<T> { /* private fields */ }
Expand description

The transmission end of a channel.

+

This is created by the channel function.

+

Implementationsยง

sourceยง

impl<T> Sender<T>

source

pub fn send(&self, item: T) -> Result<(), SendError<T>>

Sends the provided message along this channel.

+
source

pub fn close(&mut self)

Closes the sender half.

+

This prevents any further messages from being sent on the channel, by any sender, while +still enabling the receiver to drain messages that are already buffered.

+

Trait Implementationsยง

sourceยง

impl<T> Clone for Sender<T>

sourceยง

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<T: Debug> Debug for Sender<T>

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl<T> Drop for Sender<T>

sourceยง

fn drop(&mut self)

Executes the destructor for this type. Read more
sourceยง

impl<T> Sink<T> for Sender<T>

sourceยง

type Error = SendError<T>

The type of value produced by the sink when an error occurs.
sourceยง

fn poll_ready( + self: Pin<&mut Self>, + _: &mut Context<'_>, +) -> Poll<Result<(), Self::Error>>

Attempts to prepare the Sink to receive a value. Read more
sourceยง

fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), SendError<T>>

Begin the process of sending a value to the sink. +Each call to this function must be preceded by a successful call to +poll_ready which returned Poll::Ready(Ok(())). Read more
sourceยง

fn poll_flush( + self: Pin<&mut Self>, + _: &mut Context<'_>, +) -> Poll<Result<(), SendError<T>>>

Flush any remaining output from this sink. Read more
sourceยง

fn poll_close( + self: Pin<&mut Self>, + _: &mut Context<'_>, +) -> Poll<Result<(), Self::Error>>

Flush any remaining output and close this sink, if necessary. Read more
sourceยง

impl<T> Unpin for Sender<T>

Auto Trait Implementationsยง

ยง

impl<T> Freeze for Sender<T>

ยง

impl<T> !RefUnwindSafe for Sender<T>

ยง

impl<T> !Send for Sender<T>

ยง

impl<T> !Sync for Sender<T>

ยง

impl<T> !UnwindSafe for Sender<T>

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> CloneToUninit for T
where + T: Clone,

sourceยง

unsafe fn clone_to_uninit(&self, dst: *mut T)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T> ToOwned for T
where + T: Clone,

sourceยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/local_channel/sidebar-items.js b/local_channel/sidebar-items.js new file mode 100644 index 00000000..5eeb7b67 --- /dev/null +++ b/local_channel/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["mpsc"]}; \ No newline at end of file diff --git a/local_waker/all.html b/local_waker/all.html new file mode 100644 index 00000000..b8a0141b --- /dev/null +++ b/local_waker/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

\ No newline at end of file diff --git a/local_waker/index.html b/local_waker/index.html new file mode 100644 index 00000000..c6e013fa --- /dev/null +++ b/local_waker/index.html @@ -0,0 +1,3 @@ +local_waker - Rust

Crate local_waker

source
Expand description

A synchronization primitive for thread-local task wakeup.

+

See docs for LocalWaker.

+

Structsยง

  • A synchronization primitive for task wakeup.
\ No newline at end of file diff --git a/local_waker/sidebar-items.js b/local_waker/sidebar-items.js new file mode 100644 index 00000000..4b28c5cf --- /dev/null +++ b/local_waker/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["LocalWaker"]}; \ No newline at end of file diff --git a/local_waker/struct.LocalWaker.html b/local_waker/struct.LocalWaker.html new file mode 100644 index 00000000..5aa80e22 --- /dev/null +++ b/local_waker/struct.LocalWaker.html @@ -0,0 +1,29 @@ +LocalWaker in local_waker - Rust
local_waker

Struct LocalWaker

source
pub struct LocalWaker { /* private fields */ }
Expand description

A synchronization primitive for task wakeup.

+

Sometimes the task interested in a given event will change over time. A LocalWaker can +coordinate concurrent notifications with the consumer, potentially โ€œupdatingโ€ the underlying +task to wake up. This is useful in scenarios where a computation completes in another task and +wants to notify the consumer, but the consumer is in the process of being migrated to a new +logical task.

+

Consumers should call register before checking the result of a computation and producers +should call wake after producing the computation (this differs from the usual thread::park +pattern). It is also permitted for wake to be called before register. This results in +a no-op.

+

A single LocalWaker may be reused for any number of calls to register or wake.

+

Implementationsยง

sourceยง

impl LocalWaker

source

pub fn new() -> Self

Creates a new, empty LocalWaker.

+
source

pub fn register(&self, waker: &Waker) -> bool

Registers the waker to be notified on calls to wake.

+

Returns true if waker was registered before.

+
source

pub fn wake(&self)

Calls wake on the last Waker passed to register.

+

If register has not been called yet, then this does nothing.

+
source

pub fn take(&self) -> Option<Waker>

Returns the last Waker passed to register, so that the user can wake it.

+

If a waker has not been registered, this returns None.

+

Trait Implementationsยง

sourceยง

impl Debug for LocalWaker

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Default for LocalWaker

sourceยง

fn default() -> LocalWaker

Returns the โ€œdefault valueโ€ for a type. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where + T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where + T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where + T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

+
sourceยง

impl<T, U> Into<U> for T
where + U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
sourceยง

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

sourceยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

sourceยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/search-index.js b/search-index.js new file mode 100644 index 00000000..60dea389 --- /dev/null +++ b/search-index.js @@ -0,0 +1,4 @@ +var searchIndex = new Map(JSON.parse('[["actix_codec",{"t":"KKFKKRRFFRFFNNNNNNNNNNNNNNNNNNNNNONNMNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNMNNMHNMMNNONNNNNNNNNNNNNNNNNNNNNNNNNNNO","n":["AsyncRead","AsyncWrite","BytesCodec","Decoder","Encoder","Error","","Framed","FramedParts","Item","LinesCodec","ReadBuf","advance","assume_init","borrow","","","","","borrow_mut","","","","","capacity","clear","clone","","clone_into","","clone_to_uninit","","close","codec","codec_mut","codec_ref","decode","","","decode_eof","","default","encode","","","filled","filled_mut","flush","fmt","","","","","framed","from","","","","","from_parts","initialize_unfilled","initialize_unfilled_to","initialized","initialized_mut","inner_mut","into","","","","","into_map_codec","into_map_io","into_parts","io","io_mut","io_pin","io_ref","is_read_buf_empty","is_write_buf_empty","is_write_buf_full","is_write_ready","is_write_vectored","new","","","next_item","poll_close","poll_flush","","poll_next","poll_read","poll_read_buf","poll_ready","poll_shutdown","poll_write","poll_write_vectored","put_slice","read_buf","remaining","replace_codec","set_filled","start_send","take","to_owned","","try_from","","","","","try_into","","","","","try_poll_next","type_id","","","","","unfilled_mut","uninit","with_read_buf","write","write_buf"],"q":[[0,"actix_codec"],[126,"tokio::io::read_buf"],[127,"actix_codec::bcodec"],[128,"actix_codec::lines"],[129,"actix_codec::framed"],[130,"core::pin"],[131,"core::task::wake"],[132,"core::result"],[133,"core::task::poll"],[134,"tokio::io::async_write"],[135,"tokio_util::codec::encoder"],[136,"tokio_util::codec::decoder"],[137,"bytes::bytes_mut"],[138,"core::option"],[139,"std::io::error"],[140,"core::convert"],[141,"bytes::bytes"],[142,"core::fmt"],[143,"tokio_util::codec::framed"],[144,"tokio::io::async_read"],[145,"core::mem::maybe_uninit"],[146,"core::ops::function"],[147,"core::marker"],[148,"bytes::buf::buf_mut"],[149,"std::io"],[150,"core::any"],[151,"tokio_util::util::poll_buf"]],"i":"`````BbAl``1``d0l1A`Cnn34210443030302122630600530442342106342102444443421022212222222Aj53233033Db`4111636464652564325643245643266343","f":"````````````{{{f{bd}}h}j}0{f{{f{c}}}{}}0000{{{f{b}}}{{f{bc}}}{}}0000{{{f{d}}}h}{{{f{bd}}}j}{{{f{l}}}l}{{{f{n}}}n}{{f{f{bc}}}j{}}0{fj}0{{{Ab{{f{b{A`{cg}}}}}}{f{bAd}}}{{Ah{{Af{j}}}}}Aj{}{{Al{e}}}}`{{{f{b{A`{ce}}}}}{{f{be}}}{}{}}{{{f{{A`{ce}}}}}{{f{e}}}{}{}}{{{f{b{Bb{}{{An{c}}{B`{e}}}}}}{f{bBd}}}{{Af{{Bf{c}}e}}}{}{{Bj{Bh}}}}{{{f{bl}}{f{bBd}}}{{Af{{Bf{c}}e}}}{}{}}{{{f{bn}}{f{bBd}}}{{Af{{Bf{c}}e}}}{}{}}20{{}n}{{{f{b{Al{}{{B`{c}}}}}}e{f{bBd}}}{{Af{jc}}}{{Bj{Bh}}}{}}{{{f{bl}}Bl{f{bBd}}}{{Af{jc}}}{}}{{{f{bn}}c{f{bBd}}}{{Af{je}}}{{C`{Bn}}}{}}{{{f{d}}}{{f{{Cd{Cb}}}}}}{{{f{bd}}}{{f{b{Cd{Cb}}}}}};{{{f{l}}{f{bCf}}}Ch}{{{f{d}}{f{bCf}}}{{Af{jCj}}}}{{{f{{A`{ce}}}}{f{bCf}}}ChClCl}{{{f{{Cn{ce}}}}{f{bCf}}}ChClCl}{{{f{n}}{f{bCf}}}Ch}{{{Bb{}{{An{c}}{B`{e}}}}g}{{D`{g{Bb{}{{An{c}}{B`{e}}}}}}}{}{{Bj{Bh}}}{DbAj}}{cc{}}0000{{{Cn{ce}}}{{A`{ce}}}{}{}}8{{{f{bd}}h}{{f{b{Cd{Cb}}}}}}:9{{{f{bd}}}{{f{b{Cd{{Dd{Cb}}}}}}}}{{}c{}}0000{{{A`{ce}}i}{{A`{cg}}}{}{}{}{{Dh{e}{{Df{g}}}}}}{{{A`{ce}}i}{{A`{ge}}}{}{}{}{{Dh{c}{{Df{g}}}}}}{{{A`{ce}}}{{Cn{ce}}}{}{}}`{{{f{b{A`{ce}}}}}{{f{bc}}}{}{}}{{{Ab{{f{b{A`{ce}}}}}}}{{Ab{{f{bc}}}}}{}{}}{{{f{{A`{ce}}}}}{{f{c}}}{}{}}{{{f{{A`{ce}}}}}Dj{}{}}000{{{f{Aj}}}Dj}{{{f{b{Cd{Cb}}}}}d}{{ce}{{A`{ce}}}{DbAj}Bb}{{ce}{{Cn{ce}}}{}{}}{{{Ab{{f{b{A`{ce}}}}}}{f{bAd}}}{{Ah{{Bf{Af}}}}}DbBb}{{{Ab{{f{b{A`{cg}}}}}}{f{bAd}}}{{Ah{{Af{ji}}}}}Aj{}{{Al{e}}}{}}{{{Ab{{f{bAj}}}}{f{bAd}}}{{Ah{{Af{jBh}}}}}}1{{{Ab{{f{b{A`{ce}}}}}}{f{bAd}}}{{Ah{{Bf{g}}}}}DbBb{}}{{{Ab{{f{bDb}}}}{f{bAd}}{f{bd}}}{{Ah{{Af{jBh}}}}}}{{{Ab{{f{bc}}}}{f{bAd}}{f{be}}}{{Ah{{Af{hBh}}}}}{DbDl}Dn}43{{{Ab{{f{bAj}}}}{f{bAd}}{f{{Cd{Cb}}}}}{{Ah{{Af{hBh}}}}}}{{{Ab{{f{bAj}}}}{f{bAd}}{f{{Cd{E`}}}}}{{Ah{{Af{hBh}}}}}}{{{f{bd}}{f{{Cd{Cb}}}}}j}`{{{f{d}}}h}{{{A`{ce}}g}{{A`{cg}}}{}{}{}}{{{f{bd}}h}j}{{{Ab{{f{b{A`{cg}}}}}}e}{{Af{ji}}}Aj{}{{Al{e}}}{}}{{{f{bd}}h}d}{fc{}}0{c{{Af{e}}}{}{}}0000{{}{{Af{c}}}{}}0000{{{Ab{{f{bc}}}}{f{bAd}}}{{Ah{{Bf{Af}}}}}{}}{fEb}0000{{{f{bd}}}{{f{b{Cd{{Dd{Cb}}}}}}}}{{{f{b{Cd{{Dd{Cb}}}}}}}d}{{ceBd}{{Cn{ce}}}{}{}}{{{Ab{{f{b{A`{cg}}}}}}e}{{Af{j}}}Aj{}{{Al{e}}}}`","D":"Ij","p":[[0,"mut"],[5,"ReadBuf",0,126],[1,"reference"],[1,"usize"],[1,"unit"],[5,"BytesCodec",0,127],[5,"LinesCodec",0,128],[5,"Framed",0,129],[5,"Pin",130],[5,"Context",131],[6,"Result",132],[6,"Poll",133],[10,"AsyncWrite",0,134],[10,"Encoder",0,135],[17,"Item"],[17,"Error"],[10,"Decoder",0,136],[5,"BytesMut",137],[6,"Option",138],[5,"Error",139],[10,"From",140],[5,"Bytes",141],[1,"str"],[10,"AsRef",140],[1,"u8"],[1,"slice"],[5,"Formatter",142],[8,"Result",142],[5,"Error",142],[10,"Debug",142],[5,"FramedParts",0,129],[5,"Framed",143],[10,"AsyncRead",0,144],[20,"MaybeUninit",145],[17,"Output"],[10,"Fn",146],[1,"bool"],[10,"Sized",147],[10,"BufMut",148],[5,"IoSlice",149],[5,"TypeId",150]],"r":[[0,144],[1,134],[2,127],[3,136],[4,135],[7,129],[8,129],[10,128],[11,126],[91,151]],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAADEACwAPAAkAGwAFACYAAQApAAEALAABADEABABXAAAAWQABAF0AAABmAAAAaAARAA=="}],["actix_macros",{"t":"XX","n":["main","test"],"q":[[0,"actix_macros"]],"i":"``","f":"``","D":"f","p":[],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OjAAAAAAAAA="}],["actix_rt",{"t":"FFFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNXCNNNQNNCHNNNNNNNNNCXCNNNNNNNNNNNNNNNNNNNNTTTTTTFFFFFFFFTTNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHCFFNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNFFNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNHFFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHHNNNNNNNNNNNNNNNNNNNNNNNHHNNNNHNNNNNNNNNNNNNN","n":["Arbiter","ArbiterHandle","Runtime","System","SystemRunner","arbiter","block_on","","borrow","","","","","borrow_mut","","","","","clone","","clone_into","","clone_to_uninit","","current","","fmt","","","","","from","","","","","","handle","id","into","","","","","is_registered","join","main","net","new","","","pin","run","run_with_code","signal","spawn","","","","spawn_fn","","stop","","","stop_with_code","task","test","time","to_owned","","tokio_runtime","try_current","","try_from","","","","","try_into","","","","","type_id","","","","","ALL","EMPTY","ERROR","PRIORITY","READABLE","READ_CLOSED","Ready","TcpListener","TcpSocket","TcpStream","UdpSocket","UnixDatagram","UnixListener","UnixStream","WRITABLE","WRITE_CLOSED","accept","","as_fd","","","","","","","as_raw_fd","","","","","","","async_io","","","","bind","","","","","bind_device","","bitand","bitor","bitor_assign","borrow","","","","","","","","borrow_mut","","","","","","","","broadcast","clone","clone_into","clone_to_uninit","cmp","connect","","","","","device","","eq","fmt","","","","","","","","from","","","","","","","","from_raw_fd","from_std","","","","","","from_std_stream","into","","","","","","","","into_raw_fd","into_split","","into_std","","","","","","is_empty","is_error","is_priority","is_read_closed","is_readable","is_writable","is_write_closed","is_write_vectored","","join_multicast_v4","join_multicast_v6","keepalive","leave_multicast_v4","leave_multicast_v6","linger","","listen","local_addr","","","","","","","multicast_loop_v4","multicast_loop_v6","multicast_ttl_v4","new_v4","new_v6","nodelay","","pair","","partial_cmp","peek","peek_from","peek_sender","peer_addr","","","","peer_cred","poll_accept","","poll_flush","","poll_peek","poll_peek_from","poll_peek_sender","poll_read","","poll_read_ready","","poll_recv","","poll_recv_from","","poll_recv_ready","","poll_send","","poll_send_ready","","poll_send_to","","poll_shutdown","","poll_write","","poll_write_ready","","poll_write_vectored","","readable","","","","ready","","","","recv","","recv_buffer_size","recv_from","","reuseaddr","reuseport","send","","send_buffer_size","send_to","","set_broadcast","set_keepalive","set_linger","","set_multicast_loop_v4","set_multicast_loop_v6","set_multicast_ttl_v4","set_nodelay","","set_recv_buffer_size","set_reuseaddr","set_reuseport","set_send_buffer_size","set_tos","","set_ttl","","","shutdown","split","","sub","take_error","","","","","","to_owned","tos","","try_from","","","","","","","","","","","","","","try_into","","","","","","","","try_io","","","","try_peek_from","try_peek_sender","try_read","","try_read_vectored","","try_recv","","try_recv_from","","try_send","","try_send_to","","try_write","","try_write_vectored","","ttl","","","type_id","","","","","","","","unbound","writable","","","","ctrl_c","unix","Signal","SignalKind","alarm","as_raw_value","borrow","","borrow_mut","","child","clone","clone_into","clone_to_uninit","eq","fmt","","from","","","from_raw","hangup","hash","interrupt","into","","io","pipe","poll_recv","quit","recv","signal","terminate","to_owned","try_from","","try_into","","type_id","","user_defined1","user_defined2","window_change","JoinError","JoinHandle","abort","abort_handle","borrow","","borrow_mut","","drop","fmt","","","from","","into","","into_future","into_panic","is_cancelled","is_finished","is_panic","poll","spawn_blocking","to_string","try_from","","try_into","","try_into_panic","try_poll","type_id","","yield_now","Instant","Interval","Sleep","Timeout","add","add_assign","borrow","","","","borrow_mut","","","","checked_add","checked_duration_since","checked_sub","clone","clone_into","clone_to_uninit","cmp","deadline","duration_since","elapsed","eq","fmt","","","","from","","","","","from_std","get_mut","get_ref","hash","interval","interval_at","into","","","","into_future","","into_inner","into_std","is_elapsed","missed_tick_behavior","now","partial_cmp","period","poll","","poll_tick","reset","","reset_after","reset_at","reset_immediately","saturating_duration_since","set_missed_tick_behavior","sleep","sleep_until","sub","","sub_assign","tick","timeout","to_owned","try_from","","","","try_into","","","","try_poll","type_id","","",""],"q":[[0,"actix_rt"],[88,"actix_rt::net"],[388,"actix_rt::signal"],[390,"actix_rt::signal::unix"],[431,"actix_rt::task"],[464,"actix_rt::time"],[548,"actix_rt::system"],[549,"actix_rt::arbiter"],[550,"actix_rt::runtime"],[551,"core::future::future"],[552,"core::fmt"],[553,"tokio::runtime::runtime"],[554,"std::thread"],[555,"std::io::error"],[556,"tokio::runtime::task::join"],[557,"core::marker"],[558,"core::ops::function"],[559,"core::option"],[560,"core::result"],[561,"core::any"],[562,"tokio::net::tcp::listener"],[563,"tokio::net::tcp::stream"],[564,"core::net::socket_addr"],[565,"tokio::net::unix::listener"],[566,"tokio::net::unix::stream"],[567,"tokio::net::unix::socketaddr"],[568,"std::os::fd::owned"],[569,"tokio::net::tcp::socket"],[570,"tokio::net::udp"],[571,"tokio::net::unix::datagram::socket"],[572,"tokio::io::interest"],[573,"tokio::net::addr"],[574,"std::path"],[575,"core::convert"],[576,"tokio::io::ready"],[577,"core::cmp"],[578,"alloc::vec"],[579,"std::net::tcp"],[580,"std::net::udp"],[581,"std::os::unix::net::datagram"],[582,"std::os::unix::net::listener"],[583,"std::os::unix::net::stream"],[584,"tokio::net::tcp::split_owned"],[585,"tokio::net::unix::split_owned"],[586,"core::net::ip_addr"],[587,"core::time"],[588,"tokio::net::unix::ucred"],[589,"core::task::wake"],[590,"core::task::poll"],[591,"core::pin"],[592,"tokio::io::read_buf"],[593,"std::io"],[594,"std::net"],[595,"tokio::net::tcp::split"],[596,"tokio::net::unix::split"],[597,"tokio::signal::unix"],[598,"core::hash"],[599,"tokio::runtime::task::abort"],[600,"tokio::runtime::task::error"],[601,"alloc::boxed"],[602,"alloc::string"],[603,"tokio::time::instant"],[604,"tokio::time::sleep"],[605,"tokio::time::interval"],[606,"tokio::time::timeout"],[607,"std::time"],[608,"core::future::into_future"],[609,"actix_macros"],[610,"tokio"],[611,"tokio::signal::ctrl_c"],[612,"tokio::task::blocking"],[613,"tokio::task::yield_now"]],"i":"`````bhlfAf342103421414140410342103342041034240``034`22``103101044```14304103421034210342Eh00000````````00CbCl1DdCdDfDh4Cn64321503210642154277776432150764321502777743210427764321507643215046321504764321504306321507777777302242243464321502224443107322321006530322303021212121212130303030321032102142144214212443222434444426321307432150742766433221155007643215032102230302121212130306327643215013210````Id00If10111111011011111011010`11101010111``Bd0Il10110010101100101`001010101`````Jf00JjJlJh3210333333303333210332103113``32101013023321022022232``3332`33210321013210","f":"`````{{{d{b}}}{{d{f}}}}{{{d{h}}c}{}j}{{{d{l}}c}{}j}{d{{d{c}}}{}}0000{{{d{n}}}{{d{nc}}}{}}0000{{{d{f}}}f}{{{d{b}}}b}{{d{d{nc}}}A`{}}0{dA`}0{{}f}{{}b}{{{d{f}}{d{nAb}}}Ad}{{{d{Af}}{d{nAb}}}Ad}{{{d{h}}{d{nAb}}}Ad}{{{d{b}}{d{nAb}}}Ad}{{{d{l}}{d{nAb}}}Ad}{cc{}}00{Ahh}11{{{d{Af}}}f}{{{d{b}}}Aj}{{}c{}}0000{{}Al}{Af{{An{A`}}}}``{{}Af}{{}{{B`{h}}}}{{}l}`{l{{B`{A`}}}}{l{{B`{Bb}}}}`{cBdj}{{{d{f}}c}Al{{j{}{{Bf{A`}}}}Bh}}{{{d{Af}}c}Al{{j{}{{Bf{A`}}}}Bh}}{{{d{h}}c}Bdj}{{{d{f}}c}Al{BjBh}}{{{d{Af}}c}Al{BjBh}}{{{d{f}}}Al}{{{d{Af}}}Al}{{{d{b}}}A`}{{{d{b}}Bb}A`}```{dc{}}0{{{d{h}}}{{d{Ah}}}}{{}{{Bl{f}}}}{{}{{Bl{b}}}}{c{{Bn{e}}}{}{}}0000{{}{{Bn{c}}}{}}0000{dC`}0000````````````````{{{d{Cb}}}{{Bn{{Ch{CdCf}}Cj}}}}{{{d{Cl}}}{{Bn{{Ch{CnD`}}Cj}}}}{{{d{Cb}}}Db}{{{d{Dd}}}Db}{{{d{Cd}}}Db}{{{d{Df}}}Db}{{{d{Dh}}}Db}{{{d{Cl}}}Db}{{{d{Cn}}}Db}{{{d{Cb}}}Bb}{{{d{Dd}}}Bb}{{{d{Cd}}}Bb}{{{d{Df}}}Bb}{{{d{Dh}}}Bb}{{{d{Cl}}}Bb}{{{d{Cn}}}Bb}{{{d{Cd}}Dje}{{Bn{cCj}}}{}{{Dl{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Df}}Dje}{{Bn{cCj}}}{}{{Dl{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Dh}}Dje}{{Bn{cCj}}}{}{{Dl{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Cn}}Dje}{{Bn{cCj}}}{}{{Dl{}{{Bf{{Bn{cCj}}}}}}}}{c{{Bn{CbCj}}}Dn}{{{d{Dd}}Cf}{{Bn{A`Cj}}}}{c{{Bn{DfCj}}}Dn}{c{{Bn{DhCj}}}{{Eb{E`}}}}{c{{Bn{ClCj}}}{{Eb{E`}}}}{{{d{Dd}}{Bl{{d{{Ef{Ed}}}}}}}{{Bn{A`Cj}}}}{{{d{Df}}{Bl{{d{{Ef{Ed}}}}}}}{{Bn{A`Cj}}}}{{EhEh}Eh}0{{{d{nEh}}Eh}A`}{d{{d{c}}}{}}0000000{{{d{n}}}{{d{nc}}}{}}0000000{{{d{Df}}}{{Bn{AlCj}}}}{{{d{Eh}}}Eh}{{d{d{nc}}}A`{}}{dA`}{{{d{Eh}}{d{Eh}}}Ej}{{DdCf}{{Bn{CdCj}}}}{c{{Bn{CdCj}}}Dn}{{{d{Df}}c}{{Bn{A`Cj}}}Dn}{{{d{Dh}}c}{{Bn{A`Cj}}}{{Eb{E`}}}}{c{{Bn{CnCj}}}{{Eb{E`}}}}{{{d{Dd}}}{{Bn{{Bl{{El{Ed}}}}Cj}}}}{{{d{Df}}}{{Bn{{Bl{{El{Ed}}}}Cj}}}}{{{d{Eh}}{d{Eh}}}Al}{{{d{Eh}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Cb}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Dd}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Cd}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Df}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Dh}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Cl}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Cn}}{d{nAb}}}{{Bn{A`En}}}}{cc{}}0000000{BbDd}{F`{{Bn{CbCj}}}}{Fb{{Bn{CdCj}}}}{Fd{{Bn{DfCj}}}}{Ff{{Bn{DhCj}}}}{Fh{{Bn{ClCj}}}}{Fj{{Bn{CnCj}}}}{FbDd}{{}c{}}0000000{DdBb}{Cd{{Ch{FlFn}}}}{Cn{{Ch{G`Gb}}}}{Cb{{Bn{F`Cj}}}}{Cd{{Bn{FbCj}}}}{Df{{Bn{FdCj}}}}{Dh{{Bn{FfCj}}}}{Cl{{Bn{FhCj}}}}{Cn{{Bn{FjCj}}}}{EhAl}000000{{{d{Cd}}}Al}{{{d{Cn}}}Al}{{{d{Df}}GdGd}{{Bn{A`Cj}}}}{{{d{Df}}{d{Gf}}Gh}{{Bn{A`Cj}}}}{{{d{Dd}}}{{Bn{AlCj}}}}21{{{d{Dd}}}{{Bn{{Bl{Gj}}Cj}}}}{{{d{Cd}}}{{Bn{{Bl{Gj}}Cj}}}}{{DdGh}{{Bn{CbCj}}}}{{{d{Cb}}}{{Bn{CfCj}}}}{{{d{Dd}}}{{Bn{CfCj}}}}{{{d{Cd}}}{{Bn{CfCj}}}}{{{d{Df}}}{{Bn{CfCj}}}}{{{d{Dh}}}{{Bn{D`Cj}}}}{{{d{Cl}}}{{Bn{D`Cj}}}}{{{d{Cn}}}{{Bn{D`Cj}}}}{{{d{Df}}}{{Bn{AlCj}}}}0{{{d{Df}}}{{Bn{GhCj}}}}{{}{{Bn{DdCj}}}}0={{{d{Cd}}}{{Bn{AlCj}}}}{{}{{Bn{{Ch{DhDh}}Cj}}}}{{}{{Bn{{Ch{CnCn}}Cj}}}}{{{d{Eh}}{d{Eh}}}{{Bl{Ej}}}}{{{d{Cd}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Df}}{d{n{Ef{Ed}}}}}{{Bn{{Ch{AjCf}}Cj}}}}<=<;9{{{d{Cn}}}{{Bn{GlCj}}}}{{{d{Cb}}{d{nGn}}}{{H`{{Bn{{Ch{CdCf}}Cj}}}}}}{{{d{Cl}}{d{nGn}}}{{H`{{Bn{{Ch{CnD`}}Cj}}}}}}{{{Hb{{d{nCd}}}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{Hb{{d{nCn}}}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Cd}}{d{nGn}}{d{nHd}}}{{H`{{Bn{AjCj}}}}}}{{{d{Df}}{d{nGn}}{d{nHd}}}{{H`{{Bn{CfCj}}}}}}{{{d{Df}}{d{nGn}}}{{H`{{Bn{CfCj}}}}}}{{{Hb{{d{nCd}}}}{d{nGn}}{d{nHd}}}{{H`{{Bn{A`Cj}}}}}}{{{Hb{{d{nCn}}}}{d{nGn}}{d{nHd}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Cd}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Cn}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Df}}{d{nGn}}{d{nHd}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Dh}}{d{nGn}}{d{nHd}}}{{H`{{Bn{A`Cj}}}}}}7{{{d{Dh}}{d{nGn}}{d{nHd}}}{{H`{{Bn{D`Cj}}}}}}{{{d{Df}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Dh}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{d{Df}}{d{nGn}}{d{{Ef{Ed}}}}}{{H`{{Bn{AjCj}}}}}}{{{d{Dh}}{d{nGn}}{d{{Ef{Ed}}}}}{{H`{{Bn{AjCj}}}}}}32{{{d{Df}}{d{nGn}}{d{{Ef{Ed}}}}Cf}{{H`{{Bn{AjCj}}}}}}{{{d{Dh}}{d{nGn}}{d{{Ef{Ed}}}}c}{{H`{{Bn{AjCj}}}}}{{Eb{E`}}}}{{{Hb{{d{nCd}}}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{Hb{{d{nCn}}}}{d{nGn}}}{{H`{{Bn{A`Cj}}}}}}{{{Hb{{d{nCd}}}}{d{nGn}}{d{{Ef{Ed}}}}}{{H`{{Bn{AjCj}}}}}}{{{Hb{{d{nCn}}}}{d{nGn}}{d{{Ef{Ed}}}}}{{H`{{Bn{AjCj}}}}}}>={{{Hb{{d{nCd}}}}{d{nGn}}{d{{Ef{Hf}}}}}{{H`{{Bn{AjCj}}}}}}{{{Hb{{d{nCn}}}}{d{nGn}}{d{{Ef{Hf}}}}}{{H`{{Bn{AjCj}}}}}}{{{d{Cd}}}{{Bn{A`Cj}}}}{{{d{Df}}}{{Bn{A`Cj}}}}{{{d{Dh}}}{{Bn{A`Cj}}}}{{{d{Cn}}}{{Bn{A`Cj}}}}{{{d{Cd}}Dj}{{Bn{EhCj}}}}{{{d{Df}}Dj}{{Bn{EhCj}}}}{{{d{Dh}}Dj}{{Bn{EhCj}}}}{{{d{Cn}}Dj}{{Bn{EhCj}}}}{{{d{Df}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Dh}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Dd}}}{{Bn{GhCj}}}}{{{d{Df}}{d{n{Ef{Ed}}}}}{{Bn{{Ch{AjCf}}Cj}}}}{{{d{Dh}}{d{n{Ef{Ed}}}}}{{Bn{{Ch{AjD`}}Cj}}}}{{{d{Dd}}}{{Bn{AlCj}}}}0{{{d{Df}}{d{{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Dh}}{d{{Ef{Ed}}}}}{{Bn{AjCj}}}}5{{{d{Df}}{d{{Ef{Ed}}}}c}{{Bn{AjCj}}}Dn}{{{d{Dh}}{d{{Ef{Ed}}}}c}{{Bn{AjCj}}}{{Eb{E`}}}}{{{d{Df}}Al}{{Bn{A`Cj}}}}{{{d{Dd}}Al}{{Bn{A`Cj}}}}{{{d{Dd}}{Bl{Gj}}}{{Bn{A`Cj}}}}{{{d{Cd}}{Bl{Gj}}}{{Bn{A`Cj}}}}33{{{d{Df}}Gh}{{Bn{A`Cj}}}}3{{{d{Cd}}Al}{{Bn{A`Cj}}}}{{{d{Dd}}Gh}{{Bn{A`Cj}}}}55002{{{d{Cb}}Gh}{{Bn{A`Cj}}}}{{{d{Cd}}Gh}{{Bn{A`Cj}}}}4{{{d{Dh}}Hh}{{Bn{A`Cj}}}}{{{d{nCd}}}{{Ch{HjHl}}}}{{{d{nCn}}}{{Ch{HnI`}}}}{{EhEh}Eh}{{{d{Dd}}}{{Bn{{Bl{Cj}}Cj}}}}{{{d{Cd}}}{{Bn{{Bl{Cj}}Cj}}}}{{{d{Df}}}{{Bn{{Bl{Cj}}Cj}}}}{{{d{Dh}}}{{Bn{{Bl{Cj}}Cj}}}}{{{d{Cl}}}{{Bn{{Bl{Cj}}Cj}}}}{{{d{Cn}}}{{Bn{{Bl{Cj}}Cj}}}}{dc{}}{{{d{Dd}}}{{Bn{GhCj}}}}{{{d{Df}}}{{Bn{GhCj}}}}{c{{Bn{e}}}{}{}}0{F`{{Bn{Cb}}}}11{Fb{{Bn{Cd}}}}2{Fd{{Bn{Df}}}}{Ff{{Bn{Dh}}}}4{Fh{{Bn{ClCj}}}}5{Fj{{Bn{CnCj}}}}6{{}{{Bn{c}}}{}}0000000{{{d{Cd}}Dje}{{Bn{cCj}}}{}{{Bj{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Df}}Dje}{{Bn{cCj}}}{}{{Bj{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Dh}}Dje}{{Bn{cCj}}}{}{{Bj{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Cn}}Dje}{{Bn{cCj}}}{}{{Bj{}{{Bf{{Bn{cCj}}}}}}}}{{{d{Df}}{d{n{Ef{Ed}}}}}{{Bn{{Ch{AjCf}}Cj}}}}{{{d{Df}}}{{Bn{CfCj}}}}{{{d{Cd}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Cn}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Cd}}{d{n{Ef{Ib}}}}}{{Bn{AjCj}}}}{{{d{Cn}}{d{n{Ef{Ib}}}}}{{Bn{AjCj}}}}{{{d{Df}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Dh}}{d{n{Ef{Ed}}}}}{{Bn{AjCj}}}}7{{{d{Dh}}{d{n{Ef{Ed}}}}}{{Bn{{Ch{AjD`}}Cj}}}}{{{d{Df}}{d{{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Dh}}{d{{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Df}}{d{{Ef{Ed}}}}Cf}{{Bn{AjCj}}}}{{{d{Dh}}{d{{Ef{Ed}}}}c}{{Bn{AjCj}}}{{Eb{E`}}}}{{{d{Cd}}{d{{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Cn}}{d{{Ef{Ed}}}}}{{Bn{AjCj}}}}{{{d{Cd}}{d{{Ef{Hf}}}}}{{Bn{AjCj}}}}{{{d{Cn}}{d{{Ef{Hf}}}}}{{Bn{AjCj}}}}{{{d{Cb}}}{{Bn{GhCj}}}}{{{d{Cd}}}{{Bn{GhCj}}}}{{{d{Df}}}{{Bn{GhCj}}}}{dC`}0000000{{}{{Bn{DhCj}}}}{{{d{Cd}}}{{Bn{A`Cj}}}}{{{d{Df}}}{{Bn{A`Cj}}}}{{{d{Dh}}}{{Bn{A`Cj}}}}{{{d{Cn}}}{{Bn{A`Cj}}}}{{}{{Bn{A`Cj}}}}```{{}Id}{{{d{Id}}}Bb}{d{{d{c}}}{}}0{{{d{n}}}{{d{nc}}}{}}03{{{d{Id}}}Id}{{d{d{nc}}}A`{}}{dA`}{{{d{Id}}{d{Id}}}Al}{{{d{Id}}{d{nAb}}}{{Bn{A`En}}}}{{{d{If}}{d{nAb}}}{{Bn{A`En}}}}{BbId}{cc{}}01;{{{d{Id}}{d{nc}}}A`Ih}<{{}c{}}0=={{{d{nIf}}{d{nGn}}}{{H`{{Bl{A`}}}}}}>{{{d{nIf}}}{{Bl{A`}}}}{Id{{Bn{IfCj}}}}{{}Id}{dc{}}{c{{Bn{e}}}{}{}}0{{}{{Bn{c}}}{}}0{dC`}0444``{{{d{{Bd{c}}}}}A`{}}{{{d{{Bd{c}}}}}Ij{}}{d{{d{c}}}{}}0{{{d{n}}}{{d{nc}}}{}}0{{{d{n{Bd{c}}}}}A`{}}{{{d{Il}}{d{nAb}}}{{Bn{A`En}}}}0{{{d{{Bd{c}}}}{d{nAb}}}{{Bn{A`En}}}In}{cc{}}0{{}c{}}0{{}}{Il{{Jb{J`}}}}{{{d{Il}}}Al}{{{d{{Bd{c}}}}}Al{}}1{{{Hb{{d{n{Bd{c}}}}}}{d{nGn}}}H`{}}{e{{Bd{c}}}Bh{{Bj{}{{Bf{c}}}}Bh}}{dJd}{c{{Bn{e}}}{}{}}0{{}{{Bn{c}}}{}}0{Il{{Bn{{Jb{J`}}Il}}}}{{{Hb{{d{nc}}}}{d{nGn}}}H`{}}{dC`}0{{}A`}````{{JfGj}Jf}{{{d{nJf}}Gj}A`}{d{{d{c}}}{}}000{{{d{n}}}{{d{nc}}}{}}000{{{d{Jf}}Gj}{{Bl{Jf}}}}{{{d{Jf}}Jf}{{Bl{Gj}}}}1{{{d{Jf}}}Jf}{{d{d{nc}}}A`{}}{dA`}{{{d{Jf}}{d{Jf}}}Ej}{{{d{Jh}}}Jf}{{{d{Jf}}Jf}Gj}{{{d{Jf}}}Gj}{{{d{Jf}}{d{Jf}}}Al}{{{d{Jf}}{d{nAb}}}{{Bn{A`En}}}}{{{d{Jj}}{d{nAb}}}{{Bn{A`En}}}}{{{d{{Jl{c}}}}{d{nAb}}}{{Bn{A`En}}}In}{{{d{Jh}}{d{nAb}}}{{Bn{A`En}}}}{cc{}}{JnJf}1110{{{d{n{Jl{c}}}}}{{d{nc}}}{}}{{{d{{Jl{c}}}}}{{d{c}}}{}}{{{d{Jf}}{d{nc}}}A`Ih}{GjJj}{{JfGj}Jj}{{}c{}}000{{}}0{{{Jl{c}}}c{}}{JfJn}{{{d{Jh}}}Al}{{{d{Jj}}}K`}{{}Jf}{{{d{Jf}}{d{Jf}}}{{Bl{Ej}}}}{{{d{Jj}}}Gj}{{{Hb{{d{n{Jl{c}}}}}}{d{nGn}}}H`j}{{{Hb{{d{nJh}}}}{d{nGn}}}H`}{{{d{nJj}}{d{nGn}}}{{H`{Jf}}}}{{{d{nJj}}}A`}{{{Hb{{d{nJh}}}}Jf}A`}{{{d{nJj}}Gj}A`}{{{d{nJj}}Jf}A`}3{{{d{Jf}}Jf}Gj}{{{d{nJj}}K`}A`}{GjJh}{JfJh}{{JfGj}Jf}{{JfJf}Gj}{{{d{nJf}}Gj}A`}{{{d{nJj}}}Jf}{{Gjc}JlKb}{dc{}}{c{{Bn{e}}}{}{}}000{{}{{Bn{c}}}{}}000{{{Hb{{d{nc}}}}{d{nGn}}}H`{}}{dC`}000","D":"BK`","p":[[5,"System",0,548],[1,"reference"],[5,"ArbiterHandle",0,549],[5,"Runtime",0,550],[10,"Future",551],[5,"SystemRunner",0,548],[0,"mut"],[1,"unit"],[5,"Formatter",552],[8,"Result",552],[5,"Arbiter",0,549],[5,"Runtime",553],[1,"usize"],[1,"bool"],[8,"Result",554],[8,"Result",555],[1,"i32"],[5,"JoinHandle",431,556],[17,"Output"],[10,"Send",557],[10,"FnOnce",558],[6,"Option",559],[6,"Result",560],[5,"TypeId",561],[5,"TcpListener",88,562],[5,"TcpStream",88,563],[6,"SocketAddr",564],[1,"tuple"],[5,"Error",555],[5,"UnixListener",88,565],[5,"UnixStream",88,566],[5,"SocketAddr",567],[5,"BorrowedFd",568],[5,"TcpSocket",88,569],[5,"UdpSocket",88,570],[5,"UnixDatagram",88,571],[5,"Interest",572],[10,"FnMut",558],[10,"ToSocketAddrs",573],[5,"Path",574],[10,"AsRef",575],[1,"u8"],[1,"slice"],[5,"Ready",88,576],[6,"Ordering",577],[5,"Vec",578],[5,"Error",552],[5,"TcpListener",579],[5,"TcpStream",579],[5,"UdpSocket",580],[5,"UnixDatagram",581],[5,"UnixListener",582],[5,"UnixStream",583],[5,"OwnedReadHalf",584],[5,"OwnedWriteHalf",584],[5,"OwnedReadHalf",585],[5,"OwnedWriteHalf",585],[5,"Ipv4Addr",586],[5,"Ipv6Addr",586],[1,"u32"],[5,"Duration",587],[5,"UCred",588],[5,"Context",589],[6,"Poll",590],[5,"Pin",591],[5,"ReadBuf",592],[5,"IoSlice",593],[6,"Shutdown",594],[5,"ReadHalf",595],[5,"WriteHalf",595],[5,"ReadHalf",596],[5,"WriteHalf",596],[5,"IoSliceMut",593],[5,"SignalKind",390,597],[5,"Signal",390,597],[10,"Hasher",598],[5,"AbortHandle",599],[5,"JoinError",431,600],[10,"Debug",552],[10,"Any",561],[5,"Box",601],[5,"String",602],[5,"Instant",464,603],[5,"Sleep",464,604],[5,"Interval",464,605],[5,"Timeout",464,606],[5,"Instant",607],[6,"MissedTickBehavior",605],[10,"IntoFuture",608]],"r":[[0,549],[1,549],[2,550],[3,548],[4,548],[46,609],[51,610],[66,609],[94,576],[95,562],[96,569],[97,563],[98,570],[99,571],[100,565],[101,566],[388,611],[390,597],[391,597],[419,597],[431,600],[432,556],[453,612],[463,613],[464,603],[465,605],[466,604],[467,606],[502,605],[503,605],[527,604],[528,604],[533,606]],"b":[[440,"impl-Display-for-JoinError"],[441,"impl-Debug-for-JoinError"],[529,"impl-Sub%3CDuration%3E-for-Instant"],[530,"impl-Sub-for-Instant"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAMwALAAJAA8AGwAEACMAAABFAAEASgAOAGsADQCEABIAmAADAKMACADEAAAA1AABAO4AAAD5AAEA/gABAA4BAwAUAQEAPwEAAEYBAABJAQEATAEBAE8BAABSAQAAVAEAAFYBCAB4AQcAiwEDAJABBgCbAQAApgEGALQBBwDAAQAAxQEAAMcBBADNAQIA1QEJAOIBAwDpAQQA7wEAAPYBAAD9AQEABAIAAAYCAQASAgIAFwINAA=="}],["actix_server",{"t":"PGPFFFEPFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["Disabled","MpTcp","NoFallback","Server","ServerBuilder","ServerHandle","ServerServiceFactory","TcpFallback","TestServer","backlog","bind","bind_uds","borrow","","","","","borrow_mut","","","","","build","clone","","clone_into","","clone_to_uninit","","default","disable_signals","fmt","","from","","","","","handle","into","","","","","into_future","listen","listen_uds","max_concurrent_connections","mptcp","new","pause","poll","resume","run","shutdown_timeout","start","start_with_builder","stop","system_exit","to_owned","","try_from","","","","","try_into","","","","","try_poll","type_id","","","","","unused_addr","worker_max_blocking_threads","workers"],"q":[[0,"actix_server"],[80,"actix_server::builder"],[81,"std::io::error"],[82,"core::convert"],[83,"std::net::socket_addr"],[84,"tokio::net::tcp::stream"],[85,"std::path"],[86,"tokio::net::unix::stream"],[87,"actix_server::handle"],[88,"core::fmt"],[89,"actix_server::server"],[90,"std::net::tcp"],[91,"std::os::unix::net::listener"],[92,"core::future::future"],[93,"core::pin"],[94,"core::task::wake"],[95,"core::task::poll"],[96,"core::result"],[97,"core::any"],[98,"core::net::socket_addr"],[99,"actix_server::service"],[100,"actix_server::test_server"]],"i":"Ah`0````0`b000BbCn3Aj321402404040334032140232140233333020331103403214032140232140133","f":"`````````{{bd}b}{{bceg}{{f{b}}}{{j{h}}}l{{`{n}}}}{{bceg}{{f{b}}}{{j{h}}}{{j{A`}}}{{`{Ab}}}}{Ad{{Ad{c}}}{}}0000{{{Ad{Af}}}{{Ad{Afc}}}{}}0000{{}b}{{{Ad{Ah}}}Ah}{{{Ad{Aj}}}Aj}{{Ad{Ad{Afc}}}Al{}}0{AdAl}04{bb}{{{Ad{Ah}}{Ad{AfAn}}}B`}{{{Ad{Aj}}{Ad{AfAn}}}B`}{cc{}}0000{{{Ad{Bb}}}Aj}{{}c{}}0000{{}}{{bcBde}{{f{b}}}{{j{h}}}{{`{n}}}}{{bcBfe}{{f{b}}}{{j{h}}}{{`{Ab}}}}{{bBh}b}{{bAh}b}?{{{Ad{Aj}}}{{`{{Bl{}{{Bj{Al}}}}}}}}{{{Bn{{Ad{AfBb}}}}{Ad{AfC`}}}{{Cb{c}}}{}}1{bBb}{{bCd}b}``{{{Ad{Aj}}Cf}{{`{{Bl{}{{Bj{Al}}}}}}}}?{Adc{}}0{c{{Ch{e}}}{}{}}0000{{}{{Ch{c}}}{}}0000{{{Bn{{Ad{Afc}}}}{Ad{AfC`}}}Cb{}}{AdCj}0000{{}Cl}<<","D":"Eb","p":[[5,"ServerBuilder",0,80],[1,"u32"],[8,"Result",81],[1,"str"],[10,"AsRef",82],[10,"ToSocketAddrs",83],[5,"TcpStream",84],[5,"Path",85],[5,"UnixStream",86],[1,"reference"],[0,"mut"],[6,"MpTcp",0,80],[5,"ServerHandle",0,87],[1,"unit"],[5,"Formatter",88],[8,"Result",88],[5,"Server",0,89],[5,"TcpListener",90],[5,"UnixListener",91],[1,"usize"],[17,"Output"],[10,"Future",92],[5,"Pin",93],[5,"Context",94],[6,"Poll",95],[1,"u64"],[1,"bool"],[6,"Result",96],[5,"TypeId",97],[6,"SocketAddr",98],[5,"TestServer",0]],"r":[[1,80],[3,89],[4,80],[5,87],[6,99],[8,100]],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAACcABwAHAAAADQAJABgABgAgAAEALQAAADQAAAA8ABEA"}],["actix_service",{"t":"FRRRRRRRRRKKRRRKRKKKKRKQNNNNHHHHHNNCMNNNHHHQNNMNHMNNNNHNNNNNNNNMNMMNNNNHIIFINNHNNNNHHNNN","n":["ApplyTransform","Config","Error","","","Future","","","InitError","","IntoService","IntoServiceFactory","Response","","","Service","","ServiceExt","ServiceFactory","ServiceFactoryExt","Transform","","TransformExt","always_ready","and_then","","","","apply","apply_cfg","apply_cfg_factory","apply_fn","apply_fn_factory","borrow","borrow_mut","boxed","call","clone","clone_into","clone_to_uninit","fn_factory","fn_factory_with_config","fn_service","forward_ready","from","into","into_factory","","into_service","","map","","","","map_config","map_err","","","","map_init_err","","","","new_service","","new_transform","poll_ready","to_owned","try_from","try_into","type_id","unit_config","BoxFuture","BoxService","BoxServiceFactory","RcService","borrow","borrow_mut","factory","from","into","into_factory","new_service","rc_service","service","try_from","try_into","type_id"],"q":[[0,"actix_service"],[72,"actix_service::boxed"],[88,"actix_service::ext"],[89,"actix_service::transform"],[90,"core::clone"],[91,"core::result"],[92,"core::future::future"],[93,"core::ops::function"],[94,"core::task::wake"],[95,"core::task::poll"],[96,"core::any"],[97,"actix_service::apply_cfg"],[98,"actix_service::apply"],[99,"actix_service::fn_service"],[100,"actix_service::map_config"]],"i":"`A`Aff210212``102`2````1``b0j0`````Ad0`3000````00Ab1`h4433`443333C`083763333`````Cj0`0000``000","f":"````````````````````````{{bi}{{`{bgk}}}{}{}{{f{c}{{d{e}}}}}{{h{gc}}}{}}0{{jm}{{`{jko}}}{}{}{}{}{{A`{c}{{l{e}}{d{g}}{n{i}}}}}{{Ab{kc}}}{}}0{{ei}{{Ad{egc}}}{}{{Af{c}{{n{}}}}}{{A`{c}}}{{Ab{gc}}}}{{eo}{{`{{A`{c}{{l{g}}{Ah{}}{d{}}{Aj{i}}{n{k}}{Al{m}}}}An}}}{}{{f{c}}}{}{{f{c}}}{}{{Bd{}{{B`{{Bb{ik}}}}}}}{{Bh{g{Bf{e}}}{{B`{m}}}}}}{{em}{{`{{A`{c}{{l{g}}{Ah{}}{d{}}{Aj{i}}{n{}}}}An}}}{}{{A`{c}{{l{Bj}}}}}{}{{f{c}}}{{Bd{}{{B`{{Bb{i}}}}}}}{{Bh{gBf}{{B`{k}}}}}}{{iAa}{{`{gAakcme}}}{}{}{{f{c}{{d{e}}}}}{{h{gc}}}{}{}{{Bd{}{{B`{{Bb{me}}}}}}}{{Bh{k{Bf{g}}}{{B`{o}}}}}}{{iAa}{{`{gAakcme}}}{}{}{{A`{c}{{d{e}}}}}{{Ab{gc}}}{}{}{{Bd{}{{B`{{Bb{me}}}}}}}{{Bh{kBf}{{B`{o}}}}An}}{Bf{{Bf{c}}}{}}{{{Bf{Bl}}}{{Bf{Blc}}}{}}`{{{Bf{{f{}{{Ah{c}}{d{e}}{Al{g}}}}}}i}g{}{}{{Bd{}{{B`{{Bb{ce}}}}}}}{}}{{{Bf{{Ad{ceg}}}}}{{Ad{ceg}}}{}{}{}}{{Bf{Bf{Blc}}}Bj{}}{BfBj}{k{{`{kmecig}}}{}{{f{c}}}{}{{Bd{}{{B`{{Bb{eg}}}}}}}{{Bh{}{{B`{i}}}}}{}}{m{{`{mkcgei}}}{}{}{{f{e}}}{}{{Bd{}{{B`{{Bb{gi}}}}}}}{{Bh{c}{{B`{k}}}}}}{k{{`{kicegm}}}{}{}{}{{Bd{}{{B`{{Bb{eg}}}}}}}{{Bh{c}{{B`{i}}}}An}{}}`{cc{}}{{}c{}}{Abe{}{{A`{c}}}}1{ge{}{{f{c}}}{{h{ec}}}}{he{}{{f{c}}}}{{bg}{{`{bgie}}}{}{}{{Bn{c}{{B`{e}}}}}{}}0{{jg}{{`{jgie}}}{}{}{{Bn{c}{{B`{e}}}}An}{}}0{{gk}{{`{ecki}}}{}{{A`{c}}}{{Ab{ec}}}{}{{Bh{i}{{B`{}}}}}}{{bg}{{`{bige}}}{}{}{{Bh{c}{{B`{e}}}}}{}}0{{jg}{{`{jige}}}{}{}{{Bh{c}{{B`{e}}}}An}{}}0{{jg}{{`{jgie}}}{}{}{{Bh{c}{{B`{e}}}}An}{}}0{{C`g}{{`{C`ikge}}}{}{}{{Bh{c}{{B`{e}}}}An}{}{}}0{{{Bf{{A`{}{{Ah{c}}{d{e}}{l{g}}{Aj{i}}{n{m}}{Al{o}}}}}}g}o{}{}{}{{f{k}{{Ah{c}}{d{e}}}}}{}{}{{Bd{}{{B`{{Bb{im}}}}}}}}{{{Bf{{Ad{egc}}}}}i{}{{Af{c}{{n{}}}}}{{A`{c}}}{}}{{{Bf{{Af{}{{Ah{c}}{d{e}}{Cb{g}}{n{k}}{Al{m}}}}}}o}m{}{}{{f{i}{{Ah{c}}{d{e}}}}}{}{}{{Bd{}{{B`{{Bb{gk}}}}}}}{}}{{{Bf{{f{}{{Ah{c}}{d{e}}{Al{g}}}}}}{Bf{BlCd}}}{{Cf{{Bb{Bje}}}}}{}{}{{Bd{}{{B`{{Bb{ce}}}}}}}}{Bfc{}}{c{{Bb{e}}}{}{}}{{}{{Bb{c}}}{}}{BfCh}{g{{`{eic}}}{}{{A`{c}{{l{Bj}}}}}{{Ab{ec}}}{}}````{Bf{{Bf{c}}}{}}{{{Bf{Bl}}}{{Bf{Blc}}}{}}{e{{Cj{c}}}{}{{A`{c}}}}{cc{}}{{}c{}}0{{{Bf{{Cj{cegik}}}}c}m{}{}{}{}{}{}}{e{{Cl{c}}}{}{{f{c}}}}{e{{Cn{c}}}{}{{f{c}}}};:9","D":"Hn","p":[[10,"ServiceExt",0,88],[17,"Error"],[10,"Service",0],[10,"IntoService",0],[10,"ServiceFactoryExt",0,88],[17,"Config"],[17,"InitError"],[10,"ServiceFactory",0],[10,"IntoServiceFactory",0],[5,"ApplyTransform",0,89],[10,"Transform",0,89],[17,"Response"],[17,"Service"],[17,"Future"],[10,"Clone",90],[17,"Output"],[6,"Result",91],[10,"Future",92],[1,"reference"],[10,"Fn",93],[1,"unit"],[0,"mut"],[10,"FnMut",93],[10,"TransformExt",0,88],[17,"Transform"],[5,"Context",94],[6,"Poll",95],[5,"TypeId",96],[5,"BoxServiceFactory",72],[8,"RcService",72],[8,"BoxService",72]],"r":[[0,89],[17,88],[19,88],[20,89],[22,88],[28,89],[29,97],[30,97],[31,98],[32,98],[40,99],[41,99],[42,99],[54,100],[71,100]],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAABEACAAiAAEAJgACADAAAABBAAAARAADAE0AAQBSAAEAVgACAA=="}],["actix_tls",{"t":"CCPPPGNNNNNNNHCCCCCCNNNNNFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNFFNNNNNNNNNNNNNNNNNNNNNNNNNNFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNTFFPGTPFFFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNFONNNONNNNNONOOOOOONNNNFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNFONNNONNNNNONOOOOOOONNNNFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNFONNNNNONNNONNONOOOOOOONNNNFFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNFONNNNNNOOOONNNNONNNONOOOOOOOONNNNGFFFFKPPPKFPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNMCNNNNNCNNNNNNNNCCCCNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNFNNNNNNNNNNNNNCNNNNFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNFFPGPFFFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFNNNNNNNNNNNNNNNNNHNNNCNNNNNNNNNHFFJONNNNNNONNNOOONNNNNNNNNOONNNNONNNNNNNFFNNNNNNNNNNNNNNNNNHNNNCNNNNNNNNNHFFSONNNNNNONNNOONNNNNNNNNOONNNNONNNNNNNFFNNNNNNNNNNNNNNNNNHNNNCNNNNNNNNNHFFSONNNNNNNNONNNNOOONNNNNNNNNOONNNNONNNNNNNFFNNNNNNNNNNNNNNNNNHNNNCNNNNNNNNNHFFSONNNNNNNNNOOOONNNNNOOONNNNNNNNNNNOONNNNNOONNNNNNNFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["accept","connect","Service","Timeout","Tls","TlsError","borrow","borrow_mut","fmt","","from","into","into_service_error","max_concurrent_tls_connect","native_tls","openssl","rustls_0_20","rustls_0_21","rustls_0_22","rustls_0_23","source","to_string","try_from","try_into","type_id","Acceptor","AcceptorService","TlsStream","borrow","","","borrow_mut","","","call","clone","clone_into","clone_to_uninit","deref","deref_mut","from","","","","into","","","into_factory","into_service","is_write_vectored","new","new_service","poll_flush","poll_read","poll_ready","poll_shutdown","poll_write","poll_write_vectored","reexports","set_handshake_timeout","to_owned","try_from","","","try_into","","","type_id","","","Error","TlsAcceptor","accept","borrow","","borrow_mut","","clone","clone_into","clone_to_uninit","fmt","","","from","","","","into","","source","to_owned","to_string","try_from","","try_into","","type_id","","Acceptor","AcceptorService","TlsStream","borrow","","","borrow_mut","","","call","clone","clone_into","clone_to_uninit","deref","deref_mut","from","","","","into","","","into_factory","into_service","is_write_vectored","new","new_service","poll_flush","poll_read","poll_ready","poll_shutdown","poll_write","poll_write_vectored","reexports","set_handshake_timeout","to_owned","try_from","","","try_into","","","type_id","","","ALERT_FATAL","AlpnError","Error","Failure","HandshakeError","NOACK","SetupFailure","Ssl","SslAcceptor","SslAcceptorBuilder","WouldBlock","accept","","as_ptr","as_ref","borrow","","","","","borrow_mut","","","","build","clone","","clone_into","","clone_to_uninit","","connect","context","deref","","deref_mut","","drop","eq","fmt","","from","","","","from_ptr","into","","","","into_context","mozilla_intermediate","mozilla_intermediate_v5","mozilla_modern","mozilla_modern_v5","new","new_ex_index","to_owned","","try_from","","","","try_into","","","","type_id","","","","Acceptor","AcceptorService","TlsStream","borrow","","","borrow_mut","","","call","clone","clone_into","clone_to_uninit","deref","deref_mut","from","","","","into","","","into_factory","into_service","is_write_vectored","new","new_service","poll_flush","poll_read","poll_ready","poll_shutdown","poll_write","poll_write_vectored","reexports","set_handshake_timeout","to_owned","try_from","","","try_into","","","type_id","","","ServerConfig","alpn_protocols","borrow","borrow_mut","builder","cert_resolver","clone","clone_into","clone_to_uninit","fmt","from","ignore_client_order","into","key_log","max_early_data_size","max_fragment_size","send_half_rtt_data","session_storage","ticketer","to_owned","try_from","try_into","type_id","Acceptor","AcceptorService","TlsStream","borrow","","","borrow_mut","","","call","clone","clone_into","clone_to_uninit","deref","deref_mut","from","","","","into","","","into_factory","into_service","is_write_vectored","new","new_service","poll_flush","poll_read","poll_ready","poll_shutdown","poll_write","poll_write_vectored","reexports","set_handshake_timeout","to_owned","try_from","","","try_into","","","type_id","","","ServerConfig","alpn_protocols","borrow","borrow_mut","builder","cert_resolver","clone","clone_into","clone_to_uninit","fmt","from","ignore_client_order","into","key_log","max_early_data_size","max_fragment_size","send_half_rtt_data","send_tls13_tickets","session_storage","ticketer","to_owned","try_from","try_into","type_id","Acceptor","AcceptorService","TlsStream","borrow","","","borrow_mut","","","call","clone","clone_into","clone_to_uninit","deref","deref_mut","from","","","","into","","","into_factory","into_service","is_write_vectored","new","new_service","poll_flush","poll_read","poll_ready","poll_shutdown","poll_write","poll_write_vectored","reexports","set_handshake_timeout","to_owned","try_from","","","try_into","","","type_id","","","ServerConfig","alpn_protocols","borrow","borrow_mut","builder","builder_with_protocol_versions","builder_with_provider","cert_resolver","clone","clone_into","clone_to_uninit","enable_secret_extraction","fmt","from","ignore_client_order","into","key_log","max_early_data_size","max_fragment_size","send_half_rtt_data","send_tls13_tickets","session_storage","ticketer","to_owned","try_from","try_into","type_id","Acceptor","AcceptorService","TlsStream","borrow","","","borrow_mut","","","call","clone","clone_into","clone_to_uninit","deref","deref_mut","from","","","","into","","","into_factory","into_service","is_write_vectored","new","new_service","poll_flush","poll_read","poll_ready","poll_shutdown","poll_write","poll_write_vectored","reexports","set_handshake_timeout","to_owned","try_from","","","try_into","","","type_id","","","ServerConfig","alpn_protocols","borrow","borrow_mut","builder","builder_with_details","builder_with_protocol_versions","builder_with_provider","cert_compression_cache","cert_compressors","cert_decompressors","cert_resolver","clone","clone_into","clone_to_uninit","crypto_provider","enable_secret_extraction","fips","fmt","from","ignore_client_order","into","key_log","max_early_data_size","max_fragment_size","send_half_rtt_data","send_tls13_tickets","session_storage","ticketer","time_provider","to_owned","try_from","try_into","type_id","ConnectError","ConnectInfo","Connection","Connector","ConnectorService","Host","InvalidInput","Io","NoRecords","Resolve","Resolver","","ResolverService","Unresolved","addrs","borrow","","","","","","","borrow_mut","","","","","","","call","","clone","","","","clone_into","","","","clone_to_uninit","","","","custom","","default","","","","deref","deref_mut","eq","fmt","","","","","from","","","","","","","","hash","hostname","","","into","","","","","","","into_factory","","into_parts","into_service","","io_mut","io_ref","lookup","native_tls","new","","","new_service","","openssl","poll_ready","","port","","","replace_io","request","","rustls_0_20","rustls_0_21","rustls_0_22","rustls_0_23","service","","set_addr","set_addrs","set_local_addr","set_port","source","take_addrs","tcp","to_owned","","","","to_string","","try_from","","","","","","","try_into","","","","","","","type_id","","","","","","","with_addr","TlsConnector","borrow","borrow_mut","call","clone","clone_into","clone_to_uninit","from","into","into_factory","into_service","new","new_service","poll_ready","reexports","to_owned","try_from","try_into","type_id","AsyncTlsStream","TlsConnector","as_raw_fd","borrow","","borrow_mut","","builder","clone","clone_into","clone_to_uninit","connect","fmt","","from","","get_mut","get_ref","into","","new","poll_flush","poll_read","poll_shutdown","poll_write","to_owned","try_from","","try_into","","type_id","","TlsConnector","TlsConnectorService","borrow","","borrow_mut","","call","clone","","clone_into","","clone_to_uninit","","from","","into","","into_factory","into_service","new","new_service","poll_ready","reexports","service","to_owned","","try_from","","try_into","","type_id","","AsyncSslStream","Error","Failure","HandshakeError","SetupFailure","SslConnector","SslConnectorBuilder","SslMethod","WouldBlock","accept","as_ptr","borrow","","","","","","borrow_mut","","","","","","build","builder","clone","","clone_into","","clone_to_uninit","","code","configure","connect","","context","deref","deref_mut","do_handshake","dtls","fmt","","","","","","from","","","","","","","","from_ptr","get_mut","get_pin_mut","get_ref","into","","","","","","into_context","into_io_error","io_error","new","peek","poll_accept","poll_connect","poll_do_handshake","poll_flush","poll_peek","poll_read","poll_read_early_data","poll_shutdown","poll_write","poll_write_early_data","read_early_data","source","","ssl","ssl_error","tls","tls_client","tls_server","to_owned","","to_string","","try_from","","","","","","try_into","","","","","","type_id","","","","","","write_early_data","TlsConnector","TlsConnectorService","borrow","","borrow_mut","","call","clone","","clone_into","","clone_to_uninit","","from","","into","","into_factory","into_service","native_roots_cert_store","new","new_service","poll_ready","reexports","service","to_owned","","try_from","","try_into","","type_id","","webpki_roots_cert_store","AsyncTlsStream","ClientConfig","TLS_SERVER_ROOTS","alpn_protocols","as_raw_fd","borrow","","borrow_mut","","builder","client_auth_cert_resolver","clone","clone_into","clone_to_uninit","enable_early_data","enable_sni","enable_tickets","fmt","","from","","get_mut","get_ref","into","","into_inner","key_log","max_fragment_size","poll_flush","poll_read","poll_shutdown","poll_write","session_storage","to_owned","try_from","","try_into","","type_id","","TlsConnector","TlsConnectorService","borrow","","borrow_mut","","call","clone","","clone_into","","clone_to_uninit","","from","","into","","into_factory","into_service","native_roots_cert_store","new","new_service","poll_ready","reexports","service","to_owned","","try_from","","try_into","","type_id","","webpki_roots_cert_store","AsyncTlsStream","ClientConfig","TLS_SERVER_ROOTS","alpn_protocols","as_raw_fd","borrow","","borrow_mut","","builder","client_auth_cert_resolver","clone","clone_into","clone_to_uninit","enable_early_data","enable_sni","fmt","","from","","get_mut","get_ref","into","","into_inner","key_log","max_fragment_size","poll_flush","poll_read","poll_shutdown","poll_write","resumption","to_owned","try_from","","try_into","","type_id","","TlsConnector","TlsConnectorService","borrow","","borrow_mut","","call","clone","","clone_into","","clone_to_uninit","","from","","into","","into_factory","into_service","native_roots_cert_store","new","new_service","poll_ready","reexports","service","to_owned","","try_from","","try_into","","type_id","","webpki_roots_cert_store","AsyncTlsStream","ClientConfig","TLS_SERVER_ROOTS","alpn_protocols","as_raw_fd","borrow","","borrow_mut","","builder","builder_with_protocol_versions","builder_with_provider","client_auth_cert_resolver","clone","clone_into","clone_to_uninit","dangerous","enable_early_data","enable_secret_extraction","enable_sni","fmt","","from","","get_mut","get_ref","into","","into_inner","key_log","max_fragment_size","poll_flush","poll_read","poll_shutdown","poll_write","resumption","to_owned","try_from","","try_into","","type_id","","TlsConnector","TlsConnectorService","borrow","","borrow_mut","","call","clone","","clone_into","","clone_to_uninit","","from","","into","","into_factory","into_service","native_roots_cert_store","new","new_service","poll_ready","reexports","service","to_owned","","try_from","","try_into","","type_id","","webpki_roots_cert_store","AsyncTlsStream","ClientConfig","TLS_SERVER_ROOTS","alpn_protocols","as_raw_fd","borrow","","borrow_mut","","builder","builder_with_details","builder_with_protocol_versions","builder_with_provider","cert_compression_cache","cert_compressors","cert_decompressors","client_auth_cert_resolver","clone","clone_into","clone_to_uninit","crypto_provider","dangerous","enable_early_data","enable_secret_extraction","enable_sni","fips","fmt","","from","","get_mut","get_ref","into","","into_inner","is_write_vectored","key_log","max_fragment_size","poll_flush","poll_read","poll_shutdown","poll_write","poll_write_vectored","resumption","time_provider","to_owned","try_from","","try_into","","type_id","","TcpConnector","TcpConnectorService","borrow","","borrow_mut","","call","clone","","clone_into","","clone_to_uninit","","default","","fmt","","from","","into","","into_factory","into_service","new_service","poll_ready","service","to_owned","","try_from","","try_into","","type_id",""],"q":[[0,"actix_tls"],[2,"actix_tls::accept"],[25,"actix_tls::accept::native_tls"],[70,"actix_tls::accept::native_tls::reexports"],[98,"actix_tls::accept::openssl"],[143,"actix_tls::accept::openssl::reexports"],[214,"actix_tls::accept::rustls_0_20"],[259,"actix_tls::accept::rustls_0_20::reexports"],[282,"actix_tls::accept::rustls_0_21"],[327,"actix_tls::accept::rustls_0_21::reexports"],[351,"actix_tls::accept::rustls_0_22"],[396,"actix_tls::accept::rustls_0_22::reexports"],[423,"actix_tls::accept::rustls_0_23"],[468,"actix_tls::accept::rustls_0_23::reexports"],[502,"actix_tls::connect"],[642,"actix_tls::connect::native_tls"],[661,"actix_tls::connect::native_tls::reexports"],[693,"actix_tls::connect::openssl"],[725,"actix_tls::connect::openssl::reexports"],[835,"actix_tls::connect::rustls_0_20"],[869,"actix_tls::connect::rustls_0_20::reexports"],[909,"actix_tls::connect::rustls_0_21"],[943,"actix_tls::connect::rustls_0_21::reexports"],[982,"actix_tls::connect::rustls_0_22"],[1016,"actix_tls::connect::rustls_0_22::reexports"],[1059,"actix_tls::connect::rustls_0_23"],[1093,"actix_tls::connect::rustls_0_23::reexports"],[1145,"actix_tls::connect::tcp"],[1179,"core::fmt"],[1180,"core::convert"],[1181,"core::error"],[1182,"core::option"],[1183,"alloc::string"],[1184,"core::result"],[1185,"core::any"],[1186,"actix_rt::net"],[1187,"tokio_native_tls"],[1188,"core::pin"],[1189,"core::task::wake"],[1190,"std::io::error"],[1191,"core::task::poll"],[1192,"tokio::io::read_buf"],[1193,"std::io"],[1194,"core::time"],[1195,"native_tls"],[1196,"tokio::io::async_read"],[1197,"tokio::io::async_write"],[1198,"core::marker"],[1199,"native_tls::imp"],[1200,"openssl::ssl::connector"],[1201,"openssl::ssl"],[1202,"openssl::ssl::error"],[1203,"openssl_sys::openssl::handwritten::types"],[1204,"openssl::error"],[1205,"openssl::ex_data"],[1206,"tokio_rustls::server"],[1207,"rustls::server::server_conn"],[1208,"rustls::builder"],[1209,"rustls::versions"],[1210,"rustls::crypto"],[1211,"alloc::sync"],[1212,"rustls::time_provider"],[1213,"actix_tls::connect::info"],[1214,"core::net::socket_addr"],[1215,"core::iter::traits::iterator"],[1216,"core::iter::traits::exact_size"],[1217,"core::iter::traits::marker"],[1218,"core::clone"],[1219,"actix_tls::connect::host"],[1220,"actix_tls::connect::connector"],[1221,"actix_tls::connect::resolver"],[1222,"actix_tls::connect::resolve"],[1223,"actix_tls::connect::connection"],[1224,"core::cmp"],[1225,"actix_tls::connect::error"],[1226,"core::hash"],[1227,"alloc::vec"],[1228,"alloc::boxed"],[1229,"futures_core::future"],[1230,"core::iter::traits::collect"],[1231,"core::net::ip_addr"],[1232,"std::os::fd::raw"],[1233,"openssl_sys::openssl::handwritten::ssl"],[1234,"rustls::anchors"],[1235,"rustls::client::client_conn"],[1236,"rustls::webpki::anchors"],[1237,"rustls::client::client_conn::danger"],[1238,"rustls::client::client_conn::connection"],[1239,"webpki_roots"]],"i":"``f00`0000000```````00000```BdBbAn210011122221021010211220222`11210210210``BjCn101111001001101010010101```E`DnDl210011122221021010211220222`11210210210Ff``Eh`10```0EdEn00Fd2411024102424241201011441024110241222221124024102410241```GlGjGh210011122221021010211220222`11210210210`H`000000000000000000000```HjHhHf210011122221021010211220222`11210210210`Hn0000000000000000000000```IhIfId210011122221021010211220222`11210210210`Il0000000000000000000000000```JnJlJj210011122221021010211220222`11210210210`Kb00000000000000000000000000000000``````Mn00``0`0L`MjMdM`43MfMb43265102032103210321010321044546655432655105Ln5654376214253155Mh`65753`42117667````53777787`5432876548732654873265487327`Of000000000000`0000``Bf0Oh100000010101110011110101010``A@jA@h100101010101010110`110101010``Eh`0```0EbFn1AAbA@lA@n53421053211313130141122434100554210055334444210531004444444444444054033313054210534210534210534``AAjAAh100101010101010`110`110101010````AAnAB`01011111111101010001011000011010101``ABfABd100101010101010`110`110101010````ABjABl0101111111101010001011000011010101``ACbAC`100101010101010`110`110101010````ACfACh01011111111111101010001011000011010101``AD`ACn100101010101010`110`110101010````ADdADf01011111111111111111101010001001100000111010101``ADnADl100101010101010101010110101010","f":"``````{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{{b{{f{ce}}}}{b{dh}}}jll}{{{b{{f{ce}}}}{b{dh}}}j{}{}}{cc{}}{{}c{}}{{{f{cn}}}{{f{ce}}}{}{}}{A`Ab}``````{{{b{{f{ce}}}}}{{Af{{b{Ad}}}}}AdAd}{bAh}{c{{Aj{e}}}{}{}}{{}{{Aj{c}}}{}}{bAl}```<<<;;;{{{b{An}}c}eB`{}}{{{b{Bb}}}Bb}{{b{b{dc}}}Ab{}}{bAb}{{{b{{Bd{c}}}}}{{b{e}}}{}{}}{{{b{d{Bd{c}}}}}{{b{de}}}{}{}}{{{Bf{c}}}{{Bd{c}}}{}}???>>>>>{{{b{{Bd{c}}}}}BhB`}{BjBb}{{{b{Bb}}Ab}c{}}{{{Bl{{b{d{Bd{c}}}}}}{b{dBn}}}{{Cb{{C`{Ab}}}}}B`}{{{Bl{{b{d{Bd{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{C`{Ab}}}}}B`}{{{b{An}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}2{{{Bl{{b{d{Bd{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{C`{A`}}}}}B`}{{{Bl{{b{d{Bd{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{C`{A`}}}}}B`}`{{{b{dBb}}Cl}{{b{dBb}}}}{bc{}}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{bAl}00``{{{b{Bj}}c}{{Aj{{Bf{c}}Cn}}}{D`DbDd}}{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{Bj}}}Bj}{{b{b{dc}}}Ab{}}{bAb}{{{b{Cn}}{b{dh}}}{{Aj{AbDf}}}}0{{{b{Bj}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}{DhCn}{DjBj}2{{}c{}}0{{{b{Cn}}}{{Af{{b{Ad}}}}}}{bc{}}{bAh}{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0```{b{{b{c}}}{}}00{{{b{d}}}{{b{dc}}}{}}00{{{b{Dl}}c}eB`{}}{{{b{Dn}}}Dn}{{b{b{dc}}}Ab{}}{bAb}{{{b{{E`{c}}}}}{{b{e}}}{}{}}{{{b{d{E`{c}}}}}{{b{de}}}{}{}}{{{Eb{c}}}{{E`{c}}}{}}{cc{}}00{{}c{}}0000{{{b{{E`{c}}}}}BhB`}{EdDn}{{{b{Dn}}Ab}c{}}{{{Bl{{b{d{E`{c}}}}}}{b{dBn}}}{{Cb{{C`{Ab}}}}}B`}{{{Bl{{b{d{E`{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{C`{Ab}}}}}B`}{{{b{Dl}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}2{{{Bl{{b{d{E`{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{C`{A`}}}}}B`}{{{Bl{{b{d{E`{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{C`{A`}}}}}B`}`{{{b{dDn}}Cl}{{b{dDn}}}}{bc{}}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{bAl}00```````````{{{b{Ed}}c}{{Aj{{Ef{c}}{Eh{c}}}}}{EjEl}}{{Enc}{{Aj{{Ef{c}}{Eh{c}}}}}{EjEl}}{{{b{En}}}F`}{{{b{En}}}{{b{Fb}}}}{b{{b{c}}}{}}0010{{{b{d}}}{{b{dc}}}{}}000{FdEd}{{{b{Ed}}}Ed}{{{b{Ff}}}Ff}{{b{b{dc}}}Ab{}}0{bAb}09{{{b{Ed}}}{{b{Fh}}}}{{{b{Fd}}}{{b{Fj}}}}9{{{b{dFd}}}{{b{dFj}}}}{{{b{dEn}}}{{b{dFb}}}}{{{b{dEn}}}Ab}{{{b{Ff}}{b{Ff}}}Bh}{{{b{Ff}}{b{dh}}}{{Aj{AbDf}}}}{{{b{En}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}000{F`En}{{}c{}}000{EdFl}{Fn{{Aj{FdG`}}}}000{{{b{Fh}}}{{Aj{EnG`}}}}{{}{{Aj{{Gb{Enc}}G`}}}{GdGf}}{bc{}}0{c{{Aj{e}}}{}{}}000{{}{{Aj{c}}}{}}000{bAl}000```{b{{b{c}}}{}}00{{{b{d}}}{{b{dc}}}{}}00{{{b{Gh}}c}eB`{}}{{{b{Gj}}}Gj}{{b{b{dc}}}Ab{}}{bAb}{{{b{{Gl{c}}}}}{{b{e}}}{}{}}{{{b{d{Gl{c}}}}}{{b{de}}}{}{}}{{{Gn{c}}}{{Gl{c}}}{}}{cc{}}00{{}c{}}0000{{{b{{Gl{c}}}}}BhB`}{H`Gj}{{{b{Gj}}Ab}c{}}{{{Bl{{b{d{Gl{c}}}}}}{b{dBn}}}{{Cb{{C`{Ab}}}}}B`}{{{Bl{{b{d{Gl{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{C`{Ab}}}}}B`}{{{b{Gh}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}2{{{Bl{{b{d{Gl{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{C`{A`}}}}}B`}{{{Bl{{b{d{Gl{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{C`{A`}}}}}B`}`{{{b{dGj}}Cl}{{b{dGj}}}}{bc{}}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{bAl}00``{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{}{{Hd{H`Hb}}}}`{{{b{H`}}}H`}{{b{b{dc}}}Ab{}}{bAb}{{{b{H`}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}`{{}c{}}``````<;:9```888777{{{b{Hf}}c}eB`{}}{{{b{Hh}}}Hh}65{{{b{{Hj{c}}}}}{{b{e}}}{}{}}{{{b{d{Hj{c}}}}}{{b{de}}}{}{}}{{{Hl{c}}}{{Hj{c}}}{}}66655555{{{b{{Hj{c}}}}}BhB`}{HnHh}{{{b{Hh}}Ab}c{}}{{{Bl{{b{d{Hj{c}}}}}}{b{dBn}}}{{Cb{{C`{Ab}}}}}B`}{{{Bl{{b{d{Hj{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{C`{Ab}}}}}B`}{{{b{Hf}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}2{{{Bl{{b{d{Hj{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{C`{A`}}}}}B`}{{{Bl{{b{d{Hj{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{C`{A`}}}}}B`}`{{{b{dHh}}Cl}{{b{dHh}}}}{bc{}}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{bAl}00``{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{}{{Ib{HnI`}}}}`{{{b{Hn}}}Hn}{{b{b{dc}}}Ab{}}{bAb}{{{b{Hn}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}`{{}c{}}```````<;:9```888777{{{b{Id}}c}eB`{}}{{{b{If}}}If}65{{{b{{Ih{c}}}}}{{b{e}}}{}{}}{{{b{d{Ih{c}}}}}{{b{de}}}{}{}}{{{Ij{c}}}{{Ih{c}}}{}}66655555{{{b{{Ih{c}}}}}BhB`}{IlIf}{{{b{If}}Ab}c{}}{{{Bl{{b{d{Ih{c}}}}}}{b{dBn}}}{{Cb{{C`{Ab}}}}}B`}{{{Bl{{b{d{Ih{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{C`{Ab}}}}}B`}{{{b{Id}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}2{{{Bl{{b{d{Ih{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{C`{A`}}}}}B`}{{{Bl{{b{d{Ih{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{C`{A`}}}}}B`}`{{{b{dIf}}Cl}{{b{dIf}}}}{bc{}}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{bAl}00``{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{}{{J`{IlIn}}}}{{{b{{Ch{{b{Jb}}}}}}}{{J`{IlIn}}}}{{{Jf{Jd}}}{{J`{IlJh}}}}`{{{b{Il}}}Il}{{b{b{dc}}}Ab{}}{bAb}`{{{b{Il}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}`{{}c{}}```````>=<;```:::999{{{b{Jj}}c}eB`{}}{{{b{Jl}}}Jl}65{{{b{{Jn{c}}}}}{{b{e}}}{}{}}{{{b{d{Jn{c}}}}}{{b{de}}}{}{}}{{{K`{c}}}{{Jn{c}}}{}}66655555{{{b{{Jn{c}}}}}BhB`}{KbJl}{{{b{Jl}}Ab}c{}}{{{Bl{{b{d{Jn{c}}}}}}{b{dBn}}}{{Cb{{C`{Ab}}}}}B`}{{{Bl{{b{d{Jn{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{C`{Ab}}}}}B`}{{{b{Jj}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}2{{{Bl{{b{d{Jn{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{C`{A`}}}}}B`}{{{Bl{{b{d{Jn{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{C`{A`}}}}}B`}`{{{b{dJl}}Cl}{{b{dJl}}}}{bc{}}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{bAl}00``{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{}{{Kf{KbKd}}}}{{{Jf{Kh}}{Jf{Kj}}}{{Kf{KbKl}}}}{{{b{{Ch{{b{Kn}}}}}}}{{Kf{KbKd}}}}{{{Jf{Kh}}}{{Kf{KbKl}}}}````{{{b{Kb}}}Kb}{{b{b{dc}}}Ab{}}{bAb}{{{b{Kb}}}{{b{{Jf{Kh}}}}}}`{{{b{Kb}}}Bh}{{{b{Kb}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}`{{}c{}}````````{bc{}}{c{{Aj{e}}}{}{}}{{}{{Aj{c}}}{}}{bAl}``````````````{{{b{{L`{c}}}}}{{`{{Lf{}{{Lb{Ld}}}}LhLjLll}}}Ln}{b{{b{c}}}{}}000000{{{b{d}}}{{b{dc}}}{}}000000{{{b{M`}}{L`{c}}}eLn{}}{{{b{Mb}}{L`{c}}}eLn{}}{{{b{Md}}}Md}{{{b{M`}}}M`}{{{b{Mf}}}Mf}{{{b{Mb}}}Mb}{{b{b{dc}}}Ab{}}000{bAb}000{cMfMh}{cMbMh}{{}Md}{{}M`}{{}Mf}{{}Mb}{{{b{{Mj{ce}}}}}{{b{g}}}{}{}{}}{{{b{d{Mj{ce}}}}}{{b{dg}}}{}{}{}}{{{b{{L`{c}}}}{b{{L`{c}}}}}BhMl}{{{b{{Mj{ce}}}}{b{dh}}}jll}{{{b{Mn}}{b{dh}}}j}0{{{b{{L`{c}}}}{b{dh}}}jl}{{{b{{L`{c}}}}{b{dh}}}jLn}{cc{}}000{c{{L`{c}}}Ln}111{{{b{{L`{c}}}}{b{de}}}AbN`Nb}{{{b{Ln}}}{{b{Nd}}}}{{{b{{Mj{ce}}}}}{{b{Nd}}}Ln{}}{{{b{{L`{c}}}}}{{b{Nd}}}Ln}{{}c{}}00000000{{{Mj{ce}}}{{Nf{ec}}}{}{}}11{{{b{d{Mj{ce}}}}}{{b{de}}}{}{}}{{{b{{Mj{ce}}}}}{{b{e}}}{}{}}{{{b{Mh}}{b{Nd}}Nh}{{Nn{{Aj{{Nj{Ld}}{Nl{Ad}}}}}}}}`{{ce}{{Mj{ce}}}{}{}}{MfMd};{{{b{Md}}Ab}c{}}{{{b{Mf}}Ab}c{}}`{{{b{M`}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}{{{b{Mb}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}{{{b{Ln}}}{{Af{Nh}}}}0{{{b{{L`{c}}}}}NhLn}{{{Mj{ce}}g}{{Nf{e{Mj{cg}}}}}{}{}{}}{{{b{{Mj{ce}}}}}{{b{c}}}{}{}}{{{b{{L`{c}}}}}{{b{c}}}Ln}````{{{b{Md}}}M`}{{{b{Mf}}}Mb}{{{L`{c}}e}{{L`{c}}}Ln{{O`{{Af{Ld}}}}}}{{{L`{c}}e}{{L`{c}}}Ln{{Ob{}{{Lb{Ld}}}}}}{{{L`{c}}e}{{L`{c}}}Ln{{O`{Od}}}}{{{L`{c}}Nh}{{L`{c}}}Ln}{{{b{Mn}}}{{Af{{b{Ad}}}}}}{{{b{d{L`{c}}}}}{{`{{Lf{}{{Lb{Ld}}}}LhLjLll}}}Ln}`{bc{}}000{bAh}0{c{{Aj{e}}}{}{}}000000{{}{{Aj{c}}}{}}000000{bAl}000000{{cLd}{{L`{c}}}Ln}`{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{{b{Of}}{Mj{ce}}}gLnB`{}}{{{b{Of}}}Of}{{b{b{dc}}}Ab{}}{bAb}{cc{}}{{}c{}}00{OhOf}{{{b{Of}}Ab}c{}}{{{b{Of}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}`{bc{}}?>=``{{{b{{Bf{c}}}}}OjOl}<<;;{{}On}{{{b{Oh}}}Oh}:9{{{b{Oh}}{b{Nd}}c}{{Aj{{A@`{c}}{A@b{c}}}}}{EjEl}}{{{b{{Bf{c}}}}{b{dh}}}{{Aj{AbDf}}}l}{{{b{Oh}}{b{dh}}}{{Aj{AbDf}}}};;{{{b{d{Bf{c}}}}}{{b{d{A@`{{A@d{c}}}}}}}{}}{{{b{{Bf{c}}}}}{{b{{A@`{{A@d{c}}}}}}}{}}<<{{}{{Aj{OhCn}}}}{{{Bl{{b{d{Bf{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}{{{Bl{{b{d{Bf{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}1{{{Bl{{b{d{Bf{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@f}}}}}{D`DbDd}}<{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{A@h}}{Mj{ce}}}gLnB`{}}{{{b{A@j}}}A@j}{{{b{A@h}}}A@h}{{b{b{dc}}}Ab{}}0{bAb}0{cc{}}0{{}c{}}000{A@lA@j}{{{b{A@j}}Ab}c{}}{{{b{A@h}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}`{A@lA@h}{bc{}}0{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0`````````{{{Bl{{b{d{Eb{c}}}}}}}{{Aj{AbA@n}}}{D`Db}}{{{b{Fn}}}AA`}{b{{b{c}}}{}}00000{{{b{d}}}{{b{dc}}}{}}00000{AAbA@l}{Fn{{Aj{AAbG`}}}}{{{b{A@l}}}A@l}{{{b{Fn}}}Fn}{{b{b{dc}}}Ab{}}0{bAb}0{{{b{A@n}}}AAd}{{{b{A@l}}}{{Aj{AAfG`}}}};{{{b{A@l}}{b{Nd}}c}{{Aj{{Ef{c}}{Eh{c}}}}}{EjEl}}{{{b{A@l}}}{{b{Fh}}}}{{{b{AAb}}}{{b{Fj}}}}{{{b{dAAb}}}{{b{dFj}}}}?{{}Fn}{{{b{{Eb{c}}}}{b{dh}}}{{Aj{AbDf}}}l}{{{b{A@l}}{b{dh}}}{{Aj{AbDf}}}}{{{b{A@n}}{b{dh}}}{{Aj{AbDf}}}}0{{{b{{Eh{c}}}}{b{dh}}}{{Aj{AbDf}}}l}0{cc{}}00{G`A@n}1{G`{{Eh{c}}}{}}22{AA`Fn}{{{b{d{Eb{c}}}}}{{b{dc}}}{}}{{{Bl{{b{d{Eb{c}}}}}}}{{Bl{{b{dc}}}}}{}}{{{b{{Eb{c}}}}}{{b{c}}}{}}{{}c{}}00000{A@lFl}{A@n{{Aj{A@fA@n}}}}{{{b{A@n}}}{{Af{{b{A@f}}}}}}{{Enc}{{Aj{{Eb{c}}G`}}}{D`Db}}{{{Bl{{b{d{Eb{c}}}}}}{b{d{Ch{Cf}}}}}{{Aj{A`A@n}}}{D`Db}}{{{Bl{{b{d{Eb{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@n}}}}}{D`Db}}00{{{Bl{{b{d{Eb{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@f}}}}}{D`Db}}{{{Bl{{b{d{Eb{c}}}}}}{b{dBn}}{b{d{Ch{Cf}}}}}{{Cb{{Aj{A`A@n}}}}}{D`Db}}{{{Bl{{b{d{Eb{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{Aj{AbA@f}}}}}{D`Db}}12{{{Bl{{b{d{Eb{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@f}}}}}{D`Db}}{{{Bl{{b{d{Eb{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@n}}}}}{D`Db}}6{{{b{A@n}}}{{Af{{b{Ad}}}}}}{{{b{{Eh{c}}}}}{{Af{{b{Ad}}}}}l}{{{b{{Eb{c}}}}}{{b{Fb}}}{}}{{{b{A@n}}}{{Af{{b{G`}}}}}}{{}Fn}00{bc{}}0{bAh}0{c{{Aj{e}}}{}{}}00000{{}{{Aj{c}}}{}}00000{bAl}00000{{{Bl{{b{d{Eb{c}}}}}}{b{{Ch{Cf}}}}}{{Aj{A`A@n}}}{D`Db}}``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{AAh}}{Mj{ce}}}gLnB`{}}{{{b{AAj}}}AAj}{{{b{AAh}}}AAh}{{b{b{dc}}}Ab{}}0{bAb}0{cc{}}0{{}c{}}000{{}{{C`{AAl}}}}{{{Jf{AAn}}}AAj}{{{b{AAj}}Ab}c{}}{{{b{AAh}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}`{{{Jf{AAn}}}AAh}{bc{}}0{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0{{}AAl}````{{{b{{AB`{c}}}}}OjOl}{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{}{{Hd{AAnHb}}}}`{{{b{AAn}}}AAn}{{b{b{dc}}}Ab{}}{bAb}```{{{b{{AB`{c}}}}{b{dh}}}{{Aj{AbDf}}}l}{{{b{AAn}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}0{{{b{d{AB`{c}}}}}{{Nf{{b{dc}}{b{dABb}}}}}{}}{{{b{{AB`{c}}}}}{{Nf{{b{c}}{b{ABb}}}}}{}}{{}c{}}0{{{AB`{c}}}{{Nf{cABb}}}{}}``{{{Bl{{b{d{AB`{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}{{{Bl{{b{d{AB`{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}1{{{Bl{{b{d{AB`{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@f}}}}}{D`DbDd}}`{bc{}}{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{ABd}}{Mj{ce}}}gLnB`{}}{{{b{ABf}}}ABf}{{{b{ABd}}}ABd}{{b{b{dc}}}Ab{}}0{bAb}0{cc{}}0{{}c{}}000{{}{{C`{ABh}}}}{{{Jf{ABj}}}ABf}{{{b{ABf}}Ab}c{}}{{{b{ABd}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}`{{{Jf{ABj}}}ABd}{bc{}}0{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0{{}ABh}````{{{b{{ABl{c}}}}}OjOl}{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{}{{Ib{ABjI`}}}}`{{{b{ABj}}}ABj}{{b{b{dc}}}Ab{}}{bAb}``{{{b{{ABl{c}}}}{b{dh}}}{{Aj{AbDf}}}l}{{{b{ABj}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}0{{{b{d{ABl{c}}}}}{{Nf{{b{dc}}{b{dABn}}}}}{}}{{{b{{ABl{c}}}}}{{Nf{{b{c}}{b{ABn}}}}}{}}{{}c{}}0{{{ABl{c}}}{{Nf{cABn}}}{}}``{{{Bl{{b{d{ABl{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}{{{Bl{{b{d{ABl{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}1{{{Bl{{b{d{ABl{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@f}}}}}{D`DbDd}}`{bc{}}{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{AC`}}{Mj{ce}}}gLnB`{}}{{{b{ACb}}}ACb}{{{b{AC`}}}AC`}{{b{b{dc}}}Ab{}}0{bAb}0{cc{}}0{{}c{}}000{{}{{C`{ACd}}}}{{{Jf{ACf}}}ACb}{{{b{ACb}}Ab}c{}}{{{b{AC`}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}`{{{Jf{ACf}}}AC`}{bc{}}0{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0{{}ACd}````{{{b{{ACh{c}}}}}OjOl}{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{}{{J`{ACfIn}}}}{{{b{{Ch{{b{Jb}}}}}}}{{J`{ACfIn}}}}{{{Jf{Jd}}}{{J`{ACfJh}}}}`{{{b{ACf}}}ACf}{{b{b{dc}}}Ab{}}{bAb}{{{b{dACf}}}ACj}```{{{b{{ACh{c}}}}{b{dh}}}{{Aj{AbDf}}}l}{{{b{ACf}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}0{{{b{d{ACh{c}}}}}{{Nf{{b{dc}}{b{dACl}}}}}{}}{{{b{{ACh{c}}}}}{{Nf{{b{c}}{b{ACl}}}}}{}}{{}c{}}0{{{ACh{c}}}{{Nf{cACl}}}{}}``{{{Bl{{b{d{ACh{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}{{{Bl{{b{d{ACh{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}1{{{Bl{{b{d{ACh{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@f}}}}}{D`DbDd}}`{bc{}}{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{ACn}}{Mj{ce}}}gLnB`{}}{{{b{AD`}}}AD`}{{{b{ACn}}}ACn}{{b{b{dc}}}Ab{}}0{bAb}0{cc{}}0{{}c{}}000{{}{{C`{ADb}}}}{{{Jf{ADd}}}AD`}{{{b{AD`}}Ab}c{}}{{{b{ACn}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}`{{{Jf{ADd}}}ACn}{bc{}}0{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0{{}ADb}````{{{b{{ADf{c}}}}}OjOl}{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{}{{Kf{ADdKd}}}}{{{Jf{Kh}}{Jf{Kj}}}{{Kf{ADdKl}}}}{{{b{{Ch{{b{Kn}}}}}}}{{Kf{ADdKd}}}}{{{Jf{Kh}}}{{Kf{ADdKl}}}}````{{{b{ADd}}}ADd}{{b{b{dc}}}Ab{}}{bAb}{{{b{ADd}}}{{b{{Jf{Kh}}}}}}{{{b{dADd}}}ADh}```{{{b{ADd}}}Bh}{{{b{{ADf{c}}}}{b{dh}}}{{Aj{AbDf}}}l}{{{b{ADd}}{b{dh}}}{{Aj{AbDf}}}}{cc{}}0{{{b{d{ADf{c}}}}}{{Nf{{b{dc}}{b{dADj}}}}}{}}{{{b{{ADf{c}}}}}{{Nf{{b{c}}{b{ADj}}}}}{}}{{}c{}}0{{{ADf{c}}}{{Nf{cADj}}}{}}{{{b{{ADf{c}}}}}Bh{D`DbDd}}``{{{Bl{{b{d{ADf{c}}}}}}{b{dBn}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}{{{Bl{{b{d{ADf{c}}}}}}{b{dBn}}{b{dCd}}}{{Cb{{Aj{AbA@f}}}}}{D`DbDd}}1{{{Bl{{b{d{ADf{c}}}}}}{b{dBn}}{b{{Ch{Cf}}}}}{{Cb{{Aj{A`A@f}}}}}{D`DbDd}}{{{Bl{{b{d{ADf{c}}}}}}{b{dBn}}{b{{Ch{Cj}}}}}{{Cb{{Aj{A`A@f}}}}}{D`DbDd}}``{bc{}}{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{ADl}}{L`{c}}}eLn{}}{{{b{ADn}}}ADn}{{{b{ADl}}}ADl}{{b{b{dc}}}Ab{}}0{bAb}0{{}ADn}{{}ADl}{{{b{ADn}}{b{dh}}}j}{{{b{ADl}}{b{dh}}}j}{cc{}}0{{}c{}}000{{{b{ADn}}Ab}c{}}{{{b{ADl}}{b{dBn}}}{{Cb{{Aj{Abc}}}}}{}}{{{b{ADn}}}ADl}{bc{}}0{c{{Aj{e}}}{}{}}0{{}{{Aj{c}}}{}}0{bAl}0","D":"CIh","p":[[1,"reference"],[0,"mut"],[6,"TlsError",2],[5,"Formatter",1179],[8,"Result",1179],[10,"Debug",1179],[6,"Infallible",1180],[1,"usize"],[1,"unit"],[10,"Error",1181],[6,"Option",1182],[5,"String",1183],[6,"Result",1184],[5,"TypeId",1185],[5,"AcceptorService",25],[10,"ActixStream",1186],[5,"Acceptor",25],[5,"TlsStream",25],[5,"AsyncTlsStream",661],[1,"bool"],[5,"TlsAcceptor",70,1187],[5,"Pin",1188],[5,"Context",1189],[8,"Result",1190],[6,"Poll",1191],[5,"ReadBuf",1192],[1,"u8"],[1,"slice"],[5,"IoSlice",1193],[5,"Duration",1194],[5,"Error",70,1195],[10,"AsyncRead",1196],[10,"AsyncWrite",1197],[10,"Unpin",1198],[5,"Error",1179],[6,"Error",1199],[5,"TlsAcceptor",1195],[5,"AcceptorService",98],[5,"Acceptor",98],[5,"TlsStream",98],[5,"AsyncSslStream",725],[5,"SslAcceptor",143,1200],[5,"SslStream",1201],[6,"HandshakeError",725,1202],[10,"Read",1193],[10,"Write",1193],[5,"Ssl",143,1201],[6,"SSL",1203],[5,"SslRef",1201],[5,"SslAcceptorBuilder",143,1200],[5,"AlpnError",143,1201],[5,"SslContextRef",1201],[5,"SslContextBuilder",1201],[5,"SslContext",1201],[5,"SslMethod",725,1201],[5,"ErrorStack",1204],[5,"Index",1205],[10,"Sync",1198],[10,"Send",1198],[5,"AcceptorService",214],[5,"Acceptor",214],[5,"TlsStream",214],[5,"TlsStream",1206],[5,"ServerConfig",259,1207],[5,"WantsCipherSuites",1208],[5,"ConfigBuilder",1208],[5,"AcceptorService",282],[5,"Acceptor",282],[5,"TlsStream",282],[5,"TlsStream",1206],[5,"ServerConfig",327,1207],[5,"WantsCipherSuites",1208],[5,"ConfigBuilder",1208],[5,"AcceptorService",351],[5,"Acceptor",351],[5,"TlsStream",351],[5,"TlsStream",1206],[5,"ServerConfig",396,1207],[5,"WantsVerifier",1208],[5,"ConfigBuilder",1208],[5,"SupportedProtocolVersion",1209],[5,"CryptoProvider",1210],[5,"Arc",1211],[5,"WantsVersions",1208],[5,"AcceptorService",423],[5,"Acceptor",423],[5,"TlsStream",423],[5,"TlsStream",1206],[5,"ServerConfig",468,1207],[5,"WantsVerifier",1208],[5,"ConfigBuilder",1208],[5,"CryptoProvider",1210],[10,"TimeProvider",1212],[5,"WantsVersions",1208],[5,"SupportedProtocolVersion",1209],[5,"ConnectInfo",502,1213],[17,"Item"],[6,"SocketAddr",1214],[10,"Iterator",1215],[10,"ExactSizeIterator",1216],[10,"FusedIterator",1217],[10,"Clone",1218],[10,"Host",502,1219],[5,"ConnectorService",502,1220],[5,"ResolverService",502,1221],[5,"Connector",502,1220],[5,"Resolver",502,1221],[10,"Resolve",502,1222],[5,"Connection",502,1223],[10,"PartialEq",1224],[6,"ConnectError",502,1225],[10,"Hash",1226],[10,"Hasher",1226],[1,"str"],[1,"tuple"],[1,"u16"],[5,"Vec",1227],[5,"Box",1228],[8,"LocalBoxFuture",1229],[10,"Into",1180],[10,"IntoIterator",1230],[6,"IpAddr",1231],[5,"TlsConnector",642],[5,"TlsConnector",661,1195],[1,"i32"],[10,"AsRawFd",1232],[5,"TlsConnectorBuilder",1195],[5,"TlsStream",1195],[6,"HandshakeError",1195],[5,"AllowStd",1187],[5,"Error",1190],[5,"TlsConnectorService",693],[5,"TlsConnector",693],[5,"SslConnector",725,1200],[5,"Error",725,1202],[6,"SSL_METHOD",1233],[5,"SslConnectorBuilder",725,1200],[5,"ErrorCode",1202],[5,"ConnectConfiguration",1200],[5,"TlsConnectorService",835],[5,"TlsConnector",835],[5,"RootCertStore",1234],[5,"ClientConfig",869,1235],[5,"AsyncTlsStream",869],[5,"ClientConnection",1235],[5,"TlsConnectorService",909],[5,"TlsConnector",909],[5,"RootCertStore",1234],[5,"ClientConfig",943,1235],[5,"AsyncTlsStream",943],[5,"ClientConnection",1235],[5,"TlsConnectorService",982],[5,"TlsConnector",982],[5,"RootCertStore",1236],[5,"ClientConfig",1016,1235],[5,"AsyncTlsStream",1016],[5,"DangerousClientConfig",1237],[5,"ClientConnection",1235],[5,"TlsConnectorService",1059],[5,"TlsConnector",1059],[5,"RootCertStore",1236],[5,"ClientConfig",1093,1235],[5,"AsyncTlsStream",1093],[5,"DangerousClientConfig",1237],[5,"ClientConnection",1238],[5,"TcpConnectorService",1145],[5,"TcpConnector",1145]],"r":[[70,1195],[71,1187],[144,1201],[145,1202],[147,1202],[150,1201],[151,1200],[152,1200],[259,1207],[327,1207],[396,1207],[468,1207],[502,1225],[503,1213],[504,1223],[505,1220],[506,1220],[507,1219],[511,1222],[512,1221],[514,1221],[662,1195],[726,1202],[728,1202],[730,1200],[731,1200],[732,1201],[870,1235],[871,1239],[944,1235],[945,1239],[1017,1235],[1018,1239],[1094,1235],[1095,1239]],"b":[[8,"impl-Debug-for-TlsError%3CTlsErr,+SvcErr%3E"],[9,"impl-Display-for-TlsError%3CTlsErr,+SvcErr%3E"],[80,"impl-Debug-for-Error"],[81,"impl-Display-for-Error"],[555,"impl-Debug-for-ConnectError"],[556,"impl-Display-for-ConnectError"],[557,"impl-Debug-for-ConnectInfo%3CR%3E"],[558,"impl-Display-for-ConnectInfo%3CR%3E"],[767,"impl-Debug-for-Error"],[768,"impl-Display-for-Error"],[769,"impl-Debug-for-HandshakeError%3CS%3E"],[770,"impl-Display-for-HandshakeError%3CS%3E"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAM8ChgAHAAMAFQAEAB0ADAAwAAIANAAGAD0ACQBKAAkAVQABAFoACABmAAwAeQACAH0ABgCGAAkAnQAKAKkABQCxAAcAvQAAAMkADQDaAAwA7QACAPEABgD6AAkABgEBAAoBAwAXAQMAHgEMADEBAgA1AQYAPgEJAEoBAQBOAQMAXAEDAGMBDAB2AQIAegEGAIMBCQCPAQEAlQECAJkBAACkAQMAqwEMAL4BAgDCAQYAywEJANcBAQDhAQIA5wEAAPMBAwAGAhsAJAILADQCAAA4AgAAQwIBAEYCAQBPAgEAUgIBAGQCAABnAhoAhAIFAIwCAQCPAgEAkgIDAJgCBACeAgIAogIBAKsCCgC4AgoAxwIBAMoCAQDOAgcA4QILAO8CBgD6AgEA/gIFAAcDAAAJAwAAFwMBAB4DAAAgAwAAIgMBACYDAQApAwAALQMVAEYDCgBVAwEAWQMBAF0DBwBoAwAAagMEAHEDAgB3AwEAewMBAH8DAACCAwIAhwMGAJADCgCfAwEAowMBAKcDBwCyAwAAtAMEALsDAgDAAwEAxAMBAMgDAADLAwIA0AMGANkDCgDoAwEA7AMBAPADBwD7AwAA/QMEAAYEAgANBAEAEQQBABUEAAAYBAIAHQQGACYECgA1BAEAOQQBAD0EBwBIBAAASgQEAFcEAgBgBAEAZAQBAGgEAQBsBAIAcwQGAHwEDgCPBAMAlAQHAA==","a":{"dtls_method":[764],"ssl_accept":[155],"ssl_connect":[174],"ssl_get_ex_new_index":[199],"ssl_new":[198],"tls_client_method":[810],"tls_method":[809],"tls_server_method":[811]}}],["actix_tracing",{"t":"FFNNNNNNNNNNNNNNNNNNHNNNNNN","n":["TracingService","TracingTransform","borrow","","borrow_mut","","call","clone","clone_into","clone_to_uninit","from","","into","","into_service","new","","new_transform","poll_ready","to_owned","trace","try_from","","try_into","","type_id",""],"q":[[0,"actix_tracing"],[27,"actix_service"],[28,"tracing::span"],[29,"core::option"],[30,"core::ops::function"],[31,"core::clone"],[32,"core::task::wake"],[33,"core::result"],[34,"core::task::poll"],[35,"actix_service::transform"],[36,"core::any"]],"i":"``Aff1000001010010100`101010","f":"``{b{{b{c}}}{}}0{{{b{d}}}{{b{dc}}}{}}0{{{b{{f{eg}}}}c}i{}{{h{c}}}{{A`{{b{c}}}{{j{{n{l}}}}}}}{}}{{{b{{f{ce}}}}}{{f{ce}}}AbAb}{{b{b{dc}}}Ad{}}{bAd}{cc{}}0{{}c{}}00{c{{Af{egc}}}{}{}{}}{{ce}{{f{ce}}}{}{}}{{{b{{Af{egi}}}}e}k{}{{h{c}}}{{An{c}{{Ah{}}{Aj{}}{Al{e}}}}}{{A`{{b{c}}}{{j{{n{l}}}}}}Ab}{}}{{{b{{f{eg}}}}{b{dB`}}}{{Bd{{Bb{Adi}}}}}{}{{h{c}}}{{A`{{b{c}}}{{j{{n{l}}}}}}}{}}{bc{}}{{gi}{{Bf{{Af{ei}}ec}}}{}{{An{c}}}{{Bh{ec}}}{{A`{{b{c}}}{{j{{n{l}}}}}}Ab}}{c{{Bb{e}}}{}{}}0{{}{{Bb{c}}}{}}0{bBj}0","D":"A`","p":[[1,"reference"],[0,"mut"],[5,"TracingService",0],[10,"Service",27],[17,"Output"],[5,"Span",28],[6,"Option",29],[10,"Fn",30],[10,"Clone",31],[1,"unit"],[5,"TracingTransform",0],[17,"Response"],[17,"Error"],[17,"Service"],[10,"ServiceFactory",27],[5,"Context",32],[6,"Result",33],[6,"Poll",34],[5,"ApplyTransform",35],[10,"IntoServiceFactory",27],[5,"TypeId",36]],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAABMAAwADAAcADwAFABYABQA="}],["actix_utils",{"t":"CCFFNNNNNNNNNNNNNNNNNNNNNNNNNGPFFPNNNNNNNNNNNNHNNNNNNNNNNNNNNNHNNNHHNNNNNNNNNNNNOO","n":["counter","future","Counter","CounterGuard","available","borrow","","borrow_mut","","clone","clone_into","clone_to_uninit","drop","fmt","","from","","get","into","","new","to_owned","total","try_from","","try_into","","type_id","","Either","Left","PollFn","Ready","Right","borrow","","","borrow_mut","","","clone","","clone_into","","clone_to_uninit","","err","fmt","","","from","","","into","","","into_future","","","into_inner","","left","ok","poll","","","poll_fn","ready","right","to_owned","","try_from","","","try_into","","","type_id","","","value",""],"q":[[0,"actix_utils"],[2,"actix_utils::counter"],[29,"actix_utils::future"],[80,"actix_utils::future::Either"],[82,"core::task::wake"],[83,"core::fmt"],[84,"core::result"],[85,"core::any"],[86,"actix_utils::future::either"],[87,"core::clone"],[88,"actix_utils::future::ready"],[89,"actix_utils::future::poll_fn"],[90,"core::pin"],[91,"core::task::poll"],[92,"core::ops::function"],[93,"core::future::future"]],"i":"````b0n1011101010110111101010`Aj``0B`1An120202020`120120120120202`120``220120120120BnC`","f":"````{{{d{b}}{d{f}}}h}{d{{d{c}}}{}}0{{{d{j}}}{{d{jc}}}{}}0{{{d{b}}}b}{{d{d{jc}}}l{}}{dl}{{{d{jn}}}l}{{{d{b}}{d{jA`}}}Ab}{{{d{n}}{d{jA`}}}Ab}{cc{}}0{{{d{b}}}n}{{}c{}}0{Adb}{dc{}}{{{d{b}}}Ad}{c{{Af{e}}}{}{}}0{{}{{Af{c}}}{}}0{dAh}0`````{d{{d{c}}}{}}00{{{d{j}}}{{d{jc}}}{}}00{{{d{{Aj{ce}}}}}{{Aj{ce}}}AlAl}{{{d{{An{c}}}}}{{An{c}}}Al}{{d{d{jc}}}l{}}0{dl}0{c{{An{{Af{ec}}}}}{}{}}{{{d{{B`{c}}}}{d{jA`}}}Ab{}}{{{d{{Aj{ce}}}}{d{jA`}}}AbBbBb}{{{d{{An{c}}}}{d{jA`}}}AbBb}{cc{}}00{{}c{}}00{{}}00{{{Aj{cc}}}c{}}{{{An{c}}}c{}}{c{{Aj{ce}}}{}{}}{c{{An{{Af{ce}}}}}{}{}}{{{Bd{{d{j{B`{e}}}}}}{d{jf}}}{{Bf{g}}}{}{{Bj{{d{jf}}}{{Bh{{Bf{c}}}}}}}{}}{{{Bd{{d{j{Aj{ce}}}}}}{d{jf}}}{{Bf{g}}}Bl{{Bl{}{{Bh{}}}}}{}}{{{Bd{{d{j{An{c}}}}}}{d{jf}}}{{Bf{c}}}{}}{e{{B`{e}}}{}{{Bj{{d{jf}}}{{Bh{{Bf{c}}}}}}}}{c{{An{c}}}{}}{c{{Aj{ec}}}{}{}}{dc{}}0{c{{Af{e}}}{}{}}00{{}{{Af{c}}}{}}00{dAh}00``","D":"D`","p":[[5,"Counter",2],[1,"reference"],[5,"Context",82],[1,"bool"],[0,"mut"],[1,"unit"],[5,"CounterGuard",2],[5,"Formatter",83],[8,"Result",83],[1,"usize"],[6,"Result",84],[5,"TypeId",85],[6,"Either",29,86],[10,"Clone",87],[5,"Ready",29,88],[5,"PollFn",29,89],[10,"Debug",83],[5,"Pin",90],[6,"Poll",91],[17,"Output"],[10,"FnMut",92],[10,"Future",93],[15,"Left",80],[15,"Right",80]],"r":[[29,86],[31,89],[32,88],[46,88],[62,88],[66,89],[67,88]],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAADIACAAGAAkAFgAAABgABQAjAAsAMAACADkAAgBAAAIARgAMAA=="}],["bytestring",{"t":"FNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["ByteString","as_bytes","as_ref","","","borrow","","borrow_mut","clone","clone_into","clone_to_uninit","cmp","default","deref","deserialize","eq","","fmt","","from","","","","from_bytes_unchecked","from_static","hash","into","into_bytes","new","partial_cmp","serialize","slice_ref","to_owned","to_string","try_from","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","try_into","type_id"],"q":[[0,"bytestring"],[107,"bytes::bytes"],[108,"core::cmp"],[109,"core::result"],[110,"serde::de"],[111,"core::convert"],[112,"core::fmt"],[113,"alloc::string"],[114,"alloc::boxed"],[115,"core::hash"],[116,"core::option"],[117,"serde::ser"],[118,"bytes::bytes_mut"],[119,"alloc::vec"],[120,"core::any"]],"i":"`b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","f":"`{{{d{b}}}{{d{f}}}}{{{d{b}}}{{d{h}}}}{{{d{b}}}{{d{{l{j}}}}}}{{{d{b}}}{{d{b}}}}2{d{{d{c}}}{}}{{{d{n}}}{{d{nc}}}{}}{{{d{b}}}b}{{d{d{nc}}}A`{}}{dA`}{{{d{b}}{d{b}}}Ab}{{}b}9{c{{Ad{b}}}Af}{{{d{b}}{d{c}}}Ah{{Aj{h}}}}{{{d{b}}{d{h}}}Ah}{{{d{b}}{d{nAl}}}An}0{{{d{h}}}b}{cc{}}{B`b}{{{Bb{h}}}b}{fb}4{{{d{b}}{d{nc}}}A`Bd}{{}c{}}{bf}<{{{d{b}}{d{b}}}{{Bf{Ab}}}}{{{d{b}}c}AdBh}{{{d{b}}{d{h}}}b}{dc{}}{dB`}{{{Bj{j}}}{{Ad{bc}}}{}}{{{d{{l{j}}}}}{{Ad{bc}}}{}}{Bl{{Ad{bc}}}{}}2{{{d{{Bj{j}}}}}{{Ad{bc}}}{}}303030303030303030303030303030303030{f{{Ad{bc}}}{}}1414141414141414141{c{{Ad{e}}}{}{}}2525252{{{Bn{j}}}{{Ad{bc}}}{}}6{{}{{Ad{c}}}{}}{dC`}","D":"Ad","p":[[5,"ByteString",0],[1,"reference"],[5,"Bytes",107],[1,"str"],[1,"u8"],[1,"slice"],[0,"mut"],[1,"unit"],[6,"Ordering",108],[6,"Result",109],[10,"Deserializer",110],[1,"bool"],[10,"AsRef",111],[5,"Formatter",112],[8,"Result",112],[5,"String",113],[5,"Box",114],[10,"Hasher",115],[6,"Option",116],[10,"Serializer",117],[1,"array"],[5,"BytesMut",118],[5,"Vec",119],[5,"TypeId",120]],"r":[],"b":[[2,"impl-AsRef%3Cstr%3E-for-ByteString"],[3,"impl-AsRef%3C%5Bu8%5D%3E-for-ByteString"],[4,"impl-AsRef%3CByteString%3E-for-ByteString"],[15,"impl-PartialEq%3CT%3E-for-ByteString"],[16,"impl-PartialEq%3Cstr%3E-for-ByteString"],[17,"impl-Debug-for-ByteString"],[18,"impl-Display-for-ByteString"],[19,"impl-From%3C%26str%3E-for-ByteString"],[21,"impl-From%3CString%3E-for-ByteString"],[22,"impl-From%3CBox%3Cstr%3E%3E-for-ByteString"],[34,"impl-TryFrom%3C%5Bu8;+29%5D%3E-for-ByteString"],[35,"impl-TryFrom%3C%26%5Bu8%5D%3E-for-ByteString"],[36,"impl-TryFrom%3CBytesMut%3E-for-ByteString"],[37,"impl-TryFrom%3C%5Bu8;+0%5D%3E-for-ByteString"],[38,"impl-TryFrom%3C%26%5Bu8;+0%5D%3E-for-ByteString"],[39,"impl-TryFrom%3C%5Bu8;+1%5D%3E-for-ByteString"],[40,"impl-TryFrom%3C%26%5Bu8;+1%5D%3E-for-ByteString"],[41,"impl-TryFrom%3C%5Bu8;+2%5D%3E-for-ByteString"],[42,"impl-TryFrom%3C%26%5Bu8;+2%5D%3E-for-ByteString"],[43,"impl-TryFrom%3C%5Bu8;+3%5D%3E-for-ByteString"],[44,"impl-TryFrom%3C%26%5Bu8;+3%5D%3E-for-ByteString"],[45,"impl-TryFrom%3C%5Bu8;+4%5D%3E-for-ByteString"],[46,"impl-TryFrom%3C%26%5Bu8;+4%5D%3E-for-ByteString"],[47,"impl-TryFrom%3C%5Bu8;+5%5D%3E-for-ByteString"],[48,"impl-TryFrom%3C%26%5Bu8;+5%5D%3E-for-ByteString"],[49,"impl-TryFrom%3C%5Bu8;+6%5D%3E-for-ByteString"],[50,"impl-TryFrom%3C%26%5Bu8;+6%5D%3E-for-ByteString"],[51,"impl-TryFrom%3C%5Bu8;+7%5D%3E-for-ByteString"],[52,"impl-TryFrom%3C%26%5Bu8;+7%5D%3E-for-ByteString"],[53,"impl-TryFrom%3C%5Bu8;+8%5D%3E-for-ByteString"],[54,"impl-TryFrom%3C%26%5Bu8;+8%5D%3E-for-ByteString"],[55,"impl-TryFrom%3C%5Bu8;+9%5D%3E-for-ByteString"],[56,"impl-TryFrom%3C%26%5Bu8;+9%5D%3E-for-ByteString"],[57,"impl-TryFrom%3C%5Bu8;+10%5D%3E-for-ByteString"],[58,"impl-TryFrom%3C%26%5Bu8;+10%5D%3E-for-ByteString"],[59,"impl-TryFrom%3C%5Bu8;+11%5D%3E-for-ByteString"],[60,"impl-TryFrom%3C%26%5Bu8;+11%5D%3E-for-ByteString"],[61,"impl-TryFrom%3C%5Bu8;+12%5D%3E-for-ByteString"],[62,"impl-TryFrom%3C%26%5Bu8;+12%5D%3E-for-ByteString"],[63,"impl-TryFrom%3C%5Bu8;+13%5D%3E-for-ByteString"],[64,"impl-TryFrom%3C%26%5Bu8;+13%5D%3E-for-ByteString"],[65,"impl-TryFrom%3C%5Bu8;+14%5D%3E-for-ByteString"],[66,"impl-TryFrom%3C%26%5Bu8;+14%5D%3E-for-ByteString"],[67,"impl-TryFrom%3C%5Bu8;+15%5D%3E-for-ByteString"],[68,"impl-TryFrom%3C%26%5Bu8;+15%5D%3E-for-ByteString"],[69,"impl-TryFrom%3C%5Bu8;+16%5D%3E-for-ByteString"],[70,"impl-TryFrom%3C%26%5Bu8;+16%5D%3E-for-ByteString"],[71,"impl-TryFrom%3C%5Bu8;+17%5D%3E-for-ByteString"],[72,"impl-TryFrom%3C%26%5Bu8;+17%5D%3E-for-ByteString"],[73,"impl-TryFrom%3C%5Bu8;+18%5D%3E-for-ByteString"],[74,"impl-TryFrom%3C%26%5Bu8;+18%5D%3E-for-ByteString"],[75,"impl-TryFrom%3CBytes%3E-for-ByteString"],[76,"impl-TryFrom%3C%26%5Bu8;+19%5D%3E-for-ByteString"],[77,"impl-TryFrom%3C%5Bu8;+20%5D%3E-for-ByteString"],[78,"impl-TryFrom%3C%26%5Bu8;+20%5D%3E-for-ByteString"],[79,"impl-TryFrom%3C%5Bu8;+21%5D%3E-for-ByteString"],[80,"impl-TryFrom%3C%26%5Bu8;+21%5D%3E-for-ByteString"],[81,"impl-TryFrom%3C%5Bu8;+22%5D%3E-for-ByteString"],[82,"impl-TryFrom%3C%26%5Bu8;+22%5D%3E-for-ByteString"],[83,"impl-TryFrom%3C%5Bu8;+23%5D%3E-for-ByteString"],[84,"impl-TryFrom%3C%26%5Bu8;+23%5D%3E-for-ByteString"],[85,"impl-TryFrom%3C%5Bu8;+24%5D%3E-for-ByteString"],[86,"impl-TryFrom%3C%26%5Bu8;+24%5D%3E-for-ByteString"],[87,"impl-TryFrom%3C%5Bu8;+25%5D%3E-for-ByteString"],[88,"impl-TryFrom%3C%26%5Bu8;+25%5D%3E-for-ByteString"],[89,"impl-TryFrom%3C%5Bu8;+26%5D%3E-for-ByteString"],[90,"impl-TryFrom%3C%26%5Bu8;+26%5D%3E-for-ByteString"],[91,"impl-TryFrom%3C%5Bu8;+27%5D%3E-for-ByteString"],[92,"impl-TryFrom%3C%26%5Bu8;+27%5D%3E-for-ByteString"],[93,"impl-TryFrom%3C%5Bu8;+28%5D%3E-for-ByteString"],[94,"impl-TryFrom%3C%26%5Bu8;+28%5D%3E-for-ByteString"],[96,"impl-TryFrom%3C%26%5Bu8;+29%5D%3E-for-ByteString"],[97,"impl-TryFrom%3C%5Bu8;+30%5D%3E-for-ByteString"],[98,"impl-TryFrom%3C%26%5Bu8;+30%5D%3E-for-ByteString"],[99,"impl-TryFrom%3C%5Bu8;+31%5D%3E-for-ByteString"],[100,"impl-TryFrom%3C%26%5Bu8;+31%5D%3E-for-ByteString"],[101,"impl-TryFrom%3C%5Bu8;+32%5D%3E-for-ByteString"],[102,"impl-TryFrom%3C%26%5Bu8;+32%5D%3E-for-ByteString"],[103,"impl-TryFrom%3CVec%3Cu8%3E%3E-for-ByteString"],[104,"impl-TryFrom%3C%5Bu8;+19%5D%3E-for-ByteString"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAGEABQADABEAFgABABoAAAAeAAEAIQBKAA=="}],["local_channel",{"t":"CFFFNNNNNNHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["mpsc","Receiver","SendError","Sender","borrow","","","borrow_mut","","","channel","clone","clone_into","clone_to_uninit","close","drop","","fmt","","","","from","","","into","","","into_inner","poll_close","poll_flush","poll_next","poll_ready","recv","send","sender","start_send","to_owned","to_string","try_from","","","try_into","","","try_poll_next","type_id","",""],"q":[[0,"local_channel"],[1,"local_channel::mpsc"],[48,"core::fmt"],[49,"core::pin"],[50,"core::task::wake"],[51,"core::result"],[52,"core::task::poll"],[53,"core::option"],[54,"alloc::string"],[55,"core::any"]],"i":"````nfh210`1111102210210210211010101122102100210","f":"````{b{{b{c}}}{}}00{{{b{d}}}{{b{dc}}}{}}00{{}{{j{{f{c}}{h{c}}}}}{}}{{{b{{f{c}}}}}{{f{c}}}{}}{{b{b{dc}}}l{}}{bl}{{{b{d{f{c}}}}}l{}}0{{{b{d{h{c}}}}}l{}}{{{b{{n{c}}}}{b{dA`}}}Ab{}}0{{{b{{f{c}}}}{b{dA`}}}AbAd}{{{b{{h{c}}}}{b{dA`}}}AbAd}{cc{}}00{{}c{}}00{{{n{c}}}c{}}{{{Af{{b{d{f{c}}}}}}{b{dAh}}}{{Al{{Aj{le}}}}}{}{}}{{{Af{{b{d{f{c}}}}}}{b{dAh}}}{{Al{{Aj{l{n{c}}}}}}}{}}{{{Af{{b{d{h{c}}}}}}{b{dAh}}}{{Al{{An{e}}}}}{}{}}2{{{b{d{h{c}}}}}{{An{c}}}{}}{{{b{{f{c}}}}c}{{Aj{l{n{c}}}}}{}}{{{b{{h{c}}}}}{{f{c}}}{}}{{{Af{{b{d{f{c}}}}}}c}{{Aj{l{n{c}}}}}{}}{bc{}}{bB`}{c{{Aj{e}}}{}{}}00{{}{{Aj{c}}}{}}00{{{Af{{b{dc}}}}{b{dAh}}}{{Al{{An{Aj}}}}}{}}{bBb}00","D":"Bb","p":[[1,"reference"],[0,"mut"],[5,"Sender",1],[5,"Receiver",1],[1,"tuple"],[1,"unit"],[5,"SendError",1],[5,"Formatter",48],[8,"Result",48],[10,"Debug",48],[5,"Pin",49],[5,"Context",50],[6,"Result",51],[6,"Poll",52],[6,"Option",53],[5,"String",54],[5,"TypeId",55]],"r":[],"b":[[17,"impl-Display-for-SendError%3CT%3E"],[18,"impl-Debug-for-SendError%3CT%3E"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAB8ABQAFAAUADAACABAABQAdAAMAJAAMAA=="}],["local_waker",{"t":"FNNNNNNNNNNNNN","n":["LocalWaker","borrow","borrow_mut","default","fmt","from","into","new","register","take","try_from","try_into","type_id","wake"],"q":[[0,"local_waker"],[14,"core::fmt"],[15,"core::task::wake"],[16,"core::option"],[17,"core::result"],[18,"core::any"]],"i":"`f000000000000","f":"`{b{{b{c}}}{}}{{{b{d}}}{{b{dc}}}{}}{{}f}{{{b{f}}{b{dh}}}j}{cc{}}{{}c{}}3{{{b{f}}{b{l}}}n}{{{b{f}}}{{A`{l}}}}{c{{Ab{e}}}{}{}}{{}{{Ab{c}}}{}}{bAd}{{{b{f}}}Af}","D":"A`","p":[[1,"reference"],[0,"mut"],[5,"LocalWaker",0],[5,"Formatter",14],[8,"Result",14],[5,"Waker",15],[1,"bool"],[6,"Option",16],[6,"Result",17],[5,"TypeId",18],[1,"unit"]],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAAYAAgACAAMACwACAA=="}]]')); +if (typeof exports !== 'undefined') exports.searchIndex = searchIndex; +else if (window.initSearch) window.initSearch(searchIndex); +//{"start":39,"fragment_lengths":[5063,158,17781,2689,4346,35303,1534,2580,6420,1797,727]} \ No newline at end of file diff --git a/search.desc/actix_codec/actix_codec-desc-0-.js b/search.desc/actix_codec/actix_codec-desc-0-.js new file mode 100644 index 00000000..4a1a54b7 --- /dev/null +++ b/search.desc/actix_codec/actix_codec-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_codec", 0, "Codec utilities for working with framed protocols.\nReads bytes from a source.\nWrites bytes asynchronously.\nBytes codec. Reads/writes chunks of bytes from a stream.\nDecoding of frames via buffers.\nTrait of helper objects to write out messages as bytes, โ€ฆ\nThe type of unrecoverable frame decoding errors.\nThe type of encoding errors.\nA unified Stream and Sink interface to an underlying I/O โ€ฆ\nFramedParts contains an export of the data of a Framed โ€ฆ\nThe type of decoded frames.\nLines codec. Reads/writes line delimited strings.\nA wrapper around a byte buffer that is incrementally โ€ฆ\nAdvances the size of the filled region of the buffer.\nAsserts that the first n unfilled bytes of the buffer are โ€ฆ\nReturns the total capacity of the buffer.\nClears the buffer, resetting the filled region to empty.\nFlush write buffer and shutdown underlying I/O stream.\nThe codec object.\nReturns a mutable reference to the underlying codec.\nReturns a reference to the underlying codec.\nAttempts to decode a frame from the provided buffer of โ€ฆ\nA default method available to be called when there are no โ€ฆ\nEncodes a frame into the buffer provided.\nReturns a shared reference to the filled portion of the โ€ฆ\nReturns a mutable reference to the filled portion of the โ€ฆ\nFlush write buffer to underlying I/O stream.\nProvides a Stream and Sink interface for reading and โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nThis function returns a single object that is both Stream โ€ฆ\nReturns a mutable reference to the unfilled part of the โ€ฆ\nReturns a mutable reference to the first n bytes of the โ€ฆ\nReturns a shared reference to the initialized portion of โ€ฆ\nReturns a mutable reference to the initialized portion of โ€ฆ\nReturns a mutable reference to the entire buffer, without โ€ฆ\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConsume the Frame, returning Frame with different codec.\nConsume the Frame, returning Frame with different io.\nConsumes the Frame, returning its underlying I/O stream, โ€ฆ\nThe inner transport used to read bytes to and write bytes โ€ฆ\nReturns a mutable reference to the underlying I/O stream.\nReturns a Pin of a mutable reference to the underlying I/O โ€ฆ\nReturns a reference to the underlying I/O stream wrapped โ€ฆ\nCheck if read buffer is empty.\nCheck if write buffer is empty.\nCheck if write buffer is full.\nCheck if framed is able to write more data.\nDetermines if this writer has an efficient โ€ฆ\nCreates a new ReadBuf from a fully initialized buffer.\nThis function returns a single object that is both Stream โ€ฆ\nCreates a new default FramedParts.\nTry to read underlying I/O stream and decode item.\nAttempts to flush the object, ensuring that any buffered โ€ฆ\nAttempts to read from the AsyncRead into buf.\nTry to read data from an AsyncRead into an implementer of โ€ฆ\nInitiates or attempts to shut down this writer, returning โ€ฆ\nAttempt to write bytes from buf into the object.\nLike poll_write, except that it writes from a slice of โ€ฆ\nAppends data to the buffer, advancing the written position โ€ฆ\nThe buffer with read but unprocessed data.\nReturns the number of bytes at the end of the slice that โ€ฆ\nConsume the Frame, returning Frame with different codec.\nSets the size of the filled region of the buffer.\nReturns a new ReadBuf comprised of the unfilled section up โ€ฆ\nReturns a mutable reference to the unfilled part of the โ€ฆ\nCreates a new ReadBuf from a fully uninitialized buffer.\nCreates a new FramedParts with read buffer.\nSerialize item and write to the inner buffer\nA buffer with unprocessed data which are not written yet.") \ No newline at end of file diff --git a/search.desc/actix_macros/actix_macros-desc-0-.js b/search.desc/actix_macros/actix_macros-desc-0-.js new file mode 100644 index 00000000..7369b384 --- /dev/null +++ b/search.desc/actix_macros/actix_macros-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_macros", 0, "Macros for Actix system and runtime.\nMarks async entry-point function to be executed by Actix โ€ฆ\nMarks async test function to be executed in an Actix โ€ฆ") \ No newline at end of file diff --git a/search.desc/actix_rt/actix_rt-desc-0-.js b/search.desc/actix_rt/actix_rt-desc-0-.js new file mode 100644 index 00000000..23c629e5 --- /dev/null +++ b/search.desc/actix_rt/actix_rt-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_rt", 0, "Tokio-based single-threaded async runtime for the Actix โ€ฆ\nAn Arbiter represents a thread that provides an โ€ฆ\nA handle for sending spawn and stop messages to an Arbiter.\nA Tokio-based runtime proxy.\nA manager for a per-thread distributed async runtime.\nRunner that keeps a Systemโ€™s event loop alive until stop โ€ฆ\nGet handle to a the Systemโ€™s initial Arbiter.\nRuns the provided future, blocking the current thread โ€ฆ\nRuns the provided future, blocking the current thread โ€ฆ\nReturn a handle to the current threadโ€™s Arbiterโ€™s โ€ฆ\nGet current running system.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturn a handle to the this Arbiterโ€™s message sender.\nNumeric system identifier.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCheck if there is a System registered on the current โ€ฆ\nWait for Arbiterโ€™s event loop to complete.\nMarks async entry-point function to be executed by Actix โ€ฆ\nTCP/UDP/Unix bindings (mostly Tokio re-exports).\nSpawn a new Arbiter thread and start its event loop with โ€ฆ\nReturns a new runtime initialized with default โ€ฆ\nCreate a new system.\nPins a value on the stack.\nStarts event loop and will return once System is stopped.\nRuns the event loop until stopped, returning the exit code.\nAsynchronous signal handling (Tokio re-exports).\nSpawns a future on the current thread as a new task.\nSend a future to the Arbiterโ€™s thread and spawn it.\nSend a future to the Arbiterโ€™s thread and spawn it.\nOffload a future onto the single-threaded runtime.\nSend a function to the Arbiterโ€™s thread and execute it.\nSend a function to the Arbiterโ€™s thread and execute it.\nInstruct Arbiter to stop processing itโ€™s event loop.\nStop Arbiter from continuing itโ€™s event loop.\nStop the system (with code 0).\nStop the system with a given exit code.\nTask management (Tokio re-exports).\nMarks async test function to be executed in an Actix โ€ฆ\nUtilities for tracking time (Tokio re-exports).\nRetrieves a reference to the underlying Tokio runtime โ€ฆ\nTry to get current running arbiter handle.\nTry to get current running system.\nReturns a Ready representing readiness for all operations.\nReturns the empty Ready set.\nReturns a Ready representing error readiness.\nReturns a Ready representing priority readiness.\nReturns a Ready representing readable readiness.\nReturns a Ready representing read closed readiness.\nDescribes the readiness state of an I/O resources.\nA TCP socket server, listening for connections.\nA TCP socket that has not yet been converted to a TcpStreamโ€ฆ\nA TCP stream between a local and a remote socket.\nA UDP socket.\nAn I/O object representing a Unix datagram socket.\nA Unix socket which can accept connections from other Unix โ€ฆ\nA structure representing a connected Unix socket.\nReturns a Ready representing writable readiness.\nReturns a Ready representing write closed readiness.\nAccepts a new incoming connection from this listener.\nAccepts a new incoming connection to this listener.\nReads or writes from the socket using a user-provided IO โ€ฆ\nReads or writes from the socket using a user-provided IO โ€ฆ\nReads or writes from the socket using a user-provided IO โ€ฆ\nReads or writes from the socket using a user-provided IO โ€ฆ\nCreates a new TcpListener, which will be bound to the โ€ฆ\nBinds the socket to the given address.\nThis function will create a new UDP socket and attempt to โ€ฆ\nCreates a new UnixDatagram bound to the specified path.\nCreates a new UnixListener bound to the specified path.\nSets the value for the SO_BINDTODEVICE option on this โ€ฆ\nSets the value for the SO_BINDTODEVICE option on this โ€ฆ\nGets the value of the SO_BROADCAST option for this socket.\nEstablishes a TCP connection with a peer at the specified โ€ฆ\nOpens a TCP connection to a remote host.\nConnects the UDP socket setting the default destination โ€ฆ\nConnects the socket to the specified address.\nConnects to the socket named by path.\nGets the value for the SO_BINDTODEVICE option on this โ€ฆ\nGets the value for the SO_BINDTODEVICE option on this โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nConverts a RawFd to a TcpSocket.\nCreates new TcpListener from a std::net::TcpListener.\nCreates new TcpStream from a std::net::TcpStream.\nCreates new UdpSocket from a previously bound โ€ฆ\nCreates new UnixDatagram from a โ€ฆ\nCreates new UnixListener from a โ€ฆ\nCreates new UnixStream from a โ€ฆ\nConverts a std::net::TcpStream into a TcpSocket. The โ€ฆ\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nSplits a TcpStream into a read half and a write half, โ€ฆ\nSplits a UnixStream into a read half and a write half, โ€ฆ\nTurns a tokio::net::TcpListener into a โ€ฆ\nTurns a tokio::net::TcpStream into a std::net::TcpStream.\nTurns a tokio::net::UdpSocket into a std::net::UdpSocket.\nTurns a tokio::net::UnixDatagram into a โ€ฆ\nTurns a tokio::net::UnixListener into a โ€ฆ\nTurns a tokio::net::UnixStream into a โ€ฆ\nReturns true if Ready is the empty set.\nReturns true if the value includes error readiness.\nReturns true if the value includes priority readiness.\nReturns true if the value includes read-closed readiness.\nReturns true if the value includes readable.\nReturns true if the value includes writable readiness.\nReturns true if the value includes write-closed readiness.\nExecutes an operation of the IP_ADD_MEMBERSHIP type.\nExecutes an operation of the IPV6_ADD_MEMBERSHIP type.\nGets the value of the SO_KEEPALIVE option on this socket.\nExecutes an operation of the IP_DROP_MEMBERSHIP type.\nExecutes an operation of the IPV6_DROP_MEMBERSHIP type.\nReads the linger duration for this socket by getting the โ€ฆ\nReads the linger duration for this socket by getting the โ€ฆ\nConverts the socket into a TcpListener.\nReturns the local address that this listener is bound to.\nGets the local address of this socket.\nReturns the local address that this stream is bound to.\nReturns the local address that this socket is bound to.\nReturns the local address that this socket is bound to.\nReturns the local socket address of this listener.\nReturns the socket address of the local half of this โ€ฆ\nGets the value of the IP_MULTICAST_LOOP option for this โ€ฆ\nGets the value of the IPV6_MULTICAST_LOOP option for this โ€ฆ\nGets the value of the IP_MULTICAST_TTL option for this โ€ฆ\nCreates a new socket configured for IPv4.\nCreates a new socket configured for IPv6.\nGets the value of the TCP_NODELAY option on this socket.\nGets the value of the TCP_NODELAY option on this socket.\nCreates an unnamed pair of connected sockets.\nCreates an unnamed pair of connected sockets.\nReceives data on the socket from the remote address to โ€ฆ\nReceives data from the socket, without removing it from โ€ฆ\nRetrieve the sender of the data at the head of the input โ€ฆ\nReturns the remote address that this stream is connected โ€ฆ\nReturns the socket address of the remote peer this socket โ€ฆ\nReturns the address of this socketโ€™s peer.\nReturns the socket address of the remote half of this โ€ฆ\nReturns effective credentials of the process which called โ€ฆ\nPolls to accept a new incoming connection to this listener.\nPolls to accept a new incoming connection to this listener.\nAttempts to receive data on the socket, without removing โ€ฆ\nReceives data from the socket, without removing it from โ€ฆ\nRetrieve the sender of the data at the head of the input โ€ฆ\nPolls for read readiness.\nPolls for read readiness.\nAttempts to receive a single datagram message on the โ€ฆ\nAttempts to receive a single datagram message on the โ€ฆ\nAttempts to receive a single datagram on the socket.\nAttempts to receive a single datagram on the specified โ€ฆ\nPolls for read/receive readiness.\nPolls for read/receive readiness.\nAttempts to send data on the socket to the remote address โ€ฆ\nAttempts to send data on the socket to the remote address โ€ฆ\nPolls for write/send readiness.\nPolls for write/send readiness.\nAttempts to send data on the socket to a given address.\nAttempts to send data to the specified address.\nPolls for write readiness.\nPolls for write readiness.\nWaits for the socket to become readable.\nWaits for the socket to become readable.\nWaits for the socket to become readable.\nWaits for the socket to become readable.\nWaits for any of the requested ready states.\nWaits for any of the requested ready states.\nWaits for any of the requested ready states.\nWaits for any of the requested ready states.\nReceives a single datagram message on the socket from the โ€ฆ\nReceives data from the socket.\nReturns the size of the TCP receive buffer for this socket.\nReceives a single datagram message on the socket. On โ€ฆ\nReceives data from the socket.\nRetrieves the value set for SO_REUSEADDR on this socket.\nAllows the socket to bind to an in-use port. Only โ€ฆ\nSends data on the socket to the remote address that the โ€ฆ\nSends data on the socket to the socketโ€™s peer.\nReturns the size of the TCP send buffer for this socket.\nSends data on the socket to the given address. On success, โ€ฆ\nSends data on the socket to the specified address.\nSets the value of the SO_BROADCAST option for this socket.\nSets value for the SO_KEEPALIVE option on this socket.\nSets the linger duration of this socket by setting the โ€ฆ\nSets the linger duration of this socket by setting the โ€ฆ\nSets the value of the IP_MULTICAST_LOOP option for this โ€ฆ\nSets the value of the IPV6_MULTICAST_LOOP option for this โ€ฆ\nSets the value of the IP_MULTICAST_TTL option for this โ€ฆ\nSets the value of the TCP_NODELAY option on this socket.\nSets the value of the TCP_NODELAY option on this socket.\nSets the size of the TCP receive buffer on this socket.\nAllows the socket to bind to an in-use address.\nAllows the socket to bind to an in-use port. Only โ€ฆ\nSets the size of the TCP send buffer on this socket.\nSets the value for the IP_TOS option on this socket.\nSets the value for the IP_TOS option on this socket.\nSets the value for the IP_TTL option on this socket.\nSets the value for the IP_TTL option on this socket.\nSets the value for the IP_TTL option on this socket.\nShuts down the read, write, or both halves of this โ€ฆ\nSplits a TcpStream into a read half and a write half, โ€ฆ\nSplits a UnixStream into a read half and a write half, โ€ฆ\nReturns the value of the SO_ERROR option.\nReturns the value of the SO_ERROR option.\nReturns the value of the SO_ERROR option.\nReturns the value of the SO_ERROR option.\nReturns the value of the SO_ERROR option.\nReturns the value of the SO_ERROR option.\nGets the value of the IP_TOS option for this socket.\nGets the value of the IP_TOS option for this socket.\nConsumes stream, returning the tokio I/O object.\nConsumes stream, returning the tokio I/O object.\nConsumes stream, returning the tokio I/O object.\nConsumes stream, returning the Tokio I/O object.\nConsumes stream, returning the tokio I/O object.\nConsumes stream, returning the tokio I/O object.\nTries to read or write from the socket using a โ€ฆ\nTries to read or write from the socket using a โ€ฆ\nTries to read or write from the socket using a โ€ฆ\nTries to read or write from the socket using a โ€ฆ\nTries to receive data on the socket without removing it โ€ฆ\nTry to retrieve the sender of the data at the head of the โ€ฆ\nTries to read data from the stream into the provided โ€ฆ\nTry to read data from the stream into the provided buffer, โ€ฆ\nTries to read data from the stream into the provided โ€ฆ\nTries to read data from the stream into the provided โ€ฆ\nTries to receive a single datagram message on the socket โ€ฆ\nTries to receive a datagram from the peer without waiting.\nTries to receive a single datagram message on the socket. โ€ฆ\nTries to receive data from the socket without waiting.\nTries to send data on the socket to the remote address to โ€ฆ\nTries to send a datagram to the peer without waiting.\nTries to send data on the socket to the given address, but โ€ฆ\nTries to send a datagram to the peer without waiting.\nTry to write a buffer to the stream, returning how many โ€ฆ\nTries to write a buffer to the stream, returning how many โ€ฆ\nTries to write several buffers to the stream, returning โ€ฆ\nTries to write several buffers to the stream, returning โ€ฆ\nGets the value of the IP_TTL option for this socket.\nGets the value of the IP_TTL option for this socket.\nGets the value of the IP_TTL option for this socket.\nCreates a new UnixDatagram which is not bound to any โ€ฆ\nWaits for the socket to become writable.\nWaits for the socket to become writable.\nWaits for the socket to become writable.\nWaits for the socket to become writable.\nCompletes when a โ€œctrl-cโ€ notification is sent to the โ€ฆ\nUnix specific signals (Tokio re-exports).\nAn listener for receiving a particular type of OS signal.\nRepresents the specific kind of signal to listen for.\nRepresents the SIGALRM signal.\nGet the signalโ€™s numeric value.\nRepresents the SIGCHLD signal.\nReturns the argument unchanged.\nReturns the argument unchanged.\nAllows for listening to any valid OS signal.\nRepresents the SIGHUP signal.\nRepresents the SIGINT signal.\nCalls U::from(self).\nCalls U::from(self).\nRepresents the SIGIO signal.\nRepresents the SIGPIPE signal.\nPolls to receive the next signal notification event, โ€ฆ\nRepresents the SIGQUIT signal.\nReceives the next signal notification event.\nCreates a new listener which will receive notifications โ€ฆ\nRepresents the SIGTERM signal.\nRepresents the SIGUSR1 signal.\nRepresents the SIGUSR2 signal.\nRepresents the SIGWINCH signal.\nTask failed to execute to completion.\nAn owned permission to join on a task (await its โ€ฆ\nAbort the task associated with the handle.\nReturns a new AbortHandle that can be used to remotely โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nConsumes the join error, returning the object with which โ€ฆ\nReturns true if the error was caused by the task being โ€ฆ\nChecks if the task associated with this JoinHandle has โ€ฆ\nReturns true if the error was caused by the task panicking.\nRuns the provided closure on a thread where blocking is โ€ฆ\nConsumes the join error, returning the object with which โ€ฆ\nYields execution back to the Tokio runtime.\nA measurement of a monotonically nondecreasing clock. โ€ฆ\nInterval returned by interval and interval_at.\nFuture returned by sleep and sleep_until.\nFuture returned by timeout and timeout_at.\nReturns Some(t) where t is the time self + duration if t โ€ฆ\nReturns the amount of time elapsed from another instant to โ€ฆ\nReturns Some(t) where t is the time self - duration if t โ€ฆ\nReturns the instant at which the future will complete.\nReturns the amount of time elapsed from another instant to โ€ฆ\nReturns the amount of time elapsed since this instant was โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreate a tokio::time::Instant from a std::time::Instant.\nGets a mutable reference to the underlying value in this โ€ฆ\nGets a reference to the underlying value in this timeout.\nCreates new Interval that yields with interval of period. โ€ฆ\nCreates new Interval that yields with interval of period โ€ฆ\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConsumes this timeout, returning the underlying value.\nConvert the value into a std::time::Instant.\nReturns true if Sleep has elapsed.\nReturns the MissedTickBehavior strategy currently being โ€ฆ\nReturns an instant corresponding to โ€œnowโ€.\nReturns the period of the interval.\nPolls for the next instant in the interval to be reached.\nResets the interval to complete one period after the โ€ฆ\nResets the Sleep instance to a new deadline.\nResets the interval after the specified std::time::Durationโ€ฆ\nResets the interval to a crate::time::Instant deadline.\nResets the interval immediately.\nReturns the amount of time elapsed from another instant to โ€ฆ\nSets the MissedTickBehavior strategy that should be used.\nWaits until duration has elapsed.\nWaits until deadline is reached.\nCompletes when the next instant in the interval has been โ€ฆ\nRequires a Future to complete before the specified โ€ฆ") \ No newline at end of file diff --git a/search.desc/actix_server/actix_server-desc-0-.js b/search.desc/actix_server/actix_server-desc-0-.js new file mode 100644 index 00000000..6831a683 --- /dev/null +++ b/search.desc/actix_server/actix_server-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_server", 0, "General purpose TCP server.\nMPTCP will not be used when binding sockets.\nMultipath TCP (MPTCP) preference.\nMPTCP will be used when binding sockets (with no fallback).\nGeneral purpose TCP server that runs services receiving โ€ฆ\nServer builder.\nServer handle.\nMPTCP will be attempted when binding sockets. If errors โ€ฆ\nA testing server.\nSet the maximum number of pending connections.\nAdds new service to the server.\nAdds new service to the server using a UDS (unix domain โ€ฆ\nCreate server build.\nDisables OS signal handling.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nGet a Server handle that can be used issue commands and โ€ฆ\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nAdds service to the server using a socket listener already โ€ฆ\nAdds new service to the server using a UDS (unix domain โ€ฆ\nSets the maximum per-worker number of concurrent โ€ฆ\nSets MultiPath TCP (MPTCP) preference on bound sockets.\nCreate new Server builder instance\nPause accepting incoming connections.\nResume accepting incoming connections.\nStarts processing incoming connections and return server โ€ฆ\nTimeout for graceful workers shutdown in seconds.\nStart new TestServer using application factory and default โ€ฆ\nStart new TestServer using application factory and server โ€ฆ\nStop incoming connection processing, stop all workers and โ€ฆ\nSets flag to stop Actix System after server shutdown.\nGet first available unused local address.\nSet max number of threads for each workerโ€™s blocking โ€ฆ\nSets number of workers to start.") \ No newline at end of file diff --git a/search.desc/actix_service/actix_service-desc-0-.js b/search.desc/actix_service/actix_service-desc-0-.js new file mode 100644 index 00000000..52925fd1 --- /dev/null +++ b/search.desc/actix_service/actix_service-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_service", 0, "See Service docs for information on this crateโ€™s โ€ฆ\nApply a Transform to a Service.\nService factory configuration.\nErrors produced by the service.\nErrors produced by the service when polling readiness or โ€ฆ\nErrors produced by the created services.\nThe future response value.\nThe future response value.\nThe future of the Service instance.g\nErrors produced while building a transform service.\nErrors potentially raised while building a service.\nTrait for types that can be converted to a Service\nTrait for types that can be converted to a ServiceFactory\nResponses produced by the service.\nResponses given by the service.\nResponses given by the created services.\nAn asynchronous operation from Request to a Response.\nThe kind of Service created by this factory.\nAn extension trait for Services that provides a variety of โ€ฆ\nFactory for creating Services.\nAn extension trait for ServiceFactorys that provides a โ€ฆ\nDefines the interface of a service factory that wraps โ€ฆ\nThe TransformService value created by this factory\nAn extension trait for Transforms that provides a variety โ€ฆ\nAn implementation of poll_ready that always signals โ€ฆ\nCall another service after call to this one has resolved โ€ฆ\nCall another service after call to this one has resolved โ€ฆ\nCall another service after call to this one has resolved โ€ฆ\nCall another service after call to this one has resolved โ€ฆ\nApply a Transform to a Service.\nConvert Fn(Config, &Service1) -> Future<Service2> fn to a โ€ฆ\nConvert โ€ฆ\nApply transform function to a service.\nService factory that produces apply_fn service.\nTrait object forms of services and service factories.\nProcess the request and return the response asynchronously.\nCreate ServiceFactory for function that can produce โ€ฆ\nCreate ServiceFactory for function that accepts config โ€ฆ\nCreate ServiceFactory for function that can act as a โ€ฆ\nAn implementation of poll_ready that forwards readiness โ€ฆ\nReturns the argument unchanged.\nCalls U::from(self).\nConvert Self to a ServiceFactory\nConvert object of type U to a service S\nConvert to a Service\nMap this serviceโ€™s output to a different type, returning โ€ฆ\nMap this serviceโ€™s output to a different type, returning โ€ฆ\nMap this serviceโ€™s output to a different type, returning โ€ฆ\nMap this serviceโ€™s output to a different type, returning โ€ฆ\nAdapt external config argument to a config for provided โ€ฆ\nMap this serviceโ€™s error to a different error, returning โ€ฆ\nMap this serviceโ€™s error to a different error, returning โ€ฆ\nMap this serviceโ€™s error to a different error, returning โ€ฆ\nMap this serviceโ€™s error to a different error, returning โ€ฆ\nMap this factoryโ€™s init error to a different error, โ€ฆ\nMap this factoryโ€™s init error to a different error, โ€ฆ\nReturn a new Transform whose init error is mapped to to a โ€ฆ\nReturn a new Transform whose init error is mapped to to a โ€ฆ\nCreate and return a new service asynchronously.\nCreates and returns a new Transform component, โ€ฆ\nReturns Ready when the service is able to process requests.\nReplace config with unit.\nA boxed future with no send bound or lifetime parameters.\nType alias for service trait object using Box.\nWrapper for a service factory that will map itโ€™s โ€ฆ\nType alias for service trait object using Rc.\nWraps a service factory that returns service trait objects.\nReturns the argument unchanged.\nCalls U::from(self).\nWraps service as a trait object using RcService.\nWraps service as a trait object using BoxService.") \ No newline at end of file diff --git a/search.desc/actix_tls/actix_tls-desc-0-.js b/search.desc/actix_tls/actix_tls-desc-0-.js new file mode 100644 index 00000000..8d6df802 --- /dev/null +++ b/search.desc/actix_tls/actix_tls-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_tls", 0, "TLS acceptor and connector services for the Actix โ€ฆ\nTLS connection acceptor services.\nTCP and TLS connector services.\nWraps service errors.\nTLS handshake has timed-out.\nWraps TLS service errors.\nTLS handshake error, TLS timeout, or inner service error.\nReturns the argument unchanged.\nCalls U::from(self).\nCasts the infallible service error type returned from โ€ฆ\nSets the maximum per-worker concurrent TLS connection โ€ฆ\nnative-tls based TLS connection acceptor service.\nopenssl based TLS acceptor service.\nrustls v0.20 based TLS connection acceptor service.\nrustls v0.21 based TLS connection acceptor service.\nrustls v0.22 based TLS connection acceptor service.\nrustls v0.23 based TLS connection acceptor service.\nAccept TLS connections via the native-tls crate.\nNative-TLS based acceptor service.\nWraps a native-tls based async TLS stream in order to โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConstructs native-tls based acceptor service factory.\nRe-exports from native-tls that are useful for acceptors.\nLimit the amount of time that the acceptor will wait for a โ€ฆ\nAn error returned from the TLS implementation.\nA wrapper around a native_tls::TlsAcceptor, providing an โ€ฆ\nAccepts a new client connection with the provided stream.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nAccept TLS connections via the openssl crate.\nOpenSSL based acceptor service.\nWraps an openssl based async TLS stream in order to โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCreate openssl based acceptor service factory.\nRe-exports from openssl that are useful for acceptors.\nLimit the amount of time that the acceptor will wait for a โ€ฆ\nTerminate the handshake with a fatal alert.\nAn error returned from an ALPN selection callback.\nAn SSL error.\nThe handshake failed.\nAn error or intermediate state after a TLS handshake โ€ฆ\nDo not select a protocol, but continue the handshake.\nSetup failed.\nThe state of an SSL/TLS session.\nA type which wraps server-side streams in a TLS session.\nA builder for SslAcceptors.\nThe handshake encountered a WouldBlock error midway โ€ฆ\nInitiates a server-side TLS session on a stream.\nInitiates a server-side TLS handshake.\nConsumes the builder, returning a SslAcceptor.\nInitiates a client-side TLS handshake.\nReturns a shared reference to the inner raw SslContext.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConsumes the SslAcceptor, returning the inner raw โ€ฆ\nCreates a new builder configured to connect to non-legacy โ€ฆ\nCreates a new builder configured to connect to non-legacy โ€ฆ\nCreates a new builder configured to connect to modern โ€ฆ\nCreates a new builder configured to connect to modern โ€ฆ\nCreates a new Ssl.\nReturns a new extra data index.\nAccept TLS connections via the rustls crate.\nRustls based acceptor service.\nWraps a rustls based async TLS stream in order to โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConstructs rustls based acceptor service factory.\nRe-exports from rustls that are useful for acceptors.\nLimit the amount of time that the acceptor will wait for a โ€ฆ\nCommon configuration for a set of server sessions.\nProtocol names we support, most preferred first. If empty โ€ฆ\nCreate builder to build up the server configuration.\nHow to choose a server cert and key.\nReturns the argument unchanged.\nIgnore the clientโ€™s ciphersuite order. Instead, choose โ€ฆ\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nAmount of early data to accept for sessions created by โ€ฆ\nThe maximum size of TLS message weโ€™ll emit. If None, we โ€ฆ\nWhether the server should send โ€œ0.5RTTโ€ data. This โ€ฆ\nHow to store client sessions.\nHow to produce tickets.\nAccept TLS connections via the rustls crate.\nRustls based acceptor service.\nWraps a rustls based async TLS stream in order to โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConstructs rustls based acceptor service factory.\nRe-exports from rustls that are useful for acceptors.\nLimit the amount of time that the acceptor will wait for a โ€ฆ\nCommon configuration for a set of server sessions.\nProtocol names we support, most preferred first. If empty โ€ฆ\nCreate builder to build up the server configuration.\nHow to choose a server cert and key.\nReturns the argument unchanged.\nIgnore the clientโ€™s ciphersuite order. Instead, choose โ€ฆ\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nAmount of early data to accept for sessions created by โ€ฆ\nThe maximum size of TLS message weโ€™ll emit. If None, we โ€ฆ\nWhether the server should send โ€œ0.5RTTโ€ data. This โ€ฆ\nHow many TLS1.3 tickets to send immediately after a โ€ฆ\nHow to store client sessions.\nHow to produce tickets.\nAccept TLS connections via the rustls crate.\nRustls based acceptor service.\nWraps a rustls based async TLS stream in order to โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConstructs rustls based acceptor service factory.\nRe-exports from rustls that are useful for acceptors.\nLimit the amount of time that the acceptor will wait for a โ€ฆ\nCommon configuration for a set of server sessions.\nProtocol names we support, most preferred first. If empty โ€ฆ\nCreate a builder for a server configuration with the โ€ฆ\nCreate a builder for a server configuration with the โ€ฆ\nCreate a builder for a server configuration with a โ€ฆ\nHow to choose a server cert and key. This is usually set by\nAllows traffic secrets to be extracted after the handshake,\nReturns the argument unchanged.\nIgnore the clientโ€™s ciphersuite order. Instead, choose โ€ฆ\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nAmount of early data to accept for sessions created by โ€ฆ\nThe maximum size of plaintext input to be emitted in a โ€ฆ\nWhether the server should send โ€œ0.5RTTโ€ data. This โ€ฆ\nHow many TLS1.3 tickets to send immediately after a โ€ฆ\nHow to store client sessions.\nHow to produce tickets.\nAccept TLS connections via the rustls crate.\nRustls based acceptor service.\nWraps a rustls based async TLS stream in order to โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConstructs rustls based acceptor service factory.\nRe-exports from rustls that are useful for acceptors.\nLimit the amount of time that the acceptor will wait for a โ€ฆ\nCommon configuration for a set of server sessions.\nProtocol names we support, most preferred first. If empty โ€ฆ\nCreate a builder for a server configuration with the โ€ฆ\nCreate a builder for a server configuration with no โ€ฆ\nCreate a builder for a server configuration with the โ€ฆ\nCreate a builder for a server configuration with a โ€ฆ\nCaching for compressed certificates.\nHow to compress the serverโ€™s certificate chain.\nHow to decompress the clientsโ€™s certificate chain.\nHow to choose a server cert and key. This is usually set by\nReturn the crypto provider used to construct this client โ€ฆ\nAllows traffic secrets to be extracted after the handshake,\nReturn true if connections made with this ServerConfig will\nReturns the argument unchanged.\nIgnore the clientโ€™s ciphersuite order. Instead, choose โ€ฆ\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nAmount of early data to accept for sessions created by โ€ฆ\nThe maximum size of plaintext input to be emitted in a โ€ฆ\nWhether the server should send โ€œ0.5RTTโ€ data. This โ€ฆ\nHow many TLS1.3 tickets to send immediately after a โ€ฆ\nHow to store client sessions.\nHow to produce tickets.\nProvides the current system time\nErrors that can result from using a connector service.\nConnection request information.\nWraps underlying I/O and the connection request that โ€ฆ\nCombined resolver and TCP connector service factory.\nCombined resolver and TCP connector service.\nAn interface for types where host parts (hostname and โ€ฆ\nInvalid input.\nConnection IO error.\nNo DNS records.\nCustom async DNS resolvers.\nDNS resolver service factory.\nFailed to resolve the hostname.\nDNS resolver service.\nUnresolved host name.\nGet borrowed iterator of resolved request addresses.\nConstructs a new resolver factory with a custom resolver.\nConstructor for custom Resolve trait object and use it as โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nExtract hostname.\nReturns hostname.\nReturns request hostname.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nDeconstructs into IO and request parts.\nReturns a mutable reference to the underlying IO.\nReturns a shared reference to the underlying IO.\nGiven DNS lookup information, returns a future that โ€ฆ\nNative-TLS based connector service.\nConstruct new Connection from request and IO parts.\nConstructs new connector factory with the given resolver.\nConstructs new connection info using a request.\nOpenSSL based connector service.\nExtract optional port.\nExtract optional port.\nReturns request port.\nReplaces underlying IO, returning old IO and new Connectionโ€ฆ\nReturns a reference to the connection request.\nReturns a reference to the connection request.\nRustls based connector service.\nRustls based connector service.\nRustls based connector service.\nRustls based connector service.\nBuild connector service.\nReturns a new resolver service.\nSet connection socket address.\nSet list of addresses.\nSet local address to connection with.\nSet connection port.\nTake owned iterator resolved request addresses.\nTCP connector service.\nConstructs new connection info from request and known โ€ฆ\nConnector service and factory using native-tls.\nReturns the argument unchanged.\nCalls U::from(self).\nConstructs new connector service from a native-tls โ€ฆ\nRe-exports from native-tls and tokio-native-tls that are โ€ฆ\nA wrapper around an underlying raw stream which implements โ€ฆ\nA builder for client-side TLS connections.\nReturns a new builder for a TlsConnector.\nInitiates a TLS handshake.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns a mutable reference to the inner stream.\nReturns a shared reference to the inner stream.\nCalls U::from(self).\nCalls U::from(self).\nReturns a new connector with default settings.\nConnector service factory using openssl.\nConnector service using openssl.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nConstructs new connector service factory from an openssl โ€ฆ\nRe-exports from openssl and tokio-openssl that are useful โ€ฆ\nConstructs new connector service from an openssl connector.\nAn asynchronous version of openssl::ssl::SslStream.\nAn SSL error.\nThe handshake failed.\nAn error or intermediate state after a TLS handshake โ€ฆ\nSetup failed.\nA type which wraps client-side streams in a TLS session.\nA builder for SslConnectors.\nA type specifying the kind of protocol an SslContext will โ€ฆ\nThe handshake encountered a WouldBlock error midway โ€ฆ\nA convenience method wrapping poll_accept.\nReturns a pointer to the underlying OpenSSL value.\nConsumes the builder, returning an SslConnector.\nCreates a new builder for TLS connections.\nReturns a structure allowing for configuration of a single โ€ฆ\nA convenience method wrapping poll_connect.\nInitiates a client-side TLS session on a stream.\nReturns a shared reference to the inner raw SslContext.\nA convenience method wrapping poll_do_handshake.\nSupport all versions of the DTLS protocol.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nConstructs an SslMethod from a pointer to the underlying โ€ฆ\nReturns a mutable reference to the underlying stream.\nReturns a pinned mutable reference to the underlying โ€ฆ\nReturns a shared reference to the underlying stream.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConsumes the SslConnector, returning the inner raw โ€ฆ\nLike SslStream::new.\nA convenience method wrapping poll_peek.\nLike SslStream::accept.\nLike SslStream::connect.\nLike SslStream::do_handshake.\nLike SslStream::ssl_peek.\nLike SslStream::read_early_data.\nLike SslStream::write_early_data.\nA convenience method wrapping poll_read_early_data.\nReturns a shared reference to the Ssl object associated โ€ฆ\nSupport all versions of the TLS protocol.\nSupport all versions of the TLS protocol, explicitly as a โ€ฆ\nSupport all versions of the TLS protocol, explicitly as a โ€ฆ\nA convenience method wrapping poll_write_early_data.\nConnector service factory using rustls.\nConnector service using rustls.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nReturns root certificates via rustls-native-certs crate as โ€ฆ\nConstructs new connector service factory from a rustls โ€ฆ\nRe-exports from the rustls v0.20 ecosystem that are useful โ€ฆ\nConstructs new connector service from a rustls client โ€ฆ\nReturns standard root certificates from webpki-roots crate โ€ฆ\nA wrapper around an underlying raw stream which implements โ€ฆ\nCommon configuration for (typically) all connections made โ€ฆ\nWhich ALPN protocols we include in our client hello. If โ€ฆ\nCreate a builder to build up the client configuration.\nHow to decide what client auth certificate/keys to use.\nWhether to send data on the first flight (โ€œearly dataโ€โ€ฆ\nWhether to send the Server Name Indication (SNI) extension โ€ฆ\nWhether to support RFC5077 tickets. You must provide a โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nThe maximum size of TLS message weโ€™ll emit. If None, we โ€ฆ\nNote: that it does not guarantee the final data to be sent.\nHow we store session data or tickets.\nConnector service factory using rustls.\nConnector service using rustls.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nReturns root certificates via rustls-native-certs crate as โ€ฆ\nConstructs new connector service factory from a rustls โ€ฆ\nRe-exports from the rustls v0.21 ecosystem that are useful โ€ฆ\nConstructs new connector service from a rustls client โ€ฆ\nReturns standard root certificates from webpki-roots crate โ€ฆ\nA wrapper around an underlying raw stream which implements โ€ฆ\nCommon configuration for (typically) all connections made โ€ฆ\nWhich ALPN protocols we include in our client hello. If โ€ฆ\nCreate a builder to build up the client configuration.\nHow to decide what client auth certificate/keys to use.\nWhether to send data on the first flight (โ€œearly dataโ€โ€ฆ\nWhether to send the Server Name Indication (SNI) extension โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nThe maximum size of TLS message weโ€™ll emit. If None, we โ€ฆ\nNote: that it does not guarantee the final data to be sent.\nHow and when the client can resume a previous session.\nConnector service factory using rustls.\nConnector service using rustls.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nReturns root certificates via rustls-native-certs crate as โ€ฆ\nConstructs new connector service factory from a rustls โ€ฆ\nRe-exports from the rustls v0.22 ecosystem that are useful โ€ฆ\nConstructs new connector service from a rustls client โ€ฆ\nReturns standard root certificates from webpki-roots crate โ€ฆ\nA wrapper around an underlying raw stream which implements โ€ฆ\nCommon configuration for (typically) all connections made โ€ฆ\nWhich ALPN protocols we include in our client hello. If โ€ฆ\nCreate a builder for a client configuration with the โ€ฆ\nCreate a builder for a client configuration with the โ€ฆ\nCreate a builder for a client configuration with a โ€ฆ\nHow to decide what client auth certificate/keys to use.\nAccess configuration options whose use is dangerous and โ€ฆ\nWhether to send data on the first flight (โ€œearly dataโ€โ€ฆ\nAllows traffic secrets to be extracted after the handshake,\nWhether to send the Server Name Indication (SNI) extension โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nThe maximum size of plaintext input to be emitted in a โ€ฆ\nNote: that it does not guarantee the final data to be sent.\nHow and when the client can resume a previous session.\nConnector service factory using rustls.\nConnector service using rustls.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nReturns root certificates via rustls-native-certs crate as โ€ฆ\nConstructs new connector service factory from a rustls โ€ฆ\nRe-exports from the rustls v0.23 ecosystem that are useful โ€ฆ\nConstructs new connector service from a rustls client โ€ฆ\nReturns standard root certificates from webpki-roots crate โ€ฆ\nA wrapper around an underlying raw stream which implements โ€ฆ\nCommon configuration for (typically) all connections made โ€ฆ\nWhich ALPN protocols we include in our client hello. If โ€ฆ\nCreate a builder for a client configuration with the โ€ฆ\nCreate a builder for a client configuration with no โ€ฆ\nCreate a builder for a client configuration with the โ€ฆ\nCreate a builder for a client configuration with a โ€ฆ\nCaching for compressed certificates.\nHow to compress the clientโ€™s certificate chain.\nHow to decompress the serverโ€™s certificate chain.\nHow to decide what client auth certificate/keys to use.\nReturn the crypto provider used to construct this client โ€ฆ\nAccess configuration options whose use is dangerous and โ€ฆ\nWhether to send data on the first flight (โ€œearly dataโ€โ€ฆ\nAllows traffic secrets to be extracted after the handshake,\nWhether to send the Server Name Indication (SNI) extension โ€ฆ\nReturn true if connections made with this ClientConfig will\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nHow to output key material for debugging. The default โ€ฆ\nThe maximum size of plaintext input to be emitted in a โ€ฆ\nNote: that it does not guarantee the final data to be sent.\nNote: that it does not guarantee the final data to be sent.\nHow and when the client can resume a previous session.\nProvides the current system time\nTCP connector service factory.\nTCP connector service.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nReturns a new TCP connector service.") \ No newline at end of file diff --git a/search.desc/actix_tracing/actix_tracing-desc-0-.js b/search.desc/actix_tracing/actix_tracing-desc-0-.js new file mode 100644 index 00000000..047ddb25 --- /dev/null +++ b/search.desc/actix_tracing/actix_tracing-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_tracing", 0, "Actix tracing - support for tokio tracing with Actix โ€ฆ\nA Service implementation that automatically enters/exits โ€ฆ\nA Transform implementation that wraps services with a โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nWraps the provided service factory with a transform that โ€ฆ") \ No newline at end of file diff --git a/search.desc/actix_utils/actix_utils-desc-0-.js b/search.desc/actix_utils/actix_utils-desc-0-.js new file mode 100644 index 00000000..3ca2bb2f --- /dev/null +++ b/search.desc/actix_utils/actix_utils-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("actix_utils", 0, "Various utilities used in the Actix ecosystem.\nTask-notifying counter.\nHelpers for constructing futures.\nSimple counter with ability to notify task on reaching โ€ฆ\nAn RAII structure that keeps the underlying counter โ€ฆ\nReturns true if counter is below capacity. Otherwise, โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreate new counter guard, incrementing the counter.\nCalls U::from(self).\nCalls U::from(self).\nCreate Counter instance with max value.\nGet total number of acquired guards.\nCombines two different futures that have the same output โ€ฆ\nA value of type L.\nFuture for the poll_fn function.\nFuture for the ready function.\nA value of type R.\nCreates a future that is immediately ready with an error โ€ฆ\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nUnwraps into inner value when left and right have a common โ€ฆ\nUnwraps the value from this immediately ready future.\nCreates new Either using left variant.\nCreates a future that is immediately ready with a success โ€ฆ\nCreates a future driven by the provided function that โ€ฆ\nCreates a future that is immediately ready with a value.\nCreates new Either using right variant.") \ No newline at end of file diff --git a/search.desc/bytestring/bytestring-desc-0-.js b/search.desc/bytestring/bytestring-desc-0-.js new file mode 100644 index 00000000..dae1c3af --- /dev/null +++ b/search.desc/bytestring/bytestring-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("bytestring", 0, "A UTF-8 encoded read-only string using Bytes as storage.\nAn immutable UTF-8 encoded string with Bytes as a storage.\nGet a reference to the underlying Bytes object.\nReturns the argument unchanged.\nCreates a new ByteString from a Bytes.\nCreates a new ByteString from a &'static str.\nCalls U::from(self).\nUnwraps this ByteString into the underlying Bytes object.\nCreates a new empty ByteString.\nReturns a new byte string that is equivalent to the given โ€ฆ") \ No newline at end of file diff --git a/search.desc/local_channel/local_channel-desc-0-.js b/search.desc/local_channel/local_channel-desc-0-.js new file mode 100644 index 00000000..dde61ec3 --- /dev/null +++ b/search.desc/local_channel/local_channel-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("local_channel", 0, "Non-thread-safe channels.\nA non-thread-safe multi-producer, single-consumer, โ€ฆ\nThe receiving end of a channel which implements the Stream โ€ฆ\nError returned when attempting to send after the channelsโ€ฆ\nThe transmission end of a channel.\nCreates a unbounded in-memory channel with buffered โ€ฆ\nCloses the sender half.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nReturns the message that was attempted to be sent but โ€ฆ\nReceive the next value.\nSends the provided message along this channel.\nCreate an associated Sender.") \ No newline at end of file diff --git a/search.desc/local_waker/local_waker-desc-0-.js b/search.desc/local_waker/local_waker-desc-0-.js new file mode 100644 index 00000000..e2c3414a --- /dev/null +++ b/search.desc/local_waker/local_waker-desc-0-.js @@ -0,0 +1 @@ +searchState.loadedDescShard("local_waker", 0, "A synchronization primitive for thread-local task wakeup.\nA synchronization primitive for task wakeup.\nReturns the argument unchanged.\nCalls U::from(self).\nCreates a new, empty LocalWaker.\nRegisters the waker to be notified on calls to wake.\nReturns the last Waker passed to register, so that the โ€ฆ\nCalls wake on the last Waker passed to register.") \ No newline at end of file diff --git a/settings.html b/settings.html new file mode 100644 index 00000000..12fdb826 --- /dev/null +++ b/settings.html @@ -0,0 +1 @@ +Settings

Rustdoc settings

Back
\ No newline at end of file diff --git a/src-files.js b/src-files.js new file mode 100644 index 00000000..198adb61 --- /dev/null +++ b/src-files.js @@ -0,0 +1,3 @@ +var srcIndex = new Map(JSON.parse('[["actix_codec",["",[],["bcodec.rs","framed.rs","lib.rs","lines.rs"]]],["actix_macros",["",[],["lib.rs"]]],["actix_rt",["",[],["arbiter.rs","lib.rs","runtime.rs","system.rs"]]],["actix_server",["",[],["accept.rs","availability.rs","builder.rs","handle.rs","join_all.rs","lib.rs","server.rs","service.rs","signals.rs","socket.rs","test_server.rs","waker_queue.rs","worker.rs"]]],["actix_service",["",[],["and_then.rs","apply.rs","apply_cfg.rs","boxed.rs","ext.rs","fn_service.rs","lib.rs","macros.rs","map.rs","map_config.rs","map_err.rs","map_init_err.rs","pipeline.rs","ready.rs","then.rs","transform.rs","transform_err.rs"]]],["actix_tls",["",[["accept",[],["mod.rs","native_tls.rs","openssl.rs","rustls_0_20.rs","rustls_0_21.rs","rustls_0_22.rs","rustls_0_23.rs"]],["connect",[],["connect_addrs.rs","connection.rs","connector.rs","error.rs","host.rs","info.rs","mod.rs","native_tls.rs","openssl.rs","resolve.rs","resolver.rs","rustls_0_20.rs","rustls_0_21.rs","rustls_0_22.rs","rustls_0_23.rs","tcp.rs","uri.rs"]]],["lib.rs"]]],["actix_tracing",["",[],["lib.rs"]]],["actix_utils",["",[["future",[],["either.rs","mod.rs","poll_fn.rs","ready.rs"]]],["counter.rs","lib.rs"]]],["bytestring",["",[],["lib.rs"]]],["local_channel",["",[],["lib.rs","mpsc.rs"]]],["local_waker",["",[],["lib.rs"]]]]')); +createSrcSidebar(); +//{"start":36,"fragment_lengths":[69,36,70,201,250,403,37,108,34,47,35]} \ No newline at end of file diff --git a/src/actix_codec/bcodec.rs.html b/src/actix_codec/bcodec.rs.html new file mode 100644 index 00000000..ac08d196 --- /dev/null +++ b/src/actix_codec/bcodec.rs.html @@ -0,0 +1,65 @@ +bcodec.rs - source

actix_codec/
bcodec.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
use std::io;
+
+use bytes::{Buf, Bytes, BytesMut};
+
+use super::{Decoder, Encoder};
+
+/// Bytes codec. Reads/writes chunks of bytes from a stream.
+#[derive(Debug, Copy, Clone)]
+pub struct BytesCodec;
+
+impl Encoder<Bytes> for BytesCodec {
+    type Error = io::Error;
+
+    #[inline]
+    fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
+        dst.extend_from_slice(item.chunk());
+        Ok(())
+    }
+}
+
+impl Decoder for BytesCodec {
+    type Item = BytesMut;
+    type Error = io::Error;
+
+    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
+        if src.is_empty() {
+            Ok(None)
+        } else {
+            Ok(Some(src.split()))
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_codec/framed.rs.html b/src/actix_codec/framed.rs.html new file mode 100644 index 00000000..f0f0c57e --- /dev/null +++ b/src/actix_codec/framed.rs.html @@ -0,0 +1,825 @@ +framed.rs - source

actix_codec/
framed.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
use std::{
+    fmt, io,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use bitflags::bitflags;
+use bytes::{Buf, BytesMut};
+use futures_core::{ready, Stream};
+use futures_sink::Sink;
+use pin_project_lite::pin_project;
+
+use crate::{AsyncRead, AsyncWrite, Decoder, Encoder};
+
+/// Low-water mark
+const LW: usize = 1024;
+/// High-water mark
+const HW: usize = 8 * 1024;
+
+bitflags! {
+    #[derive(Debug, Clone, Copy)]
+    struct Flags: u8 {
+        const EOF = 0b0001;
+        const READABLE = 0b0010;
+    }
+}
+
+pin_project! {
+    /// A unified `Stream` and `Sink` interface to an underlying I/O object, using the `Encoder` and
+    /// `Decoder` traits to encode and decode frames.
+    ///
+    /// Raw I/O objects work with byte sequences, but higher-level code usually wants to batch these
+    /// into meaningful chunks, called "frames". This method layers framing on top of an I/O object,
+    /// by using the `Encoder`/`Decoder` traits to handle encoding and decoding of message frames.
+    /// Note that the incoming and outgoing frame types may be distinct.
+    pub struct Framed<T, U> {
+        #[pin]
+        io: T,
+        codec: U,
+        flags: Flags,
+        read_buf: BytesMut,
+        write_buf: BytesMut,
+    }
+}
+
+impl<T, U> Framed<T, U>
+where
+    T: AsyncRead + AsyncWrite,
+    U: Decoder,
+{
+    /// This function returns a *single* object that is both `Stream` and `Sink`; grouping this into
+    /// a single object is often useful for layering things like gzip or TLS, which require both
+    /// read and write access to the underlying object.
+    pub fn new(io: T, codec: U) -> Framed<T, U> {
+        Framed {
+            io,
+            codec,
+            flags: Flags::empty(),
+            read_buf: BytesMut::with_capacity(HW),
+            write_buf: BytesMut::with_capacity(HW),
+        }
+    }
+}
+
+impl<T, U> Framed<T, U> {
+    /// Returns a reference to the underlying codec.
+    pub fn codec_ref(&self) -> &U {
+        &self.codec
+    }
+
+    /// Returns a mutable reference to the underlying codec.
+    pub fn codec_mut(&mut self) -> &mut U {
+        &mut self.codec
+    }
+
+    /// Returns a reference to the underlying I/O stream wrapped by `Frame`.
+    ///
+    /// Note that care should be taken to not tamper with the underlying stream of data coming in as
+    /// it may corrupt the stream of frames otherwise being worked with.
+    pub fn io_ref(&self) -> &T {
+        &self.io
+    }
+
+    /// Returns a mutable reference to the underlying I/O stream.
+    ///
+    /// Note that care should be taken to not tamper with the underlying stream of data coming in as
+    /// it may corrupt the stream of frames otherwise being worked with.
+    pub fn io_mut(&mut self) -> &mut T {
+        &mut self.io
+    }
+
+    /// Returns a `Pin` of a mutable reference to the underlying I/O stream.
+    pub fn io_pin(self: Pin<&mut Self>) -> Pin<&mut T> {
+        self.project().io
+    }
+
+    /// Check if read buffer is empty.
+    pub fn is_read_buf_empty(&self) -> bool {
+        self.read_buf.is_empty()
+    }
+
+    /// Check if write buffer is empty.
+    pub fn is_write_buf_empty(&self) -> bool {
+        self.write_buf.is_empty()
+    }
+
+    /// Check if write buffer is full.
+    pub fn is_write_buf_full(&self) -> bool {
+        self.write_buf.len() >= HW
+    }
+
+    /// Check if framed is able to write more data.
+    ///
+    /// `Framed` object considers ready if there is free space in write buffer.
+    pub fn is_write_ready(&self) -> bool {
+        self.write_buf.len() < HW
+    }
+
+    /// Consume the `Frame`, returning `Frame` with different codec.
+    pub fn replace_codec<U2>(self, codec: U2) -> Framed<T, U2> {
+        Framed {
+            codec,
+            io: self.io,
+            flags: self.flags,
+            read_buf: self.read_buf,
+            write_buf: self.write_buf,
+        }
+    }
+
+    /// Consume the `Frame`, returning `Frame` with different io.
+    pub fn into_map_io<F, T2>(self, f: F) -> Framed<T2, U>
+    where
+        F: Fn(T) -> T2,
+    {
+        Framed {
+            io: f(self.io),
+            codec: self.codec,
+            flags: self.flags,
+            read_buf: self.read_buf,
+            write_buf: self.write_buf,
+        }
+    }
+
+    /// Consume the `Frame`, returning `Frame` with different codec.
+    pub fn into_map_codec<F, U2>(self, f: F) -> Framed<T, U2>
+    where
+        F: Fn(U) -> U2,
+    {
+        Framed {
+            io: self.io,
+            codec: f(self.codec),
+            flags: self.flags,
+            read_buf: self.read_buf,
+            write_buf: self.write_buf,
+        }
+    }
+}
+
+impl<T, U> Framed<T, U> {
+    /// Serialize item and write to the inner buffer
+    pub fn write<I>(mut self: Pin<&mut Self>, item: I) -> Result<(), <U as Encoder<I>>::Error>
+    where
+        T: AsyncWrite,
+        U: Encoder<I>,
+    {
+        let this = self.as_mut().project();
+        let remaining = this.write_buf.capacity() - this.write_buf.len();
+        if remaining < LW {
+            this.write_buf.reserve(HW - remaining);
+        }
+
+        this.codec.encode(item, this.write_buf)?;
+        Ok(())
+    }
+
+    /// Try to read underlying I/O stream and decode item.
+    pub fn next_item(
+        mut self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+    ) -> Poll<Option<Result<<U as Decoder>::Item, U::Error>>>
+    where
+        T: AsyncRead,
+        U: Decoder,
+    {
+        loop {
+            let this = self.as_mut().project();
+            // Repeatedly call `decode` or `decode_eof` as long as it is "readable". Readable is
+            // defined as not having returned `None`. If the upstream has returned EOF, and the
+            // decoder is no longer readable, it can be assumed that the decoder will never become
+            // readable again, at which point the stream is terminated.
+
+            if this.flags.contains(Flags::READABLE) {
+                if this.flags.contains(Flags::EOF) {
+                    match this.codec.decode_eof(this.read_buf) {
+                        Ok(Some(frame)) => return Poll::Ready(Some(Ok(frame))),
+                        Ok(None) => return Poll::Ready(None),
+                        Err(err) => return Poll::Ready(Some(Err(err))),
+                    }
+                }
+
+                tracing::trace!("attempting to decode a frame");
+
+                match this.codec.decode(this.read_buf) {
+                    Ok(Some(frame)) => {
+                        tracing::trace!("frame decoded from buffer");
+                        return Poll::Ready(Some(Ok(frame)));
+                    }
+                    Err(err) => return Poll::Ready(Some(Err(err))),
+                    _ => (), // Need more data
+                }
+
+                this.flags.remove(Flags::READABLE);
+            }
+
+            debug_assert!(!this.flags.contains(Flags::EOF));
+
+            // Otherwise, try to read more data and try again. Make sure we've got room.
+            let remaining = this.read_buf.capacity() - this.read_buf.len();
+            if remaining < LW {
+                this.read_buf.reserve(HW - remaining)
+            }
+
+            let cnt = match tokio_util::io::poll_read_buf(this.io, cx, this.read_buf) {
+                Poll::Pending => return Poll::Pending,
+                Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err.into()))),
+                Poll::Ready(Ok(cnt)) => cnt,
+            };
+
+            if cnt == 0 {
+                this.flags.insert(Flags::EOF);
+            }
+            this.flags.insert(Flags::READABLE);
+        }
+    }
+
+    /// Flush write buffer to underlying I/O stream.
+    pub fn flush<I>(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
+    where
+        T: AsyncWrite,
+        U: Encoder<I>,
+    {
+        let mut this = self.as_mut().project();
+        tracing::trace!("flushing framed transport");
+
+        while !this.write_buf.is_empty() {
+            tracing::trace!("writing; remaining={}", this.write_buf.len());
+
+            let n = ready!(this.io.as_mut().poll_write(cx, this.write_buf))?;
+
+            if n == 0 {
+                return Poll::Ready(Err(io::Error::new(
+                    io::ErrorKind::WriteZero,
+                    "failed to write frame to transport",
+                )
+                .into()));
+            }
+
+            // remove written data
+            this.write_buf.advance(n);
+        }
+
+        // Try flushing the underlying IO
+        ready!(this.io.poll_flush(cx))?;
+
+        tracing::trace!("framed transport flushed");
+        Poll::Ready(Ok(()))
+    }
+
+    /// Flush write buffer and shutdown underlying I/O stream.
+    pub fn close<I>(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), U::Error>>
+    where
+        T: AsyncWrite,
+        U: Encoder<I>,
+    {
+        let mut this = self.as_mut().project();
+        ready!(this.io.as_mut().poll_flush(cx))?;
+        ready!(this.io.as_mut().poll_shutdown(cx))?;
+        Poll::Ready(Ok(()))
+    }
+}
+
+impl<T, U> Stream for Framed<T, U>
+where
+    T: AsyncRead,
+    U: Decoder,
+{
+    type Item = Result<U::Item, U::Error>;
+
+    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
+        self.next_item(cx)
+    }
+}
+
+impl<T, U, I> Sink<I> for Framed<T, U>
+where
+    T: AsyncWrite,
+    U: Encoder<I>,
+    U::Error: From<io::Error>,
+{
+    type Error = U::Error;
+
+    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.is_write_ready() {
+            Poll::Ready(Ok(()))
+        } else {
+            self.flush(cx)
+        }
+    }
+
+    fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> {
+        self.write(item)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        self.flush(cx)
+    }
+
+    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        self.close(cx)
+    }
+}
+
+impl<T, U> fmt::Debug for Framed<T, U>
+where
+    T: fmt::Debug,
+    U: fmt::Debug,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("Framed")
+            .field("io", &self.io)
+            .field("codec", &self.codec)
+            .finish()
+    }
+}
+
+impl<T, U> Framed<T, U> {
+    /// This function returns a *single* object that is both `Stream` and `Sink`; grouping this into
+    /// a single object is often useful for layering things like gzip or TLS, which require both
+    /// read and write access to the underlying object.
+    ///
+    /// These objects take a stream, a read buffer and a write buffer. These fields can be obtained
+    /// from an existing `Framed` with the `into_parts` method.
+    pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> {
+        Framed {
+            io: parts.io,
+            codec: parts.codec,
+            flags: parts.flags,
+            write_buf: parts.write_buf,
+            read_buf: parts.read_buf,
+        }
+    }
+
+    /// Consumes the `Frame`, returning its underlying I/O stream, the buffer with unprocessed data,
+    /// and the codec.
+    ///
+    /// Note that care should be taken to not tamper with the underlying stream of data coming in as
+    /// it may corrupt the stream of frames otherwise being worked with.
+    pub fn into_parts(self) -> FramedParts<T, U> {
+        FramedParts {
+            io: self.io,
+            codec: self.codec,
+            flags: self.flags,
+            read_buf: self.read_buf,
+            write_buf: self.write_buf,
+        }
+    }
+}
+
+/// `FramedParts` contains an export of the data of a Framed transport.
+///
+/// It can be used to construct a new `Framed` with a different codec. It contains all current
+/// buffers and the inner transport.
+#[derive(Debug)]
+pub struct FramedParts<T, U> {
+    /// The inner transport used to read bytes to and write bytes to.
+    pub io: T,
+
+    /// The codec object.
+    pub codec: U,
+
+    /// The buffer with read but unprocessed data.
+    pub read_buf: BytesMut,
+
+    /// A buffer with unprocessed data which are not written yet.
+    pub write_buf: BytesMut,
+
+    flags: Flags,
+}
+
+impl<T, U> FramedParts<T, U> {
+    /// Creates a new default `FramedParts`.
+    pub fn new(io: T, codec: U) -> FramedParts<T, U> {
+        FramedParts {
+            io,
+            codec,
+            flags: Flags::empty(),
+            read_buf: BytesMut::new(),
+            write_buf: BytesMut::new(),
+        }
+    }
+
+    /// Creates a new `FramedParts` with read buffer.
+    pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U> {
+        FramedParts {
+            io,
+            codec,
+            read_buf,
+            flags: Flags::empty(),
+            write_buf: BytesMut::new(),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_codec/lib.rs.html b/src/actix_codec/lib.rs.html new file mode 100644 index 00000000..c0157375 --- /dev/null +++ b/src/actix_codec/lib.rs.html @@ -0,0 +1,57 @@ +lib.rs - source

actix_codec/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
//! Codec utilities for working with framed protocols.
+//!
+//! Contains adapters to go from streams of bytes, [`AsyncRead`] and [`AsyncWrite`], to framed
+//! streams implementing [`Sink`] and [`Stream`]. Framed streams are also known as `transports`.
+//!
+//! [`Sink`]: futures_sink::Sink
+//! [`Stream`]: futures_core::Stream
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+pub use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+pub use tokio_util::{
+    codec::{Decoder, Encoder},
+    io::poll_read_buf,
+};
+
+mod bcodec;
+mod framed;
+mod lines;
+
+pub use self::{
+    bcodec::BytesCodec,
+    framed::{Framed, FramedParts},
+    lines::LinesCodec,
+};
+
\ No newline at end of file diff --git a/src/actix_codec/lines.rs.html b/src/actix_codec/lines.rs.html new file mode 100644 index 00000000..f8bcb074 --- /dev/null +++ b/src/actix_codec/lines.rs.html @@ -0,0 +1,317 @@ +lines.rs - source

actix_codec/
lines.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
use std::io;
+
+use bytes::{Buf, BufMut, Bytes, BytesMut};
+use memchr::memchr;
+
+use super::{Decoder, Encoder};
+
+/// Lines codec. Reads/writes line delimited strings.
+///
+/// Will split input up by LF or CRLF delimiters. Carriage return characters at the end of lines are
+/// not preserved.
+#[derive(Debug, Copy, Clone, Default)]
+#[non_exhaustive]
+pub struct LinesCodec;
+
+impl<T: AsRef<str>> Encoder<T> for LinesCodec {
+    type Error = io::Error;
+
+    #[inline]
+    fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
+        let item = item.as_ref();
+        dst.reserve(item.len() + 1);
+        dst.put_slice(item.as_bytes());
+        dst.put_u8(b'\n');
+        Ok(())
+    }
+}
+
+impl Decoder for LinesCodec {
+    type Item = String;
+    type Error = io::Error;
+
+    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
+        if src.is_empty() {
+            return Ok(None);
+        }
+
+        let len = match memchr(b'\n', src) {
+            Some(n) => n,
+            None => {
+                return Ok(None);
+            }
+        };
+
+        // split up to new line char
+        let mut buf = src.split_to(len);
+        debug_assert_eq!(len, buf.len());
+
+        // remove new line char from source
+        src.advance(1);
+
+        match buf.last() {
+            // remove carriage returns at the end of buf
+            Some(b'\r') => buf.truncate(len - 1),
+
+            // line is empty
+            None => return Ok(Some(String::new())),
+
+            _ => {}
+        }
+
+        try_into_utf8(buf.freeze())
+    }
+
+    fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
+        match self.decode(src)? {
+            Some(frame) => Ok(Some(frame)),
+            None if src.is_empty() => Ok(None),
+            None => {
+                let buf = match src.last() {
+                    // if last line ends in a CR then take everything up to it
+                    Some(b'\r') => src.split_to(src.len() - 1),
+
+                    // take all bytes from source
+                    _ => src.split(),
+                };
+
+                if buf.is_empty() {
+                    return Ok(None);
+                }
+
+                try_into_utf8(buf.freeze())
+            }
+        }
+    }
+}
+
+// Attempts to convert bytes into a `String`.
+fn try_into_utf8(buf: Bytes) -> io::Result<Option<String>> {
+    String::from_utf8(buf.to_vec())
+        .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
+        .map(Some)
+}
+
+#[cfg(test)]
+mod tests {
+    use bytes::BufMut as _;
+
+    use super::*;
+
+    #[test]
+    fn lines_decoder() {
+        let mut codec = LinesCodec::default();
+        let mut buf = BytesMut::from("\nline 1\nline 2\r\nline 3\n\r\n\r");
+
+        assert_eq!("", codec.decode(&mut buf).unwrap().unwrap());
+        assert_eq!("line 1", codec.decode(&mut buf).unwrap().unwrap());
+        assert_eq!("line 2", codec.decode(&mut buf).unwrap().unwrap());
+        assert_eq!("line 3", codec.decode(&mut buf).unwrap().unwrap());
+        assert_eq!("", codec.decode(&mut buf).unwrap().unwrap());
+        assert!(codec.decode(&mut buf).unwrap().is_none());
+        assert!(codec.decode_eof(&mut buf).unwrap().is_none());
+
+        buf.put_slice(b"k");
+        assert!(codec.decode(&mut buf).unwrap().is_none());
+        assert_eq!("\rk", codec.decode_eof(&mut buf).unwrap().unwrap());
+
+        assert!(codec.decode(&mut buf).unwrap().is_none());
+        assert!(codec.decode_eof(&mut buf).unwrap().is_none());
+    }
+
+    #[test]
+    fn lines_encoder() {
+        let mut codec = LinesCodec::default();
+
+        let mut buf = BytesMut::new();
+
+        codec.encode("", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"\n");
+
+        codec.encode("test", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"\ntest\n");
+
+        codec.encode("a\nb", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"\ntest\na\nb\n");
+    }
+
+    #[test]
+    fn lines_encoder_no_overflow() {
+        let mut codec = LinesCodec::default();
+
+        let mut buf = BytesMut::new();
+        codec.encode("1234567", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"1234567\n");
+
+        let mut buf = BytesMut::new();
+        codec.encode("12345678", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"12345678\n");
+
+        let mut buf = BytesMut::new();
+        codec.encode("123456789111213", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"123456789111213\n");
+
+        let mut buf = BytesMut::new();
+        codec.encode("1234567891112131", &mut buf).unwrap();
+        assert_eq!(&buf[..], b"1234567891112131\n");
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_macros/lib.rs.html b/src/actix_macros/lib.rs.html new file mode 100644 index 00000000..c5e64c98 --- /dev/null +++ b/src/actix_macros/lib.rs.html @@ -0,0 +1,443 @@ +lib.rs - source

actix_macros/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
//! Macros for Actix system and runtime.
+//!
+//! The [`actix-rt`](https://docs.rs/actix-rt) crate must be available for macro output to compile.
+//!
+//! # Entry-point
+//! See docs for the [`#[main]`](macro@main) macro.
+//!
+//! # Tests
+//! See docs for the [`#[test]`](macro@test) macro.
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse::Parser as _;
+
+type AttributeArgs = syn::punctuated::Punctuated<syn::Meta, syn::Token![,]>;
+
+/// Marks async entry-point function to be executed by Actix system.
+///
+/// # Examples
+/// ```
+/// #[actix_rt::main]
+/// async fn main() {
+///     println!("Hello world");
+/// }
+/// ```
+#[proc_macro_attribute]
+pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
+    let mut input = match syn::parse::<syn::ItemFn>(item.clone()) {
+        Ok(input) => input,
+        // on parse err, make IDEs happy; see fn docs
+        Err(err) => return input_and_compile_error(item, err),
+    };
+
+    let parser = AttributeArgs::parse_terminated;
+    let args = match parser.parse(args.clone()) {
+        Ok(args) => args,
+        Err(err) => return input_and_compile_error(args, err),
+    };
+
+    let attrs = &input.attrs;
+    let vis = &input.vis;
+    let sig = &mut input.sig;
+    let body = &input.block;
+
+    if sig.asyncness.is_none() {
+        return syn::Error::new_spanned(
+            sig.fn_token,
+            "the async keyword is missing from the function declaration",
+        )
+        .to_compile_error()
+        .into();
+    }
+
+    let mut system = syn::parse_str::<syn::Path>("::actix_rt::System").unwrap();
+
+    for arg in &args {
+        match arg {
+            syn::Meta::NameValue(syn::MetaNameValue {
+                path,
+                value:
+                    syn::Expr::Lit(syn::ExprLit {
+                        lit: syn::Lit::Str(lit),
+                        ..
+                    }),
+                ..
+            }) => match path
+                .get_ident()
+                .map(|i| i.to_string().to_lowercase())
+                .as_deref()
+            {
+                Some("system") => match lit.parse() {
+                    Ok(path) => system = path,
+                    Err(_) => {
+                        return syn::Error::new_spanned(lit, "Expected path")
+                            .to_compile_error()
+                            .into();
+                    }
+                },
+                _ => {
+                    return syn::Error::new_spanned(arg, "Unknown attribute specified")
+                        .to_compile_error()
+                        .into();
+                }
+            },
+
+            _ => {
+                return syn::Error::new_spanned(arg, "Unknown attribute specified")
+                    .to_compile_error()
+                    .into();
+            }
+        }
+    }
+
+    sig.asyncness = None;
+
+    (quote! {
+        #(#attrs)*
+        #vis #sig {
+            <#system>::new().block_on(async move { #body })
+        }
+    })
+    .into()
+}
+
+/// Marks async test function to be executed in an Actix system.
+///
+/// # Examples
+/// ```
+/// #[actix_rt::test]
+/// async fn my_test() {
+///     assert!(true);
+/// }
+/// ```
+#[proc_macro_attribute]
+pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
+    let mut input = match syn::parse::<syn::ItemFn>(item.clone()) {
+        Ok(input) => input,
+        // on parse err, make IDEs happy; see fn docs
+        Err(err) => return input_and_compile_error(item, err),
+    };
+
+    let parser = AttributeArgs::parse_terminated;
+    let args = match parser.parse(args.clone()) {
+        Ok(args) => args,
+        Err(err) => return input_and_compile_error(args, err),
+    };
+
+    let attrs = &input.attrs;
+    let vis = &input.vis;
+    let sig = &mut input.sig;
+    let body = &input.block;
+    let mut has_test_attr = false;
+
+    for attr in attrs {
+        if attr.path().is_ident("test") {
+            has_test_attr = true;
+        }
+    }
+
+    if sig.asyncness.is_none() {
+        return syn::Error::new_spanned(
+            input.sig.fn_token,
+            "the async keyword is missing from the function declaration",
+        )
+        .to_compile_error()
+        .into();
+    }
+
+    sig.asyncness = None;
+
+    let missing_test_attr = if has_test_attr {
+        quote! {}
+    } else {
+        quote! { #[::core::prelude::v1::test] }
+    };
+
+    let mut system = syn::parse_str::<syn::Path>("::actix_rt::System").unwrap();
+
+    for arg in &args {
+        match arg {
+            syn::Meta::NameValue(syn::MetaNameValue {
+                path,
+                value:
+                    syn::Expr::Lit(syn::ExprLit {
+                        lit: syn::Lit::Str(lit),
+                        ..
+                    }),
+                ..
+            }) => match path
+                .get_ident()
+                .map(|i| i.to_string().to_lowercase())
+                .as_deref()
+            {
+                Some("system") => match lit.parse() {
+                    Ok(path) => system = path,
+                    Err(_) => {
+                        return syn::Error::new_spanned(lit, "Expected path")
+                            .to_compile_error()
+                            .into();
+                    }
+                },
+                _ => {
+                    return syn::Error::new_spanned(arg, "Unknown attribute specified")
+                        .to_compile_error()
+                        .into();
+                }
+            },
+            _ => {
+                return syn::Error::new_spanned(arg, "Unknown attribute specified")
+                    .to_compile_error()
+                    .into();
+            }
+        }
+    }
+
+    (quote! {
+        #missing_test_attr
+        #(#attrs)*
+        #vis #sig {
+            <#system>::new().block_on(async { #body })
+        }
+    })
+    .into()
+}
+
+/// Converts the error to a token stream and appends it to the original input.
+///
+/// Returning the original input in addition to the error is good for IDEs which can gracefully
+/// recover and show more precise errors within the macro body.
+///
+/// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info.
+fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream {
+    let compile_err = TokenStream::from(err.to_compile_error());
+    item.extend(compile_err);
+    item
+}
+
\ No newline at end of file diff --git a/src/actix_rt/arbiter.rs.html b/src/actix_rt/arbiter.rs.html new file mode 100644 index 00000000..f2ab8639 --- /dev/null +++ b/src/actix_rt/arbiter.rs.html @@ -0,0 +1,635 @@ +arbiter.rs - source

actix_rt/
arbiter.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
use std::{
+    cell::RefCell,
+    fmt,
+    future::Future,
+    pin::Pin,
+    sync::atomic::{AtomicUsize, Ordering},
+    task::{Context, Poll},
+    thread,
+};
+
+use futures_core::ready;
+use tokio::sync::mpsc;
+
+use crate::system::{System, SystemCommand};
+
+pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0);
+
+thread_local!(
+    static HANDLE: RefCell<Option<ArbiterHandle>> = const { RefCell::new(None) };
+);
+
+pub(crate) enum ArbiterCommand {
+    Stop,
+    Execute(Pin<Box<dyn Future<Output = ()> + Send>>),
+}
+
+impl fmt::Debug for ArbiterCommand {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            ArbiterCommand::Stop => write!(f, "ArbiterCommand::Stop"),
+            ArbiterCommand::Execute(_) => write!(f, "ArbiterCommand::Execute"),
+        }
+    }
+}
+
+/// A handle for sending spawn and stop messages to an [Arbiter].
+#[derive(Debug, Clone)]
+pub struct ArbiterHandle {
+    tx: mpsc::UnboundedSender<ArbiterCommand>,
+}
+
+impl ArbiterHandle {
+    pub(crate) fn new(tx: mpsc::UnboundedSender<ArbiterCommand>) -> Self {
+        Self { tx }
+    }
+
+    /// Send a future to the [Arbiter]'s thread and spawn it.
+    ///
+    /// If you require a result, include a response channel in the future.
+    ///
+    /// Returns true if future was sent successfully and false if the [Arbiter] has died.
+    pub fn spawn<Fut>(&self, future: Fut) -> bool
+    where
+        Fut: Future<Output = ()> + Send + 'static,
+    {
+        self.tx
+            .send(ArbiterCommand::Execute(Box::pin(future)))
+            .is_ok()
+    }
+
+    /// Send a function to the [Arbiter]'s thread and execute it.
+    ///
+    /// Any result from the function is discarded. If you require a result, include a response
+    /// channel in the function.
+    ///
+    /// Returns true if function was sent successfully and false if the [Arbiter] has died.
+    pub fn spawn_fn<F>(&self, f: F) -> bool
+    where
+        F: FnOnce() + Send + 'static,
+    {
+        self.spawn(async { f() })
+    }
+
+    /// Instruct [Arbiter] to stop processing it's event loop.
+    ///
+    /// Returns true if stop message was sent successfully and false if the [Arbiter] has
+    /// been dropped.
+    pub fn stop(&self) -> bool {
+        self.tx.send(ArbiterCommand::Stop).is_ok()
+    }
+}
+
+/// An Arbiter represents a thread that provides an asynchronous execution environment for futures
+/// and functions.
+///
+/// When an arbiter is created, it spawns a new [OS thread](thread), and hosts an event loop.
+#[derive(Debug)]
+pub struct Arbiter {
+    tx: mpsc::UnboundedSender<ArbiterCommand>,
+    thread_handle: thread::JoinHandle<()>,
+}
+
+impl Arbiter {
+    /// Spawn a new Arbiter thread and start its event loop.
+    ///
+    /// # Panics
+    /// Panics if a [System] is not registered on the current thread.
+    #[cfg(not(all(target_os = "linux", feature = "io-uring")))]
+    #[allow(clippy::new_without_default)]
+    pub fn new() -> Arbiter {
+        Self::with_tokio_rt(|| {
+            crate::runtime::default_tokio_runtime().expect("Cannot create new Arbiter's Runtime.")
+        })
+    }
+
+    /// Spawn a new Arbiter using the [Tokio Runtime](tokio-runtime) returned from a closure.
+    ///
+    /// [tokio-runtime]: tokio::runtime::Runtime
+    #[cfg(not(all(target_os = "linux", feature = "io-uring")))]
+    pub fn with_tokio_rt<F>(runtime_factory: F) -> Arbiter
+    where
+        F: FnOnce() -> tokio::runtime::Runtime + Send + 'static,
+    {
+        let sys = System::current();
+        let system_id = sys.id();
+        let arb_id = COUNT.fetch_add(1, Ordering::Relaxed);
+
+        let name = format!("actix-rt|system:{}|arbiter:{}", system_id, arb_id);
+        let (tx, rx) = mpsc::unbounded_channel();
+
+        let (ready_tx, ready_rx) = std::sync::mpsc::channel::<()>();
+
+        let thread_handle = thread::Builder::new()
+            .name(name.clone())
+            .spawn({
+                let tx = tx.clone();
+                move || {
+                    let rt = crate::runtime::Runtime::from(runtime_factory());
+                    let hnd = ArbiterHandle::new(tx);
+
+                    System::set_current(sys);
+
+                    HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone()));
+
+                    // register arbiter
+                    let _ = System::current()
+                        .tx()
+                        .send(SystemCommand::RegisterArbiter(arb_id, hnd));
+
+                    ready_tx.send(()).unwrap();
+
+                    // run arbiter event processing loop
+                    rt.block_on(ArbiterRunner { rx });
+
+                    // deregister arbiter
+                    let _ = System::current()
+                        .tx()
+                        .send(SystemCommand::DeregisterArbiter(arb_id));
+                }
+            })
+            .unwrap_or_else(|err| panic!("Cannot spawn Arbiter's thread: {name:?}: {err:?}"));
+
+        ready_rx.recv().unwrap();
+
+        Arbiter { tx, thread_handle }
+    }
+
+    /// Spawn a new Arbiter thread and start its event loop with `tokio-uring` runtime.
+    ///
+    /// # Panics
+    /// Panics if a [System] is not registered on the current thread.
+    #[cfg(all(target_os = "linux", feature = "io-uring"))]
+    #[allow(clippy::new_without_default)]
+    pub fn new() -> Arbiter {
+        let sys = System::current();
+        let system_id = sys.id();
+        let arb_id = COUNT.fetch_add(1, Ordering::Relaxed);
+
+        let name = format!("actix-rt|system:{}|arbiter:{}", system_id, arb_id);
+        let (tx, rx) = mpsc::unbounded_channel();
+
+        let (ready_tx, ready_rx) = std::sync::mpsc::channel::<()>();
+
+        let thread_handle = thread::Builder::new()
+            .name(name.clone())
+            .spawn({
+                let tx = tx.clone();
+                move || {
+                    let hnd = ArbiterHandle::new(tx);
+
+                    System::set_current(sys);
+
+                    HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone()));
+
+                    // register arbiter
+                    let _ = System::current()
+                        .tx()
+                        .send(SystemCommand::RegisterArbiter(arb_id, hnd));
+
+                    ready_tx.send(()).unwrap();
+
+                    // run arbiter event processing loop
+                    tokio_uring::start(ArbiterRunner { rx });
+
+                    // deregister arbiter
+                    let _ = System::current()
+                        .tx()
+                        .send(SystemCommand::DeregisterArbiter(arb_id));
+                }
+            })
+            .unwrap_or_else(|err| panic!("Cannot spawn Arbiter's thread: {name:?}: {err:?}"));
+
+        ready_rx.recv().unwrap();
+
+        Arbiter { tx, thread_handle }
+    }
+
+    /// Sets up an Arbiter runner in a new System using the environment's local set.
+    pub(crate) fn in_new_system() -> ArbiterHandle {
+        let (tx, rx) = mpsc::unbounded_channel();
+
+        let hnd = ArbiterHandle::new(tx);
+
+        HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone()));
+
+        crate::spawn(ArbiterRunner { rx });
+
+        hnd
+    }
+
+    /// Return a handle to the this Arbiter's message sender.
+    pub fn handle(&self) -> ArbiterHandle {
+        ArbiterHandle::new(self.tx.clone())
+    }
+
+    /// Return a handle to the current thread's Arbiter's message sender.
+    ///
+    /// # Panics
+    /// Panics if no Arbiter is running on the current thread.
+    pub fn current() -> ArbiterHandle {
+        HANDLE.with(|cell| match *cell.borrow() {
+            Some(ref hnd) => hnd.clone(),
+            None => panic!("Arbiter is not running."),
+        })
+    }
+
+    /// Try to get current running arbiter handle.
+    ///
+    /// Returns `None` if no Arbiter has been started.
+    ///
+    /// Unlike [`current`](Self::current), this never panics.
+    pub fn try_current() -> Option<ArbiterHandle> {
+        HANDLE.with(|cell| cell.borrow().clone())
+    }
+
+    /// Stop Arbiter from continuing it's event loop.
+    ///
+    /// Returns true if stop message was sent successfully and false if the Arbiter has been dropped.
+    pub fn stop(&self) -> bool {
+        self.tx.send(ArbiterCommand::Stop).is_ok()
+    }
+
+    /// Send a future to the Arbiter's thread and spawn it.
+    ///
+    /// If you require a result, include a response channel in the future.
+    ///
+    /// Returns true if future was sent successfully and false if the Arbiter has died.
+    #[track_caller]
+    pub fn spawn<Fut>(&self, future: Fut) -> bool
+    where
+        Fut: Future<Output = ()> + Send + 'static,
+    {
+        self.tx
+            .send(ArbiterCommand::Execute(Box::pin(future)))
+            .is_ok()
+    }
+
+    /// Send a function to the Arbiter's thread and execute it.
+    ///
+    /// Any result from the function is discarded. If you require a result, include a response
+    /// channel in the function.
+    ///
+    /// Returns true if function was sent successfully and false if the Arbiter has died.
+    #[track_caller]
+    pub fn spawn_fn<F>(&self, f: F) -> bool
+    where
+        F: FnOnce() + Send + 'static,
+    {
+        self.spawn(async { f() })
+    }
+
+    /// Wait for Arbiter's event loop to complete.
+    ///
+    /// Joins the underlying OS thread handle. See [`JoinHandle::join`](thread::JoinHandle::join).
+    pub fn join(self) -> thread::Result<()> {
+        self.thread_handle.join()
+    }
+}
+
+/// A persistent future that processes [Arbiter] commands.
+struct ArbiterRunner {
+    rx: mpsc::UnboundedReceiver<ArbiterCommand>,
+}
+
+impl Future for ArbiterRunner {
+    type Output = ();
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        // process all items currently buffered in channel
+        loop {
+            match ready!(self.rx.poll_recv(cx)) {
+                // channel closed; no more messages can be received
+                None => return Poll::Ready(()),
+
+                // process arbiter command
+                Some(item) => match item {
+                    ArbiterCommand::Stop => {
+                        return Poll::Ready(());
+                    }
+                    ArbiterCommand::Execute(task_fut) => {
+                        tokio::task::spawn_local(task_fut);
+                    }
+                },
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_rt/lib.rs.html b/src/actix_rt/lib.rs.html new file mode 100644 index 00000000..e74e8f64 --- /dev/null +++ b/src/actix_rt/lib.rs.html @@ -0,0 +1,419 @@ +lib.rs - source

actix_rt/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
//! Tokio-based single-threaded async runtime for the Actix ecosystem.
+//!
+//! In most parts of the the Actix ecosystem, it has been chosen to use !Send futures. For this
+//! reason, a single-threaded runtime is appropriate since it is guaranteed that futures will not
+//! be moved between threads. This can result in small performance improvements over cases where
+//! atomics would otherwise be needed.
+//!
+//! To achieve similar performance to multi-threaded, work-stealing runtimes, applications
+//! using `actix-rt` will create multiple, mostly disconnected, single-threaded runtimes.
+//! This approach has good performance characteristics for workloads where the majority of tasks
+//! have similar runtime expense.
+//!
+//! The disadvantage is that idle threads will not steal work from very busy, stuck or otherwise
+//! backlogged threads. Tasks that are disproportionately expensive should be offloaded to the
+//! blocking task thread-pool using [`task::spawn_blocking`].
+//!
+//! # Examples
+//! ```no_run
+//! use std::sync::mpsc;
+//! use actix_rt::{Arbiter, System};
+//!
+//! let _ = System::new();
+//!
+//! let (tx, rx) = mpsc::channel::<u32>();
+//!
+//! let arbiter = Arbiter::new();
+//! arbiter.spawn_fn(move || tx.send(42).unwrap());
+//!
+//! let num = rx.recv().unwrap();
+//! assert_eq!(num, 42);
+//!
+//! arbiter.stop();
+//! arbiter.join().unwrap();
+//! ```
+//!
+//! # `io-uring` Support
+//!
+//! There is experimental support for using io-uring with this crate by enabling the
+//! `io-uring` feature. For now, it is semver exempt.
+//!
+//! Note that there are currently some unimplemented parts of using `actix-rt` with `io-uring`.
+//! In particular, when running a `System`, only `System::block_on` is supported.
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+#![allow(clippy::type_complexity)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+#[cfg(all(not(target_os = "linux"), feature = "io-uring"))]
+compile_error!("io_uring is a linux only feature.");
+
+use std::future::Future;
+
+// Cannot define a main macro when compiled into test harness.
+// Workaround for https://github.com/rust-lang/rust/issues/62127.
+#[cfg(all(feature = "macros", not(test)))]
+pub use actix_macros::main;
+#[cfg(feature = "macros")]
+pub use actix_macros::test;
+
+mod arbiter;
+mod runtime;
+mod system;
+
+pub use tokio::pin;
+use tokio::task::JoinHandle;
+
+pub use self::{
+    arbiter::{Arbiter, ArbiterHandle},
+    runtime::Runtime,
+    system::{System, SystemRunner},
+};
+
+pub mod signal {
+    //! Asynchronous signal handling (Tokio re-exports).
+
+    #[cfg(unix)]
+    pub mod unix {
+        //! Unix specific signals (Tokio re-exports).
+        pub use tokio::signal::unix::*;
+    }
+    pub use tokio::signal::ctrl_c;
+}
+
+pub mod net {
+    //! TCP/UDP/Unix bindings (mostly Tokio re-exports).
+
+    use std::{
+        future::Future,
+        io,
+        task::{Context, Poll},
+    };
+
+    use tokio::io::{AsyncRead, AsyncWrite, Interest};
+    #[cfg(unix)]
+    pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
+    pub use tokio::{
+        io::Ready,
+        net::{TcpListener, TcpSocket, TcpStream, UdpSocket},
+    };
+
+    /// Extension trait over async read+write types that can also signal readiness.
+    #[doc(hidden)]
+    pub trait ActixStream: AsyncRead + AsyncWrite + Unpin {
+        /// Poll stream and check read readiness of Self.
+        ///
+        /// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use.
+        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
+
+        /// Poll stream and check write readiness of Self.
+        ///
+        /// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use.
+        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
+    }
+
+    impl ActixStream for TcpStream {
+        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+            let ready = self.ready(Interest::READABLE);
+            tokio::pin!(ready);
+            ready.poll(cx)
+        }
+
+        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+            let ready = self.ready(Interest::WRITABLE);
+            tokio::pin!(ready);
+            ready.poll(cx)
+        }
+    }
+
+    #[cfg(unix)]
+    impl ActixStream for UnixStream {
+        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+            let ready = self.ready(Interest::READABLE);
+            tokio::pin!(ready);
+            ready.poll(cx)
+        }
+
+        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+            let ready = self.ready(Interest::WRITABLE);
+            tokio::pin!(ready);
+            ready.poll(cx)
+        }
+    }
+
+    impl<Io: ActixStream + ?Sized> ActixStream for Box<Io> {
+        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+            (**self).poll_read_ready(cx)
+        }
+
+        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+            (**self).poll_write_ready(cx)
+        }
+    }
+}
+
+pub mod time {
+    //! Utilities for tracking time (Tokio re-exports).
+
+    pub use tokio::time::{
+        interval, interval_at, sleep, sleep_until, timeout, Instant, Interval, Sleep, Timeout,
+    };
+}
+
+pub mod task {
+    //! Task management (Tokio re-exports).
+
+    pub use tokio::task::{spawn_blocking, yield_now, JoinError, JoinHandle};
+}
+
+/// Spawns a future on the current thread as a new task.
+///
+/// If not immediately awaited, the task can be cancelled using [`JoinHandle::abort`].
+///
+/// The provided future is spawned as a new task; therefore, panics are caught.
+///
+/// # Panics
+/// Panics if Actix system is not running.
+///
+/// # Examples
+/// ```
+/// # use std::time::Duration;
+/// # actix_rt::Runtime::new().unwrap().block_on(async {
+/// // task resolves successfully
+/// assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1);
+///
+/// // task panics
+/// assert!(actix_rt::spawn(async {
+///     panic!("panic is caught at task boundary");
+/// })
+/// .await
+/// .unwrap_err()
+/// .is_panic());
+///
+/// // task is cancelled before completion
+/// let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100)));
+/// handle.abort();
+/// assert!(handle.await.unwrap_err().is_cancelled());
+/// # });
+/// ```
+#[track_caller]
+#[inline]
+pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output>
+where
+    Fut: Future + 'static,
+    Fut::Output: 'static,
+{
+    tokio::task::spawn_local(f)
+}
+
\ No newline at end of file diff --git a/src/actix_rt/runtime.rs.html b/src/actix_rt/runtime.rs.html new file mode 100644 index 00000000..8447bfa7 --- /dev/null +++ b/src/actix_rt/runtime.rs.html @@ -0,0 +1,299 @@ +runtime.rs - source

actix_rt/
runtime.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
use std::{future::Future, io};
+
+use tokio::task::{JoinHandle, LocalSet};
+
+/// A Tokio-based runtime proxy.
+///
+/// All spawned futures will be executed on the current thread. Therefore, there is no `Send` bound
+/// on submitted futures.
+#[derive(Debug)]
+pub struct Runtime {
+    local: LocalSet,
+    rt: tokio::runtime::Runtime,
+}
+
+pub(crate) fn default_tokio_runtime() -> io::Result<tokio::runtime::Runtime> {
+    tokio::runtime::Builder::new_current_thread()
+        .enable_io()
+        .enable_time()
+        .build()
+}
+
+impl Runtime {
+    /// Returns a new runtime initialized with default configuration values.
+    #[allow(clippy::new_ret_no_self)]
+    pub fn new() -> io::Result<Self> {
+        let rt = default_tokio_runtime()?;
+
+        Ok(Runtime {
+            rt,
+            local: LocalSet::new(),
+        })
+    }
+
+    /// Offload a future onto the single-threaded runtime.
+    ///
+    /// The returned join handle can be used to await the future's result.
+    ///
+    /// See [crate root][crate] documentation for more details.
+    ///
+    /// # Examples
+    /// ```
+    /// let rt = actix_rt::Runtime::new().unwrap();
+    ///
+    /// // Spawn a future onto the runtime
+    /// let handle = rt.spawn(async {
+    ///     println!("running on the runtime");
+    ///     42
+    /// });
+    ///
+    /// assert_eq!(rt.block_on(handle).unwrap(), 42);
+    /// ```
+    ///
+    /// # Panics
+    /// This function panics if the spawn fails. Failure occurs if the executor is currently at
+    /// capacity and is unable to spawn a new future.
+    #[track_caller]
+    pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
+    where
+        F: Future + 'static,
+    {
+        self.local.spawn_local(future)
+    }
+
+    /// Retrieves a reference to the underlying Tokio runtime associated with this instance.
+    ///
+    /// The Tokio runtime is responsible for executing asynchronous tasks and managing
+    /// the event loop for an asynchronous Rust program. This method allows accessing
+    /// the runtime to interact with its features directly.
+    ///
+    /// In a typical use case, you might need to share the same runtime between different
+    /// modules of your project. For example, a module might require a `tokio::runtime::Handle`
+    /// to spawn tasks on the same runtime, or the runtime itself to configure more complex
+    /// behaviours.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use actix_rt::Runtime;
+    ///
+    /// mod module_a {
+    ///     pub fn do_something(handle: tokio::runtime::Handle) {
+    ///         handle.spawn(async {
+    ///             // Some asynchronous task here
+    ///         });
+    ///     }
+    /// }
+    ///
+    /// mod module_b {
+    ///     pub fn do_something_else(rt: &tokio::runtime::Runtime) {
+    ///         rt.spawn(async {
+    ///             // Another asynchronous task here
+    ///         });
+    ///     }
+    /// }
+    ///
+    /// let actix_runtime = actix_rt::Runtime::new().unwrap();
+    /// let tokio_runtime = actix_runtime.tokio_runtime();
+    ///
+    /// let handle = tokio_runtime.handle().clone();
+    ///
+    /// module_a::do_something(handle);
+    /// module_b::do_something_else(tokio_runtime);
+    /// ```
+    ///
+    /// # Returns
+    ///
+    /// An immutable reference to the `tokio::runtime::Runtime` instance associated with this
+    /// `Runtime` instance.
+    ///
+    /// # Note
+    ///
+    /// While this method provides an immutable reference to the Tokio runtime, which is safe to share across threads,
+    /// be aware that spawning blocking tasks on the Tokio runtime could potentially impact the execution
+    /// of the Actix runtime. This is because Tokio is responsible for driving the Actix system,
+    /// and blocking tasks could delay or deadlock other tasks in run loop.
+    pub fn tokio_runtime(&self) -> &tokio::runtime::Runtime {
+        &self.rt
+    }
+
+    /// Runs the provided future, blocking the current thread until the future completes.
+    ///
+    /// This function can be used to synchronously block the current thread until the provided
+    /// `future` has resolved either successfully or with an error. The result of the future is
+    /// then returned from this function call.
+    ///
+    /// Note that this function will also execute any spawned futures on the current thread, but
+    /// will not block until these other spawned futures have completed. Once the function returns,
+    /// any uncompleted futures remain pending in the `Runtime` instance. These futures will not run
+    /// until `block_on` or `run` is called again.
+    ///
+    /// The caller is responsible for ensuring that other spawned futures complete execution by
+    /// calling `block_on` or `run`.
+    #[track_caller]
+    pub fn block_on<F>(&self, f: F) -> F::Output
+    where
+        F: Future,
+    {
+        self.local.block_on(&self.rt, f)
+    }
+}
+
+impl From<tokio::runtime::Runtime> for Runtime {
+    fn from(rt: tokio::runtime::Runtime) -> Self {
+        Self {
+            local: LocalSet::new(),
+            rt,
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_rt/system.rs.html b/src/actix_rt/system.rs.html new file mode 100644 index 00000000..d7a0d69c --- /dev/null +++ b/src/actix_rt/system.rs.html @@ -0,0 +1,715 @@ +system.rs - source

actix_rt/
system.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
use std::{
+    cell::RefCell,
+    collections::HashMap,
+    future::Future,
+    io,
+    pin::Pin,
+    sync::atomic::{AtomicUsize, Ordering},
+    task::{Context, Poll},
+};
+
+use futures_core::ready;
+use tokio::sync::{mpsc, oneshot};
+
+use crate::{arbiter::ArbiterHandle, Arbiter};
+
+static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
+
+thread_local!(
+    static CURRENT: RefCell<Option<System>> = const { RefCell::new(None) };
+);
+
+/// A manager for a per-thread distributed async runtime.
+#[derive(Clone, Debug)]
+pub struct System {
+    id: usize,
+    sys_tx: mpsc::UnboundedSender<SystemCommand>,
+
+    /// Handle to the first [Arbiter] that is created with the System.
+    arbiter_handle: ArbiterHandle,
+}
+
+#[cfg(not(feature = "io-uring"))]
+impl System {
+    /// Create a new system.
+    ///
+    /// # Panics
+    /// Panics if underlying Tokio runtime can not be created.
+    #[allow(clippy::new_ret_no_self)]
+    pub fn new() -> SystemRunner {
+        Self::with_tokio_rt(|| {
+            crate::runtime::default_tokio_runtime()
+                .expect("Default Actix (Tokio) runtime could not be created.")
+        })
+    }
+
+    /// Create a new System using the [Tokio Runtime](tokio-runtime) returned from a closure.
+    ///
+    /// [tokio-runtime]: tokio::runtime::Runtime
+    pub fn with_tokio_rt<F>(runtime_factory: F) -> SystemRunner
+    where
+        F: FnOnce() -> tokio::runtime::Runtime,
+    {
+        let (stop_tx, stop_rx) = oneshot::channel();
+        let (sys_tx, sys_rx) = mpsc::unbounded_channel();
+
+        let rt = crate::runtime::Runtime::from(runtime_factory());
+        let sys_arbiter = rt.block_on(async { Arbiter::in_new_system() });
+        let system = System::construct(sys_tx, sys_arbiter.clone());
+
+        system
+            .tx()
+            .send(SystemCommand::RegisterArbiter(usize::MAX, sys_arbiter))
+            .unwrap();
+
+        // init background system arbiter
+        let sys_ctrl = SystemController::new(sys_rx, stop_tx);
+        rt.spawn(sys_ctrl);
+
+        SystemRunner { rt, stop_rx }
+    }
+}
+
+#[cfg(feature = "io-uring")]
+impl System {
+    /// Create a new system.
+    ///
+    /// # Panics
+    /// Panics if underlying Tokio runtime can not be created.
+    #[allow(clippy::new_ret_no_self)]
+    pub fn new() -> SystemRunner {
+        SystemRunner
+    }
+
+    /// Create a new System using the [Tokio Runtime](tokio-runtime) returned from a closure.
+    ///
+    /// [tokio-runtime]: tokio::runtime::Runtime
+    #[doc(hidden)]
+    pub fn with_tokio_rt<F>(_: F) -> SystemRunner
+    where
+        F: FnOnce() -> tokio::runtime::Runtime,
+    {
+        unimplemented!("System::with_tokio_rt is not implemented for io-uring feature yet")
+    }
+}
+
+impl System {
+    /// Constructs new system and registers it on the current thread.
+    pub(crate) fn construct(
+        sys_tx: mpsc::UnboundedSender<SystemCommand>,
+        arbiter_handle: ArbiterHandle,
+    ) -> Self {
+        let sys = System {
+            sys_tx,
+            arbiter_handle,
+            id: SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst),
+        };
+
+        System::set_current(sys.clone());
+
+        sys
+    }
+
+    /// Get current running system.
+    ///
+    /// # Panics
+    /// Panics if no system is registered on the current thread.
+    pub fn current() -> System {
+        CURRENT.with(|cell| match *cell.borrow() {
+            Some(ref sys) => sys.clone(),
+            None => panic!("System is not running"),
+        })
+    }
+
+    /// Try to get current running system.
+    ///
+    /// Returns `None` if no System has been started.
+    ///
+    /// Unlike [`current`](Self::current), this never panics.
+    pub fn try_current() -> Option<System> {
+        CURRENT.with(|cell| cell.borrow().clone())
+    }
+
+    /// Get handle to a the System's initial [Arbiter].
+    pub fn arbiter(&self) -> &ArbiterHandle {
+        &self.arbiter_handle
+    }
+
+    /// Check if there is a System registered on the current thread.
+    pub fn is_registered() -> bool {
+        CURRENT.with(|sys| sys.borrow().is_some())
+    }
+
+    /// Register given system on current thread.
+    #[doc(hidden)]
+    pub fn set_current(sys: System) {
+        CURRENT.with(|cell| {
+            *cell.borrow_mut() = Some(sys);
+        })
+    }
+
+    /// Numeric system identifier.
+    ///
+    /// Useful when using multiple Systems.
+    pub fn id(&self) -> usize {
+        self.id
+    }
+
+    /// Stop the system (with code 0).
+    pub fn stop(&self) {
+        self.stop_with_code(0)
+    }
+
+    /// Stop the system with a given exit code.
+    pub fn stop_with_code(&self, code: i32) {
+        let _ = self.sys_tx.send(SystemCommand::Exit(code));
+    }
+
+    pub(crate) fn tx(&self) -> &mpsc::UnboundedSender<SystemCommand> {
+        &self.sys_tx
+    }
+}
+
+/// Runner that keeps a [System]'s event loop alive until stop message is received.
+#[cfg(not(feature = "io-uring"))]
+#[must_use = "A SystemRunner does nothing unless `run` is called."]
+#[derive(Debug)]
+pub struct SystemRunner {
+    rt: crate::runtime::Runtime,
+    stop_rx: oneshot::Receiver<i32>,
+}
+
+#[cfg(not(feature = "io-uring"))]
+impl SystemRunner {
+    /// Starts event loop and will return once [System] is [stopped](System::stop).
+    pub fn run(self) -> io::Result<()> {
+        let exit_code = self.run_with_code()?;
+
+        match exit_code {
+            0 => Ok(()),
+            nonzero => Err(io::Error::new(
+                io::ErrorKind::Other,
+                format!("Non-zero exit code: {}", nonzero),
+            )),
+        }
+    }
+
+    /// Runs the event loop until [stopped](System::stop_with_code), returning the exit code.
+    pub fn run_with_code(self) -> io::Result<i32> {
+        let SystemRunner { rt, stop_rx, .. } = self;
+
+        // run loop
+        rt.block_on(stop_rx)
+            .map_err(|err| io::Error::new(io::ErrorKind::Other, err))
+    }
+
+    /// Retrieves a reference to the underlying [Actix runtime](crate::Runtime) associated with this
+    /// `SystemRunner` instance.
+    ///
+    /// The Actix runtime is responsible for managing the event loop for an Actix system and
+    /// executing asynchronous tasks. This method provides access to the runtime, allowing direct
+    /// interaction with its features.
+    ///
+    /// In a typical use case, you might need to share the same runtime between different
+    /// parts of your project. For example, some components might require a [`Runtime`] to spawn
+    /// tasks on the same runtime.
+    ///
+    /// Read more in the documentation for [`Runtime`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let system_runner = actix_rt::System::new();
+    /// let actix_runtime = system_runner.runtime();
+    ///
+    /// // Use the runtime to spawn an async task or perform other operations
+    /// ```
+    ///
+    /// # Note
+    ///
+    /// While this method provides an immutable reference to the Actix runtime, which is safe to
+    /// share across threads, be aware that spawning blocking tasks on the Actix runtime could
+    /// potentially impact system performance. This is because the Actix runtime is responsible for
+    /// driving the system, and blocking tasks could delay other tasks in the run loop.
+    ///
+    /// [`Runtime`]: crate::Runtime
+    pub fn runtime(&self) -> &crate::runtime::Runtime {
+        &self.rt
+    }
+
+    /// Runs the provided future, blocking the current thread until the future completes.
+    #[track_caller]
+    #[inline]
+    pub fn block_on<F: Future>(&self, fut: F) -> F::Output {
+        self.rt.block_on(fut)
+    }
+}
+
+/// Runner that keeps a [System]'s event loop alive until stop message is received.
+#[cfg(feature = "io-uring")]
+#[must_use = "A SystemRunner does nothing unless `run` is called."]
+#[derive(Debug)]
+pub struct SystemRunner;
+
+#[cfg(feature = "io-uring")]
+impl SystemRunner {
+    /// Starts event loop and will return once [System] is [stopped](System::stop).
+    pub fn run(self) -> io::Result<()> {
+        unimplemented!("SystemRunner::run is not implemented for io-uring feature yet");
+    }
+
+    /// Runs the event loop until [stopped](System::stop_with_code), returning the exit code.
+    pub fn run_with_code(self) -> io::Result<i32> {
+        unimplemented!("SystemRunner::run_with_code is not implemented for io-uring feature yet");
+    }
+
+    /// Runs the provided future, blocking the current thread until the future completes.
+    #[inline]
+    pub fn block_on<F: Future>(&self, fut: F) -> F::Output {
+        tokio_uring::start(async move {
+            let (stop_tx, stop_rx) = oneshot::channel();
+            let (sys_tx, sys_rx) = mpsc::unbounded_channel();
+
+            let sys_arbiter = Arbiter::in_new_system();
+            let system = System::construct(sys_tx, sys_arbiter.clone());
+
+            system
+                .tx()
+                .send(SystemCommand::RegisterArbiter(usize::MAX, sys_arbiter))
+                .unwrap();
+
+            // init background system arbiter
+            let sys_ctrl = SystemController::new(sys_rx, stop_tx);
+            tokio_uring::spawn(sys_ctrl);
+
+            let res = fut.await;
+            drop(stop_rx);
+            res
+        })
+    }
+}
+
+#[derive(Debug)]
+pub(crate) enum SystemCommand {
+    Exit(i32),
+    RegisterArbiter(usize, ArbiterHandle),
+    DeregisterArbiter(usize),
+}
+
+/// There is one `SystemController` per [System]. It runs in the background, keeping track of
+/// [Arbiter]s and is able to distribute a system-wide stop command.
+#[derive(Debug)]
+pub(crate) struct SystemController {
+    stop_tx: Option<oneshot::Sender<i32>>,
+    cmd_rx: mpsc::UnboundedReceiver<SystemCommand>,
+    arbiters: HashMap<usize, ArbiterHandle>,
+}
+
+impl SystemController {
+    pub(crate) fn new(
+        cmd_rx: mpsc::UnboundedReceiver<SystemCommand>,
+        stop_tx: oneshot::Sender<i32>,
+    ) -> Self {
+        SystemController {
+            cmd_rx,
+            stop_tx: Some(stop_tx),
+            arbiters: HashMap::with_capacity(4),
+        }
+    }
+}
+
+impl Future for SystemController {
+    type Output = ();
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        // process all items currently buffered in channel
+        loop {
+            match ready!(self.cmd_rx.poll_recv(cx)) {
+                // channel closed; no more messages can be received
+                None => return Poll::Ready(()),
+
+                // process system command
+                Some(cmd) => match cmd {
+                    SystemCommand::Exit(code) => {
+                        // stop all arbiters
+                        for arb in self.arbiters.values() {
+                            arb.stop();
+                        }
+
+                        // stop event loop
+                        // will only fire once
+                        if let Some(stop_tx) = self.stop_tx.take() {
+                            let _ = stop_tx.send(code);
+                        }
+                    }
+
+                    SystemCommand::RegisterArbiter(id, arb) => {
+                        self.arbiters.insert(id, arb);
+                    }
+
+                    SystemCommand::DeregisterArbiter(id) => {
+                        self.arbiters.remove(&id);
+                    }
+                },
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/accept.rs.html b/src/actix_server/accept.rs.html new file mode 100644 index 00000000..f8c0a9d1 --- /dev/null +++ b/src/actix_server/accept.rs.html @@ -0,0 +1,925 @@ +accept.rs - source

actix_server/
accept.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
use std::{io, thread, time::Duration};
+
+use actix_rt::time::Instant;
+use mio::{Interest, Poll, Token as MioToken};
+use tracing::{debug, error, info};
+
+use crate::{
+    availability::Availability,
+    socket::MioListener,
+    waker_queue::{WakerInterest, WakerQueue, WAKER_TOKEN},
+    worker::{Conn, ServerWorker, WorkerHandleAccept, WorkerHandleServer},
+    ServerBuilder, ServerHandle,
+};
+
+const TIMEOUT_DURATION_ON_ERROR: Duration = Duration::from_millis(510);
+
+struct ServerSocketInfo {
+    token: usize,
+
+    lst: MioListener,
+
+    /// Timeout is used to mark the deadline when this socket's listener should be registered again
+    /// after an error.
+    timeout: Option<actix_rt::time::Instant>,
+}
+
+/// Poll instance of the server.
+pub(crate) struct Accept {
+    poll: Poll,
+    waker_queue: WakerQueue,
+    handles: Vec<WorkerHandleAccept>,
+    srv: ServerHandle,
+    next: usize,
+    avail: Availability,
+    /// use the smallest duration from sockets timeout.
+    timeout: Option<Duration>,
+    paused: bool,
+}
+
+impl Accept {
+    pub(crate) fn start(
+        sockets: Vec<(usize, MioListener)>,
+        builder: &ServerBuilder,
+    ) -> io::Result<(WakerQueue, Vec<WorkerHandleServer>, thread::JoinHandle<()>)> {
+        let handle_server = ServerHandle::new(builder.cmd_tx.clone());
+
+        // construct poll instance and its waker
+        let poll = Poll::new()?;
+        let waker_queue = WakerQueue::new(poll.registry())?;
+
+        // start workers and collect handles
+        let (handles_accept, handles_server) = (0..builder.threads)
+            .map(|idx| {
+                // clone service factories
+                let factories = builder
+                    .factories
+                    .iter()
+                    .map(|f| f.clone_factory())
+                    .collect::<Vec<_>>();
+
+                // start worker using service factories
+                ServerWorker::start(idx, factories, waker_queue.clone(), builder.worker_config)
+            })
+            .collect::<io::Result<Vec<_>>>()?
+            .into_iter()
+            .unzip();
+
+        let (mut accept, mut sockets) = Accept::new_with_sockets(
+            poll,
+            waker_queue.clone(),
+            sockets,
+            handles_accept,
+            handle_server,
+        )?;
+
+        let accept_handle = thread::Builder::new()
+            .name("actix-server acceptor".to_owned())
+            .spawn(move || accept.poll_with(&mut sockets))
+            .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
+
+        Ok((waker_queue, handles_server, accept_handle))
+    }
+
+    fn new_with_sockets(
+        poll: Poll,
+        waker_queue: WakerQueue,
+        sockets: Vec<(usize, MioListener)>,
+        accept_handles: Vec<WorkerHandleAccept>,
+        server_handle: ServerHandle,
+    ) -> io::Result<(Accept, Box<[ServerSocketInfo]>)> {
+        let sockets = sockets
+            .into_iter()
+            .map(|(token, mut lst)| {
+                // Start listening for incoming connections
+                poll.registry()
+                    .register(&mut lst, MioToken(token), Interest::READABLE)?;
+
+                Ok(ServerSocketInfo {
+                    token,
+                    lst,
+                    timeout: None,
+                })
+            })
+            .collect::<io::Result<_>>()?;
+
+        let mut avail = Availability::default();
+
+        // Assume all handles are avail at construct time.
+        avail.set_available_all(&accept_handles);
+
+        let accept = Accept {
+            poll,
+            waker_queue,
+            handles: accept_handles,
+            srv: server_handle,
+            next: 0,
+            avail,
+            timeout: None,
+            paused: false,
+        };
+
+        Ok((accept, sockets))
+    }
+
+    /// blocking wait for readiness events triggered by mio
+    fn poll_with(&mut self, sockets: &mut [ServerSocketInfo]) {
+        let mut events = mio::Events::with_capacity(256);
+
+        loop {
+            if let Err(err) = self.poll.poll(&mut events, self.timeout) {
+                match err.kind() {
+                    io::ErrorKind::Interrupted => {}
+                    _ => panic!("Poll error: {}", err),
+                }
+            }
+
+            for event in events.iter() {
+                let token = event.token();
+                match token {
+                    WAKER_TOKEN => {
+                        let exit = self.handle_waker(sockets);
+                        if exit {
+                            info!("accept thread stopped");
+                            return;
+                        }
+                    }
+                    _ => {
+                        let token = usize::from(token);
+                        self.accept(sockets, token);
+                    }
+                }
+            }
+
+            // check for timeout and re-register sockets
+            self.process_timeout(sockets);
+        }
+    }
+
+    fn handle_waker(&mut self, sockets: &mut [ServerSocketInfo]) -> bool {
+        // This is a loop because interests for command from previous version was
+        // a loop that would try to drain the command channel. It's yet unknown
+        // if it's necessary/good practice to actively drain the waker queue.
+        loop {
+            // Take guard with every iteration so no new interests can be added until the current
+            // task is done. Take care not to take the guard again inside this loop.
+            let mut guard = self.waker_queue.guard();
+
+            #[allow(clippy::significant_drop_in_scrutinee)]
+            match guard.pop_front() {
+                // Worker notified it became available.
+                Some(WakerInterest::WorkerAvailable(idx)) => {
+                    drop(guard);
+
+                    self.avail.set_available(idx, true);
+
+                    if !self.paused {
+                        self.accept_all(sockets);
+                    }
+                }
+
+                // A new worker thread has been created so store its handle.
+                Some(WakerInterest::Worker(handle)) => {
+                    drop(guard);
+
+                    self.avail.set_available(handle.idx(), true);
+                    self.handles.push(handle);
+
+                    if !self.paused {
+                        self.accept_all(sockets);
+                    }
+                }
+
+                Some(WakerInterest::Pause) => {
+                    drop(guard);
+
+                    if !self.paused {
+                        self.paused = true;
+
+                        self.deregister_all(sockets);
+                    }
+                }
+
+                Some(WakerInterest::Resume) => {
+                    drop(guard);
+
+                    if self.paused {
+                        self.paused = false;
+
+                        sockets.iter_mut().for_each(|info| {
+                            self.register_logged(info);
+                        });
+
+                        self.accept_all(sockets);
+                    }
+                }
+
+                Some(WakerInterest::Stop) => {
+                    if !self.paused {
+                        self.deregister_all(sockets);
+                    }
+
+                    return true;
+                }
+
+                // waker queue is drained
+                None => {
+                    // Reset the WakerQueue before break so it does not grow infinitely
+                    WakerQueue::reset(&mut guard);
+
+                    return false;
+                }
+            }
+        }
+    }
+
+    fn process_timeout(&mut self, sockets: &mut [ServerSocketInfo]) {
+        // always remove old timeouts
+        if self.timeout.take().is_some() {
+            let now = Instant::now();
+
+            sockets
+                .iter_mut()
+                // Only sockets that had an associated timeout were deregistered.
+                .filter(|info| info.timeout.is_some())
+                .for_each(|info| {
+                    let inst = info.timeout.take().unwrap();
+
+                    if now < inst {
+                        // still timed out; try to set new timeout
+                        info.timeout = Some(inst);
+                        self.set_timeout(inst - now);
+                    } else if !self.paused {
+                        // timeout expired; register socket again
+                        self.register_logged(info);
+                    }
+
+                    // Drop the timeout if server is paused and socket timeout is expired.
+                    // When server recovers from pause it will register all sockets without
+                    // a timeout value so this socket register will be delayed till then.
+                });
+        }
+    }
+
+    /// Update accept timeout with `duration` if it is shorter than current timeout.
+    fn set_timeout(&mut self, duration: Duration) {
+        match self.timeout {
+            Some(ref mut timeout) => {
+                if *timeout > duration {
+                    *timeout = duration;
+                }
+            }
+            None => self.timeout = Some(duration),
+        }
+    }
+
+    #[cfg(not(target_os = "windows"))]
+    fn register(&self, info: &mut ServerSocketInfo) -> io::Result<()> {
+        let token = MioToken(info.token);
+        self.poll
+            .registry()
+            .register(&mut info.lst, token, Interest::READABLE)
+    }
+
+    #[cfg(target_os = "windows")]
+    fn register(&self, info: &mut ServerSocketInfo) -> io::Result<()> {
+        // On windows, calling register without deregister cause an error.
+        // See https://github.com/actix/actix-web/issues/905
+        // Calling reregister seems to fix the issue.
+        let token = MioToken(info.token);
+        self.poll
+            .registry()
+            .register(&mut info.lst, token, Interest::READABLE)
+            .or_else(|_| {
+                self.poll
+                    .registry()
+                    .reregister(&mut info.lst, token, Interest::READABLE)
+            })
+    }
+
+    fn register_logged(&self, info: &mut ServerSocketInfo) {
+        match self.register(info) {
+            Ok(_) => debug!("resume accepting connections on {}", info.lst.local_addr()),
+            Err(err) => error!("can not register server socket {}", err),
+        }
+    }
+
+    fn deregister_logged(&self, info: &mut ServerSocketInfo) {
+        match self.poll.registry().deregister(&mut info.lst) {
+            Ok(_) => debug!("paused accepting connections on {}", info.lst.local_addr()),
+            Err(err) => {
+                error!("can not deregister server socket {}", err)
+            }
+        }
+    }
+
+    fn deregister_all(&self, sockets: &mut [ServerSocketInfo]) {
+        // This is a best effort implementation with following limitation:
+        //
+        // Every ServerSocketInfo with associated timeout will be skipped and it's timeout is
+        // removed in the process.
+        //
+        // Therefore WakerInterest::Pause followed by WakerInterest::Resume in a very short gap
+        // (less than 500ms) would cause all timing out ServerSocketInfos be re-registered before
+        // expected timing.
+        sockets
+            .iter_mut()
+            // Take all timeout.
+            // This is to prevent Accept::process_timer method re-register a socket afterwards.
+            .map(|info| (info.timeout.take(), info))
+            // Socket info with a timeout is already deregistered so skip them.
+            .filter(|(timeout, _)| timeout.is_none())
+            .for_each(|(_, info)| self.deregister_logged(info));
+    }
+
+    // Send connection to worker and handle error.
+    fn send_connection(&mut self, conn: Conn) -> Result<(), Conn> {
+        let next = self.next();
+        match next.send(conn) {
+            Ok(_) => {
+                // Increment counter of WorkerHandle.
+                // Set worker to unavailable with it hit max (Return false).
+                if !next.inc_counter() {
+                    let idx = next.idx();
+                    self.avail.set_available(idx, false);
+                }
+                self.set_next();
+                Ok(())
+            }
+            Err(conn) => {
+                // Worker thread is error and could be gone.
+                // Remove worker handle and notify `ServerBuilder`.
+                self.remove_next();
+
+                if self.handles.is_empty() {
+                    error!("no workers");
+                    // All workers are gone and Conn is nowhere to be sent.
+                    // Treat this situation as Ok and drop Conn.
+                    return Ok(());
+                } else if self.handles.len() <= self.next {
+                    self.next = 0;
+                }
+
+                Err(conn)
+            }
+        }
+    }
+
+    fn accept_one(&mut self, mut conn: Conn) {
+        loop {
+            let next = self.next();
+            let idx = next.idx();
+
+            if self.avail.get_available(idx) {
+                match self.send_connection(conn) {
+                    Ok(_) => return,
+                    Err(c) => conn = c,
+                }
+            } else {
+                self.avail.set_available(idx, false);
+                self.set_next();
+
+                if !self.avail.available() {
+                    while let Err(c) = self.send_connection(conn) {
+                        conn = c;
+                    }
+                    return;
+                }
+            }
+        }
+    }
+
+    fn accept(&mut self, sockets: &mut [ServerSocketInfo], token: usize) {
+        while self.avail.available() {
+            let info = &mut sockets[token];
+
+            match info.lst.accept() {
+                Ok(io) => {
+                    let conn = Conn { io, token };
+                    self.accept_one(conn);
+                }
+                Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => return,
+                Err(ref err) if connection_error(err) => continue,
+                Err(err) => {
+                    error!("error accepting connection: {}", err);
+
+                    // deregister listener temporary
+                    self.deregister_logged(info);
+
+                    // sleep after error. write the timeout to socket info as later
+                    // the poll would need it mark which socket and when it's
+                    // listener should be registered
+                    info.timeout = Some(Instant::now() + Duration::from_millis(500));
+                    self.set_timeout(TIMEOUT_DURATION_ON_ERROR);
+
+                    return;
+                }
+            };
+        }
+    }
+
+    fn accept_all(&mut self, sockets: &mut [ServerSocketInfo]) {
+        sockets
+            .iter_mut()
+            .map(|info| info.token)
+            .collect::<Vec<_>>()
+            .into_iter()
+            .for_each(|idx| self.accept(sockets, idx))
+    }
+
+    #[inline(always)]
+    fn next(&self) -> &WorkerHandleAccept {
+        &self.handles[self.next]
+    }
+
+    /// Set next worker handle that would accept connection.
+    #[inline(always)]
+    fn set_next(&mut self) {
+        self.next = (self.next + 1) % self.handles.len();
+    }
+
+    /// Remove next worker handle that fail to accept connection.
+    fn remove_next(&mut self) {
+        let handle = self.handles.swap_remove(self.next);
+        let idx = handle.idx();
+        // A message is sent to `ServerBuilder` future to notify it a new worker
+        // should be made.
+        self.srv.worker_faulted(idx);
+        self.avail.set_available(idx, false);
+    }
+}
+
+/// This function defines errors that are per-connection; if we get this error from the `accept()`
+/// system call it means the next connection might be ready to be accepted.
+///
+/// All other errors will incur a timeout before next `accept()` call is attempted. The timeout is
+/// useful to handle resource exhaustion errors like `ENFILE` and `EMFILE`. Otherwise, it could
+/// enter into a temporary spin loop.
+fn connection_error(e: &io::Error) -> bool {
+    e.kind() == io::ErrorKind::ConnectionRefused
+        || e.kind() == io::ErrorKind::ConnectionAborted
+        || e.kind() == io::ErrorKind::ConnectionReset
+}
+
\ No newline at end of file diff --git a/src/actix_server/availability.rs.html b/src/actix_server/availability.rs.html new file mode 100644 index 00000000..3053529f --- /dev/null +++ b/src/actix_server/availability.rs.html @@ -0,0 +1,243 @@ +availability.rs - source

actix_server/
availability.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
use crate::worker::WorkerHandleAccept;
+
+/// Array of u128 with every bit as marker for a worker handle's availability.
+#[derive(Debug, Default)]
+pub(crate) struct Availability([u128; 4]);
+
+impl Availability {
+    /// Check if any worker handle is available
+    #[inline(always)]
+    pub(crate) fn available(&self) -> bool {
+        self.0.iter().any(|a| *a != 0)
+    }
+
+    /// Check if worker handle is available by index
+    #[inline(always)]
+    pub(crate) fn get_available(&self, idx: usize) -> bool {
+        let (offset, idx) = Self::offset(idx);
+
+        self.0[offset] & (1 << idx as u128) != 0
+    }
+
+    /// Set worker handle available state by index.
+    pub(crate) fn set_available(&mut self, idx: usize, avail: bool) {
+        let (offset, idx) = Self::offset(idx);
+
+        let off = 1 << idx as u128;
+        if avail {
+            self.0[offset] |= off;
+        } else {
+            self.0[offset] &= !off
+        }
+    }
+
+    /// Set all worker handle to available state.
+    /// This would result in a re-check on all workers' availability.
+    pub(crate) fn set_available_all(&mut self, handles: &[WorkerHandleAccept]) {
+        handles.iter().for_each(|handle| {
+            self.set_available(handle.idx(), true);
+        })
+    }
+
+    /// Get offset and adjusted index of given worker handle index.
+    pub(crate) fn offset(idx: usize) -> (usize, usize) {
+        if idx < 128 {
+            (0, idx)
+        } else if idx < 128 * 2 {
+            (1, idx - 128)
+        } else if idx < 128 * 3 {
+            (2, idx - 128 * 2)
+        } else if idx < 128 * 4 {
+            (3, idx - 128 * 3)
+        } else {
+            panic!("Max WorkerHandle count is 512")
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn single(aval: &mut Availability, idx: usize) {
+        aval.set_available(idx, true);
+        assert!(aval.available());
+
+        aval.set_available(idx, true);
+
+        aval.set_available(idx, false);
+        assert!(!aval.available());
+
+        aval.set_available(idx, false);
+        assert!(!aval.available());
+    }
+
+    fn multi(aval: &mut Availability, mut idx: Vec<usize>) {
+        idx.iter().for_each(|idx| aval.set_available(*idx, true));
+
+        assert!(aval.available());
+
+        while let Some(idx) = idx.pop() {
+            assert!(aval.available());
+            aval.set_available(idx, false);
+        }
+
+        assert!(!aval.available());
+    }
+
+    #[test]
+    fn availability() {
+        let mut aval = Availability::default();
+
+        single(&mut aval, 1);
+        single(&mut aval, 128);
+        single(&mut aval, 256);
+        single(&mut aval, 511);
+
+        let idx = (0..511).filter(|i| i % 3 == 0 && i % 5 == 0).collect();
+
+        multi(&mut aval, idx);
+
+        multi(&mut aval, (0..511).collect())
+    }
+
+    #[test]
+    #[should_panic]
+    fn overflow() {
+        let mut aval = Availability::default();
+        single(&mut aval, 512);
+    }
+
+    #[test]
+    fn pin_point() {
+        let mut aval = Availability::default();
+
+        aval.set_available(438, true);
+
+        aval.set_available(479, true);
+
+        assert_eq!(aval.0[3], 1 << (438 - 384) | 1 << (479 - 384));
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/builder.rs.html b/src/actix_server/builder.rs.html new file mode 100644 index 00000000..d5a38f41 --- /dev/null +++ b/src/actix_server/builder.rs.html @@ -0,0 +1,757 @@ +builder.rs - source

actix_server/
builder.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
use std::{io, num::NonZeroUsize, time::Duration};
+
+use actix_rt::net::TcpStream;
+use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
+
+use crate::{
+    server::ServerCommand,
+    service::{InternalServiceFactory, ServerServiceFactory, StreamNewService},
+    socket::{create_mio_tcp_listener, MioListener, MioTcpListener, StdTcpListener, ToSocketAddrs},
+    worker::ServerWorkerConfig,
+    Server,
+};
+
+/// Multipath TCP (MPTCP) preference.
+///
+/// Currently only useful on Linux.
+///
+#[cfg_attr(target_os = "linux", doc = "Also see [`ServerBuilder::mptcp()`].")]
+#[derive(Debug, Clone)]
+pub enum MpTcp {
+    /// MPTCP will not be used when binding sockets.
+    Disabled,
+
+    /// MPTCP will be attempted when binding sockets. If errors occur, regular TCP will be
+    /// attempted, too.
+    TcpFallback,
+
+    /// MPTCP will be used when binding sockets (with no fallback).
+    NoFallback,
+}
+
+/// [Server] builder.
+pub struct ServerBuilder {
+    pub(crate) threads: usize,
+    pub(crate) token: usize,
+    pub(crate) backlog: u32,
+    pub(crate) factories: Vec<Box<dyn InternalServiceFactory>>,
+    pub(crate) sockets: Vec<(usize, String, MioListener)>,
+    pub(crate) mptcp: MpTcp,
+    pub(crate) exit: bool,
+    pub(crate) listen_os_signals: bool,
+    pub(crate) cmd_tx: UnboundedSender<ServerCommand>,
+    pub(crate) cmd_rx: UnboundedReceiver<ServerCommand>,
+    pub(crate) worker_config: ServerWorkerConfig,
+}
+
+impl Default for ServerBuilder {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl ServerBuilder {
+    /// Create new Server builder instance
+    pub fn new() -> ServerBuilder {
+        let (cmd_tx, cmd_rx) = unbounded_channel();
+
+        ServerBuilder {
+            threads: std::thread::available_parallelism().map_or(2, NonZeroUsize::get),
+            token: 0,
+            factories: Vec::new(),
+            sockets: Vec::new(),
+            backlog: 2048,
+            mptcp: MpTcp::Disabled,
+            exit: false,
+            listen_os_signals: true,
+            cmd_tx,
+            cmd_rx,
+            worker_config: ServerWorkerConfig::default(),
+        }
+    }
+
+    /// Sets number of workers to start.
+    ///
+    /// See [`bind()`](Self::bind()) for more details on how worker count affects the number of
+    /// server factory instantiations.
+    ///
+    /// The default worker count is the determined by [`std::thread::available_parallelism()`]. See
+    /// its documentation to determine what behavior you should expect when server is run.
+    ///
+    /// `num` must be greater than 0.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `num` is 0.
+    pub fn workers(mut self, num: usize) -> Self {
+        assert_ne!(num, 0, "workers must be greater than 0");
+        self.threads = num;
+        self
+    }
+
+    /// Set max number of threads for each worker's blocking task thread pool.
+    ///
+    /// One thread pool is set up **per worker**; not shared across workers.
+    ///
+    /// # Examples:
+    /// ```
+    /// # use actix_server::ServerBuilder;
+    /// let builder = ServerBuilder::new()
+    ///     .workers(4) // server has 4 worker thread.
+    ///     .worker_max_blocking_threads(4); // every worker has 4 max blocking threads.
+    /// ```
+    ///
+    /// See [tokio::runtime::Builder::max_blocking_threads] for behavior reference.
+    pub fn worker_max_blocking_threads(mut self, num: usize) -> Self {
+        self.worker_config.max_blocking_threads(num);
+        self
+    }
+
+    /// Set the maximum number of pending connections.
+    ///
+    /// This refers to the number of clients that can be waiting to be served. Exceeding this number
+    /// results in the client getting an error when attempting to connect. It should only affect
+    /// servers under significant load.
+    ///
+    /// Generally set in the 64-2048 range. Default value is 2048.
+    ///
+    /// This method should be called before `bind()` method call.
+    pub fn backlog(mut self, num: u32) -> Self {
+        self.backlog = num;
+        self
+    }
+
+    /// Sets MultiPath TCP (MPTCP) preference on bound sockets.
+    ///
+    /// Multipath TCP (MPTCP) builds on top of TCP to improve connection redundancy and performance
+    /// by sharing a network data stream across multiple underlying TCP sessions. See [mptcp.dev]
+    /// for more info about MPTCP itself.
+    ///
+    /// MPTCP is available on Linux kernel version 5.6 and higher. In addition, you'll also need to
+    /// ensure the kernel option is enabled using `sysctl net.mptcp.enabled=1`.
+    ///
+    /// This method will have no effect if called after a `bind()`.
+    ///
+    /// [mptcp.dev]: https://www.mptcp.dev
+    #[cfg(target_os = "linux")]
+    pub fn mptcp(mut self, mptcp_enabled: MpTcp) -> Self {
+        self.mptcp = mptcp_enabled;
+        self
+    }
+
+    /// Sets the maximum per-worker number of concurrent connections.
+    ///
+    /// All socket listeners will stop accepting connections when this limit is reached for
+    /// each worker.
+    ///
+    /// By default max connections is set to a 25k per worker.
+    pub fn max_concurrent_connections(mut self, num: usize) -> Self {
+        self.worker_config.max_concurrent_connections(num);
+        self
+    }
+
+    #[doc(hidden)]
+    #[deprecated(since = "2.0.0", note = "Renamed to `max_concurrent_connections`.")]
+    pub fn maxconn(self, num: usize) -> Self {
+        self.max_concurrent_connections(num)
+    }
+
+    /// Sets flag to stop Actix `System` after server shutdown.
+    ///
+    /// This has no effect when server is running in a Tokio-only runtime.
+    pub fn system_exit(mut self) -> Self {
+        self.exit = true;
+        self
+    }
+
+    /// Disables OS signal handling.
+    pub fn disable_signals(mut self) -> Self {
+        self.listen_os_signals = false;
+        self
+    }
+
+    /// Timeout for graceful workers shutdown in seconds.
+    ///
+    /// After receiving a stop signal, workers have this much time to finish serving requests.
+    /// Workers still alive after the timeout are force dropped.
+    ///
+    /// By default shutdown timeout sets to 30 seconds.
+    pub fn shutdown_timeout(mut self, sec: u64) -> Self {
+        self.worker_config
+            .shutdown_timeout(Duration::from_secs(sec));
+        self
+    }
+
+    /// Adds new service to the server.
+    ///
+    /// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation.
+    ///
+    /// # Worker Count
+    ///
+    /// The `factory` will be instantiated multiple times in most scenarios. The number of
+    /// instantiations is number of [`workers`](Self::workers()) ร— number of sockets resolved by
+    /// `addrs`.
+    ///
+    /// For example, if you've manually set [`workers`](Self::workers()) to 2, and use `127.0.0.1`
+    /// as the bind `addrs`, then `factory` will be instantiated twice. However, using `localhost`
+    /// as the bind `addrs` can often resolve to both `127.0.0.1` (IPv4) _and_ `::1` (IPv6), causing
+    /// the `factory` to be instantiated 4 times (2 workers ร— 2 bind addresses).
+    ///
+    /// Using a bind address of `0.0.0.0`, which signals to use all interfaces, may also multiple
+    /// the number of instantiations in a similar way.
+    ///
+    /// # Errors
+    ///
+    /// Returns an `io::Error` if:
+    /// - `addrs` cannot be resolved into one or more socket addresses;
+    /// - all the resolved socket addresses are already bound.
+    pub fn bind<F, U, N>(mut self, name: N, addrs: U, factory: F) -> io::Result<Self>
+    where
+        F: ServerServiceFactory<TcpStream>,
+        U: ToSocketAddrs,
+        N: AsRef<str>,
+    {
+        let sockets = bind_addr(addrs, self.backlog, &self.mptcp)?;
+
+        tracing::trace!("binding server to: {sockets:?}");
+
+        for lst in sockets {
+            let token = self.next_token();
+
+            self.factories.push(StreamNewService::create(
+                name.as_ref().to_string(),
+                token,
+                factory.clone(),
+                lst.local_addr()?,
+            ));
+
+            self.sockets
+                .push((token, name.as_ref().to_string(), MioListener::Tcp(lst)));
+        }
+
+        Ok(self)
+    }
+
+    /// Adds service to the server using a socket listener already bound.
+    ///
+    /// # Worker Count
+    ///
+    /// The `factory` will be instantiated multiple times in most scenarios. The number of
+    /// instantiations is: number of [`workers`](Self::workers()).
+    pub fn listen<F, N: AsRef<str>>(
+        mut self,
+        name: N,
+        lst: StdTcpListener,
+        factory: F,
+    ) -> io::Result<Self>
+    where
+        F: ServerServiceFactory<TcpStream>,
+    {
+        lst.set_nonblocking(true)?;
+        let addr = lst.local_addr()?;
+
+        let token = self.next_token();
+        self.factories.push(StreamNewService::create(
+            name.as_ref().to_string(),
+            token,
+            factory,
+            addr,
+        ));
+
+        self.sockets
+            .push((token, name.as_ref().to_string(), MioListener::from(lst)));
+
+        Ok(self)
+    }
+
+    /// Starts processing incoming connections and return server controller.
+    pub fn run(self) -> Server {
+        if self.sockets.is_empty() {
+            panic!("Server should have at least one bound socket");
+        } else {
+            tracing::info!("starting {} workers", self.threads);
+            Server::new(self)
+        }
+    }
+
+    fn next_token(&mut self) -> usize {
+        let token = self.token;
+        self.token += 1;
+        token
+    }
+}
+
+#[cfg(unix)]
+impl ServerBuilder {
+    /// Adds new service to the server using a UDS (unix domain socket) address.
+    ///
+    /// # Worker Count
+    ///
+    /// The `factory` will be instantiated multiple times in most scenarios. The number of
+    /// instantiations is: number of [`workers`](Self::workers()).
+    pub fn bind_uds<F, U, N>(self, name: N, addr: U, factory: F) -> io::Result<Self>
+    where
+        F: ServerServiceFactory<actix_rt::net::UnixStream>,
+        N: AsRef<str>,
+        U: AsRef<std::path::Path>,
+    {
+        // The path must not exist when we try to bind.
+        // Try to remove it to avoid bind error.
+        if let Err(err) = std::fs::remove_file(addr.as_ref()) {
+            // NotFound is expected and not an issue. Anything else is.
+            if err.kind() != std::io::ErrorKind::NotFound {
+                return Err(err);
+            }
+        }
+
+        let lst = crate::socket::StdUnixListener::bind(addr)?;
+        self.listen_uds(name, lst, factory)
+    }
+
+    /// Adds new service to the server using a UDS (unix domain socket) listener already bound.
+    ///
+    /// Useful when running as a systemd service and a socket FD is acquired externally.
+    ///
+    /// # Worker Count
+    ///
+    /// The `factory` will be instantiated multiple times in most scenarios. The number of
+    /// instantiations is: number of [`workers`](Self::workers()).
+    pub fn listen_uds<F, N: AsRef<str>>(
+        mut self,
+        name: N,
+        lst: crate::socket::StdUnixListener,
+        factory: F,
+    ) -> io::Result<Self>
+    where
+        F: ServerServiceFactory<actix_rt::net::UnixStream>,
+    {
+        use std::net::{IpAddr, Ipv4Addr};
+
+        lst.set_nonblocking(true)?;
+
+        let token = self.next_token();
+        let addr = crate::socket::StdSocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
+
+        self.factories.push(StreamNewService::create(
+            name.as_ref().to_string(),
+            token,
+            factory,
+            addr,
+        ));
+
+        self.sockets
+            .push((token, name.as_ref().to_string(), MioListener::from(lst)));
+
+        Ok(self)
+    }
+}
+
+pub(super) fn bind_addr<S: ToSocketAddrs>(
+    addr: S,
+    backlog: u32,
+    mptcp: &MpTcp,
+) -> io::Result<Vec<MioTcpListener>> {
+    let mut opt_err = None;
+    let mut success = false;
+    let mut sockets = Vec::new();
+
+    for addr in addr.to_socket_addrs()? {
+        match create_mio_tcp_listener(addr, backlog, mptcp) {
+            Ok(lst) => {
+                success = true;
+                sockets.push(lst);
+            }
+            Err(err) => opt_err = Some(err),
+        }
+    }
+
+    if success {
+        Ok(sockets)
+    } else if let Some(err) = opt_err.take() {
+        Err(err)
+    } else {
+        Err(io::Error::new(
+            io::ErrorKind::Other,
+            "Can not bind to address.",
+        ))
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/handle.rs.html b/src/actix_server/handle.rs.html new file mode 100644 index 00000000..fda7881b --- /dev/null +++ b/src/actix_server/handle.rs.html @@ -0,0 +1,113 @@ +handle.rs - source

actix_server/
handle.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
use std::future::Future;
+
+use tokio::sync::{mpsc::UnboundedSender, oneshot};
+
+use crate::server::ServerCommand;
+
+/// Server handle.
+#[derive(Debug, Clone)]
+pub struct ServerHandle {
+    cmd_tx: UnboundedSender<ServerCommand>,
+}
+
+impl ServerHandle {
+    pub(crate) fn new(cmd_tx: UnboundedSender<ServerCommand>) -> Self {
+        ServerHandle { cmd_tx }
+    }
+
+    pub(crate) fn worker_faulted(&self, idx: usize) {
+        let _ = self.cmd_tx.send(ServerCommand::WorkerFaulted(idx));
+    }
+
+    /// Pause accepting incoming connections.
+    ///
+    /// May drop socket pending connection. All open connections remain active.
+    pub fn pause(&self) -> impl Future<Output = ()> {
+        let (tx, rx) = oneshot::channel();
+        let _ = self.cmd_tx.send(ServerCommand::Pause(tx));
+        async {
+            let _ = rx.await;
+        }
+    }
+
+    /// Resume accepting incoming connections.
+    pub fn resume(&self) -> impl Future<Output = ()> {
+        let (tx, rx) = oneshot::channel();
+        let _ = self.cmd_tx.send(ServerCommand::Resume(tx));
+        async {
+            let _ = rx.await;
+        }
+    }
+
+    /// Stop incoming connection processing, stop all workers and exit.
+    pub fn stop(&self, graceful: bool) -> impl Future<Output = ()> {
+        let (tx, rx) = oneshot::channel();
+
+        let _ = self.cmd_tx.send(ServerCommand::Stop {
+            graceful,
+            completion: Some(tx),
+            force_system_stop: false,
+        });
+
+        async {
+            let _ = rx.await;
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/join_all.rs.html b/src/actix_server/join_all.rs.html new file mode 100644 index 00000000..b5fb8a36 --- /dev/null +++ b/src/actix_server/join_all.rs.html @@ -0,0 +1,157 @@ +join_all.rs - source

actix_server/
join_all.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
use std::{
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use futures_core::future::BoxFuture;
+
+// a poor man's join future. joined future is only used when starting/stopping the server.
+// pin_project and pinned futures are overkill for this task.
+pub(crate) struct JoinAll<T> {
+    fut: Vec<JoinFuture<T>>,
+}
+
+pub(crate) fn join_all<T>(fut: Vec<impl Future<Output = T> + Send + 'static>) -> JoinAll<T> {
+    let fut = fut
+        .into_iter()
+        .map(|f| JoinFuture::Future(Box::pin(f)))
+        .collect();
+
+    JoinAll { fut }
+}
+
+enum JoinFuture<T> {
+    Future(BoxFuture<'static, T>),
+    Result(Option<T>),
+}
+
+impl<T> Unpin for JoinAll<T> {}
+
+impl<T> Future for JoinAll<T> {
+    type Output = Vec<T>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut ready = true;
+
+        let this = self.get_mut();
+        for fut in this.fut.iter_mut() {
+            if let JoinFuture::Future(f) = fut {
+                match f.as_mut().poll(cx) {
+                    Poll::Ready(t) => {
+                        *fut = JoinFuture::Result(Some(t));
+                    }
+                    Poll::Pending => ready = false,
+                }
+            }
+        }
+
+        if ready {
+            let mut res = Vec::new();
+            for fut in this.fut.iter_mut() {
+                if let JoinFuture::Result(f) = fut {
+                    res.push(f.take().unwrap());
+                }
+            }
+
+            Poll::Ready(res)
+        } else {
+            Poll::Pending
+        }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use actix_utils::future::ready;
+
+    use super::*;
+
+    #[actix_rt::test]
+    async fn test_join_all() {
+        let futs = vec![ready(Ok(1)), ready(Err(3)), ready(Ok(9))];
+        let mut res = join_all(futs).await.into_iter();
+        assert_eq!(Ok(1), res.next().unwrap());
+        assert_eq!(Err(3), res.next().unwrap());
+        assert_eq!(Ok(9), res.next().unwrap());
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/lib.rs.html b/src/actix_server/lib.rs.html new file mode 100644 index 00000000..2d5b6617 --- /dev/null +++ b/src/actix_server/lib.rs.html @@ -0,0 +1,73 @@ +lib.rs - source

actix_server/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
//! General purpose TCP server.
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+mod accept;
+mod availability;
+mod builder;
+mod handle;
+mod join_all;
+mod server;
+mod service;
+mod signals;
+mod socket;
+mod test_server;
+mod waker_queue;
+mod worker;
+
+#[doc(hidden)]
+pub use self::socket::FromStream;
+pub use self::{
+    builder::{MpTcp, ServerBuilder},
+    handle::ServerHandle,
+    server::Server,
+    service::ServerServiceFactory,
+    test_server::TestServer,
+};
+
+/// Start server building process
+#[doc(hidden)]
+#[deprecated(since = "2.0.0", note = "Use `Server::build()`.")]
+pub fn new() -> ServerBuilder {
+    ServerBuilder::default()
+}
+
\ No newline at end of file diff --git a/src/actix_server/server.rs.html b/src/actix_server/server.rs.html new file mode 100644 index 00000000..c4110445 --- /dev/null +++ b/src/actix_server/server.rs.html @@ -0,0 +1,737 @@ +server.rs - source

actix_server/
server.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
use std::{
+    future::Future,
+    io, mem,
+    pin::Pin,
+    task::{Context, Poll},
+    thread,
+    time::Duration,
+};
+
+use actix_rt::{time::sleep, System};
+use futures_core::{future::BoxFuture, Stream};
+use futures_util::stream::StreamExt as _;
+use tokio::sync::{mpsc::UnboundedReceiver, oneshot};
+use tracing::{error, info};
+
+use crate::{
+    accept::Accept,
+    builder::ServerBuilder,
+    join_all::join_all,
+    service::InternalServiceFactory,
+    signals::{SignalKind, Signals},
+    waker_queue::{WakerInterest, WakerQueue},
+    worker::{ServerWorker, ServerWorkerConfig, WorkerHandleServer},
+    ServerHandle,
+};
+
+#[derive(Debug)]
+pub(crate) enum ServerCommand {
+    /// Worker failed to accept connection, indicating a probable panic.
+    ///
+    /// Contains index of faulted worker.
+    WorkerFaulted(usize),
+
+    /// Pause accepting connections.
+    ///
+    /// Contains return channel to notify caller of successful state change.
+    Pause(oneshot::Sender<()>),
+
+    /// Resume accepting connections.
+    ///
+    /// Contains return channel to notify caller of successful state change.
+    Resume(oneshot::Sender<()>),
+
+    /// Stop accepting connections and begin shutdown procedure.
+    Stop {
+        /// True if shut down should be graceful.
+        graceful: bool,
+
+        /// Return channel to notify caller that shutdown is complete.
+        completion: Option<oneshot::Sender<()>>,
+
+        /// Force System exit when true, overriding `ServerBuilder::system_exit()` if it is false.
+        force_system_stop: bool,
+    },
+}
+
+/// General purpose TCP server that runs services receiving Tokio `TcpStream`s.
+///
+/// Handles creating worker threads, restarting faulted workers, connection accepting, and
+/// back-pressure logic.
+///
+/// Creates a worker per CPU core (or the number specified in [`ServerBuilder::workers`]) and
+/// distributes connections with a round-robin strategy.
+///
+/// The [Server] must be awaited or polled in order to start running. It will resolve when the
+/// server has fully shut down.
+///
+/// # Shutdown Signals
+/// On UNIX systems, `SIGTERM` will start a graceful shutdown and `SIGQUIT` or `SIGINT` will start a
+/// forced shutdown. On Windows, a Ctrl-C signal will start a forced shutdown.
+///
+/// A graceful shutdown will wait for all workers to stop first.
+///
+/// # Examples
+/// The following is a TCP echo server. Test using `telnet 127.0.0.1 8080`.
+///
+/// ```no_run
+/// use std::io;
+///
+/// use actix_rt::net::TcpStream;
+/// use actix_server::Server;
+/// use actix_service::{fn_service, ServiceFactoryExt as _};
+/// use bytes::BytesMut;
+/// use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+///
+/// #[actix_rt::main]
+/// async fn main() -> io::Result<()> {
+///     let bind_addr = ("127.0.0.1", 8080);
+///
+///     Server::build()
+///         .bind("echo", bind_addr, move || {
+///             fn_service(move |mut stream: TcpStream| {
+///                 async move {
+///                     let mut size = 0;
+///                     let mut buf = BytesMut::new();
+///
+///                     loop {
+///                         match stream.read_buf(&mut buf).await {
+///                             // end of stream; bail from loop
+///                             Ok(0) => break,
+///
+///                             // write bytes back to stream
+///                             Ok(bytes_read) => {
+///                                 stream.write_all(&buf[size..]).await.unwrap();
+///                                 size += bytes_read;
+///                             }
+///
+///                             Err(err) => {
+///                                 eprintln!("Stream Error: {:?}", err);
+///                                 return Err(());
+///                             }
+///                         }
+///                     }
+///
+///                     Ok(())
+///                 }
+///             })
+///             .map_err(|err| eprintln!("Service Error: {:?}", err))
+///         })?
+///         .run()
+///         .await
+/// }
+/// ```
+#[must_use = "Server does nothing unless you `.await` or poll it"]
+pub struct Server {
+    handle: ServerHandle,
+    fut: BoxFuture<'static, io::Result<()>>,
+}
+
+impl Server {
+    /// Create server build.
+    pub fn build() -> ServerBuilder {
+        ServerBuilder::default()
+    }
+
+    pub(crate) fn new(builder: ServerBuilder) -> Self {
+        Server {
+            handle: ServerHandle::new(builder.cmd_tx.clone()),
+            fut: Box::pin(ServerInner::run(builder)),
+        }
+    }
+
+    /// Get a `Server` handle that can be used issue commands and change it's state.
+    ///
+    /// See [ServerHandle](ServerHandle) for usage.
+    pub fn handle(&self) -> ServerHandle {
+        self.handle.clone()
+    }
+}
+
+impl Future for Server {
+    type Output = io::Result<()>;
+
+    #[inline]
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        Pin::new(&mut Pin::into_inner(self).fut).poll(cx)
+    }
+}
+
+pub struct ServerInner {
+    worker_handles: Vec<WorkerHandleServer>,
+    accept_handle: Option<thread::JoinHandle<()>>,
+    worker_config: ServerWorkerConfig,
+    services: Vec<Box<dyn InternalServiceFactory>>,
+    waker_queue: WakerQueue,
+    system_stop: bool,
+    stopping: bool,
+}
+
+impl ServerInner {
+    async fn run(builder: ServerBuilder) -> io::Result<()> {
+        let (mut this, mut mux) = Self::run_sync(builder)?;
+
+        while let Some(cmd) = mux.next().await {
+            this.handle_cmd(cmd).await;
+
+            if this.stopping {
+                break;
+            }
+        }
+
+        Ok(())
+    }
+
+    fn run_sync(mut builder: ServerBuilder) -> io::Result<(Self, ServerEventMultiplexer)> {
+        // Give log information on what runtime will be used.
+        let is_actix = actix_rt::System::try_current().is_some();
+        let is_tokio = tokio::runtime::Handle::try_current().is_ok();
+
+        match (is_actix, is_tokio) {
+            (true, _) => info!("Actix runtime found; starting in Actix runtime"),
+            (_, true) => info!("Tokio runtime found; starting in existing Tokio runtime"),
+            (_, false) => panic!("Actix or Tokio runtime not found; halting"),
+        }
+
+        for (_, name, lst) in &builder.sockets {
+            info!(
+                r#"starting service: "{}", workers: {}, listening on: {}"#,
+                name,
+                builder.threads,
+                lst.local_addr()
+            );
+        }
+
+        let sockets = mem::take(&mut builder.sockets)
+            .into_iter()
+            .map(|t| (t.0, t.2))
+            .collect();
+
+        let (waker_queue, worker_handles, accept_handle) = Accept::start(sockets, &builder)?;
+
+        let mux = ServerEventMultiplexer {
+            signal_fut: (builder.listen_os_signals).then(Signals::new),
+            cmd_rx: builder.cmd_rx,
+        };
+
+        let server = ServerInner {
+            waker_queue,
+            accept_handle: Some(accept_handle),
+            worker_handles,
+            worker_config: builder.worker_config,
+            services: builder.factories,
+            system_stop: builder.exit,
+            stopping: false,
+        };
+
+        Ok((server, mux))
+    }
+
+    async fn handle_cmd(&mut self, item: ServerCommand) {
+        match item {
+            ServerCommand::Pause(tx) => {
+                self.waker_queue.wake(WakerInterest::Pause);
+                let _ = tx.send(());
+            }
+
+            ServerCommand::Resume(tx) => {
+                self.waker_queue.wake(WakerInterest::Resume);
+                let _ = tx.send(());
+            }
+
+            ServerCommand::Stop {
+                graceful,
+                completion,
+                force_system_stop,
+            } => {
+                self.stopping = true;
+
+                // Signal accept thread to stop.
+                // Signal is non-blocking; we wait for thread to stop later.
+                self.waker_queue.wake(WakerInterest::Stop);
+
+                // send stop signal to workers
+                let workers_stop = self
+                    .worker_handles
+                    .iter()
+                    .map(|worker| worker.stop(graceful))
+                    .collect::<Vec<_>>();
+
+                if graceful {
+                    // wait for all workers to shut down
+                    let _ = join_all(workers_stop).await;
+                }
+
+                // wait for accept thread stop
+                self.accept_handle
+                    .take()
+                    .unwrap()
+                    .join()
+                    .expect("Accept thread must not panic in any case");
+
+                if let Some(tx) = completion {
+                    let _ = tx.send(());
+                }
+
+                if self.system_stop || force_system_stop {
+                    sleep(Duration::from_millis(300)).await;
+                    System::try_current().as_ref().map(System::stop);
+                }
+            }
+
+            ServerCommand::WorkerFaulted(idx) => {
+                // TODO: maybe just return with warning log if not found ?
+                assert!(self.worker_handles.iter().any(|wrk| wrk.idx == idx));
+
+                error!("worker {} has died; restarting", idx);
+
+                let factories = self
+                    .services
+                    .iter()
+                    .map(|service| service.clone_factory())
+                    .collect();
+
+                match ServerWorker::start(
+                    idx,
+                    factories,
+                    self.waker_queue.clone(),
+                    self.worker_config,
+                ) {
+                    Ok((handle_accept, handle_server)) => {
+                        *self
+                            .worker_handles
+                            .iter_mut()
+                            .find(|wrk| wrk.idx == idx)
+                            .unwrap() = handle_server;
+
+                        self.waker_queue.wake(WakerInterest::Worker(handle_accept));
+                    }
+
+                    Err(err) => error!("can not restart worker {}: {}", idx, err),
+                };
+            }
+        }
+    }
+
+    fn map_signal(signal: SignalKind) -> ServerCommand {
+        match signal {
+            SignalKind::Int => {
+                info!("SIGINT received; starting forced shutdown");
+                ServerCommand::Stop {
+                    graceful: false,
+                    completion: None,
+                    force_system_stop: true,
+                }
+            }
+
+            SignalKind::Term => {
+                info!("SIGTERM received; starting graceful shutdown");
+                ServerCommand::Stop {
+                    graceful: true,
+                    completion: None,
+                    force_system_stop: true,
+                }
+            }
+
+            SignalKind::Quit => {
+                info!("SIGQUIT received; starting forced shutdown");
+                ServerCommand::Stop {
+                    graceful: false,
+                    completion: None,
+                    force_system_stop: true,
+                }
+            }
+        }
+    }
+}
+
+struct ServerEventMultiplexer {
+    cmd_rx: UnboundedReceiver<ServerCommand>,
+    signal_fut: Option<Signals>,
+}
+
+impl Stream for ServerEventMultiplexer {
+    type Item = ServerCommand;
+
+    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
+        let this = Pin::into_inner(self);
+
+        if let Some(signal_fut) = &mut this.signal_fut {
+            if let Poll::Ready(signal) = Pin::new(signal_fut).poll(cx) {
+                this.signal_fut = None;
+                return Poll::Ready(Some(ServerInner::map_signal(signal)));
+            }
+        }
+
+        this.cmd_rx.poll_recv(cx)
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/service.rs.html b/src/actix_server/service.rs.html new file mode 100644 index 00000000..f7e05d61 --- /dev/null +++ b/src/actix_server/service.rs.html @@ -0,0 +1,325 @@ +service.rs - source

actix_server/
service.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
use std::{
+    marker::PhantomData,
+    net::SocketAddr,
+    task::{Context, Poll},
+};
+
+use actix_service::{Service, ServiceFactory as BaseServiceFactory};
+use actix_utils::future::{ready, Ready};
+use futures_core::future::LocalBoxFuture;
+use tracing::error;
+
+use crate::{
+    socket::{FromStream, MioStream},
+    worker::WorkerCounterGuard,
+};
+
+#[doc(hidden)]
+pub trait ServerServiceFactory<Stream: FromStream>: Send + Clone + 'static {
+    type Factory: BaseServiceFactory<Stream, Config = ()>;
+
+    fn create(&self) -> Self::Factory;
+}
+
+pub(crate) trait InternalServiceFactory: Send {
+    fn name(&self, token: usize) -> &str;
+
+    fn clone_factory(&self) -> Box<dyn InternalServiceFactory>;
+
+    fn create(&self) -> LocalBoxFuture<'static, Result<(usize, BoxedServerService), ()>>;
+}
+
+pub(crate) type BoxedServerService = Box<
+    dyn Service<
+        (WorkerCounterGuard, MioStream),
+        Response = (),
+        Error = (),
+        Future = Ready<Result<(), ()>>,
+    >,
+>;
+
+pub(crate) struct StreamService<S, I> {
+    service: S,
+    _phantom: PhantomData<I>,
+}
+
+impl<S, I> StreamService<S, I> {
+    pub(crate) fn new(service: S) -> Self {
+        StreamService {
+            service,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<S, I> Service<(WorkerCounterGuard, MioStream)> for StreamService<S, I>
+where
+    S: Service<I>,
+    S::Future: 'static,
+    S::Error: 'static,
+    I: FromStream,
+{
+    type Response = ();
+    type Error = ();
+    type Future = Ready<Result<(), ()>>;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        self.service.poll_ready(ctx).map_err(|_| ())
+    }
+
+    fn call(&self, (guard, req): (WorkerCounterGuard, MioStream)) -> Self::Future {
+        ready(match FromStream::from_mio(req) {
+            Ok(stream) => {
+                let f = self.service.call(stream);
+                actix_rt::spawn(async move {
+                    let _ = f.await;
+                    drop(guard);
+                });
+                Ok(())
+            }
+            Err(err) => {
+                error!("can not convert to an async TCP stream: {err}");
+                Err(())
+            }
+        })
+    }
+}
+
+pub(crate) struct StreamNewService<F: ServerServiceFactory<Io>, Io: FromStream> {
+    name: String,
+    inner: F,
+    token: usize,
+    addr: SocketAddr,
+    _t: PhantomData<Io>,
+}
+
+impl<F, Io> StreamNewService<F, Io>
+where
+    F: ServerServiceFactory<Io>,
+    Io: FromStream + Send + 'static,
+{
+    pub(crate) fn create(
+        name: String,
+        token: usize,
+        inner: F,
+        addr: SocketAddr,
+    ) -> Box<dyn InternalServiceFactory> {
+        Box::new(Self {
+            name,
+            token,
+            inner,
+            addr,
+            _t: PhantomData,
+        })
+    }
+}
+
+impl<F, Io> InternalServiceFactory for StreamNewService<F, Io>
+where
+    F: ServerServiceFactory<Io>,
+    Io: FromStream + Send + 'static,
+{
+    fn name(&self, _: usize) -> &str {
+        &self.name
+    }
+
+    fn clone_factory(&self) -> Box<dyn InternalServiceFactory> {
+        Box::new(Self {
+            name: self.name.clone(),
+            inner: self.inner.clone(),
+            token: self.token,
+            addr: self.addr,
+            _t: PhantomData,
+        })
+    }
+
+    fn create(&self) -> LocalBoxFuture<'static, Result<(usize, BoxedServerService), ()>> {
+        let token = self.token;
+        let fut = self.inner.create().new_service(());
+        Box::pin(async move {
+            match fut.await {
+                Ok(inner) => {
+                    let service = Box::new(StreamService::new(inner)) as _;
+                    Ok((token, service))
+                }
+                Err(_) => Err(()),
+            }
+        })
+    }
+}
+
+impl<F, T, I> ServerServiceFactory<I> for F
+where
+    F: Fn() -> T + Send + Clone + 'static,
+    T: BaseServiceFactory<I, Config = ()>,
+    I: FromStream,
+{
+    type Factory = T;
+
+    fn create(&self) -> T {
+        (self)()
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/signals.rs.html b/src/actix_server/signals.rs.html new file mode 100644 index 00000000..b8d7efdc --- /dev/null +++ b/src/actix_server/signals.rs.html @@ -0,0 +1,217 @@ +signals.rs - source

actix_server/
signals.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
use std::{
+    fmt,
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use tracing::trace;
+
+/// Types of process signals.
+// #[allow(dead_code)]
+#[derive(Debug, Clone, Copy, PartialEq)]
+#[allow(dead_code)] // variants are never constructed on non-unix
+pub(crate) enum SignalKind {
+    /// `SIGINT`
+    Int,
+
+    /// `SIGTERM`
+    Term,
+
+    /// `SIGQUIT`
+    Quit,
+}
+
+impl fmt::Display for SignalKind {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str(match self {
+            SignalKind::Int => "SIGINT",
+            SignalKind::Term => "SIGTERM",
+            SignalKind::Quit => "SIGQUIT",
+        })
+    }
+}
+
+/// Process signal listener.
+pub(crate) struct Signals {
+    #[cfg(not(unix))]
+    signals: futures_core::future::BoxFuture<'static, std::io::Result<()>>,
+
+    #[cfg(unix)]
+    signals: Vec<(SignalKind, actix_rt::signal::unix::Signal)>,
+}
+
+impl Signals {
+    /// Constructs an OS signal listening future.
+    pub(crate) fn new() -> Self {
+        trace!("setting up OS signal listener");
+
+        #[cfg(not(unix))]
+        {
+            Signals {
+                signals: Box::pin(actix_rt::signal::ctrl_c()),
+            }
+        }
+
+        #[cfg(unix)]
+        {
+            use actix_rt::signal::unix;
+
+            let sig_map = [
+                (unix::SignalKind::interrupt(), SignalKind::Int),
+                (unix::SignalKind::terminate(), SignalKind::Term),
+                (unix::SignalKind::quit(), SignalKind::Quit),
+            ];
+
+            let signals = sig_map
+                .iter()
+                .filter_map(|(kind, sig)| {
+                    unix::signal(*kind)
+                        .map(|tokio_sig| (*sig, tokio_sig))
+                        .map_err(|e| {
+                            tracing::error!(
+                                "can not initialize stream handler for {:?} err: {}",
+                                sig,
+                                e
+                            )
+                        })
+                        .ok()
+                })
+                .collect::<Vec<_>>();
+
+            Signals { signals }
+        }
+    }
+}
+
+impl Future for Signals {
+    type Output = SignalKind;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        #[cfg(not(unix))]
+        {
+            self.signals.as_mut().poll(cx).map(|_| SignalKind::Int)
+        }
+
+        #[cfg(unix)]
+        {
+            for (sig, fut) in self.signals.iter_mut() {
+                if fut.poll_recv(cx).is_ready() {
+                    trace!("{} received", sig);
+                    return Poll::Ready(*sig);
+                }
+            }
+
+            Poll::Pending
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/socket.rs.html b/src/actix_server/socket.rs.html new file mode 100644 index 00000000..7444f591 --- /dev/null +++ b/src/actix_server/socket.rs.html @@ -0,0 +1,587 @@ +socket.rs - source

actix_server/
socket.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
pub(crate) use std::net::{
+    SocketAddr as StdSocketAddr, TcpListener as StdTcpListener, ToSocketAddrs,
+};
+use std::{fmt, io};
+
+use actix_rt::net::TcpStream;
+pub(crate) use mio::net::TcpListener as MioTcpListener;
+use mio::{event::Source, Interest, Registry, Token};
+#[cfg(unix)]
+pub(crate) use {
+    mio::net::UnixListener as MioUnixListener, std::os::unix::net::UnixListener as StdUnixListener,
+};
+
+use crate::builder::MpTcp;
+
+pub(crate) enum MioListener {
+    Tcp(MioTcpListener),
+    #[cfg(unix)]
+    Uds(MioUnixListener),
+}
+
+impl MioListener {
+    pub(crate) fn local_addr(&self) -> SocketAddr {
+        match *self {
+            MioListener::Tcp(ref lst) => lst
+                .local_addr()
+                .map(SocketAddr::Tcp)
+                .unwrap_or(SocketAddr::Unknown),
+            #[cfg(unix)]
+            MioListener::Uds(ref lst) => lst
+                .local_addr()
+                .map(SocketAddr::Uds)
+                .unwrap_or(SocketAddr::Unknown),
+        }
+    }
+
+    pub(crate) fn accept(&self) -> io::Result<MioStream> {
+        match *self {
+            MioListener::Tcp(ref lst) => lst.accept().map(|(stream, _)| MioStream::Tcp(stream)),
+            #[cfg(unix)]
+            MioListener::Uds(ref lst) => lst.accept().map(|(stream, _)| MioStream::Uds(stream)),
+        }
+    }
+}
+
+impl Source for MioListener {
+    fn register(
+        &mut self,
+        registry: &Registry,
+        token: Token,
+        interests: Interest,
+    ) -> io::Result<()> {
+        match *self {
+            MioListener::Tcp(ref mut lst) => lst.register(registry, token, interests),
+            #[cfg(unix)]
+            MioListener::Uds(ref mut lst) => lst.register(registry, token, interests),
+        }
+    }
+
+    fn reregister(
+        &mut self,
+        registry: &Registry,
+        token: Token,
+        interests: Interest,
+    ) -> io::Result<()> {
+        match *self {
+            MioListener::Tcp(ref mut lst) => lst.reregister(registry, token, interests),
+            #[cfg(unix)]
+            MioListener::Uds(ref mut lst) => lst.reregister(registry, token, interests),
+        }
+    }
+
+    fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
+        match *self {
+            MioListener::Tcp(ref mut lst) => lst.deregister(registry),
+            #[cfg(unix)]
+            MioListener::Uds(ref mut lst) => {
+                let res = lst.deregister(registry);
+
+                // cleanup file path
+                if let Ok(addr) = lst.local_addr() {
+                    if let Some(path) = addr.as_pathname() {
+                        let _ = std::fs::remove_file(path);
+                    }
+                }
+                res
+            }
+        }
+    }
+}
+
+impl From<StdTcpListener> for MioListener {
+    fn from(lst: StdTcpListener) -> Self {
+        MioListener::Tcp(MioTcpListener::from_std(lst))
+    }
+}
+
+#[cfg(unix)]
+impl From<StdUnixListener> for MioListener {
+    fn from(lst: StdUnixListener) -> Self {
+        MioListener::Uds(MioUnixListener::from_std(lst))
+    }
+}
+
+impl fmt::Debug for MioListener {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match *self {
+            MioListener::Tcp(ref lst) => write!(f, "{:?}", lst),
+            #[cfg(unix)]
+            MioListener::Uds(ref lst) => write!(f, "{:?}", lst),
+        }
+    }
+}
+
+impl fmt::Display for MioListener {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match *self {
+            MioListener::Tcp(ref lst) => write!(f, "{:?}", lst),
+            #[cfg(unix)]
+            MioListener::Uds(ref lst) => write!(f, "{:?}", lst),
+        }
+    }
+}
+
+pub(crate) enum SocketAddr {
+    Unknown,
+    Tcp(StdSocketAddr),
+    #[cfg(unix)]
+    Uds(std::os::unix::net::SocketAddr),
+}
+
+impl fmt::Display for SocketAddr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match *self {
+            Self::Unknown => write!(f, "Unknown SocketAddr"),
+            Self::Tcp(ref addr) => write!(f, "{}", addr),
+            #[cfg(unix)]
+            Self::Uds(ref addr) => write!(f, "{:?}", addr),
+        }
+    }
+}
+
+impl fmt::Debug for SocketAddr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match *self {
+            Self::Unknown => write!(f, "Unknown SocketAddr"),
+            Self::Tcp(ref addr) => write!(f, "{:?}", addr),
+            #[cfg(unix)]
+            Self::Uds(ref addr) => write!(f, "{:?}", addr),
+        }
+    }
+}
+
+#[derive(Debug)]
+pub enum MioStream {
+    Tcp(mio::net::TcpStream),
+    #[cfg(unix)]
+    Uds(mio::net::UnixStream),
+}
+
+/// Helper trait for converting a Mio stream into a Tokio stream.
+pub trait FromStream: Sized {
+    fn from_mio(sock: MioStream) -> io::Result<Self>;
+}
+
+#[cfg(windows)]
+mod win_impl {
+    use std::os::windows::io::{FromRawSocket, IntoRawSocket};
+
+    use super::*;
+
+    // TODO: This is a workaround and we need an efficient way to convert between Mio and Tokio stream
+    impl FromStream for TcpStream {
+        fn from_mio(sock: MioStream) -> io::Result<Self> {
+            match sock {
+                MioStream::Tcp(mio) => {
+                    let raw = IntoRawSocket::into_raw_socket(mio);
+                    // SAFETY: This is an in-place conversion from Mio stream to Tokio stream.
+                    TcpStream::from_std(unsafe { FromRawSocket::from_raw_socket(raw) })
+                }
+            }
+        }
+    }
+}
+
+#[cfg(unix)]
+mod unix_impl {
+    use std::os::unix::io::{FromRawFd, IntoRawFd};
+
+    use actix_rt::net::UnixStream;
+
+    use super::*;
+
+    // HACK: This is a workaround and we need an efficient way to convert between Mio and Tokio stream
+    impl FromStream for TcpStream {
+        fn from_mio(sock: MioStream) -> io::Result<Self> {
+            match sock {
+                MioStream::Tcp(mio) => {
+                    let raw = IntoRawFd::into_raw_fd(mio);
+                    // SAFETY: This is an in-place conversion from Mio stream to Tokio stream.
+                    TcpStream::from_std(unsafe { FromRawFd::from_raw_fd(raw) })
+                }
+                MioStream::Uds(_) => {
+                    panic!("Should not happen, bug in server impl");
+                }
+            }
+        }
+    }
+
+    // HACK: This is a workaround and we need an efficient way to convert between Mio and Tokio stream
+    impl FromStream for UnixStream {
+        fn from_mio(sock: MioStream) -> io::Result<Self> {
+            match sock {
+                MioStream::Tcp(_) => panic!("Should not happen, bug in server impl"),
+                MioStream::Uds(mio) => {
+                    let raw = IntoRawFd::into_raw_fd(mio);
+                    // SAFETY: This is an in-place conversion from Mio stream to Tokio stream.
+                    UnixStream::from_std(unsafe { FromRawFd::from_raw_fd(raw) })
+                }
+            }
+        }
+    }
+}
+
+pub(crate) fn create_mio_tcp_listener(
+    addr: StdSocketAddr,
+    backlog: u32,
+    mptcp: &MpTcp,
+) -> io::Result<MioTcpListener> {
+    use socket2::{Domain, Protocol, Socket, Type};
+
+    #[cfg(not(target_os = "linux"))]
+    let protocol = Protocol::TCP;
+    #[cfg(target_os = "linux")]
+    let protocol = if matches!(mptcp, MpTcp::Disabled) {
+        Protocol::TCP
+    } else {
+        Protocol::MPTCP
+    };
+
+    let socket = match Socket::new(Domain::for_address(addr), Type::STREAM, Some(protocol)) {
+        Ok(sock) => sock,
+
+        Err(err) if matches!(mptcp, MpTcp::TcpFallback) => {
+            tracing::warn!("binding socket as MPTCP failed: {err}");
+            tracing::warn!("falling back to TCP");
+            Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?
+        }
+
+        Err(err) => return Err(err),
+    };
+
+    socket.set_reuse_address(true)?;
+    socket.set_nonblocking(true)?;
+    socket.bind(&addr.into())?;
+    socket.listen(backlog as i32)?;
+
+    Ok(MioTcpListener::from_std(StdTcpListener::from(socket)))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn socket_addr() {
+        let addr = SocketAddr::Tcp("127.0.0.1:8080".parse().unwrap());
+        assert!(format!("{:?}", addr).contains("127.0.0.1:8080"));
+        assert_eq!(format!("{}", addr), "127.0.0.1:8080");
+
+        let addr: StdSocketAddr = "127.0.0.1:0".parse().unwrap();
+        let lst = create_mio_tcp_listener(addr, 128, &MpTcp::Disabled).unwrap();
+        let lst = MioListener::Tcp(lst);
+        assert!(format!("{:?}", lst).contains("TcpListener"));
+        assert!(format!("{}", lst).contains("127.0.0.1"));
+    }
+
+    #[test]
+    #[cfg(unix)]
+    fn uds() {
+        let _ = std::fs::remove_file("/tmp/sock.xxxxx");
+        if let Ok(socket) = MioUnixListener::bind("/tmp/sock.xxxxx") {
+            let addr = socket.local_addr().expect("Couldn't get local address");
+            let a = SocketAddr::Uds(addr);
+            assert!(format!("{:?}", a).contains("/tmp/sock.xxxxx"));
+            assert!(format!("{}", a).contains("/tmp/sock.xxxxx"));
+
+            let lst = MioListener::Uds(socket);
+            assert!(format!("{:?}", lst).contains("/tmp/sock.xxxxx"));
+            assert!(format!("{}", lst).contains("/tmp/sock.xxxxx"));
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/test_server.rs.html b/src/actix_server/test_server.rs.html new file mode 100644 index 00000000..51547e6b --- /dev/null +++ b/src/actix_server/test_server.rs.html @@ -0,0 +1,307 @@ +test_server.rs - source

actix_server/
test_server.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
use std::{io, net, sync::mpsc, thread};
+
+use actix_rt::{net::TcpStream, System};
+
+use crate::{Server, ServerBuilder, ServerHandle, ServerServiceFactory};
+
+/// A testing server.
+///
+/// `TestServer` is very simple test server that simplify process of writing integration tests for
+/// network applications.
+///
+/// # Examples
+/// ```
+/// use actix_service::fn_service;
+/// use actix_server::TestServer;
+///
+/// #[actix_rt::main]
+/// async fn main() {
+///     let srv = TestServer::start(|| fn_service(
+///         |sock| async move {
+///             println!("New connection: {:?}", sock);
+///             Ok::<_, ()>(())
+///         }
+///     ));
+///
+///     println!("SOCKET: {:?}", srv.connect());
+/// }
+/// ```
+pub struct TestServer;
+
+/// Test server handle.
+pub struct TestServerHandle {
+    addr: net::SocketAddr,
+    host: String,
+    port: u16,
+    server_handle: ServerHandle,
+    thread_handle: Option<thread::JoinHandle<io::Result<()>>>,
+}
+
+impl TestServer {
+    /// Start new `TestServer` using application factory and default server config.
+    pub fn start(factory: impl ServerServiceFactory<TcpStream>) -> TestServerHandle {
+        Self::start_with_builder(Server::build(), factory)
+    }
+
+    /// Start new `TestServer` using application factory and server builder.
+    pub fn start_with_builder(
+        server_builder: ServerBuilder,
+        factory: impl ServerServiceFactory<TcpStream>,
+    ) -> TestServerHandle {
+        let (tx, rx) = mpsc::channel();
+
+        // run server in separate thread
+        let thread_handle = thread::spawn(move || {
+            let lst = net::TcpListener::bind("127.0.0.1:0").unwrap();
+            let local_addr = lst.local_addr().unwrap();
+
+            System::new().block_on(async {
+                let server = server_builder
+                    .listen("test", lst, factory)
+                    .unwrap()
+                    .workers(1)
+                    .disable_signals()
+                    .run();
+
+                tx.send((server.handle(), local_addr)).unwrap();
+                server.await
+            })
+        });
+
+        let (server_handle, addr) = rx.recv().unwrap();
+
+        let host = format!("{}", addr.ip());
+        let port = addr.port();
+
+        TestServerHandle {
+            addr,
+            host,
+            port,
+            server_handle,
+            thread_handle: Some(thread_handle),
+        }
+    }
+
+    /// Get first available unused local address.
+    pub fn unused_addr() -> net::SocketAddr {
+        use socket2::{Domain, Protocol, Socket, Type};
+
+        let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
+        let domain = Domain::for_address(addr);
+        let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP)).unwrap();
+
+        socket.set_reuse_address(true).unwrap();
+        socket.set_nonblocking(true).unwrap();
+        socket.bind(&addr.into()).unwrap();
+        socket.listen(1024).unwrap();
+
+        net::TcpListener::from(socket).local_addr().unwrap()
+    }
+}
+
+impl TestServerHandle {
+    /// Test server host.
+    pub fn host(&self) -> &str {
+        &self.host
+    }
+
+    /// Test server port.
+    pub fn port(&self) -> u16 {
+        self.port
+    }
+
+    /// Get test server address.
+    pub fn addr(&self) -> net::SocketAddr {
+        self.addr
+    }
+
+    /// Stop server.
+    fn stop(&mut self) {
+        drop(self.server_handle.stop(false));
+        self.thread_handle.take().unwrap().join().unwrap().unwrap();
+    }
+
+    /// Connect to server, returning a Tokio `TcpStream`.
+    pub fn connect(&self) -> io::Result<TcpStream> {
+        TcpStream::from_std(net::TcpStream::connect(self.addr)?)
+    }
+}
+
+impl Drop for TestServerHandle {
+    fn drop(&mut self) {
+        self.stop()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use actix_service::fn_service;
+
+    use super::*;
+
+    #[tokio::test]
+    async fn connect_in_tokio_runtime() {
+        let srv = TestServer::start(|| fn_service(|_sock| async move { Ok::<_, ()>(()) }));
+        assert!(srv.connect().is_ok());
+    }
+
+    #[actix_rt::test]
+    async fn connect_in_actix_runtime() {
+        let srv = TestServer::start(|| fn_service(|_sock| async move { Ok::<_, ()>(()) }));
+        assert!(srv.connect().is_ok());
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_server/waker_queue.rs.html b/src/actix_server/waker_queue.rs.html new file mode 100644 index 00000000..1ff7dce7 --- /dev/null +++ b/src/actix_server/waker_queue.rs.html @@ -0,0 +1,169 @@ +waker_queue.rs - source

actix_server/
waker_queue.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
use std::{
+    collections::VecDeque,
+    ops::Deref,
+    sync::{Arc, Mutex, MutexGuard},
+};
+
+use mio::{Registry, Token as MioToken, Waker};
+
+use crate::worker::WorkerHandleAccept;
+
+/// Waker token for `mio::Poll` instance.
+pub(crate) const WAKER_TOKEN: MioToken = MioToken(usize::MAX);
+
+/// `mio::Waker` with a queue for waking up the `Accept`'s `Poll` and contains the `WakerInterest`
+/// the `Poll` would want to look into.
+pub(crate) struct WakerQueue(Arc<(Waker, Mutex<VecDeque<WakerInterest>>)>);
+
+impl Clone for WakerQueue {
+    fn clone(&self) -> Self {
+        Self(self.0.clone())
+    }
+}
+
+impl Deref for WakerQueue {
+    type Target = (Waker, Mutex<VecDeque<WakerInterest>>);
+
+    fn deref(&self) -> &Self::Target {
+        self.0.deref()
+    }
+}
+
+impl WakerQueue {
+    /// Construct a waker queue with given `Poll`'s `Registry` and capacity.
+    ///
+    /// A fixed `WAKER_TOKEN` is used to identify the wake interest and the `Poll` needs to match
+    /// event's token for it to properly handle `WakerInterest`.
+    pub(crate) fn new(registry: &Registry) -> std::io::Result<Self> {
+        let waker = Waker::new(registry, WAKER_TOKEN)?;
+        let queue = Mutex::new(VecDeque::with_capacity(16));
+
+        Ok(Self(Arc::new((waker, queue))))
+    }
+
+    /// Push a new interest to the queue and wake up the accept poll afterwards.
+    pub(crate) fn wake(&self, interest: WakerInterest) {
+        let (waker, queue) = self.deref();
+
+        queue
+            .lock()
+            .expect("Failed to lock WakerQueue")
+            .push_back(interest);
+
+        waker
+            .wake()
+            .unwrap_or_else(|e| panic!("can not wake up Accept Poll: {}", e));
+    }
+
+    /// Get a MutexGuard of the waker queue.
+    pub(crate) fn guard(&self) -> MutexGuard<'_, VecDeque<WakerInterest>> {
+        self.deref().1.lock().expect("Failed to lock WakerQueue")
+    }
+
+    /// Reset the waker queue so it does not grow infinitely.
+    pub(crate) fn reset(queue: &mut VecDeque<WakerInterest>) {
+        std::mem::swap(&mut VecDeque::<WakerInterest>::with_capacity(16), queue);
+    }
+}
+
+/// Types of interests we would look into when `Accept`'s `Poll` is waked up by waker.
+///
+/// These interests should not be confused with `mio::Interest` and mostly not I/O related
+pub(crate) enum WakerInterest {
+    /// `WorkerAvailable` is an interest from `Worker` notifying `Accept` there is a worker
+    /// available and can accept new tasks.
+    WorkerAvailable(usize),
+    /// `Pause`, `Resume`, `Stop` Interest are from `ServerBuilder` future. It listens to
+    /// `ServerCommand` and notify `Accept` to do exactly these tasks.
+    Pause,
+    Resume,
+    Stop,
+    /// `Worker` is an interest that is triggered after a worker faults. This is determined by
+    /// trying to send work to it. `Accept` would be waked up and add the new `WorkerHandleAccept`.
+    Worker(WorkerHandleAccept),
+}
+
\ No newline at end of file diff --git a/src/actix_server/worker.rs.html b/src/actix_server/worker.rs.html new file mode 100644 index 00000000..f828a732 --- /dev/null +++ b/src/actix_server/worker.rs.html @@ -0,0 +1,1463 @@ +worker.rs - source

actix_server/
worker.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
use std::{
+    future::Future,
+    io, mem,
+    num::NonZeroUsize,
+    pin::Pin,
+    rc::Rc,
+    sync::{
+        atomic::{AtomicUsize, Ordering},
+        Arc,
+    },
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    spawn,
+    time::{sleep, Instant, Sleep},
+    Arbiter, ArbiterHandle, System,
+};
+use futures_core::{future::LocalBoxFuture, ready};
+use tokio::sync::{
+    mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
+    oneshot,
+};
+use tracing::{error, info, trace};
+
+use crate::{
+    service::{BoxedServerService, InternalServiceFactory},
+    socket::MioStream,
+    waker_queue::{WakerInterest, WakerQueue},
+};
+
+/// Stop worker message. Returns `true` on successful graceful shutdown
+/// and `false` if some connections still alive when shutdown execute.
+pub(crate) struct Stop {
+    graceful: bool,
+    tx: oneshot::Sender<bool>,
+}
+
+#[derive(Debug)]
+pub(crate) struct Conn {
+    pub io: MioStream,
+    pub token: usize,
+}
+
+/// Create accept and server worker handles.
+fn handle_pair(
+    idx: usize,
+    conn_tx: UnboundedSender<Conn>,
+    stop_tx: UnboundedSender<Stop>,
+    counter: Counter,
+) -> (WorkerHandleAccept, WorkerHandleServer) {
+    let accept = WorkerHandleAccept {
+        idx,
+        conn_tx,
+        counter,
+    };
+
+    let server = WorkerHandleServer { idx, stop_tx };
+
+    (accept, server)
+}
+
+/// counter: Arc<AtomicUsize> field is owned by `Accept` thread and `ServerWorker` thread.
+///
+/// `Accept` would increment the counter and `ServerWorker` would decrement it.
+///
+/// # Atomic Ordering:
+///
+/// `Accept` always look into it's cached `Availability` field for `ServerWorker` state.
+/// It lazily increment counter after successful dispatching new work to `ServerWorker`.
+/// On reaching counter limit `Accept` update it's cached `Availability` and mark worker as
+/// unable to accept any work.
+///
+/// `ServerWorker` always decrement the counter when every work received from `Accept` is done.
+/// On reaching counter limit worker would use `mio::Waker` and `WakerQueue` to wake up `Accept`
+/// and notify it to update cached `Availability` again to mark worker as able to accept work again.
+///
+/// Hence, a wake up would only happen after `Accept` increment it to limit.
+/// And a decrement to limit always wake up `Accept`.
+#[derive(Clone)]
+pub(crate) struct Counter {
+    counter: Arc<AtomicUsize>,
+    limit: usize,
+}
+
+impl Counter {
+    pub(crate) fn new(limit: usize) -> Self {
+        Self {
+            counter: Arc::new(AtomicUsize::new(1)),
+            limit,
+        }
+    }
+
+    /// Increment counter by 1 and return true when hitting limit
+    #[inline(always)]
+    pub(crate) fn inc(&self) -> bool {
+        self.counter.fetch_add(1, Ordering::Relaxed) != self.limit
+    }
+
+    /// Decrement counter by 1 and return true if crossing limit.
+    #[inline(always)]
+    pub(crate) fn dec(&self) -> bool {
+        self.counter.fetch_sub(1, Ordering::Relaxed) == self.limit
+    }
+
+    pub(crate) fn total(&self) -> usize {
+        self.counter.load(Ordering::SeqCst) - 1
+    }
+}
+
+pub(crate) struct WorkerCounter {
+    idx: usize,
+    inner: Rc<(WakerQueue, Counter)>,
+}
+
+impl Clone for WorkerCounter {
+    fn clone(&self) -> Self {
+        Self {
+            idx: self.idx,
+            inner: self.inner.clone(),
+        }
+    }
+}
+
+impl WorkerCounter {
+    pub(crate) fn new(idx: usize, waker_queue: WakerQueue, counter: Counter) -> Self {
+        Self {
+            idx,
+            inner: Rc::new((waker_queue, counter)),
+        }
+    }
+
+    #[inline(always)]
+    pub(crate) fn guard(&self) -> WorkerCounterGuard {
+        WorkerCounterGuard(self.clone())
+    }
+
+    fn total(&self) -> usize {
+        self.inner.1.total()
+    }
+}
+
+pub(crate) struct WorkerCounterGuard(WorkerCounter);
+
+impl Drop for WorkerCounterGuard {
+    fn drop(&mut self) {
+        let (waker_queue, counter) = &*self.0.inner;
+        if counter.dec() {
+            waker_queue.wake(WakerInterest::WorkerAvailable(self.0.idx));
+        }
+    }
+}
+
+/// Handle to worker that can send connection message to worker and share the availability of worker
+/// to other threads.
+///
+/// Held by [Accept](crate::accept::Accept).
+pub(crate) struct WorkerHandleAccept {
+    idx: usize,
+    conn_tx: UnboundedSender<Conn>,
+    counter: Counter,
+}
+
+impl WorkerHandleAccept {
+    #[inline(always)]
+    pub(crate) fn idx(&self) -> usize {
+        self.idx
+    }
+
+    #[inline(always)]
+    pub(crate) fn send(&self, conn: Conn) -> Result<(), Conn> {
+        self.conn_tx.send(conn).map_err(|msg| msg.0)
+    }
+
+    #[inline(always)]
+    pub(crate) fn inc_counter(&self) -> bool {
+        self.counter.inc()
+    }
+}
+
+/// Handle to worker than can send stop message to worker.
+///
+/// Held by [ServerBuilder](crate::builder::ServerBuilder).
+#[derive(Debug)]
+pub(crate) struct WorkerHandleServer {
+    pub(crate) idx: usize,
+    stop_tx: UnboundedSender<Stop>,
+}
+
+impl WorkerHandleServer {
+    pub(crate) fn stop(&self, graceful: bool) -> oneshot::Receiver<bool> {
+        let (tx, rx) = oneshot::channel();
+        let _ = self.stop_tx.send(Stop { graceful, tx });
+        rx
+    }
+}
+
+/// Service worker.
+///
+/// Worker accepts Socket objects via unbounded channel and starts stream processing.
+pub(crate) struct ServerWorker {
+    // UnboundedReceiver<Conn> should always be the first field.
+    // It must be dropped as soon as ServerWorker dropping.
+    conn_rx: UnboundedReceiver<Conn>,
+    stop_rx: UnboundedReceiver<Stop>,
+    counter: WorkerCounter,
+    services: Box<[WorkerService]>,
+    factories: Box<[Box<dyn InternalServiceFactory>]>,
+    state: WorkerState,
+    shutdown_timeout: Duration,
+}
+
+struct WorkerService {
+    factory_idx: usize,
+    status: WorkerServiceStatus,
+    service: BoxedServerService,
+}
+
+impl WorkerService {
+    fn created(&mut self, service: BoxedServerService) {
+        self.service = service;
+        self.status = WorkerServiceStatus::Unavailable;
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum WorkerServiceStatus {
+    Available,
+    Unavailable,
+    Failed,
+    Restarting,
+    Stopping,
+    Stopped,
+}
+
+impl Default for WorkerServiceStatus {
+    fn default() -> Self {
+        Self::Unavailable
+    }
+}
+
+/// Config for worker behavior passed down from server builder.
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct ServerWorkerConfig {
+    shutdown_timeout: Duration,
+    max_blocking_threads: usize,
+    max_concurrent_connections: usize,
+}
+
+impl Default for ServerWorkerConfig {
+    fn default() -> Self {
+        let parallelism = std::thread::available_parallelism().map_or(2, NonZeroUsize::get);
+
+        // 512 is the default max blocking thread count of a Tokio runtime.
+        let max_blocking_threads = std::cmp::max(512 / parallelism, 1);
+
+        Self {
+            shutdown_timeout: Duration::from_secs(30),
+            max_blocking_threads,
+            max_concurrent_connections: 25600,
+        }
+    }
+}
+
+impl ServerWorkerConfig {
+    pub(crate) fn max_blocking_threads(&mut self, num: usize) {
+        self.max_blocking_threads = num;
+    }
+
+    pub(crate) fn max_concurrent_connections(&mut self, num: usize) {
+        self.max_concurrent_connections = num;
+    }
+
+    pub(crate) fn shutdown_timeout(&mut self, dur: Duration) {
+        self.shutdown_timeout = dur;
+    }
+}
+
+impl ServerWorker {
+    pub(crate) fn start(
+        idx: usize,
+        factories: Vec<Box<dyn InternalServiceFactory>>,
+        waker_queue: WakerQueue,
+        config: ServerWorkerConfig,
+    ) -> io::Result<(WorkerHandleAccept, WorkerHandleServer)> {
+        trace!("starting server worker {}", idx);
+
+        let (tx1, conn_rx) = unbounded_channel();
+        let (tx2, stop_rx) = unbounded_channel();
+
+        let counter = Counter::new(config.max_concurrent_connections);
+        let pair = handle_pair(idx, tx1, tx2, counter.clone());
+
+        // get actix system context if it is set
+        let actix_system = System::try_current();
+
+        // get tokio runtime handle if it is set
+        let tokio_handle = tokio::runtime::Handle::try_current().ok();
+
+        // service factories initialization channel
+        let (factory_tx, factory_rx) = std::sync::mpsc::sync_channel::<io::Result<()>>(1);
+
+        // outline of following code:
+        //
+        // if system exists
+        //   if uring enabled
+        //     start arbiter using uring method
+        //   else
+        //     start arbiter with regular tokio
+        // else
+        //   if uring enabled
+        //     start uring in spawned thread
+        //   else
+        //     start regular tokio in spawned thread
+
+        // every worker runs in it's own thread and tokio runtime.
+        // use a custom tokio runtime builder to change the settings of runtime.
+
+        match (actix_system, tokio_handle) {
+            (None, None) => {
+                panic!("No runtime detected. Start a Tokio (or Actix) runtime.");
+            }
+
+            // no actix system
+            (None, Some(rt_handle)) => {
+                std::thread::Builder::new()
+                    .name(format!("actix-server worker {}", idx))
+                    .spawn(move || {
+                        let (worker_stopped_tx, worker_stopped_rx) = oneshot::channel();
+
+                        // local set for running service init futures and worker services
+                        let ls = tokio::task::LocalSet::new();
+
+                        // init services using existing Tokio runtime (so probably on main thread)
+                        let services = rt_handle.block_on(ls.run_until(async {
+                            let mut services = Vec::new();
+
+                            for (idx, factory) in factories.iter().enumerate() {
+                                match factory.create().await {
+                                    Ok((token, svc)) => services.push((idx, token, svc)),
+
+                                    Err(err) => {
+                                        error!("can not start worker: {:?}", err);
+                                        return Err(io::Error::new(
+                                            io::ErrorKind::Other,
+                                            format!("can not start server service {}", idx),
+                                        ));
+                                    }
+                                }
+                            }
+
+                            Ok(services)
+                        }));
+
+                        let services = match services {
+                            Ok(services) => {
+                                factory_tx.send(Ok(())).unwrap();
+                                services
+                            }
+                            Err(err) => {
+                                factory_tx.send(Err(err)).unwrap();
+                                return;
+                            }
+                        };
+
+                        let worker_services = wrap_worker_services(services);
+
+                        let worker_fut = async move {
+                            // spawn to make sure ServerWorker runs as non boxed future.
+                            spawn(async move {
+                                ServerWorker {
+                                    conn_rx,
+                                    stop_rx,
+                                    services: worker_services.into_boxed_slice(),
+                                    counter: WorkerCounter::new(idx, waker_queue, counter),
+                                    factories: factories.into_boxed_slice(),
+                                    state: WorkerState::default(),
+                                    shutdown_timeout: config.shutdown_timeout,
+                                }
+                                .await;
+
+                                // wake up outermost task waiting for shutdown
+                                worker_stopped_tx.send(()).unwrap();
+                            });
+
+                            worker_stopped_rx.await.unwrap();
+                        };
+
+                        #[cfg(all(target_os = "linux", feature = "io-uring"))]
+                        {
+                            // TODO: pass max blocking thread config when tokio-uring enable configuration
+                            // on building runtime.
+                            let _ = config.max_blocking_threads;
+                            tokio_uring::start(worker_fut);
+                        }
+
+                        #[cfg(not(all(target_os = "linux", feature = "io-uring")))]
+                        {
+                            let rt = tokio::runtime::Builder::new_current_thread()
+                                .enable_all()
+                                .max_blocking_threads(config.max_blocking_threads)
+                                .build()
+                                .unwrap();
+
+                            rt.block_on(ls.run_until(worker_fut));
+                        }
+                    })
+                    .expect("cannot spawn server worker thread");
+            }
+
+            // with actix system
+            (Some(_sys), _) => {
+                #[cfg(all(target_os = "linux", feature = "io-uring"))]
+                let arbiter = {
+                    // TODO: pass max blocking thread config when tokio-uring enable configuration
+                    // on building runtime.
+                    let _ = config.max_blocking_threads;
+                    Arbiter::new()
+                };
+
+                #[cfg(not(all(target_os = "linux", feature = "io-uring")))]
+                let arbiter = {
+                    Arbiter::with_tokio_rt(move || {
+                        tokio::runtime::Builder::new_current_thread()
+                            .enable_all()
+                            .max_blocking_threads(config.max_blocking_threads)
+                            .build()
+                            .unwrap()
+                    })
+                };
+
+                arbiter.spawn(async move {
+                    // spawn_local to run !Send future tasks.
+                    spawn(async move {
+                        let mut services = Vec::new();
+
+                        for (idx, factory) in factories.iter().enumerate() {
+                            match factory.create().await {
+                                Ok((token, svc)) => services.push((idx, token, svc)),
+
+                                Err(err) => {
+                                    error!("can not start worker: {:?}", err);
+                                    Arbiter::current().stop();
+                                    factory_tx
+                                        .send(Err(io::Error::new(
+                                            io::ErrorKind::Other,
+                                            format!("can not start server service {}", idx),
+                                        )))
+                                        .unwrap();
+                                    return;
+                                }
+                            }
+                        }
+
+                        factory_tx.send(Ok(())).unwrap();
+
+                        let worker_services = wrap_worker_services(services);
+
+                        // spawn to make sure ServerWorker runs as non boxed future.
+                        spawn(ServerWorker {
+                            conn_rx,
+                            stop_rx,
+                            services: worker_services.into_boxed_slice(),
+                            counter: WorkerCounter::new(idx, waker_queue, counter),
+                            factories: factories.into_boxed_slice(),
+                            state: Default::default(),
+                            shutdown_timeout: config.shutdown_timeout,
+                        });
+                    });
+                });
+            }
+        };
+
+        // wait for service factories initialization
+        factory_rx.recv().unwrap()?;
+
+        Ok(pair)
+    }
+
+    fn restart_service(&mut self, idx: usize, factory_id: usize) {
+        let factory = &self.factories[factory_id];
+        trace!("service {:?} failed, restarting", factory.name(idx));
+        self.services[idx].status = WorkerServiceStatus::Restarting;
+        self.state = WorkerState::Restarting(Restart {
+            factory_id,
+            token: idx,
+            fut: factory.create(),
+        });
+    }
+
+    fn shutdown(&mut self, force: bool) {
+        self.services
+            .iter_mut()
+            .filter(|srv| srv.status == WorkerServiceStatus::Available)
+            .for_each(|srv| {
+                srv.status = if force {
+                    WorkerServiceStatus::Stopped
+                } else {
+                    WorkerServiceStatus::Stopping
+                };
+            });
+    }
+
+    fn check_readiness(&mut self, cx: &mut Context<'_>) -> Result<bool, (usize, usize)> {
+        let mut ready = true;
+        for (idx, srv) in self.services.iter_mut().enumerate() {
+            if srv.status == WorkerServiceStatus::Available
+                || srv.status == WorkerServiceStatus::Unavailable
+            {
+                match srv.service.poll_ready(cx) {
+                    Poll::Ready(Ok(_)) => {
+                        if srv.status == WorkerServiceStatus::Unavailable {
+                            trace!(
+                                "service {:?} is available",
+                                self.factories[srv.factory_idx].name(idx)
+                            );
+                            srv.status = WorkerServiceStatus::Available;
+                        }
+                    }
+                    Poll::Pending => {
+                        ready = false;
+
+                        if srv.status == WorkerServiceStatus::Available {
+                            trace!(
+                                "service {:?} is unavailable",
+                                self.factories[srv.factory_idx].name(idx)
+                            );
+                            srv.status = WorkerServiceStatus::Unavailable;
+                        }
+                    }
+                    Poll::Ready(Err(_)) => {
+                        error!(
+                            "service {:?} readiness check returned error, restarting",
+                            self.factories[srv.factory_idx].name(idx)
+                        );
+                        srv.status = WorkerServiceStatus::Failed;
+                        return Err((idx, srv.factory_idx));
+                    }
+                }
+            }
+        }
+
+        Ok(ready)
+    }
+}
+
+enum WorkerState {
+    Available,
+    Unavailable,
+    Restarting(Restart),
+    Shutdown(Shutdown),
+}
+
+struct Restart {
+    factory_id: usize,
+    token: usize,
+    fut: LocalBoxFuture<'static, Result<(usize, BoxedServerService), ()>>,
+}
+
+/// State necessary for server shutdown.
+struct Shutdown {
+    // Interval for checking the shutdown progress.
+    timer: Pin<Box<Sleep>>,
+
+    /// Start time of shutdown.
+    start_from: Instant,
+
+    /// Notify caller of the shutdown outcome (graceful/force).
+    tx: oneshot::Sender<bool>,
+}
+
+impl Default for WorkerState {
+    fn default() -> Self {
+        Self::Unavailable
+    }
+}
+
+impl Drop for ServerWorker {
+    fn drop(&mut self) {
+        Arbiter::try_current().as_ref().map(ArbiterHandle::stop);
+    }
+}
+
+impl Future for ServerWorker {
+    type Output = ();
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.as_mut().get_mut();
+
+        // `StopWorker` message handler
+        if let Poll::Ready(Some(Stop { graceful, tx })) = this.stop_rx.poll_recv(cx) {
+            let num = this.counter.total();
+            if num == 0 {
+                info!("shutting down idle worker");
+                let _ = tx.send(true);
+                return Poll::Ready(());
+            } else if graceful {
+                info!("graceful worker shutdown; finishing {} connections", num);
+                this.shutdown(false);
+
+                this.state = WorkerState::Shutdown(Shutdown {
+                    timer: Box::pin(sleep(Duration::from_secs(1))),
+                    start_from: Instant::now(),
+                    tx,
+                });
+            } else {
+                info!("force shutdown worker, closing {} connections", num);
+                this.shutdown(true);
+
+                let _ = tx.send(false);
+                return Poll::Ready(());
+            }
+        }
+
+        match this.state {
+            WorkerState::Unavailable => match this.check_readiness(cx) {
+                Ok(true) => {
+                    this.state = WorkerState::Available;
+                    self.poll(cx)
+                }
+                Ok(false) => Poll::Pending,
+                Err((token, idx)) => {
+                    this.restart_service(token, idx);
+                    self.poll(cx)
+                }
+            },
+
+            WorkerState::Restarting(ref mut restart) => {
+                let factory_id = restart.factory_id;
+                let token = restart.token;
+
+                let (token_new, service) =
+                    ready!(restart.fut.as_mut().poll(cx)).unwrap_or_else(|_| {
+                        panic!(
+                            "Can not restart {:?} service",
+                            this.factories[factory_id].name(token)
+                        )
+                    });
+
+                assert_eq!(token, token_new);
+
+                trace!(
+                    "service {:?} has been restarted",
+                    this.factories[factory_id].name(token)
+                );
+
+                this.services[token].created(service);
+                this.state = WorkerState::Unavailable;
+
+                self.poll(cx)
+            }
+
+            WorkerState::Shutdown(ref mut shutdown) => {
+                // drop all pending connections in rx channel.
+                while let Poll::Ready(Some(conn)) = this.conn_rx.poll_recv(cx) {
+                    // WorkerCounterGuard is needed as Accept thread has incremented counter.
+                    // It's guard's job to decrement the counter together with drop of Conn.
+                    let guard = this.counter.guard();
+                    drop((conn, guard));
+                }
+
+                // wait for 1 second
+                ready!(shutdown.timer.as_mut().poll(cx));
+
+                if this.counter.total() == 0 {
+                    // graceful shutdown
+                    if let WorkerState::Shutdown(shutdown) = mem::take(&mut this.state) {
+                        let _ = shutdown.tx.send(true);
+                    }
+
+                    Poll::Ready(())
+                } else if shutdown.start_from.elapsed() >= this.shutdown_timeout {
+                    // timeout forceful shutdown
+                    if let WorkerState::Shutdown(shutdown) = mem::take(&mut this.state) {
+                        let _ = shutdown.tx.send(false);
+                    }
+
+                    Poll::Ready(())
+                } else {
+                    // reset timer and wait for 1 second
+                    let time = Instant::now() + Duration::from_secs(1);
+                    shutdown.timer.as_mut().reset(time);
+                    shutdown.timer.as_mut().poll(cx)
+                }
+            }
+
+            // actively poll stream and handle worker command
+            WorkerState::Available => loop {
+                match this.check_readiness(cx) {
+                    Ok(true) => {}
+                    Ok(false) => {
+                        trace!("worker is unavailable");
+                        this.state = WorkerState::Unavailable;
+                        return self.poll(cx);
+                    }
+                    Err((token, idx)) => {
+                        this.restart_service(token, idx);
+                        return self.poll(cx);
+                    }
+                }
+
+                // handle incoming io stream
+                match ready!(this.conn_rx.poll_recv(cx)) {
+                    Some(msg) => {
+                        let guard = this.counter.guard();
+                        let _ = this.services[msg.token]
+                            .service
+                            .call((guard, msg.io))
+                            .into_inner();
+                    }
+                    None => return Poll::Ready(()),
+                };
+            },
+        }
+    }
+}
+
+fn wrap_worker_services(services: Vec<(usize, usize, BoxedServerService)>) -> Vec<WorkerService> {
+    services
+        .into_iter()
+        .fold(Vec::new(), |mut services, (idx, token, service)| {
+            assert_eq!(token, services.len());
+            services.push(WorkerService {
+                factory_idx: idx,
+                service,
+                status: WorkerServiceStatus::Unavailable,
+            });
+            services
+        })
+}
+
\ No newline at end of file diff --git a/src/actix_service/and_then.rs.html b/src/actix_service/and_then.rs.html new file mode 100644 index 00000000..f119a2a6 --- /dev/null +++ b/src/actix_service/and_then.rs.html @@ -0,0 +1,651 @@ +and_then.rs - source

actix_service/
and_then.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
use alloc::rc::Rc;
+use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use futures_core::ready;
+use pin_project_lite::pin_project;
+
+use super::{Service, ServiceFactory};
+
+/// Service for the `and_then` combinator, chaining a computation onto the end of another service
+/// which completes successfully.
+///
+/// This is created by the `Pipeline::and_then` method.
+pub struct AndThenService<A, B, Req>(Rc<(A, B)>, PhantomData<Req>);
+
+impl<A, B, Req> AndThenService<A, B, Req> {
+    /// Create new `AndThen` combinator
+    pub(crate) fn new(a: A, b: B) -> Self
+    where
+        A: Service<Req>,
+        B: Service<A::Response, Error = A::Error>,
+    {
+        Self(Rc::new((a, b)), PhantomData)
+    }
+}
+
+impl<A, B, Req> Clone for AndThenService<A, B, Req> {
+    fn clone(&self) -> Self {
+        AndThenService(self.0.clone(), PhantomData)
+    }
+}
+
+impl<A, B, Req> Service<Req> for AndThenService<A, B, Req>
+where
+    A: Service<Req>,
+    B: Service<A::Response, Error = A::Error>,
+{
+    type Response = B::Response;
+    type Error = A::Error;
+    type Future = AndThenServiceResponse<A, B, Req>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        let (a, b) = &*self.0;
+        let not_ready = !a.poll_ready(cx)?.is_ready();
+        if !b.poll_ready(cx)?.is_ready() || not_ready {
+            Poll::Pending
+        } else {
+            Poll::Ready(Ok(()))
+        }
+    }
+
+    fn call(&self, req: Req) -> Self::Future {
+        AndThenServiceResponse {
+            state: State::A {
+                fut: self.0 .0.call(req),
+                b: Some(self.0.clone()),
+            },
+        }
+    }
+}
+
+pin_project! {
+    pub struct AndThenServiceResponse<A, B, Req>
+    where
+        A: Service<Req>,
+        B: Service<A::Response, Error = A::Error>,
+    {
+        #[pin]
+        state: State<A, B, Req>,
+    }
+}
+
+pin_project! {
+    #[project = StateProj]
+    enum State<A, B, Req>
+    where
+        A: Service<Req>,
+        B: Service<A::Response, Error = A::Error>,
+    {
+        A {
+            #[pin]
+            fut: A::Future,
+            b: Option<Rc<(A, B)>>,
+        },
+        B {
+            #[pin]
+            fut: B::Future,
+        },
+    }
+}
+
+impl<A, B, Req> Future for AndThenServiceResponse<A, B, Req>
+where
+    A: Service<Req>,
+    B: Service<A::Response, Error = A::Error>,
+{
+    type Output = Result<B::Response, A::Error>;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.as_mut().project();
+
+        match this.state.as_mut().project() {
+            StateProj::A { fut, b } => {
+                let res = ready!(fut.poll(cx))?;
+                let b = b.take().unwrap();
+                let fut = b.1.call(res);
+                this.state.set(State::B { fut });
+                self.poll(cx)
+            }
+            StateProj::B { fut } => fut.poll(cx),
+        }
+    }
+}
+
+/// `.and_then()` service factory combinator
+pub struct AndThenServiceFactory<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    A::Config: Clone,
+    B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>,
+{
+    inner: Rc<(A, B)>,
+    _phantom: PhantomData<Req>,
+}
+
+impl<A, B, Req> AndThenServiceFactory<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    A::Config: Clone,
+    B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>,
+{
+    /// Create new `AndThenFactory` combinator
+    pub(crate) fn new(a: A, b: B) -> Self {
+        Self {
+            inner: Rc::new((a, b)),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<A, B, Req> ServiceFactory<Req> for AndThenServiceFactory<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    A::Config: Clone,
+    B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>,
+{
+    type Response = B::Response;
+    type Error = A::Error;
+
+    type Config = A::Config;
+    type Service = AndThenService<A::Service, B::Service, Req>;
+    type InitError = A::InitError;
+    type Future = AndThenServiceFactoryResponse<A, B, Req>;
+
+    fn new_service(&self, cfg: A::Config) -> Self::Future {
+        let inner = &*self.inner;
+        AndThenServiceFactoryResponse::new(
+            inner.0.new_service(cfg.clone()),
+            inner.1.new_service(cfg),
+        )
+    }
+}
+
+impl<A, B, Req> Clone for AndThenServiceFactory<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    A::Config: Clone,
+    B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>,
+{
+    fn clone(&self) -> Self {
+        Self {
+            inner: self.inner.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+pin_project! {
+    pub struct AndThenServiceFactoryResponse<A, B, Req>
+    where
+        A: ServiceFactory<Req>,
+        B: ServiceFactory<A::Response>,
+    {
+        #[pin]
+        fut_a: A::Future,
+        #[pin]
+        fut_b: B::Future,
+
+        a: Option<A::Service>,
+        b: Option<B::Service>,
+    }
+}
+
+impl<A, B, Req> AndThenServiceFactoryResponse<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    B: ServiceFactory<A::Response>,
+{
+    fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
+        AndThenServiceFactoryResponse {
+            fut_a,
+            fut_b,
+            a: None,
+            b: None,
+        }
+    }
+}
+
+impl<A, B, Req> Future for AndThenServiceFactoryResponse<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    B: ServiceFactory<A::Response, Error = A::Error, InitError = A::InitError>,
+{
+    type Output = Result<AndThenService<A::Service, B::Service, Req>, A::InitError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        if this.a.is_none() {
+            if let Poll::Ready(service) = this.fut_a.poll(cx)? {
+                *this.a = Some(service);
+            }
+        }
+        if this.b.is_none() {
+            if let Poll::Ready(service) = this.fut_b.poll(cx)? {
+                *this.b = Some(service);
+            }
+        }
+        if this.a.is_some() && this.b.is_some() {
+            Poll::Ready(Ok(AndThenService::new(
+                this.a.take().unwrap(),
+                this.b.take().unwrap(),
+            )))
+        } else {
+            Poll::Pending
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use alloc::rc::Rc;
+    use core::{
+        cell::Cell,
+        task::{Context, Poll},
+    };
+
+    use futures_util::future::lazy;
+
+    use crate::{
+        fn_factory, ok,
+        pipeline::{pipeline, pipeline_factory},
+        ready, Ready, Service, ServiceFactory,
+    };
+
+    struct Srv1(Rc<Cell<usize>>);
+
+    impl Service<&'static str> for Srv1 {
+        type Response = &'static str;
+        type Error = ();
+        type Future = Ready<Result<Self::Response, ()>>;
+
+        fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+            self.0.set(self.0.get() + 1);
+            Poll::Ready(Ok(()))
+        }
+
+        fn call(&self, req: &'static str) -> Self::Future {
+            ok(req)
+        }
+    }
+
+    #[derive(Clone)]
+    struct Srv2(Rc<Cell<usize>>);
+
+    impl Service<&'static str> for Srv2 {
+        type Response = (&'static str, &'static str);
+        type Error = ();
+        type Future = Ready<Result<Self::Response, ()>>;
+
+        fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+            self.0.set(self.0.get() + 1);
+            Poll::Ready(Ok(()))
+        }
+
+        fn call(&self, req: &'static str) -> Self::Future {
+            ok((req, "srv2"))
+        }
+    }
+
+    #[actix_rt::test]
+    async fn test_poll_ready() {
+        let cnt = Rc::new(Cell::new(0));
+        let srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt.clone()));
+        let res = lazy(|cx| srv.poll_ready(cx)).await;
+        assert_eq!(res, Poll::Ready(Ok(())));
+        assert_eq!(cnt.get(), 2);
+    }
+
+    #[actix_rt::test]
+    async fn test_call() {
+        let cnt = Rc::new(Cell::new(0));
+        let srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt));
+        let res = srv.call("srv1").await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv1", "srv2"));
+    }
+
+    #[actix_rt::test]
+    async fn test_new_service() {
+        let cnt = Rc::new(Cell::new(0));
+        let cnt2 = cnt.clone();
+        let new_srv = pipeline_factory(fn_factory(move || ready(Ok::<_, ()>(Srv1(cnt2.clone())))))
+            .and_then(move || ready(Ok(Srv2(cnt.clone()))));
+
+        let srv = new_srv.new_service(()).await.unwrap();
+        let res = srv.call("srv1").await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv1", "srv2"));
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/apply.rs.html b/src/actix_service/apply.rs.html new file mode 100644 index 00000000..e8aa7d7b --- /dev/null +++ b/src/actix_service/apply.rs.html @@ -0,0 +1,547 @@ +apply.rs - source

actix_service/
apply.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use futures_core::ready;
+use pin_project_lite::pin_project;
+
+use super::{IntoService, IntoServiceFactory, Service, ServiceFactory};
+
+/// Apply transform function to a service.
+///
+/// The In and Out type params refer to the request and response types for the wrapped service.
+pub fn apply_fn<I, S, F, Fut, Req, In, Res, Err>(
+    service: I,
+    wrap_fn: F,
+) -> Apply<S, F, Req, In, Res, Err>
+where
+    I: IntoService<S, In>,
+    S: Service<In, Error = Err>,
+    F: Fn(Req, &S) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    Apply::new(service.into_service(), wrap_fn)
+}
+
+/// Service factory that produces `apply_fn` service.
+///
+/// The In and Out type params refer to the request and response types for the wrapped service.
+pub fn apply_fn_factory<I, SF, F, Fut, Req, In, Res, Err>(
+    service: I,
+    f: F,
+) -> ApplyFactory<SF, F, Req, In, Res, Err>
+where
+    I: IntoServiceFactory<SF, In>,
+    SF: ServiceFactory<In, Error = Err>,
+    F: Fn(Req, &SF::Service) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    ApplyFactory::new(service.into_factory(), f)
+}
+
+/// `Apply` service combinator.
+///
+/// The In and Out type params refer to the request and response types for the wrapped service.
+pub struct Apply<S, F, Req, In, Res, Err>
+where
+    S: Service<In, Error = Err>,
+{
+    service: S,
+    wrap_fn: F,
+    _phantom: PhantomData<fn(Req) -> (In, Res, Err)>,
+}
+
+impl<S, F, Fut, Req, In, Res, Err> Apply<S, F, Req, In, Res, Err>
+where
+    S: Service<In, Error = Err>,
+    F: Fn(Req, &S) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    /// Create new `Apply` combinator
+    fn new(service: S, wrap_fn: F) -> Self {
+        Self {
+            service,
+            wrap_fn,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<S, F, Fut, Req, In, Res, Err> Clone for Apply<S, F, Req, In, Res, Err>
+where
+    S: Service<In, Error = Err> + Clone,
+    F: Fn(Req, &S) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn clone(&self) -> Self {
+        Apply {
+            service: self.service.clone(),
+            wrap_fn: self.wrap_fn.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<S, F, Fut, Req, In, Res, Err> Service<Req> for Apply<S, F, Req, In, Res, Err>
+where
+    S: Service<In, Error = Err>,
+    F: Fn(Req, &S) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    type Response = Res;
+    type Error = Err;
+    type Future = Fut;
+
+    crate::forward_ready!(service);
+
+    fn call(&self, req: Req) -> Self::Future {
+        (self.wrap_fn)(req, &self.service)
+    }
+}
+
+/// `ApplyFactory` service factory combinator.
+pub struct ApplyFactory<SF, F, Req, In, Res, Err> {
+    factory: SF,
+    wrap_fn: F,
+    _phantom: PhantomData<fn(Req) -> (In, Res, Err)>,
+}
+
+impl<SF, F, Fut, Req, In, Res, Err> ApplyFactory<SF, F, Req, In, Res, Err>
+where
+    SF: ServiceFactory<In, Error = Err>,
+    F: Fn(Req, &SF::Service) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    /// Create new `ApplyFactory` new service instance
+    fn new(factory: SF, wrap_fn: F) -> Self {
+        Self {
+            factory,
+            wrap_fn,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, F, Fut, Req, In, Res, Err> Clone for ApplyFactory<SF, F, Req, In, Res, Err>
+where
+    SF: ServiceFactory<In, Error = Err> + Clone,
+    F: Fn(Req, &SF::Service) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn clone(&self) -> Self {
+        Self {
+            factory: self.factory.clone(),
+            wrap_fn: self.wrap_fn.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, F, Fut, Req, In, Res, Err> ServiceFactory<Req> for ApplyFactory<SF, F, Req, In, Res, Err>
+where
+    SF: ServiceFactory<In, Error = Err>,
+    F: Fn(Req, &SF::Service) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    type Response = Res;
+    type Error = Err;
+
+    type Config = SF::Config;
+    type Service = Apply<SF::Service, F, Req, In, Res, Err>;
+    type InitError = SF::InitError;
+    type Future = ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err>;
+
+    fn new_service(&self, cfg: SF::Config) -> Self::Future {
+        let svc = self.factory.new_service(cfg);
+        ApplyServiceFactoryResponse::new(svc, self.wrap_fn.clone())
+    }
+}
+
+pin_project! {
+    pub struct ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err>
+    where
+        SF: ServiceFactory<In, Error = Err>,
+        F: Fn(Req, &SF::Service) -> Fut,
+        Fut: Future<Output = Result<Res, Err>>,
+    {
+        #[pin]
+        fut: SF::Future,
+        wrap_fn: Option<F>,
+        _phantom: PhantomData<fn(Req) -> Res>,
+    }
+}
+
+impl<SF, F, Fut, Req, In, Res, Err> ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err>
+where
+    SF: ServiceFactory<In, Error = Err>,
+    F: Fn(Req, &SF::Service) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn new(fut: SF::Future, wrap_fn: F) -> Self {
+        Self {
+            fut,
+            wrap_fn: Some(wrap_fn),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, F, Fut, Req, In, Res, Err> Future
+    for ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err>
+where
+    SF: ServiceFactory<In, Error = Err>,
+    F: Fn(Req, &SF::Service) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    type Output = Result<Apply<SF::Service, F, Req, In, Res, Err>, SF::InitError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        let svc = ready!(this.fut.poll(cx))?;
+        Poll::Ready(Ok(Apply::new(svc, this.wrap_fn.take().unwrap())))
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use futures_util::future::lazy;
+
+    use super::*;
+    use crate::{
+        ok,
+        pipeline::{pipeline, pipeline_factory},
+        Ready,
+    };
+
+    #[derive(Clone)]
+    struct Srv;
+
+    impl Service<()> for Srv {
+        type Response = ();
+        type Error = ();
+        type Future = Ready<Result<(), ()>>;
+
+        crate::always_ready!();
+
+        fn call(&self, _: ()) -> Self::Future {
+            ok(())
+        }
+    }
+
+    #[actix_rt::test]
+    async fn test_call() {
+        let srv = pipeline(apply_fn(Srv, |req: &'static str, srv| {
+            let fut = srv.call(());
+            async move {
+                fut.await.unwrap();
+                Ok((req, ()))
+            }
+        }));
+
+        assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
+
+        let res = srv.call("srv").await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv", ()));
+    }
+
+    #[actix_rt::test]
+    async fn test_new_service() {
+        let new_srv = pipeline_factory(apply_fn_factory(
+            || ok::<_, ()>(Srv),
+            |req: &'static str, srv| {
+                let fut = srv.call(());
+                async move {
+                    fut.await.unwrap();
+                    Ok((req, ()))
+                }
+            },
+        ));
+
+        let srv = new_srv.new_service(()).await.unwrap();
+
+        assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
+
+        let res = srv.call("srv").await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv", ()));
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/apply_cfg.rs.html b/src/actix_service/apply_cfg.rs.html new file mode 100644 index 00000000..95ae8e5c --- /dev/null +++ b/src/actix_service/apply_cfg.rs.html @@ -0,0 +1,465 @@ +apply_cfg.rs - source

actix_service/
apply_cfg.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
use alloc::rc::Rc;
+use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use futures_core::ready;
+use pin_project_lite::pin_project;
+
+use crate::{Service, ServiceFactory};
+
+/// Convert `Fn(Config, &Service1) -> Future<Service2>` fn to a service factory.
+pub fn apply_cfg<S1, Req, F, Cfg, Fut, S2, Err>(
+    srv: S1,
+    f: F,
+) -> impl ServiceFactory<
+    Req,
+    Config = Cfg,
+    Response = S2::Response,
+    Error = S2::Error,
+    Service = S2,
+    InitError = Err,
+    Future = Fut,
+> + Clone
+where
+    S1: Service<Req>,
+    F: Fn(Cfg, &S1) -> Fut,
+    Fut: Future<Output = Result<S2, Err>>,
+    S2: Service<Req>,
+{
+    ApplyConfigService {
+        srv: Rc::new((srv, f)),
+        _phantom: PhantomData,
+    }
+}
+
+/// Convert `Fn(Config, &ServiceFactory1) -> Future<ServiceFactory2>` fn to a service factory.
+///
+/// Service1 get constructed from `T` factory.
+pub fn apply_cfg_factory<SF, Req, F, Cfg, Fut, S>(
+    factory: SF,
+    f: F,
+) -> impl ServiceFactory<
+    Req,
+    Config = Cfg,
+    Response = S::Response,
+    Error = S::Error,
+    Service = S,
+    InitError = SF::InitError,
+> + Clone
+where
+    SF: ServiceFactory<Req, Config = ()>,
+    F: Fn(Cfg, &SF::Service) -> Fut,
+    SF::InitError: From<SF::Error>,
+    Fut: Future<Output = Result<S, SF::InitError>>,
+    S: Service<Req>,
+{
+    ApplyConfigServiceFactory {
+        srv: Rc::new((factory, f)),
+        _phantom: PhantomData,
+    }
+}
+
+/// Convert `Fn(Config, &Server) -> Future<Service>` fn to NewService\
+struct ApplyConfigService<S1, Req, F, Cfg, Fut, S2, Err>
+where
+    S1: Service<Req>,
+    F: Fn(Cfg, &S1) -> Fut,
+    Fut: Future<Output = Result<S2, Err>>,
+    S2: Service<Req>,
+{
+    srv: Rc<(S1, F)>,
+    _phantom: PhantomData<(Cfg, Req, Fut, S2)>,
+}
+
+impl<S1, Req, F, Cfg, Fut, S2, Err> Clone for ApplyConfigService<S1, Req, F, Cfg, Fut, S2, Err>
+where
+    S1: Service<Req>,
+    F: Fn(Cfg, &S1) -> Fut,
+    Fut: Future<Output = Result<S2, Err>>,
+    S2: Service<Req>,
+{
+    fn clone(&self) -> Self {
+        ApplyConfigService {
+            srv: self.srv.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<S1, Req, F, Cfg, Fut, S2, Err> ServiceFactory<Req>
+    for ApplyConfigService<S1, Req, F, Cfg, Fut, S2, Err>
+where
+    S1: Service<Req>,
+    F: Fn(Cfg, &S1) -> Fut,
+    Fut: Future<Output = Result<S2, Err>>,
+    S2: Service<Req>,
+{
+    type Response = S2::Response;
+    type Error = S2::Error;
+    type Config = Cfg;
+    type Service = S2;
+
+    type InitError = Err;
+    type Future = Fut;
+
+    fn new_service(&self, cfg: Cfg) -> Self::Future {
+        let (t, f) = &*self.srv;
+        f(cfg, t)
+    }
+}
+
+/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
+struct ApplyConfigServiceFactory<SF, Req, F, Cfg, Fut, S>
+where
+    SF: ServiceFactory<Req, Config = ()>,
+    F: Fn(Cfg, &SF::Service) -> Fut,
+    Fut: Future<Output = Result<S, SF::InitError>>,
+    S: Service<Req>,
+{
+    srv: Rc<(SF, F)>,
+    _phantom: PhantomData<(Cfg, Req, Fut, S)>,
+}
+
+impl<SF, Req, F, Cfg, Fut, S> Clone for ApplyConfigServiceFactory<SF, Req, F, Cfg, Fut, S>
+where
+    SF: ServiceFactory<Req, Config = ()>,
+    F: Fn(Cfg, &SF::Service) -> Fut,
+    Fut: Future<Output = Result<S, SF::InitError>>,
+    S: Service<Req>,
+{
+    fn clone(&self) -> Self {
+        Self {
+            srv: self.srv.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, Req, F, Cfg, Fut, S> ServiceFactory<Req>
+    for ApplyConfigServiceFactory<SF, Req, F, Cfg, Fut, S>
+where
+    SF: ServiceFactory<Req, Config = ()>,
+    SF::InitError: From<SF::Error>,
+    F: Fn(Cfg, &SF::Service) -> Fut,
+    Fut: Future<Output = Result<S, SF::InitError>>,
+    S: Service<Req>,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Config = Cfg;
+    type Service = S;
+
+    type InitError = SF::InitError;
+    type Future = ApplyConfigServiceFactoryResponse<SF, Req, F, Cfg, Fut, S>;
+
+    fn new_service(&self, cfg: Cfg) -> Self::Future {
+        ApplyConfigServiceFactoryResponse {
+            cfg: Some(cfg),
+            store: self.srv.clone(),
+            state: State::A {
+                fut: self.srv.0.new_service(()),
+            },
+        }
+    }
+}
+
+pin_project! {
+    struct ApplyConfigServiceFactoryResponse<SF, Req, F, Cfg, Fut, S>
+    where
+        SF: ServiceFactory<Req, Config = ()>,
+        SF::InitError: From<SF::Error>,
+        F: Fn(Cfg, &SF::Service) -> Fut,
+        Fut: Future<Output = Result<S, SF::InitError>>,
+        S: Service<Req>,
+    {
+        cfg: Option<Cfg>,
+        store: Rc<(SF, F)>,
+        #[pin]
+        state: State<SF, Fut, S, Req>,
+    }
+}
+
+pin_project! {
+    #[project = StateProj]
+    enum State<SF, Fut, S, Req>
+    where
+        SF: ServiceFactory<Req, Config = ()>,
+        SF::InitError: From<SF::Error>,
+        Fut: Future<Output = Result<S, SF::InitError>>,
+        S: Service<Req>,
+    {
+        A { #[pin] fut: SF::Future },
+        B { svc: SF::Service },
+        C { #[pin] fut: Fut },
+    }
+}
+
+impl<SF, Req, F, Cfg, Fut, S> Future for ApplyConfigServiceFactoryResponse<SF, Req, F, Cfg, Fut, S>
+where
+    SF: ServiceFactory<Req, Config = ()>,
+    SF::InitError: From<SF::Error>,
+    F: Fn(Cfg, &SF::Service) -> Fut,
+    Fut: Future<Output = Result<S, SF::InitError>>,
+    S: Service<Req>,
+{
+    type Output = Result<S, SF::InitError>;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.as_mut().project();
+
+        match this.state.as_mut().project() {
+            StateProj::A { fut } => {
+                let svc = ready!(fut.poll(cx))?;
+                this.state.set(State::B { svc });
+                self.poll(cx)
+            }
+            StateProj::B { svc } => {
+                ready!(svc.poll_ready(cx))?;
+                {
+                    let (_, f) = &**this.store;
+                    let fut = f(this.cfg.take().unwrap(), svc);
+                    this.state.set(State::C { fut });
+                }
+                self.poll(cx)
+            }
+            StateProj::C { fut } => fut.poll(cx),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/boxed.rs.html b/src/actix_service/boxed.rs.html new file mode 100644 index 00000000..9197e432 --- /dev/null +++ b/src/actix_service/boxed.rs.html @@ -0,0 +1,277 @@ +boxed.rs - source

actix_service/
boxed.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
//! Trait object forms of services and service factories.
+
+use alloc::{boxed::Box, rc::Rc};
+use core::{future::Future, pin::Pin};
+
+use paste::paste;
+
+use crate::{Service, ServiceFactory};
+
+/// A boxed future with no send bound or lifetime parameters.
+pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
+
+macro_rules! service_object {
+    ($name: ident, $type: tt, $fn_name: ident) => {
+        paste! {
+            #[doc = "Type alias for service trait object using `" $type "`."]
+            pub type $name<Req, Res, Err> = $type<
+                dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>,
+            >;
+
+            #[doc = "Wraps service as a trait object using [`" $name "`]."]
+            pub fn $fn_name<S, Req>(service: S) -> $name<Req, S::Response, S::Error>
+            where
+                S: Service<Req> + 'static,
+                Req: 'static,
+                S::Future: 'static,
+            {
+                $type::new(ServiceWrapper::new(service))
+            }
+        }
+    };
+}
+
+service_object!(BoxService, Box, service);
+service_object!(RcService, Rc, rc_service);
+
+struct ServiceWrapper<S> {
+    inner: S,
+}
+
+impl<S> ServiceWrapper<S> {
+    fn new(inner: S) -> Self {
+        Self { inner }
+    }
+}
+
+impl<S, Req, Res, Err> Service<Req> for ServiceWrapper<S>
+where
+    S: Service<Req, Response = Res, Error = Err>,
+    S::Future: 'static,
+{
+    type Response = Res;
+    type Error = Err;
+    type Future = BoxFuture<Result<Res, Err>>;
+
+    crate::forward_ready!(inner);
+
+    fn call(&self, req: Req) -> Self::Future {
+        Box::pin(self.inner.call(req))
+    }
+}
+
+/// Wrapper for a service factory that will map it's services to boxed trait object services.
+pub struct BoxServiceFactory<Cfg, Req, Res, Err, InitErr>(Inner<Cfg, Req, Res, Err, InitErr>);
+
+/// Wraps a service factory that returns service trait objects.
+pub fn factory<SF, Req>(
+    factory: SF,
+) -> BoxServiceFactory<SF::Config, Req, SF::Response, SF::Error, SF::InitError>
+where
+    SF: ServiceFactory<Req> + 'static,
+    Req: 'static,
+    SF::Response: 'static,
+    SF::Service: 'static,
+    SF::Future: 'static,
+    SF::Error: 'static,
+    SF::InitError: 'static,
+{
+    BoxServiceFactory(Box::new(FactoryWrapper(factory)))
+}
+
+type Inner<C, Req, Res, Err, InitErr> = Box<
+    dyn ServiceFactory<
+        Req,
+        Config = C,
+        Response = Res,
+        Error = Err,
+        InitError = InitErr,
+        Service = BoxService<Req, Res, Err>,
+        Future = BoxFuture<Result<BoxService<Req, Res, Err>, InitErr>>,
+    >,
+>;
+
+impl<C, Req, Res, Err, InitErr> ServiceFactory<Req> for BoxServiceFactory<C, Req, Res, Err, InitErr>
+where
+    Req: 'static,
+    Res: 'static,
+    Err: 'static,
+    InitErr: 'static,
+{
+    type Response = Res;
+    type Error = Err;
+    type Config = C;
+    type Service = BoxService<Req, Res, Err>;
+    type InitError = InitErr;
+
+    type Future = BoxFuture<Result<Self::Service, InitErr>>;
+
+    fn new_service(&self, cfg: C) -> Self::Future {
+        self.0.new_service(cfg)
+    }
+}
+
+struct FactoryWrapper<SF>(SF);
+
+impl<SF, Req, Cfg, Res, Err, InitErr> ServiceFactory<Req> for FactoryWrapper<SF>
+where
+    Req: 'static,
+    Res: 'static,
+    Err: 'static,
+    InitErr: 'static,
+    SF: ServiceFactory<Req, Config = Cfg, Response = Res, Error = Err, InitError = InitErr>,
+    SF::Future: 'static,
+    SF::Service: 'static,
+    <SF::Service as Service<Req>>::Future: 'static,
+{
+    type Response = Res;
+    type Error = Err;
+    type Config = Cfg;
+    type Service = BoxService<Req, Res, Err>;
+    type InitError = InitErr;
+    type Future = BoxFuture<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, cfg: Cfg) -> Self::Future {
+        let f = self.0.new_service(cfg);
+        Box::pin(async { f.await.map(|s| Box::new(ServiceWrapper::new(s)) as _) })
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/ext.rs.html b/src/actix_service/ext.rs.html new file mode 100644 index 00000000..44aba5da --- /dev/null +++ b/src/actix_service/ext.rs.html @@ -0,0 +1,249 @@ +ext.rs - source

actix_service/
ext.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
use crate::{
+    and_then::{AndThenService, AndThenServiceFactory},
+    map::Map,
+    map_err::MapErr,
+    transform_err::TransformMapInitErr,
+    IntoService, IntoServiceFactory, Service, ServiceFactory, Transform,
+};
+
+/// An extension trait for [`Service`]s that provides a variety of convenient adapters.
+pub trait ServiceExt<Req>: Service<Req> {
+    /// Map this service's output to a different type, returning a new service
+    /// of the resulting type.
+    ///
+    /// This function is similar to the `Option::map` or `Iterator::map` where
+    /// it will change the type of the underlying service.
+    ///
+    /// Note that this function consumes the receiving service and returns a
+    /// wrapped version of it, similar to the existing `map` methods in the
+    /// standard library.
+    fn map<F, R>(self, f: F) -> Map<Self, F, Req, R>
+    where
+        Self: Sized,
+        F: FnMut(Self::Response) -> R,
+    {
+        Map::new(self, f)
+    }
+
+    /// Map this service's error to a different error, returning a new service.
+    ///
+    /// This function is similar to the `Result::map_err` where it will change
+    /// the error type of the underlying service. For example, this can be useful to
+    /// ensure that services have the same error type.
+    ///
+    /// Note that this function consumes the receiving service and returns a
+    /// wrapped version of it.
+    fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E>
+    where
+        Self: Sized,
+        F: Fn(Self::Error) -> E,
+    {
+        MapErr::new(self, f)
+    }
+
+    /// Call another service after call to this one has resolved successfully.
+    ///
+    /// This function can be used to chain two services together and ensure that the second service
+    /// isn't called until call to the first service have finished. Result of the call to the first
+    /// service is used as an input parameter for the second service's call.
+    ///
+    /// Note that this function consumes the receiving service and returns a wrapped version of it.
+    fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req>
+    where
+        Self: Sized,
+        I: IntoService<S1, Self::Response>,
+        S1: Service<Self::Response, Error = Self::Error>,
+    {
+        AndThenService::new(self, service.into_service())
+    }
+}
+
+impl<S, Req> ServiceExt<Req> for S where S: Service<Req> {}
+
+/// An extension trait for [`ServiceFactory`]s that provides a variety of convenient adapters.
+pub trait ServiceFactoryExt<Req>: ServiceFactory<Req> {
+    /// Map this service's output to a different type, returning a new service
+    /// of the resulting type.
+    fn map<F, R>(self, f: F) -> crate::map::MapServiceFactory<Self, F, Req, R>
+    where
+        Self: Sized,
+        F: FnMut(Self::Response) -> R + Clone,
+    {
+        crate::map::MapServiceFactory::new(self, f)
+    }
+
+    /// Map this service's error to a different error, returning a new service.
+    fn map_err<F, E>(self, f: F) -> crate::map_err::MapErrServiceFactory<Self, Req, F, E>
+    where
+        Self: Sized,
+        F: Fn(Self::Error) -> E + Clone,
+    {
+        crate::map_err::MapErrServiceFactory::new(self, f)
+    }
+
+    /// Map this factory's init error to a different error, returning a new service.
+    fn map_init_err<F, E>(self, f: F) -> crate::map_init_err::MapInitErr<Self, F, Req, E>
+    where
+        Self: Sized,
+        F: Fn(Self::InitError) -> E + Clone,
+    {
+        crate::map_init_err::MapInitErr::new(self, f)
+    }
+
+    /// Call another service after call to this one has resolved successfully.
+    fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req>
+    where
+        Self: Sized,
+        Self::Config: Clone,
+        I: IntoServiceFactory<SF1, Self::Response>,
+        SF1: ServiceFactory<
+            Self::Response,
+            Config = Self::Config,
+            Error = Self::Error,
+            InitError = Self::InitError,
+        >,
+    {
+        AndThenServiceFactory::new(self, factory.into_factory())
+    }
+}
+
+impl<SF, Req> ServiceFactoryExt<Req> for SF where SF: ServiceFactory<Req> {}
+
+/// An extension trait for [`Transform`]s that provides a variety of convenient adapters.
+pub trait TransformExt<S, Req>: Transform<S, Req> {
+    /// Return a new `Transform` whose init error is mapped to to a different type.
+    fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, Req, F, E>
+    where
+        Self: Sized,
+        F: Fn(Self::InitError) -> E + Clone,
+    {
+        TransformMapInitErr::new(self, f)
+    }
+}
+
+impl<T, Req> TransformExt<T, Req> for T where T: Transform<T, Req> {}
+
\ No newline at end of file diff --git a/src/actix_service/fn_service.rs.html b/src/actix_service/fn_service.rs.html new file mode 100644 index 00000000..ac8755ef --- /dev/null +++ b/src/actix_service/fn_service.rs.html @@ -0,0 +1,849 @@ +fn_service.rs - source

actix_service/
fn_service.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
use core::{future::Future, marker::PhantomData};
+
+use crate::{ok, IntoService, IntoServiceFactory, Ready, Service, ServiceFactory};
+
+/// Create `ServiceFactory` for function that can act as a `Service`
+pub fn fn_service<F, Fut, Req, Res, Err, Cfg>(f: F) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
+where
+    F: Fn(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    FnServiceFactory::new(f)
+}
+
+/// Create `ServiceFactory` for function that can produce services
+///
+/// # Examples
+/// ```
+/// use std::io;
+/// use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
+/// use futures_util::future::ok;
+///
+/// /// Service that divides two usize values.
+/// async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> {
+///     if y == 0 {
+///         Err(io::Error::new(io::ErrorKind::Other, "divide by zero"))
+///     } else {
+///         Ok(x / y)
+///     }
+/// }
+///
+/// #[actix_rt::main]
+/// async fn main() -> io::Result<()> {
+///     // Create service factory that produces `div` services
+///     let factory = fn_factory(|| {
+///         ok::<_, io::Error>(fn_service(div))
+///     });
+///
+///     // construct new service
+///     let srv = factory.new_service(()).await?;
+///
+///     // now we can use `div` service
+///     let result = srv.call((10, 20)).await?;
+///
+///     println!("10 / 20 = {}", result);
+///
+///     Ok(())
+/// }
+/// ```
+pub fn fn_factory<F, Cfg, Srv, Req, Fut, Err>(f: F) -> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
+where
+    F: Fn() -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    FnServiceNoConfig::new(f)
+}
+
+/// Create `ServiceFactory` for function that accepts config argument and can produce services
+///
+/// Any function that has following form `Fn(Config) -> Future<Output = Service>` could act as
+/// a `ServiceFactory`.
+///
+/// # Examples
+/// ```
+/// use std::io;
+/// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory};
+/// use futures_util::future::ok;
+///
+/// #[actix_rt::main]
+/// async fn main() -> io::Result<()> {
+///     // Create service factory. factory uses config argument for
+///     // services it generates.
+///     let factory = fn_factory_with_config(|y: usize| {
+///         ok::<_, io::Error>(fn_service(move |x: usize| ok::<_, io::Error>(x * y)))
+///     });
+///
+///     // construct new service with config argument
+///     let srv = factory.new_service(10).await?;
+///
+///     let result = srv.call(10).await?;
+///     assert_eq!(result, 100);
+///
+///     println!("10 * 10 = {}", result);
+///     Ok(())
+/// }
+/// ```
+pub fn fn_factory_with_config<F, Fut, Cfg, Srv, Req, Err>(
+    f: F,
+) -> FnServiceConfig<F, Fut, Cfg, Srv, Req, Err>
+where
+    F: Fn(Cfg) -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    FnServiceConfig::new(f)
+}
+
+pub struct FnService<F, Fut, Req, Res, Err>
+where
+    F: FnMut(Req) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    f: F,
+    _t: PhantomData<fn(Req)>,
+}
+
+impl<F, Fut, Req, Res, Err> FnService<F, Fut, Req, Res, Err>
+where
+    F: FnMut(Req) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    pub(crate) fn new(f: F) -> Self {
+        Self { f, _t: PhantomData }
+    }
+}
+
+impl<F, Fut, Req, Res, Err> Clone for FnService<F, Fut, Req, Res, Err>
+where
+    F: FnMut(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn clone(&self) -> Self {
+        Self::new(self.f.clone())
+    }
+}
+
+impl<F, Fut, Req, Res, Err> Service<Req> for FnService<F, Fut, Req, Res, Err>
+where
+    F: Fn(Req) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    type Response = Res;
+    type Error = Err;
+    type Future = Fut;
+
+    crate::always_ready!();
+
+    fn call(&self, req: Req) -> Self::Future {
+        (self.f)(req)
+    }
+}
+
+impl<F, Fut, Req, Res, Err> IntoService<FnService<F, Fut, Req, Res, Err>, Req> for F
+where
+    F: Fn(Req) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn into_service(self) -> FnService<F, Fut, Req, Res, Err> {
+        FnService::new(self)
+    }
+}
+
+pub struct FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
+where
+    F: Fn(Req) -> Fut,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    f: F,
+    _t: PhantomData<fn(Req, Cfg)>,
+}
+
+impl<F, Fut, Req, Res, Err, Cfg> FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
+where
+    F: Fn(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn new(f: F) -> Self {
+        FnServiceFactory { f, _t: PhantomData }
+    }
+}
+
+impl<F, Fut, Req, Res, Err, Cfg> Clone for FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
+where
+    F: Fn(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn clone(&self) -> Self {
+        Self::new(self.f.clone())
+    }
+}
+
+impl<F, Fut, Req, Res, Err> Service<Req> for FnServiceFactory<F, Fut, Req, Res, Err, ()>
+where
+    F: Fn(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    type Response = Res;
+    type Error = Err;
+    type Future = Fut;
+
+    crate::always_ready!();
+
+    fn call(&self, req: Req) -> Self::Future {
+        (self.f)(req)
+    }
+}
+
+impl<F, Fut, Req, Res, Err, Cfg> ServiceFactory<Req>
+    for FnServiceFactory<F, Fut, Req, Res, Err, Cfg>
+where
+    F: Fn(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    type Response = Res;
+    type Error = Err;
+
+    type Config = Cfg;
+    type Service = FnService<F, Fut, Req, Res, Err>;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: Cfg) -> Self::Future {
+        ok(FnService::new(self.f.clone()))
+    }
+}
+
+impl<F, Fut, Req, Res, Err, Cfg>
+    IntoServiceFactory<FnServiceFactory<F, Fut, Req, Res, Err, Cfg>, Req> for F
+where
+    F: Fn(Req) -> Fut + Clone,
+    Fut: Future<Output = Result<Res, Err>>,
+{
+    fn into_factory(self) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg> {
+        FnServiceFactory::new(self)
+    }
+}
+
+/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
+pub struct FnServiceConfig<F, Fut, Cfg, Srv, Req, Err>
+where
+    F: Fn(Cfg) -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    f: F,
+    _t: PhantomData<fn(Cfg, Req) -> (Fut, Srv, Err)>,
+}
+
+impl<F, Fut, Cfg, Srv, Req, Err> FnServiceConfig<F, Fut, Cfg, Srv, Req, Err>
+where
+    F: Fn(Cfg) -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    fn new(f: F) -> Self {
+        FnServiceConfig { f, _t: PhantomData }
+    }
+}
+
+impl<F, Fut, Cfg, Srv, Req, Err> Clone for FnServiceConfig<F, Fut, Cfg, Srv, Req, Err>
+where
+    F: Fn(Cfg) -> Fut + Clone,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    fn clone(&self) -> Self {
+        FnServiceConfig {
+            f: self.f.clone(),
+            _t: PhantomData,
+        }
+    }
+}
+
+impl<F, Fut, Cfg, Srv, Req, Err> ServiceFactory<Req> for FnServiceConfig<F, Fut, Cfg, Srv, Req, Err>
+where
+    F: Fn(Cfg) -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    type Response = Srv::Response;
+    type Error = Srv::Error;
+
+    type Config = Cfg;
+    type Service = Srv;
+    type InitError = Err;
+    type Future = Fut;
+
+    fn new_service(&self, cfg: Cfg) -> Self::Future {
+        (self.f)(cfg)
+    }
+}
+
+/// Converter for `Fn() -> Future<Service>` fn
+pub struct FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
+where
+    F: Fn() -> Fut,
+    Srv: Service<Req>,
+    Fut: Future<Output = Result<Srv, Err>>,
+{
+    f: F,
+    _t: PhantomData<fn(Cfg, Req)>,
+}
+
+impl<F, Cfg, Srv, Req, Fut, Err> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
+where
+    F: Fn() -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    fn new(f: F) -> Self {
+        Self { f, _t: PhantomData }
+    }
+}
+
+impl<F, Cfg, Srv, Req, Fut, Err> ServiceFactory<Req>
+    for FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
+where
+    F: Fn() -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    type Response = Srv::Response;
+    type Error = Srv::Error;
+    type Config = Cfg;
+    type Service = Srv;
+    type InitError = Err;
+    type Future = Fut;
+
+    fn new_service(&self, _: Cfg) -> Self::Future {
+        (self.f)()
+    }
+}
+
+impl<F, Cfg, Srv, Req, Fut, Err> Clone for FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
+where
+    F: Fn() -> Fut + Clone,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    fn clone(&self) -> Self {
+        Self::new(self.f.clone())
+    }
+}
+
+impl<F, Cfg, Srv, Req, Fut, Err>
+    IntoServiceFactory<FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>, Req> for F
+where
+    F: Fn() -> Fut,
+    Fut: Future<Output = Result<Srv, Err>>,
+    Srv: Service<Req>,
+{
+    fn into_factory(self) -> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> {
+        FnServiceNoConfig::new(self)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use core::task::Poll;
+
+    use futures_util::future::lazy;
+
+    use super::*;
+
+    #[actix_rt::test]
+    async fn test_fn_service() {
+        let new_srv = fn_service(|()| ok::<_, ()>("srv"));
+
+        let srv = new_srv.new_service(()).await.unwrap();
+        let res = srv.call(()).await;
+        assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), "srv");
+    }
+
+    #[actix_rt::test]
+    async fn test_fn_service_service() {
+        let srv = fn_service(|()| ok::<_, ()>("srv"));
+
+        let res = srv.call(()).await;
+        assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), "srv");
+    }
+
+    #[actix_rt::test]
+    async fn test_fn_service_with_config() {
+        let new_srv = fn_factory_with_config(|cfg: usize| {
+            ok::<_, ()>(fn_service(move |()| ok::<_, ()>(("srv", cfg))))
+        });
+
+        let srv = new_srv.new_service(1).await.unwrap();
+        let res = srv.call(()).await;
+        assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(())));
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv", 1));
+    }
+
+    #[actix_rt::test]
+    async fn test_auto_impl_send() {
+        use alloc::rc::Rc;
+
+        use crate::{map_config, ServiceExt, ServiceFactoryExt};
+
+        let srv_1 = fn_service(|_: Rc<u8>| ok::<_, Rc<u8>>(Rc::new(0u8)));
+
+        let fac_1 = fn_factory_with_config(|_: Rc<u8>| {
+            ok::<_, Rc<u8>>(fn_service(|_: Rc<u8>| ok::<_, Rc<u8>>(Rc::new(0u8))))
+        });
+
+        let fac_2 =
+            fn_factory(|| ok::<_, Rc<u8>>(fn_service(|_: Rc<u8>| ok::<_, Rc<u8>>(Rc::new(0u8)))));
+
+        fn is_send<T: Send + Sync + Clone>(_: &T) {}
+
+        is_send(&fac_1);
+        is_send(&map_config(fac_1.clone(), |_: Rc<u8>| Rc::new(0u8)));
+        is_send(&fac_1.clone().map_err(|_| Rc::new(0u8)));
+        is_send(&fac_1.clone().map(|_| Rc::new(0u8)));
+        is_send(&fac_1.clone().map_init_err(|_| Rc::new(0u8)));
+        // `and_then` is always !Send
+        // is_send(&fac_1.clone().and_then(fac_1.clone()));
+        is_send(&fac_1.new_service(Rc::new(0u8)).await.unwrap());
+
+        is_send(&fac_2);
+        is_send(&fac_2.new_service(Rc::new(0u8)).await.unwrap());
+
+        is_send(&srv_1);
+        is_send(&ServiceExt::map(srv_1.clone(), |_| Rc::new(0u8)));
+        is_send(&ServiceExt::map_err(srv_1.clone(), |_| Rc::new(0u8)));
+        // `and_then` is always !Send
+        // is_send(&ServiceExt::and_then(srv_1.clone(), srv_1.clone()));
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/lib.rs.html b/src/actix_service/lib.rs.html new file mode 100644 index 00000000..39ae0d83 --- /dev/null +++ b/src/actix_service/lib.rs.html @@ -0,0 +1,651 @@ +lib.rs - source

actix_service/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
//! See [`Service`] docs for information on this crate's foundational trait.
+
+#![no_std]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+#![allow(clippy::type_complexity)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+extern crate alloc;
+
+use alloc::{boxed::Box, rc::Rc, sync::Arc};
+use core::{
+    cell::RefCell,
+    future::Future,
+    task::{self, Context, Poll},
+};
+
+mod and_then;
+mod apply;
+mod apply_cfg;
+pub mod boxed;
+mod ext;
+mod fn_service;
+mod macros;
+mod map;
+mod map_config;
+mod map_err;
+mod map_init_err;
+mod pipeline;
+mod ready;
+mod then;
+mod transform;
+mod transform_err;
+
+#[allow(unused_imports)]
+use self::ready::{err, ok, ready, Ready};
+pub use self::{
+    apply::{apply_fn, apply_fn_factory},
+    apply_cfg::{apply_cfg, apply_cfg_factory},
+    ext::{ServiceExt, ServiceFactoryExt, TransformExt},
+    fn_service::{fn_factory, fn_factory_with_config, fn_service},
+    map_config::{map_config, unit_config},
+    transform::{apply, ApplyTransform, Transform},
+};
+
+/// An asynchronous operation from `Request` to a `Response`.
+///
+/// The `Service` trait models a request/response interaction, receiving requests and returning
+/// replies. You can think about a service as a function with one argument that returns some result
+/// asynchronously. Conceptually, the operation looks like this:
+///
+/// ```ignore
+/// async fn(Request) -> Result<Response, Err>
+/// ```
+///
+/// The `Service` trait just generalizes this form. Requests are defined as a generic type parameter
+/// and responses and other details are defined as associated types on the trait impl. Notice that
+/// this design means that services can receive many request types and converge them to a single
+/// response type.
+///
+/// Services can also have mutable state that influence computation by using a `Cell`, `RefCell`
+/// or `Mutex`. Services intentionally do not take `&mut self` to reduce overhead in the
+/// common cases.
+///
+/// `Service` provides a symmetric and uniform API; the same abstractions can be used to represent
+/// both clients and servers. Services describe only _transformation_ operations which encourage
+/// simple API surfaces. This leads to simpler design of each service, improves test-ability and
+/// makes composition easier.
+///
+/// ```ignore
+/// struct MyService;
+///
+/// impl Service<u8> for MyService {
+///      type Response = u64;
+///      type Error = MyError;
+///      type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
+///
+///      fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
+///
+///      fn call(&self, req: u8) -> Self::Future { ... }
+/// }
+/// ```
+///
+/// Sometimes it is not necessary to implement the Service trait. For example, the above service
+/// could be rewritten as a simple function and passed to [`fn_service`](fn_service()).
+///
+/// ```ignore
+/// async fn my_service(req: u8) -> Result<u64, MyError>;
+///
+/// let svc = fn_service(my_service)
+/// svc.call(123)
+/// ```
+pub trait Service<Req> {
+    /// Responses given by the service.
+    type Response;
+
+    /// Errors produced by the service when polling readiness or executing call.
+    type Error;
+
+    /// The future response value.
+    type Future: Future<Output = Result<Self::Response, Self::Error>>;
+
+    /// Returns `Ready` when the service is able to process requests.
+    ///
+    /// If the service is at capacity, then `Pending` is returned and the task is notified when the
+    /// service becomes ready again. This function is expected to be called while on a task.
+    ///
+    /// This is a best effort implementation. False positives are permitted. It is permitted for
+    /// the service to return `Ready` from a `poll_ready` call and the next invocation of `call`
+    /// results in an error.
+    ///
+    /// # Notes
+    /// 1. `poll_ready` might be called on a different task to `call`.
+    /// 1. In cases of chained services, `.poll_ready()` is called for all services at once.
+    fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
+
+    /// Process the request and return the response asynchronously.
+    ///
+    /// This function is expected to be callable off-task. As such, implementations of `call` should
+    /// take care to not call `poll_ready`. If the service is at capacity and the request is unable
+    /// to be handled, the returned `Future` should resolve to an error.
+    ///
+    /// Invoking `call` without first invoking `poll_ready` is permitted. Implementations must be
+    /// resilient to this fact.
+    fn call(&self, req: Req) -> Self::Future;
+}
+
+/// Factory for creating `Service`s.
+///
+/// This is useful for cases where new `Service`s must be produced. One case is a TCP
+/// server listener: a listener accepts new connections, constructs a new `Service` for each using
+/// the `ServiceFactory` trait, and uses the new `Service` to process inbound requests on that new
+/// connection.
+///
+/// `Config` is a service factory configuration type.
+///
+/// Simple factories may be able to use [`fn_factory`] or [`fn_factory_with_config`] to
+/// reduce boilerplate.
+pub trait ServiceFactory<Req> {
+    /// Responses given by the created services.
+    type Response;
+
+    /// Errors produced by the created services.
+    type Error;
+
+    /// Service factory configuration.
+    type Config;
+
+    /// The kind of `Service` created by this factory.
+    type Service: Service<Req, Response = Self::Response, Error = Self::Error>;
+
+    /// Errors potentially raised while building a service.
+    type InitError;
+
+    /// The future of the `Service` instance.g
+    type Future: Future<Output = Result<Self::Service, Self::InitError>>;
+
+    /// Create and return a new service asynchronously.
+    fn new_service(&self, cfg: Self::Config) -> Self::Future;
+}
+
+// TODO: remove implement on mut reference.
+impl<'a, S, Req> Service<Req> for &'a mut S
+where
+    S: Service<Req> + 'a,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        (**self).poll_ready(ctx)
+    }
+
+    fn call(&self, request: Req) -> S::Future {
+        (**self).call(request)
+    }
+}
+
+impl<'a, S, Req> Service<Req> for &'a S
+where
+    S: Service<Req> + 'a,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        (**self).poll_ready(ctx)
+    }
+
+    fn call(&self, request: Req) -> S::Future {
+        (**self).call(request)
+    }
+}
+
+impl<S, Req> Service<Req> for Box<S>
+where
+    S: Service<Req> + ?Sized,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
+        (**self).poll_ready(ctx)
+    }
+
+    fn call(&self, request: Req) -> S::Future {
+        (**self).call(request)
+    }
+}
+
+impl<S, Req> Service<Req> for Rc<S>
+where
+    S: Service<Req> + ?Sized,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        (**self).poll_ready(ctx)
+    }
+
+    fn call(&self, request: Req) -> S::Future {
+        (**self).call(request)
+    }
+}
+
+/// This impl is deprecated since v2 because the `Service` trait now receives shared reference.
+impl<S, Req> Service<Req> for RefCell<S>
+where
+    S: Service<Req>,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        self.borrow().poll_ready(ctx)
+    }
+
+    fn call(&self, request: Req) -> S::Future {
+        self.borrow().call(request)
+    }
+}
+
+impl<S, Req> ServiceFactory<Req> for Rc<S>
+where
+    S: ServiceFactory<Req>,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Config = S::Config;
+    type Service = S::Service;
+    type InitError = S::InitError;
+    type Future = S::Future;
+
+    fn new_service(&self, cfg: S::Config) -> S::Future {
+        self.as_ref().new_service(cfg)
+    }
+}
+
+impl<S, Req> ServiceFactory<Req> for Arc<S>
+where
+    S: ServiceFactory<Req>,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Config = S::Config;
+    type Service = S::Service;
+    type InitError = S::InitError;
+    type Future = S::Future;
+
+    fn new_service(&self, cfg: S::Config) -> S::Future {
+        self.as_ref().new_service(cfg)
+    }
+}
+
+/// Trait for types that can be converted to a `Service`
+pub trait IntoService<S, Req>
+where
+    S: Service<Req>,
+{
+    /// Convert to a `Service`
+    fn into_service(self) -> S;
+}
+
+/// Trait for types that can be converted to a `ServiceFactory`
+pub trait IntoServiceFactory<SF, Req>
+where
+    SF: ServiceFactory<Req>,
+{
+    /// Convert `Self` to a `ServiceFactory`
+    fn into_factory(self) -> SF;
+}
+
+impl<S, Req> IntoService<S, Req> for S
+where
+    S: Service<Req>,
+{
+    fn into_service(self) -> S {
+        self
+    }
+}
+
+impl<SF, Req> IntoServiceFactory<SF, Req> for SF
+where
+    SF: ServiceFactory<Req>,
+{
+    fn into_factory(self) -> SF {
+        self
+    }
+}
+
+/// Convert object of type `U` to a service `S`
+pub fn into_service<I, S, Req>(tp: I) -> S
+where
+    I: IntoService<S, Req>,
+    S: Service<Req>,
+{
+    tp.into_service()
+}
+
\ No newline at end of file diff --git a/src/actix_service/macros.rs.html b/src/actix_service/macros.rs.html new file mode 100644 index 00000000..c90bcec7 --- /dev/null +++ b/src/actix_service/macros.rs.html @@ -0,0 +1,375 @@ +macros.rs - source

actix_service/
macros.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
/// An implementation of [`poll_ready`]() that always signals readiness.
+///
+/// This should only be used for basic leaf services that have no concept of un-readiness.
+/// For wrapper or other service types, use [`forward_ready!`] for simple cases or write a bespoke
+/// `poll_ready` implementation.
+///
+/// [`poll_ready`]: crate::Service::poll_ready
+///
+/// # Examples
+/// ```no_run
+/// use actix_service::Service;
+/// use futures_util::future::{ready, Ready};
+///
+/// struct IdentityService;
+///
+/// impl Service<u32> for IdentityService {
+///     type Response = u32;
+///     type Error = ();
+///     type Future = Ready<Result<Self::Response, Self::Error>>;
+///
+///     actix_service::always_ready!();
+///
+///     fn call(&self, req: u32) -> Self::Future {
+///         ready(Ok(req))
+///     }
+/// }
+/// ```
+///
+/// [`forward_ready!`]: crate::forward_ready
+#[macro_export]
+macro_rules! always_ready {
+    () => {
+        #[inline]
+        fn poll_ready(
+            &self,
+            _: &mut ::core::task::Context<'_>,
+        ) -> ::core::task::Poll<Result<(), Self::Error>> {
+            ::core::task::Poll::Ready(Ok(()))
+        }
+    };
+}
+
+/// An implementation of [`poll_ready`] that forwards readiness checks to a
+/// named struct field.
+///
+/// Tuple structs are not supported.
+///
+/// [`poll_ready`]: crate::Service::poll_ready
+///
+/// # Examples
+/// ```no_run
+/// use actix_service::Service;
+/// use futures_util::future::{ready, Ready};
+///
+/// struct WrapperService<S> {
+///     inner: S,
+/// }
+///
+/// impl<S> Service<()> for WrapperService<S>
+/// where
+///     S: Service<()>,
+/// {
+///     type Response = S::Response;
+///     type Error = S::Error;
+///     type Future = S::Future;
+///
+///     actix_service::forward_ready!(inner);
+///
+///     fn call(&self, req: ()) -> Self::Future {
+///         self.inner.call(req)
+///     }
+/// }
+/// ```
+#[macro_export]
+macro_rules! forward_ready {
+    ($field:ident) => {
+        #[inline]
+        fn poll_ready(
+            &self,
+            cx: &mut ::core::task::Context<'_>,
+        ) -> ::core::task::Poll<Result<(), Self::Error>> {
+            self.$field
+                .poll_ready(cx)
+                .map_err(::core::convert::Into::into)
+        }
+    };
+}
+
+#[cfg(test)]
+mod tests {
+    use core::{
+        cell::Cell,
+        convert::Infallible,
+        task::{self, Context, Poll},
+    };
+
+    use futures_util::{
+        future::{ready, Ready},
+        task::noop_waker,
+    };
+
+    use crate::Service;
+
+    struct IdentityService;
+
+    impl Service<u32> for IdentityService {
+        type Response = u32;
+        type Error = Infallible;
+        type Future = Ready<Result<Self::Response, Self::Error>>;
+
+        always_ready!();
+
+        fn call(&self, req: u32) -> Self::Future {
+            ready(Ok(req))
+        }
+    }
+
+    struct CountdownService(Cell<u32>);
+
+    impl Service<()> for CountdownService {
+        type Response = ();
+        type Error = Infallible;
+        type Future = Ready<Result<Self::Response, Self::Error>>;
+
+        fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+            let count = self.0.get();
+
+            if count == 0 {
+                Poll::Ready(Ok(()))
+            } else {
+                self.0.set(count - 1);
+                cx.waker().wake_by_ref();
+                Poll::Pending
+            }
+        }
+
+        fn call(&self, _: ()) -> Self::Future {
+            ready(Ok(()))
+        }
+    }
+
+    struct WrapperService<S> {
+        inner: S,
+    }
+
+    impl<S> Service<()> for WrapperService<S>
+    where
+        S: Service<()>,
+    {
+        type Response = S::Response;
+        type Error = S::Error;
+        type Future = S::Future;
+
+        forward_ready!(inner);
+
+        fn call(&self, _: ()) -> Self::Future {
+            self.inner.call(())
+        }
+    }
+
+    #[test]
+    fn test_always_ready_macro() {
+        let waker = noop_waker();
+        let mut cx = task::Context::from_waker(&waker);
+
+        let svc = IdentityService;
+
+        assert!(svc.poll_ready(&mut cx).is_ready());
+        assert!(svc.poll_ready(&mut cx).is_ready());
+        assert!(svc.poll_ready(&mut cx).is_ready());
+    }
+
+    #[test]
+    fn test_forward_ready_macro() {
+        let waker = noop_waker();
+        let mut cx = task::Context::from_waker(&waker);
+
+        let svc = WrapperService {
+            inner: CountdownService(Cell::new(3)),
+        };
+
+        assert!(svc.poll_ready(&mut cx).is_pending());
+        assert!(svc.poll_ready(&mut cx).is_pending());
+        assert!(svc.poll_ready(&mut cx).is_pending());
+        assert!(svc.poll_ready(&mut cx).is_ready());
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/map.rs.html b/src/actix_service/map.rs.html new file mode 100644 index 00000000..6641015e --- /dev/null +++ b/src/actix_service/map.rs.html @@ -0,0 +1,489 @@ +map.rs - source

actix_service/
map.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use pin_project_lite::pin_project;
+
+use super::{Service, ServiceFactory};
+
+/// Service for the `map` combinator, changing the type of a service's response.
+///
+/// This is created by the `ServiceExt::map` method.
+pub struct Map<A, F, Req, Res> {
+    service: A,
+    f: F,
+    _t: PhantomData<fn(Req) -> Res>,
+}
+
+impl<A, F, Req, Res> Map<A, F, Req, Res> {
+    /// Create new `Map` combinator
+    pub(crate) fn new(service: A, f: F) -> Self
+    where
+        A: Service<Req>,
+        F: FnMut(A::Response) -> Res,
+    {
+        Self {
+            service,
+            f,
+            _t: PhantomData,
+        }
+    }
+}
+
+impl<A, F, Req, Res> Clone for Map<A, F, Req, Res>
+where
+    A: Clone,
+    F: Clone,
+{
+    fn clone(&self) -> Self {
+        Map {
+            service: self.service.clone(),
+            f: self.f.clone(),
+            _t: PhantomData,
+        }
+    }
+}
+
+impl<A, F, Req, Res> Service<Req> for Map<A, F, Req, Res>
+where
+    A: Service<Req>,
+    F: FnMut(A::Response) -> Res + Clone,
+{
+    type Response = Res;
+    type Error = A::Error;
+    type Future = MapFuture<A, F, Req, Res>;
+
+    crate::forward_ready!(service);
+
+    fn call(&self, req: Req) -> Self::Future {
+        MapFuture::new(self.service.call(req), self.f.clone())
+    }
+}
+
+pin_project! {
+    pub struct MapFuture<A, F, Req, Res>
+    where
+        A: Service<Req>,
+        F: FnMut(A::Response) -> Res,
+    {
+        f: F,
+        #[pin]
+        fut: A::Future,
+    }
+}
+
+impl<A, F, Req, Res> MapFuture<A, F, Req, Res>
+where
+    A: Service<Req>,
+    F: FnMut(A::Response) -> Res,
+{
+    fn new(fut: A::Future, f: F) -> Self {
+        MapFuture { f, fut }
+    }
+}
+
+impl<A, F, Req, Res> Future for MapFuture<A, F, Req, Res>
+where
+    A: Service<Req>,
+    F: FnMut(A::Response) -> Res,
+{
+    type Output = Result<Res, A::Error>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        match this.fut.poll(cx) {
+            Poll::Ready(Ok(resp)) => Poll::Ready(Ok((this.f)(resp))),
+            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
+            Poll::Pending => Poll::Pending,
+        }
+    }
+}
+
+/// `MapNewService` new service combinator
+pub struct MapServiceFactory<A, F, Req, Res> {
+    a: A,
+    f: F,
+    r: PhantomData<fn(Req) -> Res>,
+}
+
+impl<A, F, Req, Res> MapServiceFactory<A, F, Req, Res> {
+    /// Create new `Map` new service instance
+    pub(crate) fn new(a: A, f: F) -> Self
+    where
+        A: ServiceFactory<Req>,
+        F: FnMut(A::Response) -> Res,
+    {
+        Self {
+            a,
+            f,
+            r: PhantomData,
+        }
+    }
+}
+
+impl<A, F, Req, Res> Clone for MapServiceFactory<A, F, Req, Res>
+where
+    A: Clone,
+    F: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            a: self.a.clone(),
+            f: self.f.clone(),
+            r: PhantomData,
+        }
+    }
+}
+
+impl<A, F, Req, Res> ServiceFactory<Req> for MapServiceFactory<A, F, Req, Res>
+where
+    A: ServiceFactory<Req>,
+    F: FnMut(A::Response) -> Res + Clone,
+{
+    type Response = Res;
+    type Error = A::Error;
+
+    type Config = A::Config;
+    type Service = Map<A::Service, F, Req, Res>;
+    type InitError = A::InitError;
+    type Future = MapServiceFuture<A, F, Req, Res>;
+
+    fn new_service(&self, cfg: A::Config) -> Self::Future {
+        MapServiceFuture::new(self.a.new_service(cfg), self.f.clone())
+    }
+}
+
+pin_project! {
+    pub struct MapServiceFuture<A, F, Req, Res>
+    where
+        A: ServiceFactory<Req>,
+        F: FnMut(A::Response) -> Res,
+    {
+        #[pin]
+        fut: A::Future,
+        f: Option<F>,
+    }
+}
+
+impl<A, F, Req, Res> MapServiceFuture<A, F, Req, Res>
+where
+    A: ServiceFactory<Req>,
+    F: FnMut(A::Response) -> Res,
+{
+    fn new(fut: A::Future, f: F) -> Self {
+        MapServiceFuture { f: Some(f), fut }
+    }
+}
+
+impl<A, F, Req, Res> Future for MapServiceFuture<A, F, Req, Res>
+where
+    A: ServiceFactory<Req>,
+    F: FnMut(A::Response) -> Res,
+{
+    type Output = Result<Map<A::Service, F, Req, Res>, A::InitError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        if let Poll::Ready(svc) = this.fut.poll(cx)? {
+            Poll::Ready(Ok(Map::new(svc, this.f.take().unwrap())))
+        } else {
+            Poll::Pending
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use futures_util::future::lazy;
+
+    use super::*;
+    use crate::{ok, IntoServiceFactory, Ready, ServiceExt, ServiceFactoryExt};
+
+    struct Srv;
+
+    impl Service<()> for Srv {
+        type Response = ();
+        type Error = ();
+        type Future = Ready<Result<(), ()>>;
+
+        crate::always_ready!();
+
+        fn call(&self, _: ()) -> Self::Future {
+            ok(())
+        }
+    }
+
+    #[actix_rt::test]
+    async fn test_poll_ready() {
+        let srv = Srv.map(|_| "ok");
+        let res = lazy(|cx| srv.poll_ready(cx)).await;
+        assert_eq!(res, Poll::Ready(Ok(())));
+    }
+
+    #[actix_rt::test]
+    async fn test_call() {
+        let srv = Srv.map(|_| "ok");
+        let res = srv.call(()).await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), "ok");
+    }
+
+    #[actix_rt::test]
+    async fn test_new_service() {
+        let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map(|_| "ok");
+        let srv = new_srv.new_service(&()).await.unwrap();
+        let res = srv.call(()).await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("ok"));
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/map_config.rs.html b/src/actix_service/map_config.rs.html new file mode 100644 index 00000000..20f4dd10 --- /dev/null +++ b/src/actix_service/map_config.rs.html @@ -0,0 +1,257 @@ +map_config.rs - source

actix_service/
map_config.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
use core::marker::PhantomData;
+
+use super::{IntoServiceFactory, ServiceFactory};
+
+/// Adapt external config argument to a config for provided service factory
+///
+/// Note that this function consumes the receiving service factory and returns
+/// a wrapped version of it.
+pub fn map_config<I, SF, Req, F, Cfg>(factory: I, f: F) -> MapConfig<SF, Req, F, Cfg>
+where
+    I: IntoServiceFactory<SF, Req>,
+    SF: ServiceFactory<Req>,
+    F: Fn(Cfg) -> SF::Config,
+{
+    MapConfig::new(factory.into_factory(), f)
+}
+
+/// Replace config with unit.
+pub fn unit_config<I, SF, Cfg, Req>(factory: I) -> UnitConfig<SF, Cfg, Req>
+where
+    I: IntoServiceFactory<SF, Req>,
+    SF: ServiceFactory<Req, Config = ()>,
+{
+    UnitConfig::new(factory.into_factory())
+}
+
+/// `map_config()` adapter service factory
+pub struct MapConfig<SF, Req, F, Cfg> {
+    factory: SF,
+    cfg_mapper: F,
+    e: PhantomData<fn(Cfg, Req)>,
+}
+
+impl<SF, Req, F, Cfg> MapConfig<SF, Req, F, Cfg> {
+    /// Create new `MapConfig` combinator
+    pub(crate) fn new(factory: SF, cfg_mapper: F) -> Self
+    where
+        SF: ServiceFactory<Req>,
+        F: Fn(Cfg) -> SF::Config,
+    {
+        Self {
+            factory,
+            cfg_mapper,
+            e: PhantomData,
+        }
+    }
+}
+
+impl<SF, Req, F, Cfg> Clone for MapConfig<SF, Req, F, Cfg>
+where
+    SF: Clone,
+    F: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            factory: self.factory.clone(),
+            cfg_mapper: self.cfg_mapper.clone(),
+            e: PhantomData,
+        }
+    }
+}
+
+impl<SF, Req, F, Cfg> ServiceFactory<Req> for MapConfig<SF, Req, F, Cfg>
+where
+    SF: ServiceFactory<Req>,
+    F: Fn(Cfg) -> SF::Config,
+{
+    type Response = SF::Response;
+    type Error = SF::Error;
+
+    type Config = Cfg;
+    type Service = SF::Service;
+    type InitError = SF::InitError;
+    type Future = SF::Future;
+
+    fn new_service(&self, cfg: Self::Config) -> Self::Future {
+        let mapped_cfg = (self.cfg_mapper)(cfg);
+        self.factory.new_service(mapped_cfg)
+    }
+}
+
+/// `unit_config()` config combinator
+pub struct UnitConfig<SF, Cfg, Req> {
+    factory: SF,
+    _phantom: PhantomData<fn(Cfg, Req)>,
+}
+
+impl<SF, Cfg, Req> UnitConfig<SF, Cfg, Req>
+where
+    SF: ServiceFactory<Req, Config = ()>,
+{
+    /// Create new `UnitConfig` combinator
+    pub(crate) fn new(factory: SF) -> Self {
+        Self {
+            factory,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, Cfg, Req> Clone for UnitConfig<SF, Cfg, Req>
+where
+    SF: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            factory: self.factory.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, Cfg, Req> ServiceFactory<Req> for UnitConfig<SF, Cfg, Req>
+where
+    SF: ServiceFactory<Req, Config = ()>,
+{
+    type Response = SF::Response;
+    type Error = SF::Error;
+
+    type Config = Cfg;
+    type Service = SF::Service;
+    type InitError = SF::InitError;
+    type Future = SF::Future;
+
+    fn new_service(&self, _: Cfg) -> Self::Future {
+        self.factory.new_service(())
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/map_err.rs.html b/src/actix_service/map_err.rs.html new file mode 100644 index 00000000..2972033f --- /dev/null +++ b/src/actix_service/map_err.rs.html @@ -0,0 +1,499 @@ +map_err.rs - source

actix_service/
map_err.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use pin_project_lite::pin_project;
+
+use super::{Service, ServiceFactory};
+
+/// Service for the `map_err` combinator, changing the type of a service's error.
+///
+/// This is created by the `ServiceExt::map_err` method.
+pub struct MapErr<S, Req, F, E> {
+    service: S,
+    mapper: F,
+    _t: PhantomData<fn(Req) -> E>,
+}
+
+impl<S, Req, F, E> MapErr<S, Req, F, E> {
+    /// Create new `MapErr` combinator
+    pub(crate) fn new(service: S, mapper: F) -> Self
+    where
+        S: Service<Req>,
+        F: Fn(S::Error) -> E,
+    {
+        Self {
+            service,
+            mapper,
+            _t: PhantomData,
+        }
+    }
+}
+
+impl<S, Req, F, E> Clone for MapErr<S, Req, F, E>
+where
+    S: Clone,
+    F: Clone,
+{
+    fn clone(&self) -> Self {
+        MapErr {
+            service: self.service.clone(),
+            mapper: self.mapper.clone(),
+            _t: PhantomData,
+        }
+    }
+}
+
+impl<A, Req, F, E> Service<Req> for MapErr<A, Req, F, E>
+where
+    A: Service<Req>,
+    F: Fn(A::Error) -> E + Clone,
+{
+    type Response = A::Response;
+    type Error = E;
+    type Future = MapErrFuture<A, Req, F, E>;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        self.service.poll_ready(ctx).map_err(&self.mapper)
+    }
+
+    fn call(&self, req: Req) -> Self::Future {
+        MapErrFuture::new(self.service.call(req), self.mapper.clone())
+    }
+}
+
+pin_project! {
+    pub struct MapErrFuture<A, Req, F, E>
+    where
+        A: Service<Req>,
+        F: Fn(A::Error) -> E,
+    {
+        f: F,
+        #[pin]
+        fut: A::Future,
+    }
+}
+
+impl<A, Req, F, E> MapErrFuture<A, Req, F, E>
+where
+    A: Service<Req>,
+    F: Fn(A::Error) -> E,
+{
+    fn new(fut: A::Future, f: F) -> Self {
+        MapErrFuture { f, fut }
+    }
+}
+
+impl<A, Req, F, E> Future for MapErrFuture<A, Req, F, E>
+where
+    A: Service<Req>,
+    F: Fn(A::Error) -> E,
+{
+    type Output = Result<A::Response, E>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+        this.fut.poll(cx).map_err(this.f)
+    }
+}
+
+/// Factory for the `map_err` combinator, changing the type of a new
+/// service's error.
+///
+/// This is created by the `NewServiceExt::map_err` method.
+pub struct MapErrServiceFactory<SF, Req, F, E>
+where
+    SF: ServiceFactory<Req>,
+    F: Fn(SF::Error) -> E + Clone,
+{
+    a: SF,
+    f: F,
+    e: PhantomData<fn(Req) -> E>,
+}
+
+impl<SF, Req, F, E> MapErrServiceFactory<SF, Req, F, E>
+where
+    SF: ServiceFactory<Req>,
+    F: Fn(SF::Error) -> E + Clone,
+{
+    /// Create new `MapErr` new service instance
+    pub(crate) fn new(a: SF, f: F) -> Self {
+        Self {
+            a,
+            f,
+            e: PhantomData,
+        }
+    }
+}
+
+impl<SF, Req, F, E> Clone for MapErrServiceFactory<SF, Req, F, E>
+where
+    SF: ServiceFactory<Req> + Clone,
+    F: Fn(SF::Error) -> E + Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            a: self.a.clone(),
+            f: self.f.clone(),
+            e: PhantomData,
+        }
+    }
+}
+
+impl<SF, Req, F, E> ServiceFactory<Req> for MapErrServiceFactory<SF, Req, F, E>
+where
+    SF: ServiceFactory<Req>,
+    F: Fn(SF::Error) -> E + Clone,
+{
+    type Response = SF::Response;
+    type Error = E;
+
+    type Config = SF::Config;
+    type Service = MapErr<SF::Service, Req, F, E>;
+    type InitError = SF::InitError;
+    type Future = MapErrServiceFuture<SF, Req, F, E>;
+
+    fn new_service(&self, cfg: SF::Config) -> Self::Future {
+        MapErrServiceFuture::new(self.a.new_service(cfg), self.f.clone())
+    }
+}
+
+pin_project! {
+    pub struct MapErrServiceFuture<SF, Req, F, E>
+    where
+        SF: ServiceFactory<Req>,
+        F: Fn(SF::Error) -> E,
+    {
+        #[pin]
+        fut: SF::Future,
+        mapper: F,
+    }
+}
+
+impl<SF, Req, F, E> MapErrServiceFuture<SF, Req, F, E>
+where
+    SF: ServiceFactory<Req>,
+    F: Fn(SF::Error) -> E,
+{
+    fn new(fut: SF::Future, mapper: F) -> Self {
+        MapErrServiceFuture { fut, mapper }
+    }
+}
+
+impl<SF, Req, F, E> Future for MapErrServiceFuture<SF, Req, F, E>
+where
+    SF: ServiceFactory<Req>,
+    F: Fn(SF::Error) -> E + Clone,
+{
+    type Output = Result<MapErr<SF::Service, Req, F, E>, SF::InitError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+        if let Poll::Ready(svc) = this.fut.poll(cx)? {
+            Poll::Ready(Ok(MapErr::new(svc, this.mapper.clone())))
+        } else {
+            Poll::Pending
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use futures_util::future::lazy;
+
+    use super::*;
+    use crate::{err, ok, IntoServiceFactory, Ready, ServiceExt, ServiceFactoryExt};
+
+    struct Srv;
+
+    impl Service<()> for Srv {
+        type Response = ();
+        type Error = ();
+        type Future = Ready<Result<(), ()>>;
+
+        fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+            Poll::Ready(Err(()))
+        }
+
+        fn call(&self, _: ()) -> Self::Future {
+            err(())
+        }
+    }
+
+    #[actix_rt::test]
+    async fn test_poll_ready() {
+        let srv = Srv.map_err(|_| "error");
+        let res = lazy(|cx| srv.poll_ready(cx)).await;
+        assert_eq!(res, Poll::Ready(Err("error")));
+    }
+
+    #[actix_rt::test]
+    async fn test_call() {
+        let srv = Srv.map_err(|_| "error");
+        let res = srv.call(()).await;
+        assert!(res.is_err());
+        assert_eq!(res.err().unwrap(), "error");
+    }
+
+    #[actix_rt::test]
+    async fn test_new_service() {
+        let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map_err(|_| "error");
+        let srv = new_srv.new_service(&()).await.unwrap();
+        let res = srv.call(()).await;
+        assert!(res.is_err());
+        assert_eq!(res.err().unwrap(), "error");
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/map_init_err.rs.html b/src/actix_service/map_init_err.rs.html new file mode 100644 index 00000000..0faca6ab --- /dev/null +++ b/src/actix_service/map_init_err.rs.html @@ -0,0 +1,199 @@ +map_init_err.rs - source

actix_service/
map_init_err.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use pin_project_lite::pin_project;
+
+use super::ServiceFactory;
+
+/// `MapInitErr` service combinator
+pub struct MapInitErr<A, F, Req, Err> {
+    a: A,
+    f: F,
+    e: PhantomData<fn(Req) -> Err>,
+}
+
+impl<A, F, Req, Err> MapInitErr<A, F, Req, Err>
+where
+    A: ServiceFactory<Req>,
+    F: Fn(A::InitError) -> Err,
+{
+    /// Create new `MapInitErr` combinator
+    pub(crate) fn new(a: A, f: F) -> Self {
+        Self {
+            a,
+            f,
+            e: PhantomData,
+        }
+    }
+}
+
+impl<A, F, Req, E> Clone for MapInitErr<A, F, Req, E>
+where
+    A: Clone,
+    F: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            a: self.a.clone(),
+            f: self.f.clone(),
+            e: PhantomData,
+        }
+    }
+}
+
+impl<A, F, Req, E> ServiceFactory<Req> for MapInitErr<A, F, Req, E>
+where
+    A: ServiceFactory<Req>,
+    F: Fn(A::InitError) -> E + Clone,
+{
+    type Response = A::Response;
+    type Error = A::Error;
+
+    type Config = A::Config;
+    type Service = A::Service;
+    type InitError = E;
+    type Future = MapInitErrFuture<A, F, Req, E>;
+
+    fn new_service(&self, cfg: A::Config) -> Self::Future {
+        MapInitErrFuture::new(self.a.new_service(cfg), self.f.clone())
+    }
+}
+
+pin_project! {
+    pub struct MapInitErrFuture<A, F, Req, E>
+    where
+        A: ServiceFactory<Req>,
+        F: Fn(A::InitError) -> E,
+    {
+        f: F,
+        #[pin]
+        fut: A::Future,
+    }
+}
+
+impl<A, F, Req, E> MapInitErrFuture<A, F, Req, E>
+where
+    A: ServiceFactory<Req>,
+    F: Fn(A::InitError) -> E,
+{
+    fn new(fut: A::Future, f: F) -> Self {
+        MapInitErrFuture { f, fut }
+    }
+}
+
+impl<A, F, Req, E> Future for MapInitErrFuture<A, F, Req, E>
+where
+    A: ServiceFactory<Req>,
+    F: Fn(A::InitError) -> E,
+{
+    type Output = Result<A::Service, E>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+        this.fut.poll(cx).map_err(this.f)
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/pipeline.rs.html b/src/actix_service/pipeline.rs.html new file mode 100644 index 00000000..0168c6b5 --- /dev/null +++ b/src/actix_service/pipeline.rs.html @@ -0,0 +1,617 @@ +pipeline.rs - source

actix_service/
pipeline.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
// TODO: see if pipeline is necessary
+#![allow(dead_code)]
+
+use core::{
+    marker::PhantomData,
+    task::{Context, Poll},
+};
+
+use crate::{
+    and_then::{AndThenService, AndThenServiceFactory},
+    map::{Map, MapServiceFactory},
+    map_err::{MapErr, MapErrServiceFactory},
+    map_init_err::MapInitErr,
+    then::{ThenService, ThenServiceFactory},
+    IntoService, IntoServiceFactory, Service, ServiceFactory,
+};
+
+/// Construct new pipeline with one service in pipeline chain.
+pub(crate) fn pipeline<I, S, Req>(service: I) -> Pipeline<S, Req>
+where
+    I: IntoService<S, Req>,
+    S: Service<Req>,
+{
+    Pipeline {
+        service: service.into_service(),
+        _phantom: PhantomData,
+    }
+}
+
+/// Construct new pipeline factory with one service factory.
+pub(crate) fn pipeline_factory<I, SF, Req>(factory: I) -> PipelineFactory<SF, Req>
+where
+    I: IntoServiceFactory<SF, Req>,
+    SF: ServiceFactory<Req>,
+{
+    PipelineFactory {
+        factory: factory.into_factory(),
+        _phantom: PhantomData,
+    }
+}
+
+/// Pipeline service - pipeline allows to compose multiple service into one service.
+pub(crate) struct Pipeline<S, Req> {
+    service: S,
+    _phantom: PhantomData<fn(Req)>,
+}
+
+impl<S, Req> Pipeline<S, Req>
+where
+    S: Service<Req>,
+{
+    /// Call another service after call to this one has resolved successfully.
+    ///
+    /// This function can be used to chain two services together and ensure that
+    /// the second service isn't called until call to the first service have
+    /// finished. Result of the call to the first service is used as an
+    /// input parameter for the second service's call.
+    ///
+    /// Note that this function consumes the receiving service and returns a
+    /// wrapped version of it.
+    pub fn and_then<I, S1>(
+        self,
+        service: I,
+    ) -> Pipeline<impl Service<Req, Response = S1::Response, Error = S::Error> + Clone, Req>
+    where
+        Self: Sized,
+        I: IntoService<S1, S::Response>,
+        S1: Service<S::Response, Error = S::Error>,
+    {
+        Pipeline {
+            service: AndThenService::new(self.service, service.into_service()),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Chain on a computation for when a call to the service finished,
+    /// passing the result of the call to the next service `U`.
+    ///
+    /// Note that this function consumes the receiving pipeline and returns a
+    /// wrapped version of it.
+    pub fn then<F, S1>(
+        self,
+        service: F,
+    ) -> Pipeline<impl Service<Req, Response = S1::Response, Error = S::Error> + Clone, Req>
+    where
+        Self: Sized,
+        F: IntoService<S1, Result<S::Response, S::Error>>,
+        S1: Service<Result<S::Response, S::Error>, Error = S::Error>,
+    {
+        Pipeline {
+            service: ThenService::new(self.service, service.into_service()),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Map this service's output to a different type, returning a new service
+    /// of the resulting type.
+    ///
+    /// This function is similar to the `Option::map` or `Iterator::map` where
+    /// it will change the type of the underlying service.
+    ///
+    /// Note that this function consumes the receiving service and returns a
+    /// wrapped version of it, similar to the existing `map` methods in the
+    /// standard library.
+    pub fn map<F, R>(self, f: F) -> Pipeline<Map<S, F, Req, R>, Req>
+    where
+        Self: Sized,
+        F: FnMut(S::Response) -> R,
+    {
+        Pipeline {
+            service: Map::new(self.service, f),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Map this service's error to a different error, returning a new service.
+    ///
+    /// This function is similar to the `Result::map_err` where it will change
+    /// the error type of the underlying service. This is useful for example to
+    /// ensure that services have the same error type.
+    ///
+    /// Note that this function consumes the receiving service and returns a
+    /// wrapped version of it.
+    pub fn map_err<F, E>(self, f: F) -> Pipeline<MapErr<S, Req, F, E>, Req>
+    where
+        Self: Sized,
+        F: Fn(S::Error) -> E,
+    {
+        Pipeline {
+            service: MapErr::new(self.service, f),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<T, Req> Clone for Pipeline<T, Req>
+where
+    T: Clone,
+{
+    fn clone(&self) -> Self {
+        Pipeline {
+            service: self.service.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<S: Service<Req>, Req> Service<Req> for Pipeline<S, Req> {
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = S::Future;
+
+    #[inline]
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
+        self.service.poll_ready(ctx)
+    }
+
+    #[inline]
+    fn call(&self, req: Req) -> Self::Future {
+        self.service.call(req)
+    }
+}
+
+/// Pipeline factory
+pub(crate) struct PipelineFactory<SF, Req> {
+    factory: SF,
+    _phantom: PhantomData<fn(Req)>,
+}
+
+impl<SF, Req> PipelineFactory<SF, Req>
+where
+    SF: ServiceFactory<Req>,
+{
+    /// Call another service after call to this one has resolved successfully.
+    pub fn and_then<I, SF1>(
+        self,
+        factory: I,
+    ) -> PipelineFactory<
+        impl ServiceFactory<
+                Req,
+                Response = SF1::Response,
+                Error = SF::Error,
+                Config = SF::Config,
+                InitError = SF::InitError,
+                Service = impl Service<Req, Response = SF1::Response, Error = SF::Error> + Clone,
+            > + Clone,
+        Req,
+    >
+    where
+        Self: Sized,
+        SF::Config: Clone,
+        I: IntoServiceFactory<SF1, SF::Response>,
+        SF1: ServiceFactory<
+            SF::Response,
+            Config = SF::Config,
+            Error = SF::Error,
+            InitError = SF::InitError,
+        >,
+    {
+        PipelineFactory {
+            factory: AndThenServiceFactory::new(self.factory, factory.into_factory()),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Create `NewService` to chain on a computation for when a call to the
+    /// service finished, passing the result of the call to the next
+    /// service `U`.
+    ///
+    /// Note that this function consumes the receiving pipeline and returns a
+    /// wrapped version of it.
+    pub fn then<I, SF1>(
+        self,
+        factory: I,
+    ) -> PipelineFactory<
+        impl ServiceFactory<
+                Req,
+                Response = SF1::Response,
+                Error = SF::Error,
+                Config = SF::Config,
+                InitError = SF::InitError,
+                Service = impl Service<Req, Response = SF1::Response, Error = SF::Error> + Clone,
+            > + Clone,
+        Req,
+    >
+    where
+        Self: Sized,
+        SF::Config: Clone,
+        I: IntoServiceFactory<SF1, Result<SF::Response, SF::Error>>,
+        SF1: ServiceFactory<
+            Result<SF::Response, SF::Error>,
+            Config = SF::Config,
+            Error = SF::Error,
+            InitError = SF::InitError,
+        >,
+    {
+        PipelineFactory {
+            factory: ThenServiceFactory::new(self.factory, factory.into_factory()),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Map this service's output to a different type, returning a new service
+    /// of the resulting type.
+    pub fn map<F, R>(self, f: F) -> PipelineFactory<MapServiceFactory<SF, F, Req, R>, Req>
+    where
+        Self: Sized,
+        F: FnMut(SF::Response) -> R + Clone,
+    {
+        PipelineFactory {
+            factory: MapServiceFactory::new(self.factory, f),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Map this service's error to a different error, returning a new service.
+    pub fn map_err<F, E>(self, f: F) -> PipelineFactory<MapErrServiceFactory<SF, Req, F, E>, Req>
+    where
+        Self: Sized,
+        F: Fn(SF::Error) -> E + Clone,
+    {
+        PipelineFactory {
+            factory: MapErrServiceFactory::new(self.factory, f),
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Map this factory's init error to a different error, returning a new service.
+    pub fn map_init_err<F, E>(self, f: F) -> PipelineFactory<MapInitErr<SF, F, Req, E>, Req>
+    where
+        Self: Sized,
+        F: Fn(SF::InitError) -> E + Clone,
+    {
+        PipelineFactory {
+            factory: MapInitErr::new(self.factory, f),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<T, Req> Clone for PipelineFactory<T, Req>
+where
+    T: Clone,
+{
+    fn clone(&self) -> Self {
+        PipelineFactory {
+            factory: self.factory.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<SF, Req> ServiceFactory<Req> for PipelineFactory<SF, Req>
+where
+    SF: ServiceFactory<Req>,
+{
+    type Config = SF::Config;
+    type Response = SF::Response;
+    type Error = SF::Error;
+    type Service = SF::Service;
+    type InitError = SF::InitError;
+    type Future = SF::Future;
+
+    #[inline]
+    fn new_service(&self, cfg: SF::Config) -> Self::Future {
+        self.factory.new_service(cfg)
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/ready.rs.html b/src/actix_service/ready.rs.html new file mode 100644 index 00000000..8097bc1f --- /dev/null +++ b/src/actix_service/ready.rs.html @@ -0,0 +1,109 @@ +ready.rs - source

actix_service/
ready.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
//! When MSRV is 1.48, replace with `core::future::Ready` and `core::future::ready()`.
+
+use core::{
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+/// Future for the [`ready`](ready()) function.
+#[derive(Debug, Clone)]
+#[must_use = "futures do nothing unless you `.await` or poll them"]
+pub struct Ready<T> {
+    val: Option<T>,
+}
+
+impl<T> Ready<T> {
+    /// Unwraps the value from this immediately ready future.
+    #[inline]
+    pub fn into_inner(mut self) -> T {
+        self.val.take().unwrap()
+    }
+}
+
+impl<T> Unpin for Ready<T> {}
+
+impl<T> Future for Ready<T> {
+    type Output = T;
+
+    #[inline]
+    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> {
+        let val = self.val.take().expect("Ready can not be polled twice.");
+        Poll::Ready(val)
+    }
+}
+
+/// Creates a future that is immediately ready with a value.
+#[allow(dead_code)]
+pub(crate) fn ready<T>(val: T) -> Ready<T> {
+    Ready { val: Some(val) }
+}
+
+/// Create a future that is immediately ready with a success value.
+#[allow(dead_code)]
+pub(crate) fn ok<T, E>(val: T) -> Ready<Result<T, E>> {
+    Ready { val: Some(Ok(val)) }
+}
+
+/// Create a future that is immediately ready with an error value.
+#[allow(dead_code)]
+pub(crate) fn err<T, E>(err: E) -> Ready<Result<T, E>> {
+    Ready {
+        val: Some(Err(err)),
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/then.rs.html b/src/actix_service/then.rs.html new file mode 100644 index 00000000..92dbd226 --- /dev/null +++ b/src/actix_service/then.rs.html @@ -0,0 +1,669 @@ +then.rs - source

actix_service/
then.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
use alloc::rc::Rc;
+use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use futures_core::ready;
+use pin_project_lite::pin_project;
+
+use super::{Service, ServiceFactory};
+
+/// Service for the `then` combinator, chaining a computation onto the end of
+/// another service.
+///
+/// This is created by the `Pipeline::then` method.
+pub(crate) struct ThenService<A, B, Req>(Rc<(A, B)>, PhantomData<Req>);
+
+impl<A, B, Req> ThenService<A, B, Req> {
+    /// Create new `.then()` combinator
+    pub(crate) fn new(a: A, b: B) -> ThenService<A, B, Req>
+    where
+        A: Service<Req>,
+        B: Service<Result<A::Response, A::Error>, Error = A::Error>,
+    {
+        Self(Rc::new((a, b)), PhantomData)
+    }
+}
+
+impl<A, B, Req> Clone for ThenService<A, B, Req> {
+    fn clone(&self) -> Self {
+        ThenService(self.0.clone(), PhantomData)
+    }
+}
+
+impl<A, B, Req> Service<Req> for ThenService<A, B, Req>
+where
+    A: Service<Req>,
+    B: Service<Result<A::Response, A::Error>, Error = A::Error>,
+{
+    type Response = B::Response;
+    type Error = B::Error;
+    type Future = ThenServiceResponse<A, B, Req>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        let (a, b) = &*self.0;
+        let not_ready = !a.poll_ready(cx)?.is_ready();
+        if !b.poll_ready(cx)?.is_ready() || not_ready {
+            Poll::Pending
+        } else {
+            Poll::Ready(Ok(()))
+        }
+    }
+
+    fn call(&self, req: Req) -> Self::Future {
+        ThenServiceResponse {
+            state: State::A {
+                fut: self.0 .0.call(req),
+                b: Some(self.0.clone()),
+            },
+        }
+    }
+}
+
+pin_project! {
+    pub(crate) struct ThenServiceResponse<A, B, Req>
+    where
+        A: Service<Req>,
+        B: Service<Result<A::Response, A::Error>>,
+    {
+        #[pin]
+        state: State<A, B, Req>,
+    }
+}
+
+pin_project! {
+    #[project = StateProj]
+    enum State<A, B, Req>
+    where
+        A: Service<Req>,
+        B: Service<Result<A::Response, A::Error>>,
+    {
+        A { #[pin] fut: A::Future, b: Option<Rc<(A, B)>> },
+        B { #[pin] fut: B::Future },
+    }
+}
+
+impl<A, B, Req> Future for ThenServiceResponse<A, B, Req>
+where
+    A: Service<Req>,
+    B: Service<Result<A::Response, A::Error>>,
+{
+    type Output = Result<B::Response, B::Error>;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.as_mut().project();
+
+        match this.state.as_mut().project() {
+            StateProj::A { fut, b } => {
+                let res = ready!(fut.poll(cx));
+                let b = b.take().unwrap();
+                let fut = b.1.call(res);
+                this.state.set(State::B { fut });
+                self.poll(cx)
+            }
+            StateProj::B { fut } => fut.poll(cx),
+        }
+    }
+}
+
+/// `.then()` service factory combinator
+pub(crate) struct ThenServiceFactory<A, B, Req>(Rc<(A, B)>, PhantomData<Req>);
+
+impl<A, B, Req> ThenServiceFactory<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    A::Config: Clone,
+    B: ServiceFactory<
+        Result<A::Response, A::Error>,
+        Config = A::Config,
+        Error = A::Error,
+        InitError = A::InitError,
+    >,
+{
+    /// Create new `AndThen` combinator
+    pub(crate) fn new(a: A, b: B) -> Self {
+        Self(Rc::new((a, b)), PhantomData)
+    }
+}
+
+impl<A, B, Req> ServiceFactory<Req> for ThenServiceFactory<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    A::Config: Clone,
+    B: ServiceFactory<
+        Result<A::Response, A::Error>,
+        Config = A::Config,
+        Error = A::Error,
+        InitError = A::InitError,
+    >,
+{
+    type Response = B::Response;
+    type Error = A::Error;
+
+    type Config = A::Config;
+    type Service = ThenService<A::Service, B::Service, Req>;
+    type InitError = A::InitError;
+    type Future = ThenServiceFactoryResponse<A, B, Req>;
+
+    fn new_service(&self, cfg: A::Config) -> Self::Future {
+        let srv = &*self.0;
+        ThenServiceFactoryResponse::new(srv.0.new_service(cfg.clone()), srv.1.new_service(cfg))
+    }
+}
+
+impl<A, B, Req> Clone for ThenServiceFactory<A, B, Req> {
+    fn clone(&self) -> Self {
+        Self(self.0.clone(), PhantomData)
+    }
+}
+
+pin_project! {
+    pub(crate) struct ThenServiceFactoryResponse<A, B, Req>
+    where
+        A: ServiceFactory<Req>,
+        B: ServiceFactory<
+            Result<A::Response, A::Error>,
+            Config = A::Config,
+            Error = A::Error,
+            InitError = A::InitError,
+        >,
+    {
+        #[pin]
+        fut_b: B::Future,
+        #[pin]
+        fut_a: A::Future,
+        a: Option<A::Service>,
+        b: Option<B::Service>,
+    }
+}
+
+impl<A, B, Req> ThenServiceFactoryResponse<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    B: ServiceFactory<
+        Result<A::Response, A::Error>,
+        Config = A::Config,
+        Error = A::Error,
+        InitError = A::InitError,
+    >,
+{
+    fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
+        Self {
+            fut_a,
+            fut_b,
+            a: None,
+            b: None,
+        }
+    }
+}
+
+impl<A, B, Req> Future for ThenServiceFactoryResponse<A, B, Req>
+where
+    A: ServiceFactory<Req>,
+    B: ServiceFactory<
+        Result<A::Response, A::Error>,
+        Config = A::Config,
+        Error = A::Error,
+        InitError = A::InitError,
+    >,
+{
+    type Output = Result<ThenService<A::Service, B::Service, Req>, A::InitError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        if this.a.is_none() {
+            if let Poll::Ready(service) = this.fut_a.poll(cx)? {
+                *this.a = Some(service);
+            }
+        }
+        if this.b.is_none() {
+            if let Poll::Ready(service) = this.fut_b.poll(cx)? {
+                *this.b = Some(service);
+            }
+        }
+        if this.a.is_some() && this.b.is_some() {
+            Poll::Ready(Ok(ThenService::new(
+                this.a.take().unwrap(),
+                this.b.take().unwrap(),
+            )))
+        } else {
+            Poll::Pending
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use alloc::rc::Rc;
+    use core::{
+        cell::Cell,
+        task::{Context, Poll},
+    };
+
+    use futures_util::future::lazy;
+
+    use crate::{
+        err, ok,
+        pipeline::{pipeline, pipeline_factory},
+        ready, Ready, Service, ServiceFactory,
+    };
+
+    #[derive(Clone)]
+    struct Srv1(Rc<Cell<usize>>);
+
+    impl Service<Result<&'static str, &'static str>> for Srv1 {
+        type Response = &'static str;
+        type Error = ();
+        type Future = Ready<Result<Self::Response, Self::Error>>;
+
+        fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+            self.0.set(self.0.get() + 1);
+            Poll::Ready(Ok(()))
+        }
+
+        fn call(&self, req: Result<&'static str, &'static str>) -> Self::Future {
+            match req {
+                Ok(msg) => ok(msg),
+                Err(_) => err(()),
+            }
+        }
+    }
+
+    struct Srv2(Rc<Cell<usize>>);
+
+    impl Service<Result<&'static str, ()>> for Srv2 {
+        type Response = (&'static str, &'static str);
+        type Error = ();
+        type Future = Ready<Result<Self::Response, ()>>;
+
+        fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+            self.0.set(self.0.get() + 1);
+            Poll::Ready(Err(()))
+        }
+
+        fn call(&self, req: Result<&'static str, ()>) -> Self::Future {
+            match req {
+                Ok(msg) => ok((msg, "ok")),
+                Err(()) => ok(("srv2", "err")),
+            }
+        }
+    }
+
+    #[actix_rt::test]
+    async fn test_poll_ready() {
+        let cnt = Rc::new(Cell::new(0));
+        let srv = pipeline(Srv1(cnt.clone())).then(Srv2(cnt.clone()));
+        let res = lazy(|cx| srv.poll_ready(cx)).await;
+        assert_eq!(res, Poll::Ready(Err(())));
+        assert_eq!(cnt.get(), 2);
+    }
+
+    #[actix_rt::test]
+    async fn test_call() {
+        let cnt = Rc::new(Cell::new(0));
+        let srv = pipeline(Srv1(cnt.clone())).then(Srv2(cnt));
+
+        let res = srv.call(Ok("srv1")).await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv1", "ok"));
+
+        let res = srv.call(Err("srv")).await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv2", "err"));
+    }
+
+    #[actix_rt::test]
+    async fn test_factory() {
+        let cnt = Rc::new(Cell::new(0));
+        let cnt2 = cnt.clone();
+        let blank = move || ready(Ok::<_, ()>(Srv1(cnt2.clone())));
+        let factory = pipeline_factory(blank).then(move || ready(Ok(Srv2(cnt.clone()))));
+        let srv = factory.new_service(&()).await.unwrap();
+        let res = srv.call(Ok("srv1")).await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv1", "ok"));
+
+        let res = srv.call(Err("srv")).await;
+        assert!(res.is_ok());
+        assert_eq!(res.unwrap(), ("srv2", "err"));
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/transform.rs.html b/src/actix_service/transform.rs.html new file mode 100644 index 00000000..357999fb --- /dev/null +++ b/src/actix_service/transform.rs.html @@ -0,0 +1,543 @@ +transform.rs - source

actix_service/
transform.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
use alloc::{rc::Rc, sync::Arc};
+use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use futures_core::ready;
+use pin_project_lite::pin_project;
+
+use crate::{IntoServiceFactory, Service, ServiceFactory};
+
+/// Apply a [`Transform`] to a [`Service`].
+pub fn apply<T, S, I, Req>(t: T, factory: I) -> ApplyTransform<T, S, Req>
+where
+    I: IntoServiceFactory<S, Req>,
+    S: ServiceFactory<Req>,
+    T: Transform<S::Service, Req, InitError = S::InitError>,
+{
+    ApplyTransform::new(t, factory.into_factory())
+}
+
+/// Defines the interface of a service factory that wraps inner service during construction.
+///
+/// Transformers wrap an inner service and runs during inbound and/or outbound processing in the
+/// service lifecycle. It may modify request and/or response.
+///
+/// For example, a timeout service wrapper:
+///
+/// ```ignore
+/// pub struct Timeout<S> {
+///     service: S,
+///     timeout: Duration,
+/// }
+///
+/// impl<S: Service<Req>, Req> Service<Req> for Timeout<S> {
+///     type Response = S::Response;
+///     type Error = TimeoutError<S::Error>;
+///     type Future = TimeoutServiceResponse<S>;
+///
+///     actix_service::forward_ready!(service);
+///
+///     fn call(&self, req: Req) -> Self::Future {
+///         TimeoutServiceResponse {
+///             fut: self.service.call(req),
+///             sleep: Sleep::new(clock::now() + self.timeout),
+///         }
+///     }
+/// }
+/// ```
+///
+/// This wrapper service is decoupled from the underlying service implementation and could be
+/// applied to any service.
+///
+/// The `Transform` trait defines the interface of a service wrapper. `Transform` is often
+/// implemented for middleware, defining how to construct a middleware Service. A Service that is
+/// constructed by the factory takes the Service that follows it during execution as a parameter,
+/// assuming ownership of the next Service.
+///
+/// A transform for the `Timeout` middleware could look like this:
+///
+/// ```ignore
+/// pub struct TimeoutTransform {
+///     timeout: Duration,
+/// }
+///
+/// impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform {
+///     type Response = S::Response;
+///     type Error = TimeoutError<S::Error>;
+///     type InitError = S::Error;
+///     type Transform = Timeout<S>;
+///     type Future = Ready<Result<Self::Transform, Self::InitError>>;
+///
+///     fn new_transform(&self, service: S) -> Self::Future {
+///         ready(Ok(Timeout {
+///             service,
+///             timeout: self.timeout,
+///         }))
+///     }
+/// }
+/// ```
+pub trait Transform<S, Req> {
+    /// Responses produced by the service.
+    type Response;
+
+    /// Errors produced by the service.
+    type Error;
+
+    /// The `TransformService` value created by this factory
+    type Transform: Service<Req, Response = Self::Response, Error = Self::Error>;
+
+    /// Errors produced while building a transform service.
+    type InitError;
+
+    /// The future response value.
+    type Future: Future<Output = Result<Self::Transform, Self::InitError>>;
+
+    /// Creates and returns a new Transform component, asynchronously
+    fn new_transform(&self, service: S) -> Self::Future;
+}
+
+impl<T, S, Req> Transform<S, Req> for Rc<T>
+where
+    T: Transform<S, Req>,
+{
+    type Response = T::Response;
+    type Error = T::Error;
+    type Transform = T::Transform;
+    type InitError = T::InitError;
+    type Future = T::Future;
+
+    fn new_transform(&self, service: S) -> T::Future {
+        self.as_ref().new_transform(service)
+    }
+}
+
+impl<T, S, Req> Transform<S, Req> for Arc<T>
+where
+    T: Transform<S, Req>,
+{
+    type Response = T::Response;
+    type Error = T::Error;
+    type Transform = T::Transform;
+    type InitError = T::InitError;
+    type Future = T::Future;
+
+    fn new_transform(&self, service: S) -> T::Future {
+        self.as_ref().new_transform(service)
+    }
+}
+
+/// Apply a [`Transform`] to a [`Service`].
+pub struct ApplyTransform<T, S, Req>(Rc<(T, S)>, PhantomData<Req>);
+
+impl<T, S, Req> ApplyTransform<T, S, Req>
+where
+    S: ServiceFactory<Req>,
+    T: Transform<S::Service, Req, InitError = S::InitError>,
+{
+    /// Create new `ApplyTransform` new service instance
+    fn new(t: T, service: S) -> Self {
+        Self(Rc::new((t, service)), PhantomData)
+    }
+}
+
+impl<T, S, Req> Clone for ApplyTransform<T, S, Req> {
+    fn clone(&self) -> Self {
+        ApplyTransform(self.0.clone(), PhantomData)
+    }
+}
+
+impl<T, S, Req> ServiceFactory<Req> for ApplyTransform<T, S, Req>
+where
+    S: ServiceFactory<Req>,
+    T: Transform<S::Service, Req, InitError = S::InitError>,
+{
+    type Response = T::Response;
+    type Error = T::Error;
+
+    type Config = S::Config;
+    type Service = T::Transform;
+    type InitError = T::InitError;
+    type Future = ApplyTransformFuture<T, S, Req>;
+
+    fn new_service(&self, cfg: S::Config) -> Self::Future {
+        ApplyTransformFuture {
+            store: self.0.clone(),
+            state: ApplyTransformFutureState::A {
+                fut: self.0.as_ref().1.new_service(cfg),
+            },
+        }
+    }
+}
+
+pin_project! {
+    pub struct ApplyTransformFuture<T, S, Req>
+    where
+        S: ServiceFactory<Req>,
+        T: Transform<S::Service, Req, InitError = S::InitError>,
+    {
+        store: Rc<(T, S)>,
+        #[pin]
+        state: ApplyTransformFutureState<T, S, Req>,
+    }
+}
+
+pin_project! {
+    #[project = ApplyTransformFutureStateProj]
+    pub enum ApplyTransformFutureState<T, S, Req>
+    where
+        S: ServiceFactory<Req>,
+        T: Transform<S::Service, Req, InitError = S::InitError>,
+    {
+        A { #[pin] fut: S::Future },
+        B { #[pin] fut: T::Future },
+    }
+}
+
+impl<T, S, Req> Future for ApplyTransformFuture<T, S, Req>
+where
+    S: ServiceFactory<Req>,
+    T: Transform<S::Service, Req, InitError = S::InitError>,
+{
+    type Output = Result<T::Transform, T::InitError>;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.as_mut().project();
+
+        match this.state.as_mut().project() {
+            ApplyTransformFutureStateProj::A { fut } => {
+                let srv = ready!(fut.poll(cx))?;
+                let fut = this.store.0.new_transform(srv);
+                this.state.set(ApplyTransformFutureState::B { fut });
+                self.poll(cx)
+            }
+            ApplyTransformFutureStateProj::B { fut } => fut.poll(cx),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use core::time::Duration;
+
+    use actix_utils::future::{ready, Ready};
+
+    use super::*;
+
+    // pseudo-doctest for Transform trait
+    #[allow(unused)]
+    pub struct TimeoutTransform {
+        timeout: Duration,
+    }
+
+    // pseudo-doctest for Transform trait
+    impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform {
+        type Response = S::Response;
+        type Error = S::Error;
+        type InitError = S::Error;
+        type Transform = Timeout<S>;
+        type Future = Ready<Result<Self::Transform, Self::InitError>>;
+
+        fn new_transform(&self, service: S) -> Self::Future {
+            ready(Ok(Timeout {
+                service,
+                _timeout: self.timeout,
+            }))
+        }
+    }
+
+    // pseudo-doctest for Transform trait
+    #[allow(unused)]
+    pub struct Timeout<S> {
+        service: S,
+        _timeout: Duration,
+    }
+
+    // pseudo-doctest for Transform trait
+    impl<S: Service<Req>, Req> Service<Req> for Timeout<S> {
+        type Response = S::Response;
+        type Error = S::Error;
+        type Future = S::Future;
+
+        crate::forward_ready!(service);
+
+        fn call(&self, req: Req) -> Self::Future {
+            self.service.call(req)
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_service/transform_err.rs.html b/src/actix_service/transform_err.rs.html new file mode 100644 index 00000000..eba32950 --- /dev/null +++ b/src/actix_service/transform_err.rs.html @@ -0,0 +1,191 @@ +transform_err.rs - source

actix_service/
transform_err.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
use core::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use pin_project_lite::pin_project;
+
+use super::Transform;
+
+/// Transform for the [`TransformExt::map_init_err`] combinator, changing the type of a new
+/// [`Transform`]'s initialization error.
+pub struct TransformMapInitErr<T, S, Req, F, E> {
+    transform: T,
+    mapper: F,
+    _phantom: PhantomData<fn(Req) -> (S, E)>,
+}
+
+impl<T, S, F, E, Req> TransformMapInitErr<T, S, Req, F, E> {
+    pub(crate) fn new(t: T, f: F) -> Self
+    where
+        T: Transform<S, Req>,
+        F: Fn(T::InitError) -> E,
+    {
+        Self {
+            transform: t,
+            mapper: f,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<T, S, Req, F, E> Clone for TransformMapInitErr<T, S, Req, F, E>
+where
+    T: Clone,
+    F: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            transform: self.transform.clone(),
+            mapper: self.mapper.clone(),
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<T, S, F, E, Req> Transform<S, Req> for TransformMapInitErr<T, S, Req, F, E>
+where
+    T: Transform<S, Req>,
+    F: Fn(T::InitError) -> E + Clone,
+{
+    type Response = T::Response;
+    type Error = T::Error;
+    type Transform = T::Transform;
+
+    type InitError = E;
+    type Future = TransformMapInitErrFuture<T, S, F, E, Req>;
+
+    fn new_transform(&self, service: S) -> Self::Future {
+        TransformMapInitErrFuture {
+            fut: self.transform.new_transform(service),
+            f: self.mapper.clone(),
+        }
+    }
+}
+
+pin_project! {
+    pub struct TransformMapInitErrFuture<T, S, F, E, Req>
+    where
+    T: Transform<S, Req>,
+    F: Fn(T::InitError) -> E,
+    {
+        #[pin]
+        fut: T::Future,
+        f: F,
+    }
+}
+
+impl<T, S, F, E, Req> Future for TransformMapInitErrFuture<T, S, F, E, Req>
+where
+    T: Transform<S, Req>,
+    F: Fn(T::InitError) -> E + Clone,
+{
+    type Output = Result<T::Transform, E>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+        if let Poll::Ready(res) = this.fut.poll(cx) {
+            Poll::Ready(res.map_err(this.f))
+        } else {
+            Poll::Pending
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/mod.rs.html b/src/actix_tls/accept/mod.rs.html new file mode 100644 index 00000000..b376ff47 --- /dev/null +++ b/src/actix_tls/accept/mod.rs.html @@ -0,0 +1,263 @@ +mod.rs - source

actix_tls/accept/
mod.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
//! TLS connection acceptor services.
+
+use std::{
+    convert::Infallible,
+    error::Error,
+    fmt,
+    sync::atomic::{AtomicUsize, Ordering},
+};
+
+use actix_utils::counter::Counter;
+
+#[cfg(feature = "openssl")]
+pub mod openssl;
+
+#[cfg(feature = "rustls-0_20")]
+pub mod rustls_0_20;
+
+#[doc(hidden)]
+#[cfg(feature = "rustls-0_20")]
+pub use rustls_0_20 as rustls;
+
+#[cfg(feature = "rustls-0_21")]
+pub mod rustls_0_21;
+
+#[cfg(feature = "rustls-0_22")]
+pub mod rustls_0_22;
+
+#[cfg(feature = "rustls-0_23")]
+pub mod rustls_0_23;
+
+#[cfg(feature = "native-tls")]
+pub mod native_tls;
+
+pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
+
+#[cfg(any(
+    feature = "openssl",
+    feature = "rustls-0_20",
+    feature = "rustls-0_21",
+    feature = "rustls-0_22",
+    feature = "rustls-0_23",
+    feature = "native-tls",
+))]
+pub(crate) const DEFAULT_TLS_HANDSHAKE_TIMEOUT: std::time::Duration =
+    std::time::Duration::from_secs(3);
+
+thread_local! {
+    static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed));
+}
+
+/// Sets the maximum per-worker concurrent TLS connection limit.
+///
+/// All listeners will stop accepting connections when this limit is reached.
+/// It can be used to regulate the global TLS CPU usage.
+///
+/// By default, the connection limit is 256.
+pub fn max_concurrent_tls_connect(num: usize) {
+    MAX_CONN.store(num, Ordering::Relaxed);
+}
+
+/// TLS handshake error, TLS timeout, or inner service error.
+///
+/// All TLS acceptors from this crate will return the `SvcErr` type parameter as [`Infallible`],
+/// which can be cast to your own service type, inferred or otherwise, using [`into_service_error`].
+///
+/// [`into_service_error`]: Self::into_service_error
+#[derive(Debug)]
+pub enum TlsError<TlsErr, SvcErr> {
+    /// TLS handshake has timed-out.
+    Timeout,
+
+    /// Wraps TLS service errors.
+    Tls(TlsErr),
+
+    /// Wraps service errors.
+    Service(SvcErr),
+}
+
+impl<TlsErr> TlsError<TlsErr, Infallible> {
+    /// Casts the infallible service error type returned from acceptors into caller's type.
+    ///
+    /// # Examples
+    /// ```
+    /// # use std::convert::Infallible;
+    /// # use actix_tls::accept::TlsError;
+    /// let a: TlsError<u32, Infallible> = TlsError::Tls(42);
+    /// let _b: TlsError<u32, u64> = a.into_service_error();
+    /// ```
+    pub fn into_service_error<SvcErr>(self) -> TlsError<TlsErr, SvcErr> {
+        match self {
+            Self::Timeout => TlsError::Timeout,
+            Self::Tls(err) => TlsError::Tls(err),
+            Self::Service(err) => match err {},
+        }
+    }
+}
+
+impl<TlsErr, SvcErr> fmt::Display for TlsError<TlsErr, SvcErr> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            Self::Timeout => f.write_str("TLS handshake has timed-out"),
+            Self::Tls(_) => f.write_str("TLS handshake error"),
+            Self::Service(_) => f.write_str("Service error"),
+        }
+    }
+}
+
+impl<TlsErr, SvcErr> Error for TlsError<TlsErr, SvcErr>
+where
+    TlsErr: Error + 'static,
+    SvcErr: Error + 'static,
+{
+    fn source(&self) -> Option<&(dyn Error + 'static)> {
+        match self {
+            TlsError::Tls(err) => Some(err),
+            TlsError::Service(err) => Some(err),
+            TlsError::Timeout => None,
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn tls_service_error_inference() {
+        let a: TlsError<u32, Infallible> = TlsError::Tls(42);
+        let _b: TlsError<u32, u64> = a.into_service_error();
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/native_tls.rs.html b/src/actix_tls/accept/native_tls.rs.html new file mode 100644 index 00000000..222b16b1 --- /dev/null +++ b/src/actix_tls/accept/native_tls.rs.html @@ -0,0 +1,365 @@ +native_tls.rs - source

actix_tls/accept/
native_tls.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
//! `native-tls` based TLS connection acceptor service.
+//!
+//! See [`Acceptor`] for main service factory docs.
+
+use std::{
+    convert::Infallible,
+    io::{self, IoSlice},
+    pin::Pin,
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    net::{ActixStream, Ready},
+    time::timeout,
+};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::{
+    counter::Counter,
+    future::{ready, Ready as FutReady},
+};
+use futures_core::future::LocalBoxFuture;
+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+use tokio_native_tls::{native_tls::Error, TlsAcceptor};
+
+use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
+
+pub mod reexports {
+    //! Re-exports from `native-tls` that are useful for acceptors.
+
+    pub use tokio_native_tls::{native_tls::Error, TlsAcceptor};
+}
+
+/// Wraps a `native-tls` based async TLS stream in order to implement [`ActixStream`].
+pub struct TlsStream<IO>(tokio_native_tls::TlsStream<IO>);
+
+impl_more::impl_from!(<IO> in tokio_native_tls::TlsStream<IO> => TlsStream<IO>);
+impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_native_tls::TlsStream<IO>);
+
+impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
+    }
+}
+
+impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_flush(cx)
+    }
+
+    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
+    }
+
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
+    }
+
+    fn is_write_vectored(&self) -> bool {
+        (**self).is_write_vectored()
+    }
+}
+
+impl<IO: ActixStream> ActixStream for TlsStream<IO> {
+    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_read_ready((**self).get_ref().get_ref().get_ref(), cx)
+    }
+
+    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_write_ready((**self).get_ref().get_ref().get_ref(), cx)
+    }
+}
+
+/// Accept TLS connections via the `native-tls` crate.
+pub struct Acceptor {
+    acceptor: TlsAcceptor,
+    handshake_timeout: Duration,
+}
+
+impl Acceptor {
+    /// Constructs `native-tls` based acceptor service factory.
+    pub fn new(acceptor: TlsAcceptor) -> Self {
+        Acceptor {
+            acceptor,
+            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
+        }
+    }
+
+    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
+    ///
+    /// Default timeout is 3 seconds.
+    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
+        self.handshake_timeout = handshake_timeout;
+        self
+    }
+}
+
+impl Clone for Acceptor {
+    #[inline]
+    fn clone(&self) -> Self {
+        Self {
+            acceptor: self.acceptor.clone(),
+            handshake_timeout: self.handshake_timeout,
+        }
+    }
+}
+
+impl<IO: ActixStream + 'static> ServiceFactory<IO> for Acceptor {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<Error, Infallible>;
+    type Config = ();
+    type Service = AcceptorService;
+    type InitError = ();
+    type Future = FutReady<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        let res = MAX_CONN_COUNTER.with(|conns| {
+            Ok(AcceptorService {
+                acceptor: self.acceptor.clone(),
+                conns: conns.clone(),
+                handshake_timeout: self.handshake_timeout,
+            })
+        });
+
+        ready(res)
+    }
+}
+
+/// Native-TLS based acceptor service.
+pub struct AcceptorService {
+    acceptor: TlsAcceptor,
+    conns: Counter,
+    handshake_timeout: Duration,
+}
+
+impl<IO: ActixStream + 'static> Service<IO> for AcceptorService {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<Error, Infallible>;
+    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.conns.available(cx) {
+            Poll::Ready(Ok(()))
+        } else {
+            Poll::Pending
+        }
+    }
+
+    fn call(&self, io: IO) -> Self::Future {
+        let guard = self.conns.get();
+        let acceptor = self.acceptor.clone();
+
+        let dur = self.handshake_timeout;
+
+        Box::pin(async move {
+            match timeout(dur, acceptor.accept(io)).await {
+                Ok(Ok(io)) => {
+                    drop(guard);
+                    Ok(TlsStream(io))
+                }
+                Ok(Err(err)) => Err(TlsError::Tls(err)),
+                Err(_timeout) => Err(TlsError::Timeout),
+            }
+        })
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/openssl.rs.html b/src/actix_tls/accept/openssl.rs.html new file mode 100644 index 00000000..3395cafa --- /dev/null +++ b/src/actix_tls/accept/openssl.rs.html @@ -0,0 +1,417 @@ +openssl.rs - source

actix_tls/accept/
openssl.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
//! `openssl` based TLS acceptor service.
+//!
+//! See [`Acceptor`] for main service factory docs.
+
+use std::{
+    convert::Infallible,
+    future::Future,
+    io::{self, IoSlice},
+    pin::Pin,
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    net::{ActixStream, Ready},
+    time::{sleep, Sleep},
+};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::{
+    counter::{Counter, CounterGuard},
+    future::{ready, Ready as FutReady},
+};
+use openssl::ssl::{Error, Ssl, SslAcceptor};
+use pin_project_lite::pin_project;
+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+
+use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
+
+pub mod reexports {
+    //! Re-exports from `openssl` that are useful for acceptors.
+
+    pub use openssl::ssl::{
+        AlpnError, Error, HandshakeError, Ssl, SslAcceptor, SslAcceptorBuilder,
+    };
+}
+
+/// Wraps an `openssl` based async TLS stream in order to implement [`ActixStream`].
+pub struct TlsStream<IO>(tokio_openssl::SslStream<IO>);
+
+impl_more::impl_from!(<IO> in tokio_openssl::SslStream<IO> => TlsStream<IO>);
+impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_openssl::SslStream<IO>);
+
+impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
+    }
+}
+
+impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_flush(cx)
+    }
+
+    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
+    }
+
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
+    }
+
+    fn is_write_vectored(&self) -> bool {
+        (**self).is_write_vectored()
+    }
+}
+
+impl<IO: ActixStream> ActixStream for TlsStream<IO> {
+    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_read_ready((**self).get_ref(), cx)
+    }
+
+    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_write_ready((**self).get_ref(), cx)
+    }
+}
+
+/// Accept TLS connections via the `openssl` crate.
+pub struct Acceptor {
+    acceptor: SslAcceptor,
+    handshake_timeout: Duration,
+}
+
+impl Acceptor {
+    /// Create `openssl` based acceptor service factory.
+    #[inline]
+    pub fn new(acceptor: SslAcceptor) -> Self {
+        Acceptor {
+            acceptor,
+            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
+        }
+    }
+
+    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
+    ///
+    /// Default timeout is 3 seconds.
+    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
+        self.handshake_timeout = handshake_timeout;
+        self
+    }
+}
+
+impl Clone for Acceptor {
+    #[inline]
+    fn clone(&self) -> Self {
+        Self {
+            acceptor: self.acceptor.clone(),
+            handshake_timeout: self.handshake_timeout,
+        }
+    }
+}
+
+impl<IO: ActixStream> ServiceFactory<IO> for Acceptor {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<Error, Infallible>;
+    type Config = ();
+    type Service = AcceptorService;
+    type InitError = ();
+    type Future = FutReady<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        let res = MAX_CONN_COUNTER.with(|conns| {
+            Ok(AcceptorService {
+                acceptor: self.acceptor.clone(),
+                conns: conns.clone(),
+                handshake_timeout: self.handshake_timeout,
+            })
+        });
+
+        ready(res)
+    }
+}
+
+/// OpenSSL based acceptor service.
+pub struct AcceptorService {
+    acceptor: SslAcceptor,
+    conns: Counter,
+    handshake_timeout: Duration,
+}
+
+impl<IO: ActixStream> Service<IO> for AcceptorService {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<Error, Infallible>;
+    type Future = AcceptFut<IO>;
+
+    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.conns.available(ctx) {
+            Poll::Ready(Ok(()))
+        } else {
+            Poll::Pending
+        }
+    }
+
+    fn call(&self, io: IO) -> Self::Future {
+        let ssl_ctx = self.acceptor.context();
+        let ssl = Ssl::new(ssl_ctx).expect("Provided SSL acceptor was invalid.");
+
+        AcceptFut {
+            _guard: self.conns.get(),
+            timeout: sleep(self.handshake_timeout),
+            stream: Some(tokio_openssl::SslStream::new(ssl, io).unwrap()),
+        }
+    }
+}
+
+pin_project! {
+    /// Accept future for OpenSSL service.
+    #[doc(hidden)]
+    pub struct AcceptFut<IO: ActixStream> {
+        stream: Option<tokio_openssl::SslStream<IO>>,
+        #[pin]
+        timeout: Sleep,
+        _guard: CounterGuard,
+    }
+}
+
+impl<IO: ActixStream> Future for AcceptFut<IO> {
+    type Output = Result<TlsStream<IO>, TlsError<Error, Infallible>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        match Pin::new(this.stream.as_mut().unwrap()).poll_accept(cx) {
+            Poll::Ready(Ok(())) => Poll::Ready(Ok(this
+                .stream
+                .take()
+                .expect("Acceptor should not be polled after it has completed.")
+                .into())),
+            Poll::Ready(Err(err)) => Poll::Ready(Err(TlsError::Tls(err))),
+            Poll::Pending => this.timeout.poll(cx).map(|_| Err(TlsError::Timeout)),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/rustls_0_20.rs.html b/src/actix_tls/accept/rustls_0_20.rs.html new file mode 100644 index 00000000..37a95507 --- /dev/null +++ b/src/actix_tls/accept/rustls_0_20.rs.html @@ -0,0 +1,397 @@ +rustls_0_20.rs - source

actix_tls/accept/
rustls_0_20.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
//! `rustls` v0.20 based TLS connection acceptor service.
+//!
+//! See [`Acceptor`] for main service factory docs.
+
+use std::{
+    convert::Infallible,
+    future::Future,
+    io::{self, IoSlice},
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    net::{ActixStream, Ready},
+    time::{sleep, Sleep},
+};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::{
+    counter::{Counter, CounterGuard},
+    future::{ready, Ready as FutReady},
+};
+use pin_project_lite::pin_project;
+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+use tokio_rustls::{Accept, TlsAcceptor};
+use tokio_rustls_023 as tokio_rustls;
+
+use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
+
+pub mod reexports {
+    //! Re-exports from `rustls` that are useful for acceptors.
+
+    pub use tokio_rustls_023::rustls::ServerConfig;
+}
+
+/// Wraps a `rustls` based async TLS stream in order to implement [`ActixStream`].
+pub struct TlsStream<IO>(tokio_rustls::server::TlsStream<IO>);
+
+impl_more::impl_from!(<IO> in tokio_rustls::server::TlsStream<IO> => TlsStream<IO>);
+impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_rustls::server::TlsStream<IO>);
+
+impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
+    }
+}
+
+impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_flush(cx)
+    }
+
+    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
+    }
+
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
+    }
+
+    fn is_write_vectored(&self) -> bool {
+        (**self).is_write_vectored()
+    }
+}
+
+impl<IO: ActixStream> ActixStream for TlsStream<IO> {
+    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_read_ready((**self).get_ref().0, cx)
+    }
+
+    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_write_ready((**self).get_ref().0, cx)
+    }
+}
+
+/// Accept TLS connections via the `rustls` crate.
+pub struct Acceptor {
+    config: Arc<reexports::ServerConfig>,
+    handshake_timeout: Duration,
+}
+
+impl Acceptor {
+    /// Constructs `rustls` based acceptor service factory.
+    pub fn new(config: reexports::ServerConfig) -> Self {
+        Acceptor {
+            config: Arc::new(config),
+            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
+        }
+    }
+
+    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
+    ///
+    /// Default timeout is 3 seconds.
+    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
+        self.handshake_timeout = handshake_timeout;
+        self
+    }
+}
+
+impl Clone for Acceptor {
+    fn clone(&self) -> Self {
+        Self {
+            config: self.config.clone(),
+            handshake_timeout: self.handshake_timeout,
+        }
+    }
+}
+
+impl<IO: ActixStream> ServiceFactory<IO> for Acceptor {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Config = ();
+    type Service = AcceptorService;
+    type InitError = ();
+    type Future = FutReady<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        let res = MAX_CONN_COUNTER.with(|conns| {
+            Ok(AcceptorService {
+                acceptor: self.config.clone().into(),
+                conns: conns.clone(),
+                handshake_timeout: self.handshake_timeout,
+            })
+        });
+
+        ready(res)
+    }
+}
+
+/// Rustls based acceptor service.
+pub struct AcceptorService {
+    acceptor: TlsAcceptor,
+    conns: Counter,
+    handshake_timeout: Duration,
+}
+
+impl<IO: ActixStream> Service<IO> for AcceptorService {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Future = AcceptFut<IO>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.conns.available(cx) {
+            Poll::Ready(Ok(()))
+        } else {
+            Poll::Pending
+        }
+    }
+
+    fn call(&self, req: IO) -> Self::Future {
+        AcceptFut {
+            fut: self.acceptor.accept(req),
+            timeout: sleep(self.handshake_timeout),
+            _guard: self.conns.get(),
+        }
+    }
+}
+
+pin_project! {
+    /// Accept future for Rustls service.
+    #[doc(hidden)]
+    pub struct AcceptFut<IO: ActixStream> {
+        fut: Accept<IO>,
+        #[pin]
+        timeout: Sleep,
+        _guard: CounterGuard,
+    }
+}
+
+impl<IO: ActixStream> Future for AcceptFut<IO> {
+    type Output = Result<TlsStream<IO>, TlsError<io::Error, Infallible>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.project();
+        match Pin::new(&mut this.fut).poll(cx) {
+            Poll::Ready(Ok(stream)) => Poll::Ready(Ok(TlsStream(stream))),
+            Poll::Ready(Err(err)) => Poll::Ready(Err(TlsError::Tls(err))),
+            Poll::Pending => this.timeout.poll(cx).map(|_| Err(TlsError::Timeout)),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/rustls_0_21.rs.html b/src/actix_tls/accept/rustls_0_21.rs.html new file mode 100644 index 00000000..440e7723 --- /dev/null +++ b/src/actix_tls/accept/rustls_0_21.rs.html @@ -0,0 +1,397 @@ +rustls_0_21.rs - source

actix_tls/accept/
rustls_0_21.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
//! `rustls` v0.21 based TLS connection acceptor service.
+//!
+//! See [`Acceptor`] for main service factory docs.
+
+use std::{
+    convert::Infallible,
+    future::Future,
+    io::{self, IoSlice},
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    net::{ActixStream, Ready},
+    time::{sleep, Sleep},
+};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::{
+    counter::{Counter, CounterGuard},
+    future::{ready, Ready as FutReady},
+};
+use pin_project_lite::pin_project;
+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+use tokio_rustls::{Accept, TlsAcceptor};
+use tokio_rustls_024 as tokio_rustls;
+
+use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
+
+pub mod reexports {
+    //! Re-exports from `rustls` that are useful for acceptors.
+
+    pub use tokio_rustls_024::rustls::ServerConfig;
+}
+
+/// Wraps a `rustls` based async TLS stream in order to implement [`ActixStream`].
+pub struct TlsStream<IO>(tokio_rustls::server::TlsStream<IO>);
+
+impl_more::impl_from!(<IO> in tokio_rustls::server::TlsStream<IO> => TlsStream<IO>);
+impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_rustls::server::TlsStream<IO>);
+
+impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
+    }
+}
+
+impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_flush(cx)
+    }
+
+    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
+    }
+
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
+    }
+
+    fn is_write_vectored(&self) -> bool {
+        (**self).is_write_vectored()
+    }
+}
+
+impl<IO: ActixStream> ActixStream for TlsStream<IO> {
+    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_read_ready((**self).get_ref().0, cx)
+    }
+
+    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_write_ready((**self).get_ref().0, cx)
+    }
+}
+
+/// Accept TLS connections via the `rustls` crate.
+pub struct Acceptor {
+    config: Arc<reexports::ServerConfig>,
+    handshake_timeout: Duration,
+}
+
+impl Acceptor {
+    /// Constructs `rustls` based acceptor service factory.
+    pub fn new(config: reexports::ServerConfig) -> Self {
+        Acceptor {
+            config: Arc::new(config),
+            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
+        }
+    }
+
+    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
+    ///
+    /// Default timeout is 3 seconds.
+    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
+        self.handshake_timeout = handshake_timeout;
+        self
+    }
+}
+
+impl Clone for Acceptor {
+    fn clone(&self) -> Self {
+        Self {
+            config: self.config.clone(),
+            handshake_timeout: self.handshake_timeout,
+        }
+    }
+}
+
+impl<IO: ActixStream> ServiceFactory<IO> for Acceptor {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Config = ();
+    type Service = AcceptorService;
+    type InitError = ();
+    type Future = FutReady<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        let res = MAX_CONN_COUNTER.with(|conns| {
+            Ok(AcceptorService {
+                acceptor: self.config.clone().into(),
+                conns: conns.clone(),
+                handshake_timeout: self.handshake_timeout,
+            })
+        });
+
+        ready(res)
+    }
+}
+
+/// Rustls based acceptor service.
+pub struct AcceptorService {
+    acceptor: TlsAcceptor,
+    conns: Counter,
+    handshake_timeout: Duration,
+}
+
+impl<IO: ActixStream> Service<IO> for AcceptorService {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Future = AcceptFut<IO>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.conns.available(cx) {
+            Poll::Ready(Ok(()))
+        } else {
+            Poll::Pending
+        }
+    }
+
+    fn call(&self, req: IO) -> Self::Future {
+        AcceptFut {
+            fut: self.acceptor.accept(req),
+            timeout: sleep(self.handshake_timeout),
+            _guard: self.conns.get(),
+        }
+    }
+}
+
+pin_project! {
+    /// Accept future for Rustls service.
+    #[doc(hidden)]
+    pub struct AcceptFut<IO: ActixStream> {
+        fut: Accept<IO>,
+        #[pin]
+        timeout: Sleep,
+        _guard: CounterGuard,
+    }
+}
+
+impl<IO: ActixStream> Future for AcceptFut<IO> {
+    type Output = Result<TlsStream<IO>, TlsError<io::Error, Infallible>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.project();
+        match Pin::new(&mut this.fut).poll(cx) {
+            Poll::Ready(Ok(stream)) => Poll::Ready(Ok(TlsStream(stream))),
+            Poll::Ready(Err(err)) => Poll::Ready(Err(TlsError::Tls(err))),
+            Poll::Pending => this.timeout.poll(cx).map(|_| Err(TlsError::Timeout)),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/rustls_0_22.rs.html b/src/actix_tls/accept/rustls_0_22.rs.html new file mode 100644 index 00000000..ad2bc85f --- /dev/null +++ b/src/actix_tls/accept/rustls_0_22.rs.html @@ -0,0 +1,397 @@ +rustls_0_22.rs - source

actix_tls/accept/
rustls_0_22.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
//! `rustls` v0.22 based TLS connection acceptor service.
+//!
+//! See [`Acceptor`] for main service factory docs.
+
+use std::{
+    convert::Infallible,
+    future::Future,
+    io::{self, IoSlice},
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    net::{ActixStream, Ready},
+    time::{sleep, Sleep},
+};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::{
+    counter::{Counter, CounterGuard},
+    future::{ready, Ready as FutReady},
+};
+use pin_project_lite::pin_project;
+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+use tokio_rustls::{Accept, TlsAcceptor};
+use tokio_rustls_025 as tokio_rustls;
+
+use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
+
+pub mod reexports {
+    //! Re-exports from `rustls` that are useful for acceptors.
+
+    pub use tokio_rustls_025::rustls::ServerConfig;
+}
+
+/// Wraps a `rustls` based async TLS stream in order to implement [`ActixStream`].
+pub struct TlsStream<IO>(tokio_rustls::server::TlsStream<IO>);
+
+impl_more::impl_from!(<IO> in tokio_rustls::server::TlsStream<IO> => TlsStream<IO>);
+impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_rustls::server::TlsStream<IO>);
+
+impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
+    }
+}
+
+impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_flush(cx)
+    }
+
+    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
+    }
+
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
+    }
+
+    fn is_write_vectored(&self) -> bool {
+        (**self).is_write_vectored()
+    }
+}
+
+impl<IO: ActixStream> ActixStream for TlsStream<IO> {
+    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_read_ready((**self).get_ref().0, cx)
+    }
+
+    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_write_ready((**self).get_ref().0, cx)
+    }
+}
+
+/// Accept TLS connections via the `rustls` crate.
+pub struct Acceptor {
+    config: Arc<reexports::ServerConfig>,
+    handshake_timeout: Duration,
+}
+
+impl Acceptor {
+    /// Constructs `rustls` based acceptor service factory.
+    pub fn new(config: reexports::ServerConfig) -> Self {
+        Acceptor {
+            config: Arc::new(config),
+            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
+        }
+    }
+
+    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
+    ///
+    /// Default timeout is 3 seconds.
+    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
+        self.handshake_timeout = handshake_timeout;
+        self
+    }
+}
+
+impl Clone for Acceptor {
+    fn clone(&self) -> Self {
+        Self {
+            config: self.config.clone(),
+            handshake_timeout: self.handshake_timeout,
+        }
+    }
+}
+
+impl<IO: ActixStream> ServiceFactory<IO> for Acceptor {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Config = ();
+    type Service = AcceptorService;
+    type InitError = ();
+    type Future = FutReady<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        let res = MAX_CONN_COUNTER.with(|conns| {
+            Ok(AcceptorService {
+                acceptor: self.config.clone().into(),
+                conns: conns.clone(),
+                handshake_timeout: self.handshake_timeout,
+            })
+        });
+
+        ready(res)
+    }
+}
+
+/// Rustls based acceptor service.
+pub struct AcceptorService {
+    acceptor: TlsAcceptor,
+    conns: Counter,
+    handshake_timeout: Duration,
+}
+
+impl<IO: ActixStream> Service<IO> for AcceptorService {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Future = AcceptFut<IO>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.conns.available(cx) {
+            Poll::Ready(Ok(()))
+        } else {
+            Poll::Pending
+        }
+    }
+
+    fn call(&self, req: IO) -> Self::Future {
+        AcceptFut {
+            fut: self.acceptor.accept(req),
+            timeout: sleep(self.handshake_timeout),
+            _guard: self.conns.get(),
+        }
+    }
+}
+
+pin_project! {
+    /// Accept future for Rustls service.
+    #[doc(hidden)]
+    pub struct AcceptFut<IO: ActixStream> {
+        fut: Accept<IO>,
+        #[pin]
+        timeout: Sleep,
+        _guard: CounterGuard,
+    }
+}
+
+impl<IO: ActixStream> Future for AcceptFut<IO> {
+    type Output = Result<TlsStream<IO>, TlsError<io::Error, Infallible>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.project();
+        match Pin::new(&mut this.fut).poll(cx) {
+            Poll::Ready(Ok(stream)) => Poll::Ready(Ok(TlsStream(stream))),
+            Poll::Ready(Err(err)) => Poll::Ready(Err(TlsError::Tls(err))),
+            Poll::Pending => this.timeout.poll(cx).map(|_| Err(TlsError::Timeout)),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/accept/rustls_0_23.rs.html b/src/actix_tls/accept/rustls_0_23.rs.html new file mode 100644 index 00000000..605dc65e --- /dev/null +++ b/src/actix_tls/accept/rustls_0_23.rs.html @@ -0,0 +1,397 @@ +rustls_0_23.rs - source

actix_tls/accept/
rustls_0_23.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
//! `rustls` v0.23 based TLS connection acceptor service.
+//!
+//! See [`Acceptor`] for main service factory docs.
+
+use std::{
+    convert::Infallible,
+    future::Future,
+    io::{self, IoSlice},
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+    time::Duration,
+};
+
+use actix_rt::{
+    net::{ActixStream, Ready},
+    time::{sleep, Sleep},
+};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::{
+    counter::{Counter, CounterGuard},
+    future::{ready, Ready as FutReady},
+};
+use pin_project_lite::pin_project;
+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
+use tokio_rustls::{Accept, TlsAcceptor};
+use tokio_rustls_026 as tokio_rustls;
+
+use super::{TlsError, DEFAULT_TLS_HANDSHAKE_TIMEOUT, MAX_CONN_COUNTER};
+
+pub mod reexports {
+    //! Re-exports from `rustls` that are useful for acceptors.
+
+    pub use tokio_rustls_026::rustls::ServerConfig;
+}
+
+/// Wraps a `rustls` based async TLS stream in order to implement [`ActixStream`].
+pub struct TlsStream<IO>(tokio_rustls::server::TlsStream<IO>);
+
+impl_more::impl_from!(<IO> in tokio_rustls::server::TlsStream<IO> => TlsStream<IO>);
+impl_more::impl_deref_and_mut!(<IO> in TlsStream<IO> => tokio_rustls::server::TlsStream<IO>);
+
+impl<IO: ActixStream> AsyncRead for TlsStream<IO> {
+    fn poll_read(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &mut ReadBuf<'_>,
+    ) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_read(cx, buf)
+    }
+}
+
+impl<IO: ActixStream> AsyncWrite for TlsStream<IO> {
+    fn poll_write(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        buf: &[u8],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write(cx, buf)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_flush(cx)
+    }
+
+    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+        Pin::new(&mut **self.get_mut()).poll_shutdown(cx)
+    }
+
+    fn poll_write_vectored(
+        self: Pin<&mut Self>,
+        cx: &mut Context<'_>,
+        bufs: &[IoSlice<'_>],
+    ) -> Poll<io::Result<usize>> {
+        Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs)
+    }
+
+    fn is_write_vectored(&self) -> bool {
+        (**self).is_write_vectored()
+    }
+}
+
+impl<IO: ActixStream> ActixStream for TlsStream<IO> {
+    fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_read_ready((**self).get_ref().0, cx)
+    }
+
+    fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
+        IO::poll_write_ready((**self).get_ref().0, cx)
+    }
+}
+
+/// Accept TLS connections via the `rustls` crate.
+pub struct Acceptor {
+    config: Arc<reexports::ServerConfig>,
+    handshake_timeout: Duration,
+}
+
+impl Acceptor {
+    /// Constructs `rustls` based acceptor service factory.
+    pub fn new(config: reexports::ServerConfig) -> Self {
+        Acceptor {
+            config: Arc::new(config),
+            handshake_timeout: DEFAULT_TLS_HANDSHAKE_TIMEOUT,
+        }
+    }
+
+    /// Limit the amount of time that the acceptor will wait for a TLS handshake to complete.
+    ///
+    /// Default timeout is 3 seconds.
+    pub fn set_handshake_timeout(&mut self, handshake_timeout: Duration) -> &mut Self {
+        self.handshake_timeout = handshake_timeout;
+        self
+    }
+}
+
+impl Clone for Acceptor {
+    fn clone(&self) -> Self {
+        Self {
+            config: self.config.clone(),
+            handshake_timeout: self.handshake_timeout,
+        }
+    }
+}
+
+impl<IO: ActixStream> ServiceFactory<IO> for Acceptor {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Config = ();
+    type Service = AcceptorService;
+    type InitError = ();
+    type Future = FutReady<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        let res = MAX_CONN_COUNTER.with(|conns| {
+            Ok(AcceptorService {
+                acceptor: self.config.clone().into(),
+                conns: conns.clone(),
+                handshake_timeout: self.handshake_timeout,
+            })
+        });
+
+        ready(res)
+    }
+}
+
+/// Rustls based acceptor service.
+pub struct AcceptorService {
+    acceptor: TlsAcceptor,
+    conns: Counter,
+    handshake_timeout: Duration,
+}
+
+impl<IO: ActixStream> Service<IO> for AcceptorService {
+    type Response = TlsStream<IO>;
+    type Error = TlsError<io::Error, Infallible>;
+    type Future = AcceptFut<IO>;
+
+    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        if self.conns.available(cx) {
+            Poll::Ready(Ok(()))
+        } else {
+            Poll::Pending
+        }
+    }
+
+    fn call(&self, req: IO) -> Self::Future {
+        AcceptFut {
+            fut: self.acceptor.accept(req),
+            timeout: sleep(self.handshake_timeout),
+            _guard: self.conns.get(),
+        }
+    }
+}
+
+pin_project! {
+    /// Accept future for Rustls service.
+    #[doc(hidden)]
+    pub struct AcceptFut<IO: ActixStream> {
+        fut: Accept<IO>,
+        #[pin]
+        timeout: Sleep,
+        _guard: CounterGuard,
+    }
+}
+
+impl<IO: ActixStream> Future for AcceptFut<IO> {
+    type Output = Result<TlsStream<IO>, TlsError<io::Error, Infallible>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut this = self.project();
+        match Pin::new(&mut this.fut).poll(cx) {
+            Poll::Ready(Ok(stream)) => Poll::Ready(Ok(TlsStream(stream))),
+            Poll::Ready(Err(err)) => Poll::Ready(Err(TlsError::Tls(err))),
+            Poll::Pending => this.timeout.poll(cx).map(|_| Err(TlsError::Timeout)),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/connect_addrs.rs.html b/src/actix_tls/connect/connect_addrs.rs.html new file mode 100644 index 00000000..1d90c0cf --- /dev/null +++ b/src/actix_tls/connect/connect_addrs.rs.html @@ -0,0 +1,165 @@ +connect_addrs.rs - source

actix_tls/connect/
connect_addrs.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
use std::{
+    collections::{vec_deque, VecDeque},
+    fmt, iter,
+    net::SocketAddr,
+};
+
+#[derive(Debug, Clone, Eq, PartialEq, Hash)]
+pub(crate) enum ConnectAddrs {
+    None,
+    One(SocketAddr),
+    // TODO: consider using smallvec
+    Multi(VecDeque<SocketAddr>),
+}
+
+impl ConnectAddrs {
+    pub(crate) fn is_unresolved(&self) -> bool {
+        matches!(self, Self::None)
+    }
+
+    pub(crate) fn is_resolved(&self) -> bool {
+        !self.is_unresolved()
+    }
+}
+
+impl Default for ConnectAddrs {
+    fn default() -> Self {
+        Self::None
+    }
+}
+
+impl From<Option<SocketAddr>> for ConnectAddrs {
+    fn from(addr: Option<SocketAddr>) -> Self {
+        match addr {
+            Some(addr) => ConnectAddrs::One(addr),
+            None => ConnectAddrs::None,
+        }
+    }
+}
+
+/// Iterator over addresses in a [`Connect`] request.
+#[derive(Clone)]
+pub(crate) enum ConnectAddrsIter<'a> {
+    None,
+    One(SocketAddr),
+    Multi(vec_deque::Iter<'a, SocketAddr>),
+    MultiOwned(vec_deque::IntoIter<SocketAddr>),
+}
+
+impl Iterator for ConnectAddrsIter<'_> {
+    type Item = SocketAddr;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        match *self {
+            Self::None => None,
+            Self::One(addr) => {
+                *self = Self::None;
+                Some(addr)
+            }
+            Self::Multi(ref mut iter) => iter.next().copied(),
+            Self::MultiOwned(ref mut iter) => iter.next(),
+        }
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        match *self {
+            Self::None => (0, Some(0)),
+            Self::One(_) => (1, Some(1)),
+            Self::Multi(ref iter) => iter.size_hint(),
+            Self::MultiOwned(ref iter) => iter.size_hint(),
+        }
+    }
+}
+
+impl fmt::Debug for ConnectAddrsIter<'_> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_list().entries(self.clone()).finish()
+    }
+}
+
+impl iter::ExactSizeIterator for ConnectAddrsIter<'_> {}
+
+impl iter::FusedIterator for ConnectAddrsIter<'_> {}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/connection.rs.html b/src/actix_tls/connect/connection.rs.html new file mode 100644 index 00000000..b722389f --- /dev/null +++ b/src/actix_tls/connect/connection.rs.html @@ -0,0 +1,103 @@ +connection.rs - source

actix_tls/connect/
connection.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
use super::Host;
+
+/// Wraps underlying I/O and the connection request that initiated it.
+#[derive(Debug)]
+pub struct Connection<R, IO> {
+    pub(crate) req: R,
+    pub(crate) io: IO,
+}
+
+impl_more::impl_deref_and_mut!(<R, IO> in Connection<R, IO> => io: IO);
+
+impl<R, IO> Connection<R, IO> {
+    /// Construct new `Connection` from request and IO parts.
+    pub fn new(req: R, io: IO) -> Self {
+        Self { req, io }
+    }
+}
+
+impl<R, IO> Connection<R, IO> {
+    /// Deconstructs into IO and request parts.
+    pub fn into_parts(self) -> (IO, R) {
+        (self.io, self.req)
+    }
+
+    /// Replaces underlying IO, returning old IO and new `Connection`.
+    pub fn replace_io<IO2>(self, io: IO2) -> (IO, Connection<R, IO2>) {
+        (self.io, Connection { io, req: self.req })
+    }
+
+    /// Returns a shared reference to the underlying IO.
+    pub fn io_ref(&self) -> &IO {
+        &self.io
+    }
+
+    /// Returns a mutable reference to the underlying IO.
+    pub fn io_mut(&mut self) -> &mut IO {
+        &mut self.io
+    }
+
+    /// Returns a reference to the connection request.
+    pub fn request(&self) -> &R {
+        &self.req
+    }
+}
+
+impl<R: Host, IO> Connection<R, IO> {
+    /// Returns hostname.
+    pub fn hostname(&self) -> &str {
+        self.req.hostname()
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/connector.rs.html b/src/actix_tls/connect/connector.rs.html new file mode 100644 index 00000000..38f0701d --- /dev/null +++ b/src/actix_tls/connect/connector.rs.html @@ -0,0 +1,257 @@ +connector.rs - source

actix_tls/connect/
connector.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
use std::{
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::TcpStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+
+use super::{
+    error::ConnectError,
+    resolver::{Resolver, ResolverService},
+    tcp::{TcpConnector, TcpConnectorService},
+    ConnectInfo, Connection, Host,
+};
+
+/// Combined resolver and TCP connector service factory.
+///
+/// Used to create [`ConnectorService`]s which receive connection information, resolve DNS if
+/// required, and return a TCP stream.
+#[derive(Clone, Default)]
+pub struct Connector {
+    resolver: Resolver,
+}
+
+impl Connector {
+    /// Constructs new connector factory with the given resolver.
+    pub fn new(resolver: Resolver) -> Self {
+        Connector { resolver }
+    }
+
+    /// Build connector service.
+    pub fn service(&self) -> ConnectorService {
+        ConnectorService {
+            tcp: TcpConnector::default().service(),
+            resolver: self.resolver.service(),
+        }
+    }
+}
+
+impl<R: Host> ServiceFactory<ConnectInfo<R>> for Connector {
+    type Response = Connection<R, TcpStream>;
+    type Error = ConnectError;
+    type Config = ();
+    type Service = ConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(self.service())
+    }
+}
+
+/// Combined resolver and TCP connector service.
+///
+/// Service implementation receives connection information, resolves DNS if required, and returns
+/// a TCP stream.
+#[derive(Clone, Default)]
+pub struct ConnectorService {
+    tcp: TcpConnectorService,
+    resolver: ResolverService,
+}
+
+impl<R: Host> Service<ConnectInfo<R>> for ConnectorService {
+    type Response = Connection<R, TcpStream>;
+    type Error = ConnectError;
+    type Future = ConnectServiceResponse<R>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, req: ConnectInfo<R>) -> Self::Future {
+        ConnectServiceResponse {
+            fut: ConnectFut::Resolve(self.resolver.call(req)),
+            tcp: self.tcp,
+        }
+    }
+}
+
+/// Chains futures of resolve and connect steps.
+pub(crate) enum ConnectFut<R: Host> {
+    Resolve(<ResolverService as Service<ConnectInfo<R>>>::Future),
+    Connect(<TcpConnectorService as Service<ConnectInfo<R>>>::Future),
+}
+
+/// Container for the intermediate states of [`ConnectFut`].
+pub(crate) enum ConnectFutState<R: Host> {
+    Resolved(ConnectInfo<R>),
+    Connected(Connection<R, TcpStream>),
+}
+
+impl<R: Host> ConnectFut<R> {
+    fn poll_connect(
+        &mut self,
+        cx: &mut Context<'_>,
+    ) -> Poll<Result<ConnectFutState<R>, ConnectError>> {
+        match self {
+            ConnectFut::Resolve(ref mut fut) => {
+                Pin::new(fut).poll(cx).map_ok(ConnectFutState::Resolved)
+            }
+
+            ConnectFut::Connect(ref mut fut) => {
+                Pin::new(fut).poll(cx).map_ok(ConnectFutState::Connected)
+            }
+        }
+    }
+}
+
+pub struct ConnectServiceResponse<R: Host> {
+    fut: ConnectFut<R>,
+    tcp: TcpConnectorService,
+}
+
+impl<R: Host> Future for ConnectServiceResponse<R> {
+    type Output = Result<Connection<R, TcpStream>, ConnectError>;
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        loop {
+            match ready!(self.fut.poll_connect(cx))? {
+                ConnectFutState::Resolved(res) => {
+                    self.fut = ConnectFut::Connect(self.tcp.call(res));
+                }
+                ConnectFutState::Connected(res) => return Poll::Ready(Ok(res)),
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/error.rs.html b/src/actix_tls/connect/error.rs.html new file mode 100644 index 00000000..fc981ff2 --- /dev/null +++ b/src/actix_tls/connect/error.rs.html @@ -0,0 +1,89 @@ +error.rs - source

actix_tls/connect/
error.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
use std::{error::Error, fmt, io};
+
+/// Errors that can result from using a connector service.
+#[derive(Debug)]
+pub enum ConnectError {
+    /// Failed to resolve the hostname.
+    Resolver(Box<dyn std::error::Error>),
+
+    /// No DNS records.
+    NoRecords,
+
+    /// Invalid input.
+    InvalidInput,
+
+    /// Unresolved host name.
+    Unresolved,
+
+    /// Connection IO error.
+    Io(io::Error),
+}
+
+impl fmt::Display for ConnectError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            Self::NoRecords => f.write_str("No DNS records found for the input"),
+            Self::InvalidInput => f.write_str("Invalid input"),
+            Self::Unresolved => {
+                f.write_str("Connector received `Connect` method with unresolved host")
+            }
+            Self::Resolver(_) => f.write_str("Failed to resolve hostname"),
+            Self::Io(_) => f.write_str("I/O error"),
+        }
+    }
+}
+
+impl Error for ConnectError {
+    fn source(&self) -> Option<&(dyn Error + 'static)> {
+        match self {
+            Self::Resolver(err) => Some(&**err),
+            Self::Io(err) => Some(err),
+            Self::NoRecords | Self::InvalidInput | Self::Unresolved => None,
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/host.rs.html b/src/actix_tls/connect/host.rs.html new file mode 100644 index 00000000..9802cae8 --- /dev/null +++ b/src/actix_tls/connect/host.rs.html @@ -0,0 +1,143 @@ +host.rs - source

actix_tls/connect/
host.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
//! The [`Host`] trait.
+
+/// An interface for types where host parts (hostname and port) can be derived.
+///
+/// The [WHATWG URL Standard] defines the terminology used for this trait and its methods.
+///
+/// ```plain
+/// +------------------------+
+/// |          host          |
+/// +-----------------+------+
+/// |    hostname     | port |
+/// |                 |      |
+/// | sub.example.com : 8080 |
+/// +-----------------+------+
+/// ```
+///
+/// [WHATWG URL Standard]: https://url.spec.whatwg.org/
+pub trait Host: Unpin + 'static {
+    /// Extract hostname.
+    fn hostname(&self) -> &str;
+
+    /// Extract optional port.
+    fn port(&self) -> Option<u16> {
+        None
+    }
+}
+
+impl Host for String {
+    fn hostname(&self) -> &str {
+        self.split_once(':')
+            .map(|(hostname, _)| hostname)
+            .unwrap_or(self)
+    }
+
+    fn port(&self) -> Option<u16> {
+        self.split_once(':').and_then(|(_, port)| port.parse().ok())
+    }
+}
+
+impl Host for &'static str {
+    fn hostname(&self) -> &str {
+        self.split_once(':')
+            .map(|(hostname, _)| hostname)
+            .unwrap_or(self)
+    }
+
+    fn port(&self) -> Option<u16> {
+        self.split_once(':').and_then(|(_, port)| port.parse().ok())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    macro_rules! assert_connection_info_eq {
+        ($req:expr, $hostname:expr, $port:expr) => {{
+            assert_eq!($req.hostname(), $hostname);
+            assert_eq!($req.port(), $port);
+        }};
+    }
+
+    #[test]
+    fn host_parsing() {
+        assert_connection_info_eq!("example.com", "example.com", None);
+        assert_connection_info_eq!("example.com:8080", "example.com", Some(8080));
+        assert_connection_info_eq!("example:8080", "example", Some(8080));
+        assert_connection_info_eq!("example.com:false", "example.com", None);
+        assert_connection_info_eq!("example.com:false:false", "example.com", None);
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/info.rs.html b/src/actix_tls/connect/info.rs.html new file mode 100644 index 00000000..d85a1436 --- /dev/null +++ b/src/actix_tls/connect/info.rs.html @@ -0,0 +1,503 @@ +info.rs - source

actix_tls/connect/
info.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
//! Connection info struct.
+
+use std::{
+    collections::VecDeque,
+    fmt,
+    iter::{self, FromIterator as _},
+    mem,
+    net::{IpAddr, SocketAddr},
+};
+
+use super::{
+    connect_addrs::{ConnectAddrs, ConnectAddrsIter},
+    Host,
+};
+
+/// Connection request information.
+///
+/// May contain known/pre-resolved socket address(es) or a host that needs resolving with DNS.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct ConnectInfo<R> {
+    pub(crate) request: R,
+    pub(crate) port: u16,
+    pub(crate) addr: ConnectAddrs,
+    pub(crate) local_addr: Option<IpAddr>,
+}
+
+impl<R: Host> ConnectInfo<R> {
+    /// Constructs new connection info using a request.
+    pub fn new(request: R) -> ConnectInfo<R> {
+        let port = request.port();
+
+        ConnectInfo {
+            request,
+            port: port.unwrap_or(0),
+            addr: ConnectAddrs::None,
+            local_addr: None,
+        }
+    }
+
+    /// Constructs new connection info from request and known socket address.
+    ///
+    /// Since socket address is known, [`Connector`](super::Connector) will skip the DNS
+    /// resolution step.
+    pub fn with_addr(request: R, addr: SocketAddr) -> ConnectInfo<R> {
+        ConnectInfo {
+            request,
+            port: 0,
+            addr: ConnectAddrs::One(addr),
+            local_addr: None,
+        }
+    }
+
+    /// Set connection port.
+    ///
+    /// If request provided a port, this will override it.
+    pub fn set_port(mut self, port: u16) -> Self {
+        self.port = port;
+        self
+    }
+
+    /// Set connection socket address.
+    pub fn set_addr(mut self, addr: impl Into<Option<SocketAddr>>) -> Self {
+        self.addr = ConnectAddrs::from(addr.into());
+        self
+    }
+
+    /// Set list of addresses.
+    pub fn set_addrs<I>(mut self, addrs: I) -> Self
+    where
+        I: IntoIterator<Item = SocketAddr>,
+    {
+        let mut addrs = VecDeque::from_iter(addrs);
+        self.addr = if addrs.len() < 2 {
+            ConnectAddrs::from(addrs.pop_front())
+        } else {
+            ConnectAddrs::Multi(addrs)
+        };
+        self
+    }
+
+    /// Set local address to connection with.
+    ///
+    /// Useful in situations where the IP address bound to a particular network interface is known.
+    /// This would make sure the socket is opened through that interface.
+    pub fn set_local_addr(mut self, addr: impl Into<IpAddr>) -> Self {
+        self.local_addr = Some(addr.into());
+        self
+    }
+
+    /// Returns a reference to the connection request.
+    pub fn request(&self) -> &R {
+        &self.request
+    }
+
+    /// Returns request hostname.
+    pub fn hostname(&self) -> &str {
+        self.request.hostname()
+    }
+
+    /// Returns request port.
+    pub fn port(&self) -> u16 {
+        self.request.port().unwrap_or(self.port)
+    }
+
+    /// Get borrowed iterator of resolved request addresses.
+    ///
+    /// # Examples
+    /// ```
+    /// # use std::net::SocketAddr;
+    /// # use actix_tls::connect::ConnectInfo;
+    /// let addr = SocketAddr::from(([127, 0, 0, 1], 4242));
+    ///
+    /// let conn = ConnectInfo::new("localhost");
+    /// let mut addrs = conn.addrs();
+    /// assert!(addrs.next().is_none());
+    ///
+    /// let conn = ConnectInfo::with_addr("localhost", addr);
+    /// let mut addrs = conn.addrs();
+    /// assert_eq!(addrs.next().unwrap(), addr);
+    /// ```
+    #[allow(clippy::implied_bounds_in_impls)]
+    pub fn addrs(
+        &self,
+    ) -> impl Iterator<Item = SocketAddr>
+           + ExactSizeIterator
+           + iter::FusedIterator
+           + Clone
+           + fmt::Debug
+           + '_ {
+        match self.addr {
+            ConnectAddrs::None => ConnectAddrsIter::None,
+            ConnectAddrs::One(addr) => ConnectAddrsIter::One(addr),
+            ConnectAddrs::Multi(ref addrs) => ConnectAddrsIter::Multi(addrs.iter()),
+        }
+    }
+
+    /// Take owned iterator resolved request addresses.
+    ///
+    /// # Examples
+    /// ```
+    /// # use std::net::SocketAddr;
+    /// # use actix_tls::connect::ConnectInfo;
+    /// let addr = SocketAddr::from(([127, 0, 0, 1], 4242));
+    ///
+    /// let mut conn = ConnectInfo::new("localhost");
+    /// let mut addrs = conn.take_addrs();
+    /// assert!(addrs.next().is_none());
+    ///
+    /// let mut conn = ConnectInfo::with_addr("localhost", addr);
+    /// let mut addrs = conn.take_addrs();
+    /// assert_eq!(addrs.next().unwrap(), addr);
+    /// ```
+    #[allow(clippy::implied_bounds_in_impls)]
+    pub fn take_addrs(
+        &mut self,
+    ) -> impl Iterator<Item = SocketAddr>
+           + ExactSizeIterator
+           + iter::FusedIterator
+           + Clone
+           + fmt::Debug
+           + 'static {
+        match mem::take(&mut self.addr) {
+            ConnectAddrs::None => ConnectAddrsIter::None,
+            ConnectAddrs::One(addr) => ConnectAddrsIter::One(addr),
+            ConnectAddrs::Multi(addrs) => ConnectAddrsIter::MultiOwned(addrs.into_iter()),
+        }
+    }
+}
+
+impl<R: Host> From<R> for ConnectInfo<R> {
+    fn from(addr: R) -> Self {
+        ConnectInfo::new(addr)
+    }
+}
+
+impl<R: Host> fmt::Display for ConnectInfo<R> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "{}:{}", self.hostname(), self.port())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::net::Ipv4Addr;
+
+    use super::*;
+
+    #[test]
+    fn test_addr_iter_multi() {
+        let localhost = SocketAddr::from((IpAddr::from(Ipv4Addr::LOCALHOST), 8080));
+        let unspecified = SocketAddr::from((IpAddr::from(Ipv4Addr::UNSPECIFIED), 8080));
+
+        let mut addrs = VecDeque::new();
+        addrs.push_back(localhost);
+        addrs.push_back(unspecified);
+
+        let mut iter = ConnectAddrsIter::Multi(addrs.iter());
+        assert_eq!(iter.next(), Some(localhost));
+        assert_eq!(iter.next(), Some(unspecified));
+        assert_eq!(iter.next(), None);
+
+        let mut iter = ConnectAddrsIter::MultiOwned(addrs.into_iter());
+        assert_eq!(iter.next(), Some(localhost));
+        assert_eq!(iter.next(), Some(unspecified));
+        assert_eq!(iter.next(), None);
+    }
+
+    #[test]
+    fn test_addr_iter_single() {
+        let localhost = SocketAddr::from((IpAddr::from(Ipv4Addr::LOCALHOST), 8080));
+
+        let mut iter = ConnectAddrsIter::One(localhost);
+        assert_eq!(iter.next(), Some(localhost));
+        assert_eq!(iter.next(), None);
+
+        let mut iter = ConnectAddrsIter::None;
+        assert_eq!(iter.next(), None);
+    }
+
+    #[test]
+    fn test_local_addr() {
+        let conn = ConnectInfo::new("hello").set_local_addr([127, 0, 0, 1]);
+        assert_eq!(
+            conn.local_addr.unwrap(),
+            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))
+        )
+    }
+
+    #[test]
+    fn request_ref() {
+        let conn = ConnectInfo::new("hello");
+        assert_eq!(conn.request(), &"hello")
+    }
+
+    #[test]
+    fn set_connect_addr_into_option() {
+        let addr = SocketAddr::from(([127, 0, 0, 1], 4242));
+
+        let conn = ConnectInfo::new("hello").set_addr(None);
+        let mut addrs = conn.addrs();
+        assert!(addrs.next().is_none());
+
+        let conn = ConnectInfo::new("hello").set_addr(addr);
+        let mut addrs = conn.addrs();
+        assert_eq!(addrs.next().unwrap(), addr);
+
+        let conn = ConnectInfo::new("hello").set_addr(Some(addr));
+        let mut addrs = conn.addrs();
+        assert_eq!(addrs.next().unwrap(), addr);
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/mod.rs.html b/src/actix_tls/connect/mod.rs.html new file mode 100644 index 00000000..fdc674be --- /dev/null +++ b/src/actix_tls/connect/mod.rs.html @@ -0,0 +1,133 @@ +mod.rs - source

actix_tls/connect/
mod.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
//! TCP and TLS connector services.
+//!
+//! # Stages of the TCP connector service:
+//! 1. Resolve [`Host`] (if needed) with given [`Resolver`] and collect list of socket addresses.
+//! 1. Establish TCP connection and return [`TcpStream`].
+//!
+//! # Stages of TLS connector services:
+//! 1. Resolve DNS and establish a [`TcpStream`] with the TCP connector service.
+//! 1. Wrap the stream and perform connect handshake with remote peer.
+//! 1. Return wrapped stream type that implements `AsyncRead` and `AsyncWrite`.
+//!
+//! [`TcpStream`]: actix_rt::net::TcpStream
+
+mod connect_addrs;
+mod connection;
+mod connector;
+mod error;
+mod host;
+mod info;
+mod resolve;
+mod resolver;
+pub mod tcp;
+
+#[cfg(feature = "uri")]
+mod uri;
+
+#[cfg(feature = "openssl")]
+pub mod openssl;
+
+#[cfg(any(
+    feature = "rustls-0_20-webpki-roots",
+    feature = "rustls-0_20-native-roots",
+))]
+pub mod rustls_0_20;
+
+#[doc(hidden)]
+#[cfg(any(
+    feature = "rustls-0_20-webpki-roots",
+    feature = "rustls-0_20-native-roots",
+))]
+pub use rustls_0_20 as rustls;
+
+#[cfg(any(
+    feature = "rustls-0_21-webpki-roots",
+    feature = "rustls-0_21-native-roots",
+))]
+pub mod rustls_0_21;
+
+#[cfg(feature = "rustls-0_22")]
+pub mod rustls_0_22;
+
+#[cfg(feature = "rustls-0_23")]
+pub mod rustls_0_23;
+
+#[cfg(feature = "native-tls")]
+pub mod native_tls;
+
+pub use self::{
+    connection::Connection,
+    connector::{Connector, ConnectorService},
+    error::ConnectError,
+    host::Host,
+    info::ConnectInfo,
+    resolve::Resolve,
+    resolver::{Resolver, ResolverService},
+};
+
\ No newline at end of file diff --git a/src/actix_tls/connect/native_tls.rs.html b/src/actix_tls/connect/native_tls.rs.html new file mode 100644 index 00000000..08657047 --- /dev/null +++ b/src/actix_tls/connect/native_tls.rs.html @@ -0,0 +1,181 @@ +native_tls.rs - source

actix_tls/connect/
native_tls.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
//! Native-TLS based connector service.
+//!
+//! See [`TlsConnector`] for main connector service factory docs.
+
+use std::io;
+
+use actix_rt::net::ActixStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::future::LocalBoxFuture;
+use tokio_native_tls::{
+    native_tls::TlsConnector as NativeTlsConnector, TlsConnector as AsyncNativeTlsConnector,
+    TlsStream as AsyncTlsStream,
+};
+use tracing::trace;
+
+use crate::connect::{Connection, Host};
+
+pub mod reexports {
+    //! Re-exports from `native-tls` and `tokio-native-tls` that are useful for connectors.
+
+    pub use tokio_native_tls::{native_tls::TlsConnector, TlsStream as AsyncTlsStream};
+}
+
+/// Connector service and factory using `native-tls`.
+#[derive(Clone)]
+pub struct TlsConnector {
+    connector: AsyncNativeTlsConnector,
+}
+
+impl TlsConnector {
+    /// Constructs new connector service from a `native-tls` connector.
+    ///
+    /// This type is it's own service factory, so it can be used in that setting, too.
+    pub fn new(connector: NativeTlsConnector) -> Self {
+        Self {
+            connector: AsyncNativeTlsConnector::from(connector),
+        }
+    }
+}
+
+impl<R: Host, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
+where
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Config = ();
+    type Service = Self;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(self.clone())
+    }
+}
+
+/// The `native-tls` connector is both it's ServiceFactory and Service impl type.
+/// As the factory and service share the same type and state.
+impl<R, IO> Service<Connection<R, IO>> for TlsConnector
+where
+    R: Host,
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, stream: Connection<R, IO>) -> Self::Future {
+        let (io, stream) = stream.replace_io(());
+        let connector = self.connector.clone();
+
+        Box::pin(async move {
+            trace!("TLS handshake start for: {:?}", stream.hostname());
+            connector
+                .connect(stream.hostname(), io)
+                .await
+                .map(|res| {
+                    trace!("TLS handshake success: {:?}", stream.hostname());
+                    stream.replace_io(res).1
+                })
+                .map_err(|e| {
+                    trace!("TLS handshake error: {:?}", e);
+                    io::Error::new(io::ErrorKind::Other, format!("{}", e))
+                })
+        })
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/openssl.rs.html b/src/actix_tls/connect/openssl.rs.html new file mode 100644 index 00000000..2ad5885c --- /dev/null +++ b/src/actix_tls/connect/openssl.rs.html @@ -0,0 +1,303 @@ +openssl.rs - source

actix_tls/connect/
openssl.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
//! OpenSSL based connector service.
+//!
+//! See [`TlsConnector`] for main connector service factory docs.
+
+use std::{
+    future::Future,
+    io,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::ActixStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+use openssl::ssl::SslConnector;
+use tokio_openssl::SslStream as AsyncSslStream;
+use tracing::trace;
+
+use crate::connect::{Connection, Host};
+
+pub mod reexports {
+    //! Re-exports from `openssl` and `tokio-openssl` that are useful for connectors.
+
+    pub use openssl::ssl::{Error, HandshakeError, SslConnector, SslConnectorBuilder, SslMethod};
+    pub use tokio_openssl::SslStream as AsyncSslStream;
+}
+
+/// Connector service factory using `openssl`.
+pub struct TlsConnector {
+    connector: SslConnector,
+}
+
+impl TlsConnector {
+    /// Constructs new connector service factory from an `openssl` connector.
+    pub fn new(connector: SslConnector) -> Self {
+        TlsConnector { connector }
+    }
+
+    /// Constructs new connector service from an `openssl` connector.
+    pub fn service(connector: SslConnector) -> TlsConnectorService {
+        TlsConnectorService { connector }
+    }
+}
+
+impl Clone for TlsConnector {
+    fn clone(&self) -> Self {
+        Self {
+            connector: self.connector.clone(),
+        }
+    }
+}
+
+impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
+where
+    R: Host,
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncSslStream<IO>>;
+    type Error = io::Error;
+    type Config = ();
+    type Service = TlsConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(TlsConnectorService {
+            connector: self.connector.clone(),
+        })
+    }
+}
+
+/// Connector service using `openssl`.
+pub struct TlsConnectorService {
+    connector: SslConnector,
+}
+
+impl Clone for TlsConnectorService {
+    fn clone(&self) -> Self {
+        Self {
+            connector: self.connector.clone(),
+        }
+    }
+}
+
+impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Response = Connection<R, AsyncSslStream<IO>>;
+    type Error = io::Error;
+    type Future = ConnectFut<R, IO>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, stream: Connection<R, IO>) -> Self::Future {
+        trace!("TLS handshake start for: {:?}", stream.hostname());
+
+        let (io, stream) = stream.replace_io(());
+        let host = stream.hostname();
+
+        let config = self
+            .connector
+            .configure()
+            .expect("SSL connect configuration was invalid.");
+
+        let ssl = config
+            .into_ssl(host)
+            .expect("SSL connect configuration was invalid.");
+
+        ConnectFut {
+            io: Some(AsyncSslStream::new(ssl, io).unwrap()),
+            stream: Some(stream),
+        }
+    }
+}
+
+/// Connect future for OpenSSL service.
+#[doc(hidden)]
+pub struct ConnectFut<R, IO> {
+    io: Option<AsyncSslStream<IO>>,
+    stream: Option<Connection<R, ()>>,
+}
+
+impl<R: Host, IO> Future for ConnectFut<R, IO>
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Output = Result<Connection<R, AsyncSslStream<IO>>, io::Error>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.get_mut();
+
+        match ready!(Pin::new(this.io.as_mut().unwrap()).poll_connect(cx)) {
+            Ok(_) => {
+                let stream = this.stream.take().unwrap();
+                trace!("TLS handshake success: {:?}", stream.hostname());
+                Poll::Ready(Ok(stream.replace_io(this.io.take().unwrap()).1))
+            }
+            Err(err) => {
+                trace!("TLS handshake error: {:?}", err);
+                Poll::Ready(Err(io::Error::new(
+                    io::ErrorKind::Other,
+                    format!("{}", err),
+                )))
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/resolve.rs.html b/src/actix_tls/connect/resolve.rs.html new file mode 100644 index 00000000..dcf531ef --- /dev/null +++ b/src/actix_tls/connect/resolve.rs.html @@ -0,0 +1,125 @@ +resolve.rs - source

actix_tls/connect/
resolve.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
//! The [`Resolve`] trait.
+
+use std::{error::Error as StdError, net::SocketAddr};
+
+use futures_core::future::LocalBoxFuture;
+
+/// Custom async DNS resolvers.
+///
+/// # Examples
+/// ```
+/// use std::net::SocketAddr;
+///
+/// use actix_tls::connect::{Resolve, Resolver};
+/// use futures_util::future::LocalBoxFuture;
+///
+/// // use trust-dns async tokio resolver
+/// use trust_dns_resolver::TokioAsyncResolver;
+///
+/// struct MyResolver {
+///     trust_dns: TokioAsyncResolver,
+/// };
+///
+/// // impl Resolve trait and convert given host address str and port to SocketAddr.
+/// impl Resolve for MyResolver {
+///     fn lookup<'a>(
+///         &'a self,
+///         host: &'a str,
+///         port: u16,
+///     ) -> LocalBoxFuture<'a, Result<Vec<SocketAddr>, Box<dyn std::error::Error>>> {
+///         Box::pin(async move {
+///             let res = self
+///                 .trust_dns
+///                 .lookup_ip(host)
+///                 .await?
+///                 .iter()
+///                 .map(|ip| SocketAddr::new(ip, port))
+///                 .collect();
+///             Ok(res)
+///         })
+///     }
+/// }
+///
+/// let my_resolver = MyResolver {
+///     trust_dns: TokioAsyncResolver::tokio_from_system_conf().unwrap(),
+/// };
+///
+/// // wrap custom resolver
+/// let resolver = Resolver::custom(my_resolver);
+///
+/// // resolver can be passed to connector factory where returned service factory
+/// // can be used to construct new connector services for use in clients
+/// let factory = actix_tls::connect::Connector::new(resolver);
+/// let connector = factory.service();
+/// ```
+pub trait Resolve {
+    /// Given DNS lookup information, returns a future that completes with socket information.
+    fn lookup<'a>(
+        &'a self,
+        host: &'a str,
+        port: u16,
+    ) -> LocalBoxFuture<'a, Result<Vec<SocketAddr>, Box<dyn StdError>>>;
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/resolver.rs.html b/src/actix_tls/connect/resolver.rs.html new file mode 100644 index 00000000..59b9ff3b --- /dev/null +++ b/src/actix_tls/connect/resolver.rs.html @@ -0,0 +1,403 @@ +resolver.rs - source

actix_tls/connect/
resolver.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
use std::{
+    future::Future,
+    io,
+    net::SocketAddr,
+    pin::Pin,
+    rc::Rc,
+    task::{Context, Poll},
+    vec::IntoIter,
+};
+
+use actix_rt::task::{spawn_blocking, JoinHandle};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::{future::LocalBoxFuture, ready};
+use tracing::trace;
+
+use super::{ConnectError, ConnectInfo, Host, Resolve};
+
+/// DNS resolver service factory.
+#[derive(Clone, Default)]
+pub struct Resolver {
+    resolver: ResolverService,
+}
+
+impl Resolver {
+    /// Constructs a new resolver factory with a custom resolver.
+    pub fn custom(resolver: impl Resolve + 'static) -> Self {
+        Self {
+            resolver: ResolverService::custom(resolver),
+        }
+    }
+
+    /// Returns a new resolver service.
+    pub fn service(&self) -> ResolverService {
+        self.resolver.clone()
+    }
+}
+
+impl<R: Host> ServiceFactory<ConnectInfo<R>> for Resolver {
+    type Response = ConnectInfo<R>;
+    type Error = ConnectError;
+    type Config = ();
+    type Service = ResolverService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(self.resolver.clone())
+    }
+}
+
+#[derive(Clone)]
+enum ResolverKind {
+    /// Built-in DNS resolver.
+    ///
+    /// See [`std::net::ToSocketAddrs`] trait.
+    Default,
+
+    /// Custom, user-provided DNS resolver.
+    Custom(Rc<dyn Resolve>),
+}
+
+impl Default for ResolverKind {
+    fn default() -> Self {
+        Self::Default
+    }
+}
+
+/// DNS resolver service.
+#[derive(Clone, Default)]
+pub struct ResolverService {
+    kind: ResolverKind,
+}
+
+impl ResolverService {
+    /// Constructor for custom Resolve trait object and use it as resolver.
+    pub fn custom(resolver: impl Resolve + 'static) -> Self {
+        Self {
+            kind: ResolverKind::Custom(Rc::new(resolver)),
+        }
+    }
+
+    /// Resolve DNS with default resolver.
+    fn default_lookup<R: Host>(
+        req: &ConnectInfo<R>,
+    ) -> JoinHandle<io::Result<IntoIter<SocketAddr>>> {
+        // reconstruct host; concatenate hostname and port together
+        let host = format!("{}:{}", req.hostname(), req.port());
+
+        // run blocking DNS lookup in thread pool since DNS lookups can take upwards of seconds on
+        // some platforms if conditions are poor and OS-level cache is not populated
+        spawn_blocking(move || std::net::ToSocketAddrs::to_socket_addrs(&host))
+    }
+}
+
+impl<R: Host> Service<ConnectInfo<R>> for ResolverService {
+    type Response = ConnectInfo<R>;
+    type Error = ConnectError;
+    type Future = ResolverFut<R>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, req: ConnectInfo<R>) -> Self::Future {
+        if req.addr.is_resolved() {
+            // socket address(es) already resolved; return existing connection request
+            ResolverFut::Resolved(Some(req))
+        } else if let Ok(ip) = req.hostname().parse() {
+            // request hostname is valid ip address; add address to request and return
+            let addr = SocketAddr::new(ip, req.port());
+            let req = req.set_addr(Some(addr));
+            ResolverFut::Resolved(Some(req))
+        } else {
+            trace!("DNS resolver: resolving host {:?}", req.hostname());
+
+            match &self.kind {
+                ResolverKind::Default => {
+                    let fut = Self::default_lookup(&req);
+                    ResolverFut::LookUp(fut, Some(req))
+                }
+
+                ResolverKind::Custom(resolver) => {
+                    let resolver = Rc::clone(resolver);
+
+                    ResolverFut::LookupCustom(Box::pin(async move {
+                        let addrs = resolver
+                            .lookup(req.hostname(), req.port())
+                            .await
+                            .map_err(ConnectError::Resolver)?;
+
+                        let req = req.set_addrs(addrs);
+
+                        if req.addr.is_unresolved() {
+                            Err(ConnectError::NoRecords)
+                        } else {
+                            Ok(req)
+                        }
+                    }))
+                }
+            }
+        }
+    }
+}
+
+/// Future for resolver service.
+#[doc(hidden)]
+pub enum ResolverFut<R: Host> {
+    Resolved(Option<ConnectInfo<R>>),
+    LookUp(
+        JoinHandle<io::Result<IntoIter<SocketAddr>>>,
+        Option<ConnectInfo<R>>,
+    ),
+    LookupCustom(LocalBoxFuture<'static, Result<ConnectInfo<R>, ConnectError>>),
+}
+
+impl<R: Host> Future for ResolverFut<R> {
+    type Output = Result<ConnectInfo<R>, ConnectError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.get_mut() {
+            Self::Resolved(conn) => Poll::Ready(Ok(conn
+                .take()
+                .expect("ResolverFuture polled after finished"))),
+
+            Self::LookUp(fut, req) => {
+                let res = match ready!(Pin::new(fut).poll(cx)) {
+                    Ok(Ok(res)) => Ok(res),
+                    Ok(Err(err)) => Err(ConnectError::Resolver(Box::new(err))),
+                    Err(err) => Err(ConnectError::Io(err.into())),
+                };
+
+                let req = req.take().unwrap();
+
+                let addrs = res.map_err(|err| {
+                    trace!(
+                        "DNS resolver: failed to resolve host {:?} err: {:?}",
+                        req.hostname(),
+                        err
+                    );
+
+                    err
+                })?;
+
+                let req = req.set_addrs(addrs);
+
+                trace!(
+                    "DNS resolver: host {:?} resolved to {:?}",
+                    req.hostname(),
+                    req.addrs()
+                );
+
+                if req.addr.is_unresolved() {
+                    Poll::Ready(Err(ConnectError::NoRecords))
+                } else {
+                    Poll::Ready(Ok(req))
+                }
+            }
+
+            Self::LookupCustom(fut) => fut.as_mut().poll(cx),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/rustls_0_20.rs.html b/src/actix_tls/connect/rustls_0_20.rs.html new file mode 100644 index 00000000..87b20a29 --- /dev/null +++ b/src/actix_tls/connect/rustls_0_20.rs.html @@ -0,0 +1,359 @@ +rustls_0_20.rs - source

actix_tls/connect/
rustls_0_20.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
//! Rustls based connector service.
+//!
+//! See [`TlsConnector`] for main connector service factory docs.
+
+use std::{
+    future::Future,
+    io,
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::ActixStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+use tokio_rustls::{
+    client::TlsStream as AsyncTlsStream,
+    rustls::{client::ServerName, ClientConfig, RootCertStore},
+    Connect as RustlsConnect, TlsConnector as RustlsTlsConnector,
+};
+use tokio_rustls_023 as tokio_rustls;
+
+use crate::connect::{Connection, Host};
+
+pub mod reexports {
+    //! Re-exports from the `rustls` v0.20 ecosystem that are useful for connectors.
+
+    pub use tokio_rustls_023::{client::TlsStream as AsyncTlsStream, rustls::ClientConfig};
+    #[cfg(feature = "rustls-0_20-webpki-roots")]
+    pub use webpki_roots_022::TLS_SERVER_ROOTS;
+}
+
+/// Returns root certificates via `rustls-native-certs` crate as a rustls certificate store.
+///
+/// See [`rustls_native_certs::load_native_certs()`] for more info on behavior and errors.
+///
+/// [`rustls_native_certs::load_native_certs()`]: rustls_native_certs_06::load_native_certs()
+#[cfg(feature = "rustls-0_20-native-roots")]
+pub fn native_roots_cert_store() -> io::Result<RootCertStore> {
+    let mut root_certs = RootCertStore::empty();
+
+    for cert in rustls_native_certs_06::load_native_certs()? {
+        root_certs
+            .add(&tokio_rustls_023::rustls::Certificate(cert.0))
+            .unwrap();
+    }
+
+    Ok(root_certs)
+}
+
+/// Returns standard root certificates from `webpki-roots` crate as a rustls certificate store.
+#[cfg(feature = "rustls-0_20-webpki-roots")]
+pub fn webpki_roots_cert_store() -> RootCertStore {
+    use tokio_rustls_023::rustls;
+
+    let mut root_certs = RootCertStore::empty();
+
+    for cert in webpki_roots_022::TLS_SERVER_ROOTS.0 {
+        let cert = rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
+            cert.subject,
+            cert.spki,
+            cert.name_constraints,
+        );
+        let certs = vec![cert].into_iter();
+        root_certs.add_server_trust_anchors(certs);
+    }
+
+    root_certs
+}
+
+/// Connector service factory using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnector {
+    connector: Arc<ClientConfig>,
+}
+
+impl TlsConnector {
+    /// Constructs new connector service factory from a `rustls` client configuration.
+    pub fn new(connector: Arc<ClientConfig>) -> Self {
+        TlsConnector { connector }
+    }
+
+    /// Constructs new connector service from a `rustls` client configuration.
+    pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService {
+        TlsConnectorService { connector }
+    }
+}
+
+impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
+where
+    R: Host,
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Config = ();
+    type Service = TlsConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(TlsConnectorService {
+            connector: self.connector.clone(),
+        })
+    }
+}
+
+/// Connector service using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnectorService {
+    connector: Arc<ClientConfig>,
+}
+
+impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Future = ConnectFut<R, IO>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, connection: Connection<R, IO>) -> Self::Future {
+        tracing::trace!("TLS handshake start for: {:?}", connection.hostname());
+        let (stream, connection) = connection.replace_io(());
+
+        match ServerName::try_from(connection.hostname()) {
+            Ok(host) => ConnectFut::Future {
+                connect: RustlsTlsConnector::from(Arc::clone(&self.connector))
+                    .connect(host, stream),
+                connection: Some(connection),
+            },
+            Err(_) => ConnectFut::InvalidDns,
+        }
+    }
+}
+
+/// Connect future for Rustls service.
+#[doc(hidden)]
+#[allow(clippy::large_enum_variant)]
+pub enum ConnectFut<R, IO> {
+    /// See issue <https://github.com/briansmith/webpki/issues/54>
+    InvalidDns,
+    Future {
+        connect: RustlsConnect<IO>,
+        connection: Option<Connection<R, ()>>,
+    },
+}
+
+impl<R, IO> Future for ConnectFut<R, IO>
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Output = io::Result<Connection<R, AsyncTlsStream<IO>>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.get_mut() {
+            Self::InvalidDns => Poll::Ready(Err(io::Error::new(
+                io::ErrorKind::Other,
+                "Rustls v0.20 can only handle hostname-based connections. Enable the `rustls-0_21` \
+                feature and use the Rustls v0.21 utilities to gain this feature.",
+            ))),
+
+            Self::Future {
+                connect,
+                connection,
+            } => {
+                let stream = ready!(Pin::new(connect).poll(cx))?;
+                let connection = connection.take().unwrap();
+                tracing::trace!("TLS handshake success: {:?}", connection.hostname());
+                Poll::Ready(Ok(connection.replace_io(stream).1))
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/rustls_0_21.rs.html b/src/actix_tls/connect/rustls_0_21.rs.html new file mode 100644 index 00000000..05949d10 --- /dev/null +++ b/src/actix_tls/connect/rustls_0_21.rs.html @@ -0,0 +1,355 @@ +rustls_0_21.rs - source

actix_tls/connect/
rustls_0_21.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
//! Rustls based connector service.
+//!
+//! See [`TlsConnector`] for main connector service factory docs.
+
+use std::{
+    future::Future,
+    io,
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::ActixStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+use tokio_rustls::{
+    client::TlsStream as AsyncTlsStream,
+    rustls::{client::ServerName, ClientConfig, RootCertStore},
+    Connect as RustlsConnect, TlsConnector as RustlsTlsConnector,
+};
+use tokio_rustls_024 as tokio_rustls;
+
+use crate::connect::{Connection, Host};
+
+pub mod reexports {
+    //! Re-exports from the `rustls` v0.21 ecosystem that are useful for connectors.
+
+    pub use tokio_rustls_024::{client::TlsStream as AsyncTlsStream, rustls::ClientConfig};
+    #[cfg(feature = "rustls-0_21-webpki-roots")]
+    pub use webpki_roots_025::TLS_SERVER_ROOTS;
+}
+
+/// Returns root certificates via `rustls-native-certs` crate as a rustls certificate store.
+///
+/// See [`rustls_native_certs::load_native_certs()`] for more info on behavior and errors.
+///
+/// [`rustls_native_certs::load_native_certs()`]: rustls_native_certs_06::load_native_certs()
+#[cfg(feature = "rustls-0_21-native-roots")]
+pub fn native_roots_cert_store() -> io::Result<RootCertStore> {
+    let mut root_certs = RootCertStore::empty();
+
+    for cert in rustls_native_certs_06::load_native_certs()? {
+        root_certs
+            .add(&tokio_rustls_024::rustls::Certificate(cert.0))
+            .unwrap();
+    }
+
+    Ok(root_certs)
+}
+
+/// Returns standard root certificates from `webpki-roots` crate as a rustls certificate store.
+#[cfg(feature = "rustls-0_21-webpki-roots")]
+pub fn webpki_roots_cert_store() -> RootCertStore {
+    use tokio_rustls_024::rustls;
+
+    let mut root_certs = RootCertStore::empty();
+
+    for cert in webpki_roots_025::TLS_SERVER_ROOTS {
+        let cert = rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
+            cert.subject,
+            cert.spki,
+            cert.name_constraints,
+        );
+        let certs = vec![cert].into_iter();
+        root_certs.add_trust_anchors(certs);
+    }
+
+    root_certs
+}
+
+/// Connector service factory using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnector {
+    connector: Arc<ClientConfig>,
+}
+
+impl TlsConnector {
+    /// Constructs new connector service factory from a `rustls` client configuration.
+    pub fn new(connector: Arc<ClientConfig>) -> Self {
+        TlsConnector { connector }
+    }
+
+    /// Constructs new connector service from a `rustls` client configuration.
+    pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService {
+        TlsConnectorService { connector }
+    }
+}
+
+impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
+where
+    R: Host,
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Config = ();
+    type Service = TlsConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(TlsConnectorService {
+            connector: self.connector.clone(),
+        })
+    }
+}
+
+/// Connector service using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnectorService {
+    connector: Arc<ClientConfig>,
+}
+
+impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Future = ConnectFut<R, IO>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, connection: Connection<R, IO>) -> Self::Future {
+        tracing::trace!("TLS handshake start for: {:?}", connection.hostname());
+        let (stream, connection) = connection.replace_io(());
+
+        match ServerName::try_from(connection.hostname()) {
+            Ok(host) => ConnectFut::Future {
+                connect: RustlsTlsConnector::from(Arc::clone(&self.connector))
+                    .connect(host, stream),
+                connection: Some(connection),
+            },
+            Err(_) => ConnectFut::InvalidServerName,
+        }
+    }
+}
+
+/// Connect future for Rustls service.
+#[doc(hidden)]
+#[allow(clippy::large_enum_variant)]
+pub enum ConnectFut<R, IO> {
+    InvalidServerName,
+    Future {
+        connect: RustlsConnect<IO>,
+        connection: Option<Connection<R, ()>>,
+    },
+}
+
+impl<R, IO> Future for ConnectFut<R, IO>
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Output = io::Result<Connection<R, AsyncTlsStream<IO>>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.get_mut() {
+            Self::InvalidServerName => Poll::Ready(Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "connection parameters specified invalid server name",
+            ))),
+
+            Self::Future {
+                connect,
+                connection,
+            } => {
+                let stream = ready!(Pin::new(connect).poll(cx))?;
+                let connection = connection.take().unwrap();
+                tracing::trace!("TLS handshake success: {:?}", connection.hostname());
+                Poll::Ready(Ok(connection.replace_io(stream).1))
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/rustls_0_22.rs.html b/src/actix_tls/connect/rustls_0_22.rs.html new file mode 100644 index 00000000..c65f1ff8 --- /dev/null +++ b/src/actix_tls/connect/rustls_0_22.rs.html @@ -0,0 +1,327 @@ +rustls_0_22.rs - source

actix_tls/connect/
rustls_0_22.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
//! Rustls based connector service.
+//!
+//! See [`TlsConnector`] for main connector service factory docs.
+
+use std::{
+    future::Future,
+    io,
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::ActixStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+use rustls_pki_types_1::ServerName;
+use tokio_rustls::{
+    client::TlsStream as AsyncTlsStream, rustls::ClientConfig, Connect as RustlsConnect,
+    TlsConnector as RustlsTlsConnector,
+};
+use tokio_rustls_025 as tokio_rustls;
+
+use crate::connect::{Connection, Host};
+
+pub mod reexports {
+    //! Re-exports from the `rustls` v0.22 ecosystem that are useful for connectors.
+
+    pub use tokio_rustls_025::{client::TlsStream as AsyncTlsStream, rustls::ClientConfig};
+    #[cfg(feature = "rustls-0_22-webpki-roots")]
+    pub use webpki_roots_026::TLS_SERVER_ROOTS;
+}
+
+/// Returns root certificates via `rustls-native-certs` crate as a rustls certificate store.
+///
+/// See [`rustls_native_certs::load_native_certs()`] for more info on behavior and errors.
+///
+/// [`rustls_native_certs::load_native_certs()`]: rustls_native_certs_07::load_native_certs()
+#[cfg(feature = "rustls-0_22-native-roots")]
+pub fn native_roots_cert_store() -> io::Result<tokio_rustls::rustls::RootCertStore> {
+    let mut root_certs = tokio_rustls::rustls::RootCertStore::empty();
+
+    for cert in rustls_native_certs_07::load_native_certs()? {
+        root_certs.add(cert).unwrap();
+    }
+
+    Ok(root_certs)
+}
+
+/// Returns standard root certificates from `webpki-roots` crate as a rustls certificate store.
+#[cfg(feature = "rustls-0_22-webpki-roots")]
+pub fn webpki_roots_cert_store() -> tokio_rustls::rustls::RootCertStore {
+    let mut root_certs = tokio_rustls::rustls::RootCertStore::empty();
+    root_certs.extend(webpki_roots_026::TLS_SERVER_ROOTS.to_owned());
+    root_certs
+}
+
+/// Connector service factory using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnector {
+    connector: Arc<ClientConfig>,
+}
+
+impl TlsConnector {
+    /// Constructs new connector service factory from a `rustls` client configuration.
+    pub fn new(connector: Arc<ClientConfig>) -> Self {
+        TlsConnector { connector }
+    }
+
+    /// Constructs new connector service from a `rustls` client configuration.
+    pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService {
+        TlsConnectorService { connector }
+    }
+}
+
+impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
+where
+    R: Host,
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Config = ();
+    type Service = TlsConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(TlsConnectorService {
+            connector: self.connector.clone(),
+        })
+    }
+}
+
+/// Connector service using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnectorService {
+    connector: Arc<ClientConfig>,
+}
+
+impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Future = ConnectFut<R, IO>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, connection: Connection<R, IO>) -> Self::Future {
+        tracing::trace!("TLS handshake start for: {:?}", connection.hostname());
+        let (stream, conn) = connection.replace_io(());
+
+        match ServerName::try_from(conn.hostname()) {
+            Ok(host) => ConnectFut::Future {
+                connect: RustlsTlsConnector::from(Arc::clone(&self.connector))
+                    .connect(host.to_owned(), stream),
+                connection: Some(conn),
+            },
+            Err(_) => ConnectFut::InvalidServerName,
+        }
+    }
+}
+
+/// Connect future for Rustls service.
+#[doc(hidden)]
+#[allow(clippy::large_enum_variant)]
+pub enum ConnectFut<R, IO> {
+    InvalidServerName,
+    Future {
+        connect: RustlsConnect<IO>,
+        connection: Option<Connection<R, ()>>,
+    },
+}
+
+impl<R, IO> Future for ConnectFut<R, IO>
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Output = io::Result<Connection<R, AsyncTlsStream<IO>>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.get_mut() {
+            Self::InvalidServerName => Poll::Ready(Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "connection parameters specified invalid server name",
+            ))),
+
+            Self::Future {
+                connect,
+                connection,
+            } => {
+                let stream = ready!(Pin::new(connect).poll(cx))?;
+                let connection = connection.take().unwrap();
+                tracing::trace!("TLS handshake success: {:?}", connection.hostname());
+                Poll::Ready(Ok(connection.replace_io(stream).1))
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/rustls_0_23.rs.html b/src/actix_tls/connect/rustls_0_23.rs.html new file mode 100644 index 00000000..7ea63499 --- /dev/null +++ b/src/actix_tls/connect/rustls_0_23.rs.html @@ -0,0 +1,327 @@ +rustls_0_23.rs - source

actix_tls/connect/
rustls_0_23.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
//! Rustls based connector service.
+//!
+//! See [`TlsConnector`] for main connector service factory docs.
+
+use std::{
+    future::Future,
+    io,
+    pin::Pin,
+    sync::Arc,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::ActixStream;
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+use rustls_pki_types_1::ServerName;
+use tokio_rustls::{
+    client::TlsStream as AsyncTlsStream, rustls::ClientConfig, Connect as RustlsConnect,
+    TlsConnector as RustlsTlsConnector,
+};
+use tokio_rustls_026 as tokio_rustls;
+
+use crate::connect::{Connection, Host};
+
+pub mod reexports {
+    //! Re-exports from the `rustls` v0.23 ecosystem that are useful for connectors.
+
+    pub use tokio_rustls_026::{client::TlsStream as AsyncTlsStream, rustls::ClientConfig};
+    #[cfg(feature = "rustls-0_23-webpki-roots")]
+    pub use webpki_roots_026::TLS_SERVER_ROOTS;
+}
+
+/// Returns root certificates via `rustls-native-certs` crate as a rustls certificate store.
+///
+/// See [`rustls_native_certs::load_native_certs()`] for more info on behavior and errors.
+///
+/// [`rustls_native_certs::load_native_certs()`]: rustls_native_certs_07::load_native_certs()
+#[cfg(feature = "rustls-0_23-native-roots")]
+pub fn native_roots_cert_store() -> io::Result<tokio_rustls::rustls::RootCertStore> {
+    let mut root_certs = tokio_rustls::rustls::RootCertStore::empty();
+
+    for cert in rustls_native_certs_07::load_native_certs()? {
+        root_certs.add(cert).unwrap();
+    }
+
+    Ok(root_certs)
+}
+
+/// Returns standard root certificates from `webpki-roots` crate as a rustls certificate store.
+#[cfg(feature = "rustls-0_23-webpki-roots")]
+pub fn webpki_roots_cert_store() -> tokio_rustls::rustls::RootCertStore {
+    let mut root_certs = tokio_rustls::rustls::RootCertStore::empty();
+    root_certs.extend(webpki_roots_026::TLS_SERVER_ROOTS.to_owned());
+    root_certs
+}
+
+/// Connector service factory using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnector {
+    connector: Arc<ClientConfig>,
+}
+
+impl TlsConnector {
+    /// Constructs new connector service factory from a `rustls` client configuration.
+    pub fn new(connector: Arc<ClientConfig>) -> Self {
+        TlsConnector { connector }
+    }
+
+    /// Constructs new connector service from a `rustls` client configuration.
+    pub fn service(connector: Arc<ClientConfig>) -> TlsConnectorService {
+        TlsConnectorService { connector }
+    }
+}
+
+impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
+where
+    R: Host,
+    IO: ActixStream + 'static,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Config = ();
+    type Service = TlsConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(TlsConnectorService {
+            connector: self.connector.clone(),
+        })
+    }
+}
+
+/// Connector service using `rustls`.
+#[derive(Clone)]
+pub struct TlsConnectorService {
+    connector: Arc<ClientConfig>,
+}
+
+impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Response = Connection<R, AsyncTlsStream<IO>>;
+    type Error = io::Error;
+    type Future = ConnectFut<R, IO>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, connection: Connection<R, IO>) -> Self::Future {
+        tracing::trace!("TLS handshake start for: {:?}", connection.hostname());
+        let (stream, conn) = connection.replace_io(());
+
+        match ServerName::try_from(conn.hostname()) {
+            Ok(host) => ConnectFut::Future {
+                connect: RustlsTlsConnector::from(Arc::clone(&self.connector))
+                    .connect(host.to_owned(), stream),
+                connection: Some(conn),
+            },
+            Err(_) => ConnectFut::InvalidServerName,
+        }
+    }
+}
+
+/// Connect future for Rustls service.
+#[doc(hidden)]
+#[allow(clippy::large_enum_variant)]
+pub enum ConnectFut<R, IO> {
+    InvalidServerName,
+    Future {
+        connect: RustlsConnect<IO>,
+        connection: Option<Connection<R, ()>>,
+    },
+}
+
+impl<R, IO> Future for ConnectFut<R, IO>
+where
+    R: Host,
+    IO: ActixStream,
+{
+    type Output = io::Result<Connection<R, AsyncTlsStream<IO>>>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.get_mut() {
+            Self::InvalidServerName => Poll::Ready(Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "connection parameters specified invalid server name",
+            ))),
+
+            Self::Future {
+                connect,
+                connection,
+            } => {
+                let stream = ready!(Pin::new(connect).poll(cx))?;
+                let connection = connection.take().unwrap();
+                tracing::trace!("TLS handshake success: {:?}", connection.hostname());
+                Poll::Ready(Ok(connection.replace_io(stream).1))
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/tcp.rs.html b/src/actix_tls/connect/tcp.rs.html new file mode 100644 index 00000000..0feffb86 --- /dev/null +++ b/src/actix_tls/connect/tcp.rs.html @@ -0,0 +1,409 @@ +tcp.rs - source

actix_tls/connect/
tcp.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
//! TCP connector service.
+//!
+//! See [`TcpConnector`] for main connector service factory docs.
+
+use std::{
+    collections::VecDeque,
+    future::Future,
+    io,
+    net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6},
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use actix_rt::net::{TcpSocket, TcpStream};
+use actix_service::{Service, ServiceFactory};
+use actix_utils::future::{ok, Ready};
+use futures_core::ready;
+use tokio_util::sync::ReusableBoxFuture;
+use tracing::{error, trace};
+
+use super::{connect_addrs::ConnectAddrs, error::ConnectError, ConnectInfo, Connection, Host};
+
+/// TCP connector service factory.
+#[derive(Debug, Clone, Copy, Default)]
+#[non_exhaustive]
+pub struct TcpConnector;
+
+impl TcpConnector {
+    /// Returns a new TCP connector service.
+    pub fn service(&self) -> TcpConnectorService {
+        TcpConnectorService::default()
+    }
+}
+
+impl<R: Host> ServiceFactory<ConnectInfo<R>> for TcpConnector {
+    type Response = Connection<R, TcpStream>;
+    type Error = ConnectError;
+    type Config = ();
+    type Service = TcpConnectorService;
+    type InitError = ();
+    type Future = Ready<Result<Self::Service, Self::InitError>>;
+
+    fn new_service(&self, _: ()) -> Self::Future {
+        ok(self.service())
+    }
+}
+
+/// TCP connector service.
+#[derive(Debug, Copy, Clone, Default)]
+#[non_exhaustive]
+pub struct TcpConnectorService;
+
+impl<R: Host> Service<ConnectInfo<R>> for TcpConnectorService {
+    type Response = Connection<R, TcpStream>;
+    type Error = ConnectError;
+    type Future = TcpConnectorFut<R>;
+
+    actix_service::always_ready!();
+
+    fn call(&self, req: ConnectInfo<R>) -> Self::Future {
+        let port = req.port();
+
+        let ConnectInfo {
+            request: req,
+            addr,
+            local_addr,
+            ..
+        } = req;
+
+        TcpConnectorFut::new(req, port, local_addr, addr)
+    }
+}
+
+/// Connect future for TCP service.
+#[doc(hidden)]
+pub enum TcpConnectorFut<R> {
+    Response {
+        req: Option<R>,
+        port: u16,
+        local_addr: Option<IpAddr>,
+        addrs: Option<VecDeque<SocketAddr>>,
+        stream: ReusableBoxFuture<'static, Result<TcpStream, io::Error>>,
+    },
+
+    Error(Option<ConnectError>),
+}
+
+impl<R: Host> TcpConnectorFut<R> {
+    pub(crate) fn new(
+        req: R,
+        port: u16,
+        local_addr: Option<IpAddr>,
+        addr: ConnectAddrs,
+    ) -> TcpConnectorFut<R> {
+        if addr.is_unresolved() {
+            error!("TCP connector: unresolved connection address");
+            return TcpConnectorFut::Error(Some(ConnectError::Unresolved));
+        }
+
+        trace!(
+            "TCP connector: connecting to {} on port {}",
+            req.hostname(),
+            port
+        );
+
+        match addr {
+            ConnectAddrs::None => unreachable!("none variant already checked"),
+
+            ConnectAddrs::One(addr) => TcpConnectorFut::Response {
+                req: Some(req),
+                port,
+                local_addr,
+                addrs: None,
+                stream: ReusableBoxFuture::new(connect(addr, local_addr)),
+            },
+
+            // When resolver returns multiple socket addr for request they would be popped from
+            // front end of queue and returns with the first successful TCP connection.
+            ConnectAddrs::Multi(mut addrs) => {
+                let addr = addrs.pop_front().unwrap();
+
+                TcpConnectorFut::Response {
+                    req: Some(req),
+                    port,
+                    local_addr,
+                    addrs: Some(addrs),
+                    stream: ReusableBoxFuture::new(connect(addr, local_addr)),
+                }
+            }
+        }
+    }
+}
+
+impl<R: Host> Future for TcpConnectorFut<R> {
+    type Output = Result<Connection<R, TcpStream>, ConnectError>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.get_mut() {
+            TcpConnectorFut::Error(err) => Poll::Ready(Err(err.take().unwrap())),
+
+            TcpConnectorFut::Response {
+                req,
+                port,
+                local_addr,
+                addrs,
+                stream,
+            } => loop {
+                match ready!(stream.poll(cx)) {
+                    Ok(sock) => {
+                        let req = req.take().unwrap();
+
+                        trace!(
+                            "TCP connector: successfully connected to {:?} - {:?}",
+                            req.hostname(),
+                            sock.peer_addr()
+                        );
+
+                        return Poll::Ready(Ok(Connection::new(req, sock)));
+                    }
+
+                    Err(err) => {
+                        trace!(
+                            "TCP connector: failed to connect to {:?} port: {}",
+                            req.as_ref().unwrap().hostname(),
+                            port,
+                        );
+
+                        if let Some(addr) = addrs.as_mut().and_then(|addrs| addrs.pop_front()) {
+                            stream.set(connect(addr, *local_addr));
+                        } else {
+                            return Poll::Ready(Err(ConnectError::Io(err)));
+                        }
+                    }
+                }
+            },
+        }
+    }
+}
+
+async fn connect(addr: SocketAddr, local_addr: Option<IpAddr>) -> io::Result<TcpStream> {
+    // use local addr if connect asks for it
+    match local_addr {
+        Some(ip_addr) => {
+            let socket = match ip_addr {
+                IpAddr::V4(ip_addr) => {
+                    let socket = TcpSocket::new_v4()?;
+                    let addr = SocketAddr::V4(SocketAddrV4::new(ip_addr, 0));
+                    socket.bind(addr)?;
+                    socket
+                }
+                IpAddr::V6(ip_addr) => {
+                    let socket = TcpSocket::new_v6()?;
+                    let addr = SocketAddr::V6(SocketAddrV6::new(ip_addr, 0, 0, 0));
+                    socket.bind(addr)?;
+                    socket
+                }
+            };
+
+            socket.connect(addr).await
+        }
+
+        None => TcpStream::connect(addr).await,
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/connect/uri.rs.html b/src/actix_tls/connect/uri.rs.html new file mode 100644 index 00000000..23297dab --- /dev/null +++ b/src/actix_tls/connect/uri.rs.html @@ -0,0 +1,127 @@ +uri.rs - source

actix_tls/connect/
uri.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
use super::Host;
+
+impl Host for http_0_2::Uri {
+    fn hostname(&self) -> &str {
+        self.host().unwrap_or("")
+    }
+
+    fn port(&self) -> Option<u16> {
+        match self.port_u16() {
+            Some(port) => Some(port),
+            None => scheme_to_port(self.scheme_str()),
+        }
+    }
+}
+
+impl Host for http_1::Uri {
+    fn hostname(&self) -> &str {
+        self.host().unwrap_or("")
+    }
+
+    fn port(&self) -> Option<u16> {
+        match self.port_u16() {
+            Some(port) => Some(port),
+            None => scheme_to_port(self.scheme_str()),
+        }
+    }
+}
+
+// Get port from well-known URL schemes.
+fn scheme_to_port(scheme: Option<&str>) -> Option<u16> {
+    match scheme {
+        // HTTP
+        Some("http") => Some(80),
+        Some("https") => Some(443),
+
+        // WebSockets
+        Some("ws") => Some(80),
+        Some("wss") => Some(443),
+
+        // Advanced Message Queuing Protocol (AMQP)
+        Some("amqp") => Some(5672),
+        Some("amqps") => Some(5671),
+
+        // Message Queuing Telemetry Transport (MQTT)
+        Some("mqtt") => Some(1883),
+        Some("mqtts") => Some(8883),
+
+        // File Transfer Protocol (FTP)
+        Some("ftp") => Some(21),
+        Some("ftps") => Some(990),
+
+        // Redis
+        Some("redis") => Some(6379),
+
+        // MySQL
+        Some("mysql") => Some(3306),
+
+        // PostgreSQL
+        Some("postgres") => Some(5432),
+
+        _ => None,
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_tls/lib.rs.html b/src/actix_tls/lib.rs.html new file mode 100644 index 00000000..9991dc8a --- /dev/null +++ b/src/actix_tls/lib.rs.html @@ -0,0 +1,35 @@ +lib.rs - source

actix_tls/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
//! TLS acceptor and connector services for the Actix ecosystem.
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+#![cfg_attr(docsrs, feature(doc_auto_cfg))]
+
+#[cfg(feature = "openssl")]
+#[allow(unused_extern_crates)]
+extern crate tls_openssl as openssl;
+
+#[cfg(feature = "accept")]
+pub mod accept;
+
+#[cfg(feature = "connect")]
+pub mod connect;
+
\ No newline at end of file diff --git a/src/actix_tracing/lib.rs.html b/src/actix_tracing/lib.rs.html new file mode 100644 index 00000000..b5717635 --- /dev/null +++ b/src/actix_tracing/lib.rs.html @@ -0,0 +1,511 @@ +lib.rs - source

actix_tracing/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
//! Actix tracing - support for tokio tracing with Actix services.
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+use core::marker::PhantomData;
+
+use actix_service::{
+    apply, ApplyTransform, IntoServiceFactory, Service, ServiceFactory, Transform,
+};
+use actix_utils::future::{ok, Either, Ready};
+use tracing_futures::{Instrument, Instrumented};
+
+/// A `Service` implementation that automatically enters/exits tracing spans
+/// for the wrapped inner service.
+#[derive(Clone)]
+pub struct TracingService<S, F> {
+    inner: S,
+    make_span: F,
+}
+
+impl<S, F> TracingService<S, F> {
+    pub fn new(inner: S, make_span: F) -> Self {
+        TracingService { inner, make_span }
+    }
+}
+
+impl<S, Req, F> Service<Req> for TracingService<S, F>
+where
+    S: Service<Req>,
+    F: Fn(&Req) -> Option<tracing::Span>,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Future = Either<S::Future, Instrumented<S::Future>>;
+
+    actix_service::forward_ready!(inner);
+
+    fn call(&self, req: Req) -> Self::Future {
+        let span = (self.make_span)(&req);
+        let _enter = span.as_ref().map(|s| s.enter());
+
+        let fut = self.inner.call(req);
+
+        // make a child span to track the future's execution
+        if let Some(span) = span
+            .clone()
+            .map(|span| tracing::span!(parent: &span, tracing::Level::INFO, "future"))
+        {
+            Either::right(fut.instrument(span))
+        } else {
+            Either::left(fut)
+        }
+    }
+}
+
+/// A `Transform` implementation that wraps services with a [`TracingService`].
+pub struct TracingTransform<S, U, F> {
+    make_span: F,
+    _p: PhantomData<fn(S, U)>,
+}
+
+impl<S, U, F> TracingTransform<S, U, F> {
+    pub fn new(make_span: F) -> Self {
+        TracingTransform {
+            make_span,
+            _p: PhantomData,
+        }
+    }
+}
+
+impl<S, Req, U, F> Transform<S, Req> for TracingTransform<S, U, F>
+where
+    S: Service<Req>,
+    U: ServiceFactory<Req, Response = S::Response, Error = S::Error, Service = S>,
+    F: Fn(&Req) -> Option<tracing::Span> + Clone,
+{
+    type Response = S::Response;
+    type Error = S::Error;
+    type Transform = TracingService<S, F>;
+    type InitError = U::InitError;
+    type Future = Ready<Result<Self::Transform, Self::InitError>>;
+
+    fn new_transform(&self, service: S) -> Self::Future {
+        ok(TracingService::new(service, self.make_span.clone()))
+    }
+}
+
+/// Wraps the provided service factory with a transform that automatically
+/// enters/exits the given span.
+///
+/// The span to be entered/exited can be provided via a closure. The closure
+/// is passed in a reference to the request being handled by the service.
+///
+/// For example:
+/// ```ignore
+/// let traced_service = trace(
+///     web_service,
+///     |req: &Request| Some(span!(Level::INFO, "request", req.id))
+/// );
+/// ```
+pub fn trace<S, Req, I, F>(
+    service_factory: I,
+    make_span: F,
+) -> ApplyTransform<TracingTransform<S::Service, S, F>, S, Req>
+where
+    I: IntoServiceFactory<S, Req>,
+    S: ServiceFactory<Req>,
+    F: Fn(&Req) -> Option<tracing::Span> + Clone,
+{
+    apply(
+        TracingTransform::new(make_span),
+        service_factory.into_factory(),
+    )
+}
+
+#[cfg(test)]
+mod test {
+    use std::{
+        cell::RefCell,
+        collections::{BTreeMap, BTreeSet},
+        sync::{Arc, RwLock},
+    };
+
+    use actix_service::{fn_factory, fn_service};
+    use slab::Slab;
+    use tracing::{span, Event, Level, Metadata, Subscriber};
+
+    use super::*;
+
+    thread_local! {
+        static SPAN: RefCell<Vec<span::Id>> = const { RefCell::new(Vec::new()) };
+    }
+
+    #[derive(Default)]
+    struct Stats {
+        entered_spans: BTreeSet<u64>,
+        exited_spans: BTreeSet<u64>,
+        events_count: BTreeMap<u64, usize>,
+    }
+
+    #[derive(Default)]
+    struct Inner {
+        spans: Slab<&'static Metadata<'static>>,
+        stats: Stats,
+    }
+
+    #[derive(Clone, Default)]
+    struct TestSubscriber {
+        inner: Arc<RwLock<Inner>>,
+    }
+
+    impl Subscriber for TestSubscriber {
+        fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
+            true
+        }
+
+        fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
+            let id = self.inner.write().unwrap().spans.insert(span.metadata());
+            span::Id::from_u64(id as u64 + 1)
+        }
+
+        fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}
+
+        fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}
+
+        fn event(&self, event: &Event<'_>) {
+            let id = event
+                .parent()
+                .cloned()
+                .or_else(|| SPAN.with(|current_span| current_span.borrow().last().cloned()))
+                .unwrap();
+
+            *self
+                .inner
+                .write()
+                .unwrap()
+                .stats
+                .events_count
+                .entry(id.into_u64())
+                .or_insert(0) += 1;
+        }
+
+        fn enter(&self, span: &span::Id) {
+            self.inner
+                .write()
+                .unwrap()
+                .stats
+                .entered_spans
+                .insert(span.into_u64());
+
+            SPAN.with(|current_span| {
+                current_span.borrow_mut().push(span.clone());
+            });
+        }
+
+        fn exit(&self, span: &span::Id) {
+            self.inner
+                .write()
+                .unwrap()
+                .stats
+                .exited_spans
+                .insert(span.into_u64());
+
+            // we are guaranteed that on any given thread, spans are exited in reverse order
+            SPAN.with(|current_span| {
+                let leaving = current_span
+                    .borrow_mut()
+                    .pop()
+                    .expect("told to exit span when not in span");
+                assert_eq!(
+                    &leaving, span,
+                    "told to exit span that was not most recently entered"
+                );
+            });
+        }
+    }
+
+    #[actix_rt::test]
+    async fn service_call() {
+        let service_factory = fn_factory(|| {
+            ok::<_, ()>(fn_service(|req: &'static str| {
+                tracing::event!(Level::TRACE, "It's happening - {}!", req);
+                ok::<_, ()>(())
+            }))
+        });
+
+        let subscriber = TestSubscriber::default();
+        let _guard = tracing::subscriber::set_default(subscriber.clone());
+
+        let span_svc = span!(Level::TRACE, "span_svc");
+        let trace_service_factory = trace(service_factory, |_: &&str| Some(span_svc.clone()));
+        let service = trace_service_factory.new_service(()).await.unwrap();
+        service.call("boo").await.unwrap();
+
+        let id = span_svc.id().unwrap().into_u64();
+        assert!(subscriber
+            .inner
+            .read()
+            .unwrap()
+            .stats
+            .entered_spans
+            .contains(&id));
+        assert!(subscriber
+            .inner
+            .read()
+            .unwrap()
+            .stats
+            .exited_spans
+            .contains(&id));
+        assert_eq!(subscriber.inner.read().unwrap().stats.events_count[&id], 1);
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_utils/counter.rs.html b/src/actix_utils/counter.rs.html new file mode 100644 index 00000000..6d83cf33 --- /dev/null +++ b/src/actix_utils/counter.rs.html @@ -0,0 +1,199 @@ +counter.rs - source

actix_utils/
counter.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
//! Task-notifying counter.
+
+use core::{cell::Cell, fmt, task};
+use std::rc::Rc;
+
+use local_waker::LocalWaker;
+
+/// Simple counter with ability to notify task on reaching specific number
+///
+/// Counter could be cloned, total n-count is shared across all clones.
+#[derive(Debug, Clone)]
+pub struct Counter(Rc<CounterInner>);
+
+impl Counter {
+    /// Create `Counter` instance with max value.
+    pub fn new(capacity: usize) -> Self {
+        Counter(Rc::new(CounterInner {
+            capacity,
+            count: Cell::new(0),
+            task: LocalWaker::new(),
+        }))
+    }
+
+    /// Create new counter guard, incrementing the counter.
+    #[inline]
+    pub fn get(&self) -> CounterGuard {
+        CounterGuard::new(self.0.clone())
+    }
+
+    /// Returns true if counter is below capacity. Otherwise, register to wake task when it is.
+    #[inline]
+    pub fn available(&self, cx: &task::Context<'_>) -> bool {
+        self.0.available(cx)
+    }
+
+    /// Get total number of acquired guards.
+    #[inline]
+    pub fn total(&self) -> usize {
+        self.0.count.get()
+    }
+}
+
+struct CounterInner {
+    count: Cell<usize>,
+    capacity: usize,
+    task: LocalWaker,
+}
+
+impl CounterInner {
+    fn inc(&self) {
+        self.count.set(self.count.get() + 1);
+    }
+
+    fn dec(&self) {
+        let num = self.count.get();
+        self.count.set(num - 1);
+        if num == self.capacity {
+            self.task.wake();
+        }
+    }
+
+    fn available(&self, cx: &task::Context<'_>) -> bool {
+        if self.count.get() < self.capacity {
+            true
+        } else {
+            self.task.register(cx.waker());
+            false
+        }
+    }
+}
+
+impl fmt::Debug for CounterInner {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("Counter")
+            .field("count", &self.count.get())
+            .field("capacity", &self.capacity)
+            .field("task", &self.task)
+            .finish()
+    }
+}
+
+/// An RAII structure that keeps the underlying counter incremented until this guard is dropped.
+#[derive(Debug)]
+pub struct CounterGuard(Rc<CounterInner>);
+
+impl CounterGuard {
+    fn new(inner: Rc<CounterInner>) -> Self {
+        inner.inc();
+        CounterGuard(inner)
+    }
+}
+
+impl Unpin for CounterGuard {}
+
+impl Drop for CounterGuard {
+    fn drop(&mut self) {
+        self.0.dec();
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_utils/future/either.rs.html b/src/actix_utils/future/either.rs.html new file mode 100644 index 00000000..9ada25fc --- /dev/null +++ b/src/actix_utils/future/either.rs.html @@ -0,0 +1,191 @@ +either.rs - source

actix_utils/future/
either.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
//! A symmetric either future.
+
+use core::{
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+use pin_project_lite::pin_project;
+
+pin_project! {
+    /// Combines two different futures that have the same output type.
+    ///
+    /// Construct variants with [`Either::left`] and [`Either::right`].
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_utils::future::{ready, Ready, Either};
+    ///
+    /// # async fn run() {
+    /// let res = Either::<_, Ready<usize>>::left(ready(42));
+    /// assert_eq!(res.await, 42);
+    ///
+    /// let res = Either::<Ready<usize>, _>::right(ready(43));
+    /// assert_eq!(res.await, 43);
+    /// # }
+    /// ```
+    #[project = EitherProj]
+    #[derive(Debug, Clone)]
+    pub enum Either<L, R> {
+        /// A value of type `L`.
+        #[allow(missing_docs)]
+        Left { #[pin] value: L },
+
+        /// A value of type `R`.
+        #[allow(missing_docs)]
+        Right { #[pin] value: R },
+    }
+}
+
+impl<L, R> Either<L, R> {
+    /// Creates new `Either` using left variant.
+    #[inline]
+    pub fn left(value: L) -> Either<L, R> {
+        Either::Left { value }
+    }
+
+    /// Creates new `Either` using right variant.
+    #[inline]
+    pub fn right(value: R) -> Either<L, R> {
+        Either::Right { value }
+    }
+}
+
+impl<T> Either<T, T> {
+    /// Unwraps into inner value when left and right have a common type.
+    #[inline]
+    pub fn into_inner(self) -> T {
+        match self {
+            Either::Left { value } => value,
+            Either::Right { value } => value,
+        }
+    }
+}
+
+impl<L, R> Future for Either<L, R>
+where
+    L: Future,
+    R: Future<Output = L::Output>,
+{
+    type Output = L::Output;
+
+    #[inline]
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        match self.project() {
+            EitherProj::Left { value } => value.poll(cx),
+            EitherProj::Right { value } => value.poll(cx),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::future::{ready, Ready};
+
+    #[actix_rt::test]
+    async fn test_either() {
+        let res = Either::<_, Ready<usize>>::left(ready(42));
+        assert_eq!(res.await, 42);
+
+        let res = Either::<Ready<usize>, _>::right(ready(43));
+        assert_eq!(res.await, 43);
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_utils/future/mod.rs.html b/src/actix_utils/future/mod.rs.html new file mode 100644 index 00000000..c28023e7 --- /dev/null +++ b/src/actix_utils/future/mod.rs.html @@ -0,0 +1,23 @@ +mod.rs - source

actix_utils/future/
mod.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
//! Helpers for constructing futures.
+
+mod either;
+mod poll_fn;
+mod ready;
+
+pub use self::{
+    either::Either,
+    poll_fn::{poll_fn, PollFn},
+    ready::{err, ok, ready, Ready},
+};
+
\ No newline at end of file diff --git a/src/actix_utils/future/poll_fn.rs.html b/src/actix_utils/future/poll_fn.rs.html new file mode 100644 index 00000000..6eb9257b --- /dev/null +++ b/src/actix_utils/future/poll_fn.rs.html @@ -0,0 +1,249 @@ +poll_fn.rs - source

actix_utils/future/
poll_fn.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
//! Simple "poll function" future and factory.
+
+use core::{
+    fmt,
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+/// Creates a future driven by the provided function that receives a task context.
+///
+/// # Examples
+/// ```
+/// # use std::task::Poll;
+/// # use actix_utils::future::poll_fn;
+/// # async fn test_poll_fn() {
+/// let res = poll_fn(|_| Poll::Ready(42)).await;
+/// assert_eq!(res, 42);
+///
+/// let mut i = 5;
+/// let res = poll_fn(|cx| {
+///     i -= 1;
+///
+///     if i > 0 {
+///         cx.waker().wake_by_ref();
+///         Poll::Pending
+///     } else {
+///         Poll::Ready(42)
+///     }
+/// })
+/// .await;
+/// assert_eq!(res, 42);
+/// # }
+/// # actix_rt::Runtime::new().unwrap().block_on(test_poll_fn());
+/// ```
+#[inline]
+pub fn poll_fn<F, T>(f: F) -> PollFn<F>
+where
+    F: FnMut(&mut Context<'_>) -> Poll<T>,
+{
+    PollFn { f }
+}
+
+/// Future for the [`poll_fn`] function.
+pub struct PollFn<F> {
+    f: F,
+}
+
+impl<F> fmt::Debug for PollFn<F> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("PollFn").finish()
+    }
+}
+
+impl<F, T> Future for PollFn<F>
+where
+    F: FnMut(&mut Context<'_>) -> Poll<T>,
+{
+    type Output = T;
+
+    #[inline]
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        // SAFETY: we are not moving out of the pinned field
+        // see https://github.com/rust-lang/rust/pull/102737
+        #[allow(clippy::needless_borrow)]
+        (unsafe { &mut self.get_unchecked_mut().f })(cx)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::marker::PhantomPinned;
+
+    use super::*;
+
+    static_assertions::assert_impl_all!(PollFn<()>: Unpin);
+    static_assertions::assert_not_impl_all!(PollFn<PhantomPinned>: Unpin);
+
+    #[actix_rt::test]
+    async fn test_poll_fn() {
+        let res = poll_fn(|_| Poll::Ready(42)).await;
+        assert_eq!(res, 42);
+
+        let mut i = 5;
+        let res = poll_fn(|cx| {
+            i -= 1;
+
+            if i > 0 {
+                cx.waker().wake_by_ref();
+                Poll::Pending
+            } else {
+                Poll::Ready(42)
+            }
+        })
+        .await;
+        assert_eq!(res, 42);
+    }
+
+    // following soundness tests taken from https://github.com/tokio-rs/tokio/pull/5087
+
+    #[allow(dead_code)]
+    fn require_send<T: Send>(_t: &T) {}
+    #[allow(dead_code)]
+    fn require_sync<T: Sync>(_t: &T) {}
+
+    #[allow(unused)]
+    trait AmbiguousIfUnpin<A> {
+        fn some_item(&self) {}
+    }
+    impl<T: ?Sized> AmbiguousIfUnpin<()> for T {}
+    impl<T: ?Sized + Unpin> AmbiguousIfUnpin<[u8; 0]> for T {}
+
+    const _: fn() = || {
+        let pinned = std::marker::PhantomPinned;
+        let f = poll_fn(move |_| {
+            // Use `pinned` to take ownership of it.
+            let _ = &pinned;
+            std::task::Poll::Pending::<()>
+        });
+        require_send(&f);
+        require_sync(&f);
+        AmbiguousIfUnpin::some_item(&f);
+    };
+}
+
\ No newline at end of file diff --git a/src/actix_utils/future/ready.rs.html b/src/actix_utils/future/ready.rs.html new file mode 100644 index 00000000..412010a7 --- /dev/null +++ b/src/actix_utils/future/ready.rs.html @@ -0,0 +1,265 @@ +ready.rs - source

actix_utils/future/
ready.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
//! When `core::future::Ready` has a `into_inner()` method, this can be deprecated.
+
+use core::{
+    future::Future,
+    pin::Pin,
+    task::{Context, Poll},
+};
+
+/// Future for the [`ready`] function.
+///
+/// Panic will occur if polled more than once.
+///
+/// # Examples
+/// ```
+/// use actix_utils::future::ready;
+///
+/// // async
+/// # async fn run() {
+/// let a = ready(1);
+/// assert_eq!(a.await, 1);
+/// # }
+///
+/// // sync
+/// let a = ready(1);
+/// assert_eq!(a.into_inner(), 1);
+/// ```
+#[derive(Debug, Clone)]
+#[must_use = "futures do nothing unless you `.await` or poll them"]
+pub struct Ready<T> {
+    val: Option<T>,
+}
+
+impl<T> Ready<T> {
+    /// Unwraps the value from this immediately ready future.
+    #[inline]
+    pub fn into_inner(mut self) -> T {
+        self.val.take().unwrap()
+    }
+}
+
+impl<T> Unpin for Ready<T> {}
+
+impl<T> Future for Ready<T> {
+    type Output = T;
+
+    #[inline]
+    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> {
+        let val = self.val.take().expect("Ready polled after completion");
+        Poll::Ready(val)
+    }
+}
+
+/// Creates a future that is immediately ready with a value.
+///
+/// # Examples
+/// ```no_run
+/// use actix_utils::future::ready;
+///
+/// # async fn run() {
+/// let a = ready(1);
+/// assert_eq!(a.await, 1);
+/// # }
+///
+/// // sync
+/// let a = ready(1);
+/// assert_eq!(a.into_inner(), 1);
+/// ```
+#[inline]
+pub fn ready<T>(val: T) -> Ready<T> {
+    Ready { val: Some(val) }
+}
+
+/// Creates a future that is immediately ready with a success value.
+///
+/// # Examples
+/// ```no_run
+/// use actix_utils::future::ok;
+///
+/// # async fn run() {
+/// let a = ok::<_, ()>(1);
+/// assert_eq!(a.await, Ok(1));
+/// # }
+/// ```
+#[inline]
+pub fn ok<T, E>(val: T) -> Ready<Result<T, E>> {
+    Ready { val: Some(Ok(val)) }
+}
+
+/// Creates a future that is immediately ready with an error value.
+///
+/// # Examples
+/// ```no_run
+/// use actix_utils::future::err;
+///
+/// # async fn run() {
+/// let a = err::<(), _>(1);
+/// assert_eq!(a.await, Err(1));
+/// # }
+/// ```
+#[inline]
+pub fn err<T, E>(err: E) -> Ready<Result<T, E>> {
+    Ready {
+        val: Some(Err(err)),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::rc::Rc;
+
+    use futures_util::task::noop_waker;
+    use static_assertions::{assert_impl_all, assert_not_impl_any};
+
+    use super::*;
+
+    assert_impl_all!(Ready<()>: Send, Sync, Unpin, Clone);
+    assert_impl_all!(Ready<Rc<()>>: Unpin, Clone);
+    assert_not_impl_any!(Ready<Rc<()>>: Send, Sync);
+
+    #[test]
+    #[should_panic]
+    fn multiple_poll_panics() {
+        let waker = noop_waker();
+        let mut cx = Context::from_waker(&waker);
+
+        let mut ready = ready(1);
+        assert_eq!(Pin::new(&mut ready).poll(&mut cx), Poll::Ready(1));
+
+        // panic!
+        let _ = Pin::new(&mut ready).poll(&mut cx);
+    }
+}
+
\ No newline at end of file diff --git a/src/actix_utils/lib.rs.html b/src/actix_utils/lib.rs.html new file mode 100644 index 00000000..59f7d428 --- /dev/null +++ b/src/actix_utils/lib.rs.html @@ -0,0 +1,19 @@ +lib.rs - source

actix_utils/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
//! Various utilities used in the Actix ecosystem.
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+
+pub mod counter;
+pub mod future;
+
\ No newline at end of file diff --git a/src/bytestring/lib.rs.html b/src/bytestring/lib.rs.html new file mode 100644 index 00000000..863d0199 --- /dev/null +++ b/src/bytestring/lib.rs.html @@ -0,0 +1,937 @@ +lib.rs - source

bytestring/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
//! A UTF-8 encoded read-only string using `Bytes` as storage.
+//!
+//! See docs for [`ByteString`].
+
+#![no_std]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+
+extern crate alloc;
+
+use alloc::{
+    boxed::Box,
+    string::{String, ToString},
+    vec::Vec,
+};
+use core::{borrow::Borrow, fmt, hash, ops, str};
+
+use bytes::Bytes;
+
+/// An immutable UTF-8 encoded string with [`Bytes`] as a storage.
+#[derive(Clone, Default, Eq, PartialOrd, Ord)]
+pub struct ByteString(Bytes);
+
+impl ByteString {
+    /// Creates a new empty `ByteString`.
+    pub const fn new() -> Self {
+        ByteString(Bytes::new())
+    }
+
+    /// Get a reference to the underlying `Bytes` object.
+    pub fn as_bytes(&self) -> &Bytes {
+        &self.0
+    }
+
+    /// Unwraps this `ByteString` into the underlying `Bytes` object.
+    pub fn into_bytes(self) -> Bytes {
+        self.0
+    }
+
+    /// Creates a new `ByteString` from a `&'static str`.
+    pub const fn from_static(src: &'static str) -> ByteString {
+        Self(Bytes::from_static(src.as_bytes()))
+    }
+
+    /// Creates a new `ByteString` from a Bytes.
+    ///
+    /// # Safety
+    /// This function is unsafe because it does not check 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 `ByteString`, as we assume that `ByteString`s are valid UTF-8. However, the most likely
+    /// issue is that the data gets corrupted.
+    pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
+        Self(src)
+    }
+
+    /// Returns a new byte string that is equivalent to the given `subset`.
+    ///
+    /// When processing a `ByteString` buffer with other tools, one often gets a `&str` which is in
+    /// fact a slice of the original `ByteString`; i.e., a subset of it. This function turns that
+    /// `&str` into another `ByteString`, as if one had sliced the `ByteString` with the offsets
+    /// that correspond to `subset`.
+    ///
+    /// Corresponds to [`Bytes::slice_ref`].
+    ///
+    /// This operation is `O(1)`.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `subset` is not a sub-slice of this byte string.
+    ///
+    /// Note that strings which are only subsets from an equality perspective do not uphold this
+    /// requirement; see examples.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use bytestring::ByteString;
+    /// let string = ByteString::from_static(" foo ");
+    /// let subset = string.trim();
+    /// let substring = string.slice_ref(subset);
+    /// assert_eq!(substring, "foo");
+    /// ```
+    ///
+    /// ```should_panic
+    /// # use bytestring::ByteString;
+    /// // panics because the given slice is not derived from the original byte string, despite
+    /// // being a logical subset of the string
+    /// ByteString::from_static("foo bar").slice_ref("foo");
+    /// ```
+    pub fn slice_ref(&self, subset: &str) -> Self {
+        Self(self.0.slice_ref(subset.as_bytes()))
+    }
+}
+
+impl PartialEq<str> for ByteString {
+    fn eq(&self, other: &str) -> bool {
+        &self[..] == other
+    }
+}
+
+impl<T: AsRef<str>> PartialEq<T> for ByteString {
+    fn eq(&self, other: &T) -> bool {
+        &self[..] == other.as_ref()
+    }
+}
+
+impl AsRef<ByteString> for ByteString {
+    fn as_ref(&self) -> &ByteString {
+        self
+    }
+}
+
+impl AsRef<[u8]> for ByteString {
+    fn as_ref(&self) -> &[u8] {
+        self.0.as_ref()
+    }
+}
+
+impl AsRef<str> for ByteString {
+    fn as_ref(&self) -> &str {
+        self
+    }
+}
+
+impl hash::Hash for ByteString {
+    fn hash<H: hash::Hasher>(&self, state: &mut H) {
+        (**self).hash(state);
+    }
+}
+
+impl ops::Deref for ByteString {
+    type Target = str;
+
+    #[inline]
+    fn deref(&self) -> &str {
+        let bytes = self.0.as_ref();
+        // SAFETY: UTF-8 validity is guaranteed during construction.
+        unsafe { str::from_utf8_unchecked(bytes) }
+    }
+}
+
+impl Borrow<str> for ByteString {
+    fn borrow(&self) -> &str {
+        self
+    }
+}
+
+impl From<String> for ByteString {
+    #[inline]
+    fn from(value: String) -> Self {
+        Self(Bytes::from(value))
+    }
+}
+
+impl From<&str> for ByteString {
+    #[inline]
+    fn from(value: &str) -> Self {
+        Self(Bytes::copy_from_slice(value.as_ref()))
+    }
+}
+
+impl From<Box<str>> for ByteString {
+    #[inline]
+    fn from(value: Box<str>) -> Self {
+        Self(Bytes::from(value.into_boxed_bytes()))
+    }
+}
+
+impl From<ByteString> for String {
+    #[inline]
+    fn from(value: ByteString) -> Self {
+        value.to_string()
+    }
+}
+
+impl TryFrom<&[u8]> for ByteString {
+    type Error = str::Utf8Error;
+
+    #[inline]
+    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
+        let _ = str::from_utf8(value)?;
+        Ok(ByteString(Bytes::copy_from_slice(value)))
+    }
+}
+
+impl TryFrom<Vec<u8>> for ByteString {
+    type Error = str::Utf8Error;
+
+    #[inline]
+    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
+        let buf = String::from_utf8(value).map_err(|err| err.utf8_error())?;
+        Ok(ByteString(Bytes::from(buf)))
+    }
+}
+
+impl TryFrom<Bytes> for ByteString {
+    type Error = str::Utf8Error;
+
+    #[inline]
+    fn try_from(value: Bytes) -> Result<Self, Self::Error> {
+        let _ = str::from_utf8(value.as_ref())?;
+        Ok(ByteString(value))
+    }
+}
+
+impl TryFrom<bytes::BytesMut> for ByteString {
+    type Error = str::Utf8Error;
+
+    #[inline]
+    fn try_from(value: bytes::BytesMut) -> Result<Self, Self::Error> {
+        let _ = str::from_utf8(&value)?;
+        Ok(ByteString(value.freeze()))
+    }
+}
+
+macro_rules! array_impls {
+    ($($len:expr)+) => {
+        $(
+            impl TryFrom<[u8; $len]> for ByteString {
+                type Error = str::Utf8Error;
+
+                #[inline]
+                fn try_from(value: [u8; $len]) -> Result<Self, Self::Error> {
+                    ByteString::try_from(&value[..])
+                }
+            }
+
+            impl TryFrom<&[u8; $len]> for ByteString {
+                type Error = str::Utf8Error;
+
+                #[inline]
+                fn try_from(value: &[u8; $len]) -> Result<Self, Self::Error> {
+                    ByteString::try_from(&value[..])
+                }
+            }
+        )+
+    }
+}
+
+array_impls!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32);
+
+impl fmt::Debug for ByteString {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
+        (**self).fmt(fmt)
+    }
+}
+
+impl fmt::Display for ByteString {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
+        (**self).fmt(fmt)
+    }
+}
+
+#[cfg(feature = "serde")]
+mod serde {
+    use alloc::string::String;
+
+    use serde::{
+        de::{Deserialize, Deserializer},
+        ser::{Serialize, Serializer},
+    };
+
+    use super::ByteString;
+
+    impl Serialize for ByteString {
+        #[inline]
+        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+        where
+            S: Serializer,
+        {
+            serializer.serialize_str(self.as_ref())
+        }
+    }
+
+    impl<'de> Deserialize<'de> for ByteString {
+        #[inline]
+        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+        where
+            D: Deserializer<'de>,
+        {
+            String::deserialize(deserializer).map(ByteString::from)
+        }
+    }
+
+    #[cfg(test)]
+    mod serde_impl_tests {
+        use serde::de::DeserializeOwned;
+        use static_assertions::assert_impl_all;
+
+        use super::*;
+
+        assert_impl_all!(ByteString: Serialize, DeserializeOwned);
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use alloc::{borrow::ToOwned, format, vec};
+    use core::{
+        hash::{Hash, Hasher},
+        panic::{RefUnwindSafe, UnwindSafe},
+    };
+
+    use ahash::AHasher;
+    use static_assertions::assert_impl_all;
+
+    use super::*;
+
+    assert_impl_all!(ByteString: Send, Sync, Unpin, Sized);
+    assert_impl_all!(ByteString: Clone, Default, Eq, PartialOrd, Ord);
+    assert_impl_all!(ByteString: fmt::Debug, fmt::Display);
+    assert_impl_all!(ByteString: UnwindSafe, RefUnwindSafe);
+
+    #[test]
+    fn eq() {
+        let s: ByteString = ByteString::from_static("test");
+        assert_eq!(s, "test");
+        assert_eq!(s, *"test");
+        assert_eq!(s, "test".to_owned());
+    }
+
+    #[test]
+    fn new() {
+        let _: ByteString = ByteString::new();
+    }
+
+    #[test]
+    fn as_bytes() {
+        let buf = ByteString::new();
+        assert!(buf.as_bytes().is_empty());
+
+        let buf = ByteString::from("hello");
+        assert_eq!(buf.as_bytes(), "hello");
+    }
+
+    #[test]
+    fn from_bytes_unchecked() {
+        let buf = unsafe { ByteString::from_bytes_unchecked(Bytes::new()) };
+        assert!(buf.is_empty());
+
+        let buf = unsafe { ByteString::from_bytes_unchecked(Bytes::from("hello")) };
+        assert_eq!(buf, "hello");
+    }
+
+    #[test]
+    fn as_ref() {
+        let buf = ByteString::new();
+
+        let _: &ByteString = buf.as_ref();
+        let _: &[u8] = buf.as_ref();
+    }
+
+    #[test]
+    fn borrow() {
+        let buf = ByteString::new();
+
+        let _: &str = buf.borrow();
+    }
+
+    #[test]
+    fn hash() {
+        let mut hasher1 = AHasher::default();
+        "str".hash(&mut hasher1);
+
+        let mut hasher2 = AHasher::default();
+        let s = ByteString::from_static("str");
+        s.hash(&mut hasher2);
+        assert_eq!(hasher1.finish(), hasher2.finish());
+    }
+
+    #[test]
+    fn from_string() {
+        let s: ByteString = "hello".to_owned().into();
+        assert_eq!(&s, "hello");
+        let t: &str = s.as_ref();
+        assert_eq!(t, "hello");
+    }
+
+    #[test]
+    fn from_str() {
+        let _: ByteString = "str".into();
+        let _: ByteString = "str".to_owned().into_boxed_str().into();
+    }
+
+    #[test]
+    fn to_string() {
+        let buf = ByteString::from("foo");
+        assert_eq!(String::from(buf), "foo");
+    }
+
+    #[test]
+    fn from_static_str() {
+        static _S: ByteString = ByteString::from_static("hello");
+        let _ = ByteString::from_static("str");
+    }
+
+    #[test]
+    fn try_from_slice() {
+        let _ = ByteString::try_from(b"nice bytes").unwrap();
+    }
+
+    #[test]
+    fn try_from_array() {
+        assert_eq!(
+            ByteString::try_from([b'h', b'i']).unwrap(),
+            ByteString::from_static("hi")
+        );
+    }
+
+    #[test]
+    fn try_from_vec() {
+        let _ = ByteString::try_from(vec![b'f', b'o', b'o']).unwrap();
+        ByteString::try_from(vec![0, 159, 146, 150]).unwrap_err();
+    }
+
+    #[test]
+    fn try_from_bytes() {
+        let _ = ByteString::try_from(Bytes::from_static(b"nice bytes")).unwrap();
+    }
+
+    #[test]
+    fn try_from_bytes_mut() {
+        let _ = ByteString::try_from(bytes::BytesMut::from(&b"nice bytes"[..])).unwrap();
+    }
+
+    #[test]
+    fn display() {
+        let buf = ByteString::from("bar");
+        assert_eq!(format!("{buf}"), "bar");
+    }
+
+    #[test]
+    fn debug() {
+        let buf = ByteString::from("baz");
+        assert_eq!(format!("{buf:?}"), r#""baz""#);
+    }
+
+    #[cfg(feature = "serde")]
+    #[test]
+    fn serialize() {
+        let s: ByteString = serde_json::from_str(r#""nice bytes""#).unwrap();
+        assert_eq!(s, "nice bytes");
+    }
+
+    #[cfg(feature = "serde")]
+    #[test]
+    fn deserialize() {
+        let s = serde_json::to_string(&ByteString::from_static("nice bytes")).unwrap();
+        assert_eq!(s, r#""nice bytes""#);
+    }
+
+    #[test]
+    fn slice_ref() {
+        let string = ByteString::from_static(" foo ");
+        let subset = string.trim();
+        // subset is derived from original byte string
+        let substring = string.slice_ref(subset);
+        assert_eq!(substring, "foo");
+    }
+
+    #[test]
+    #[should_panic]
+    fn slice_ref_catches_not_a_subset() {
+        // panics because the given slice is not derived from the original byte string, despite
+        // being a logical subset of the string
+        ByteString::from_static("foo bar").slice_ref("foo");
+    }
+}
+
\ No newline at end of file diff --git a/src/local_channel/lib.rs.html b/src/local_channel/lib.rs.html new file mode 100644 index 00000000..a1c07568 --- /dev/null +++ b/src/local_channel/lib.rs.html @@ -0,0 +1,21 @@ +lib.rs - source

local_channel/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
//! Non-thread-safe channels.
+//!
+//! See docs for [`mpsc::channel()`].
+
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+
+extern crate alloc;
+
+pub mod mpsc;
+
\ No newline at end of file diff --git a/src/local_channel/mpsc.rs.html b/src/local_channel/mpsc.rs.html new file mode 100644 index 00000000..6b40eef6 --- /dev/null +++ b/src/local_channel/mpsc.rs.html @@ -0,0 +1,511 @@ +mpsc.rs - source

local_channel/
mpsc.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
//! A non-thread-safe multi-producer, single-consumer, futures-aware, FIFO queue.
+
+use alloc::{collections::VecDeque, rc::Rc};
+use core::{
+    cell::RefCell,
+    fmt,
+    future::poll_fn,
+    pin::Pin,
+    task::{Context, Poll},
+};
+use std::error::Error;
+
+use futures_core::stream::Stream;
+use futures_sink::Sink;
+use local_waker::LocalWaker;
+
+/// Creates a unbounded in-memory channel with buffered storage.
+///
+/// [Sender]s and [Receiver]s are `!Send`.
+pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
+    let shared = Rc::new(RefCell::new(Shared {
+        has_receiver: true,
+        buffer: VecDeque::new(),
+        blocked_recv: LocalWaker::new(),
+    }));
+
+    let sender = Sender {
+        shared: shared.clone(),
+    };
+
+    let receiver = Receiver { shared };
+
+    (sender, receiver)
+}
+
+#[derive(Debug)]
+struct Shared<T> {
+    buffer: VecDeque<T>,
+    blocked_recv: LocalWaker,
+    has_receiver: bool,
+}
+
+/// The transmission end of a channel.
+///
+/// This is created by the `channel` function.
+#[derive(Debug)]
+pub struct Sender<T> {
+    shared: Rc<RefCell<Shared<T>>>,
+}
+
+impl<T> Unpin for Sender<T> {}
+
+impl<T> Sender<T> {
+    /// Sends the provided message along this channel.
+    pub fn send(&self, item: T) -> Result<(), SendError<T>> {
+        let mut shared = self.shared.borrow_mut();
+
+        if !shared.has_receiver {
+            // receiver was dropped
+            return Err(SendError(item));
+        };
+
+        shared.buffer.push_back(item);
+        shared.blocked_recv.wake();
+
+        Ok(())
+    }
+
+    /// Closes the sender half.
+    ///
+    /// This prevents any further messages from being sent on the channel, by any sender, while
+    /// still enabling the receiver to drain messages that are already buffered.
+    pub fn close(&mut self) {
+        self.shared.borrow_mut().has_receiver = false;
+    }
+}
+
+impl<T> Clone for Sender<T> {
+    fn clone(&self) -> Self {
+        Sender {
+            shared: self.shared.clone(),
+        }
+    }
+}
+
+impl<T> Sink<T> for Sender<T> {
+    type Error = SendError<T>;
+
+    fn poll_ready(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        Poll::Ready(Ok(()))
+    }
+
+    fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), SendError<T>> {
+        self.send(item)
+    }
+
+    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), SendError<T>>> {
+        Poll::Ready(Ok(()))
+    }
+
+    fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
+        Poll::Ready(Ok(()))
+    }
+}
+
+impl<T> Drop for Sender<T> {
+    fn drop(&mut self) {
+        let count = Rc::strong_count(&self.shared);
+        let shared = self.shared.borrow_mut();
+
+        // check is last sender is about to drop
+        if shared.has_receiver && count == 2 {
+            // Wake up receiver as its stream has ended
+            shared.blocked_recv.wake();
+        }
+    }
+}
+
+/// The receiving end of a channel which implements the `Stream` trait.
+///
+/// This is created by the [`channel`] function.
+#[derive(Debug)]
+pub struct Receiver<T> {
+    shared: Rc<RefCell<Shared<T>>>,
+}
+
+impl<T> Receiver<T> {
+    /// Receive the next value.
+    ///
+    /// Returns `None` if the channel is empty and has been [closed](Sender::close) explicitly or
+    /// when all senders have been dropped and, therefore, no more values can ever be sent though
+    /// this channel.
+    pub async fn recv(&mut self) -> Option<T> {
+        let mut this = Pin::new(self);
+        poll_fn(|cx| this.as_mut().poll_next(cx)).await
+    }
+
+    /// Create an associated [Sender].
+    pub fn sender(&self) -> Sender<T> {
+        Sender {
+            shared: self.shared.clone(),
+        }
+    }
+}
+
+impl<T> Unpin for Receiver<T> {}
+
+impl<T> Stream for Receiver<T> {
+    type Item = T;
+
+    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
+        let mut shared = self.shared.borrow_mut();
+
+        if Rc::strong_count(&self.shared) == 1 {
+            // All senders have been dropped, so drain the buffer and end the stream.
+            return Poll::Ready(shared.buffer.pop_front());
+        }
+
+        if let Some(msg) = shared.buffer.pop_front() {
+            Poll::Ready(Some(msg))
+        } else {
+            shared.blocked_recv.register(cx.waker());
+            Poll::Pending
+        }
+    }
+}
+
+impl<T> Drop for Receiver<T> {
+    fn drop(&mut self) {
+        let mut shared = self.shared.borrow_mut();
+        shared.buffer.clear();
+        shared.has_receiver = false;
+    }
+}
+
+/// Error returned when attempting to send after the channels' [Receiver] is dropped or closed.
+///
+/// Allows access to message that failed to send with [`into_inner`](Self::into_inner).
+pub struct SendError<T>(pub T);
+
+impl<T> SendError<T> {
+    /// Returns the message that was attempted to be sent but failed.
+    pub fn into_inner(self) -> T {
+        self.0
+    }
+}
+
+impl<T> fmt::Debug for SendError<T> {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt.debug_tuple("SendError").field(&"...").finish()
+    }
+}
+
+impl<T> fmt::Display for SendError<T> {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(fmt, "send failed because receiver is gone")
+    }
+}
+
+impl<T> Error for SendError<T> {}
+
+#[cfg(test)]
+mod tests {
+    use futures_util::{future::lazy, StreamExt as _};
+
+    use super::*;
+
+    #[tokio::test]
+    async fn test_mpsc() {
+        let (tx, mut rx) = channel();
+        tx.send("test").unwrap();
+        assert_eq!(rx.next().await.unwrap(), "test");
+
+        let tx2 = tx.clone();
+        tx2.send("test2").unwrap();
+        assert_eq!(rx.next().await.unwrap(), "test2");
+
+        assert_eq!(
+            lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
+            Poll::Pending
+        );
+        drop(tx2);
+        assert_eq!(
+            lazy(|cx| Pin::new(&mut rx).poll_next(cx)).await,
+            Poll::Pending
+        );
+        drop(tx);
+        assert_eq!(rx.next().await, None);
+
+        let (tx, rx) = channel();
+        tx.send("test").unwrap();
+        drop(rx);
+        assert!(tx.send("test").is_err());
+
+        let (mut tx, _) = channel();
+        let tx2 = tx.clone();
+        tx.close();
+        assert!(tx.send("test").is_err());
+        assert!(tx2.send("test").is_err());
+    }
+
+    #[tokio::test]
+    async fn test_recv() {
+        let (tx, mut rx) = channel();
+        tx.send("test").unwrap();
+        assert_eq!(rx.recv().await.unwrap(), "test");
+        drop(tx);
+
+        let (tx, mut rx) = channel();
+        tx.send("test").unwrap();
+        assert_eq!(rx.recv().await.unwrap(), "test");
+        drop(tx);
+        assert!(rx.recv().await.is_none());
+    }
+}
+
\ No newline at end of file diff --git a/src/local_waker/lib.rs.html b/src/local_waker/lib.rs.html new file mode 100644 index 00000000..ce44a295 --- /dev/null +++ b/src/local_waker/lib.rs.html @@ -0,0 +1,147 @@ +lib.rs - source

local_waker/
lib.rs

+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
//! A synchronization primitive for thread-local task wakeup.
+//!
+//! See docs for [`LocalWaker`].
+
+#![no_std]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
+
+use core::{cell::Cell, fmt, marker::PhantomData, task::Waker};
+
+/// A synchronization primitive for task wakeup.
+///
+/// Sometimes the task interested in a given event will change over time. A `LocalWaker` can
+/// coordinate concurrent notifications with the consumer, potentially "updating" the underlying
+/// task to wake up. This is useful in scenarios where a computation completes in another task and
+/// wants to notify the consumer, but the consumer is in the process of being migrated to a new
+/// logical task.
+///
+/// Consumers should call [`register`] before checking the result of a computation and producers
+/// should call [`wake`] after producing the computation (this differs from the usual `thread::park`
+/// pattern). It is also permitted for [`wake`] to be called _before_ [`register`]. This results in
+/// a no-op.
+///
+/// A single `LocalWaker` may be reused for any number of calls to [`register`] or [`wake`].
+///
+/// [`register`]: LocalWaker::register
+/// [`wake`]: LocalWaker::wake
+#[derive(Default)]
+pub struct LocalWaker {
+    pub(crate) waker: Cell<Option<Waker>>,
+    // mark LocalWaker as a !Send type.
+    _phantom: PhantomData<*const ()>,
+}
+
+impl LocalWaker {
+    /// Creates a new, empty `LocalWaker`.
+    pub fn new() -> Self {
+        LocalWaker::default()
+    }
+
+    /// Registers the waker to be notified on calls to `wake`.
+    ///
+    /// Returns `true` if waker was registered before.
+    #[inline]
+    pub fn register(&self, waker: &Waker) -> bool {
+        let last_waker = self.waker.replace(Some(waker.clone()));
+        last_waker.is_some()
+    }
+
+    /// Calls `wake` on the last `Waker` passed to `register`.
+    ///
+    /// If `register` has not been called yet, then this does nothing.
+    #[inline]
+    pub fn wake(&self) {
+        if let Some(waker) = self.take() {
+            waker.wake();
+        }
+    }
+
+    /// Returns the last `Waker` passed to `register`, so that the user can wake it.
+    ///
+    /// If a waker has not been registered, this returns `None`.
+    #[inline]
+    pub fn take(&self) -> Option<Waker> {
+        self.waker.take()
+    }
+}
+
+impl fmt::Debug for LocalWaker {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "LocalWaker")
+    }
+}
+
\ No newline at end of file diff --git a/static.files/COPYRIGHT-23e9bde6c69aea69.txt b/static.files/COPYRIGHT-23e9bde6c69aea69.txt new file mode 100644 index 00000000..1447df79 --- /dev/null +++ b/static.files/COPYRIGHT-23e9bde6c69aea69.txt @@ -0,0 +1,50 @@ +# REUSE-IgnoreStart + +These documentation pages include resources by third parties. This copyright +file applies only to those resources. The following third party resources are +included, and carry their own copyright notices and license terms: + +* Fira Sans (FiraSans-Regular.woff2, FiraSans-Medium.woff2): + + Copyright (c) 2014, Mozilla Foundation https://mozilla.org/ + with Reserved Font Name Fira Sans. + + Copyright (c) 2014, Telefonica S.A. + + Licensed under the SIL Open Font License, Version 1.1. + See FiraSans-LICENSE.txt. + +* rustdoc.css, main.js, and playpen.js: + + Copyright 2015 The Rust Developers. + Licensed under the Apache License, Version 2.0 (see LICENSE-APACHE.txt) or + the MIT license (LICENSE-MIT.txt) at your option. + +* normalize.css: + + Copyright (c) Nicolas Gallagher and Jonathan Neal. + Licensed under the MIT license (see LICENSE-MIT.txt). + +* Source Code Pro (SourceCodePro-Regular.ttf.woff2, + SourceCodePro-Semibold.ttf.woff2, SourceCodePro-It.ttf.woff2): + + Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), + with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark + of Adobe Systems Incorporated in the United States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceCodePro-LICENSE.txt. + +* Source Serif 4 (SourceSerif4-Regular.ttf.woff2, SourceSerif4-Bold.ttf.woff2, + SourceSerif4-It.ttf.woff2): + + Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name + 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United + States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceSerif4-LICENSE.md. + +This copyright file is intended to be distributed with rustdoc output. + +# REUSE-IgnoreEnd diff --git a/static.files/FiraSans-LICENSE-db4b642586e02d97.txt b/static.files/FiraSans-LICENSE-db4b642586e02d97.txt new file mode 100644 index 00000000..d7e9c149 --- /dev/null +++ b/static.files/FiraSans-LICENSE-db4b642586e02d97.txt @@ -0,0 +1,98 @@ +// REUSE-IgnoreStart + +Digitized data copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A. +with Reserved Font Name < Fira >, + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 b/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 new file mode 100644 index 00000000..7a1e5fc5 Binary files /dev/null and b/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 differ diff --git a/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 b/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 new file mode 100644 index 00000000..e766e06c Binary files /dev/null and b/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 differ diff --git a/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt b/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/static.files/LICENSE-MIT-65090b722b3f6c56.txt b/static.files/LICENSE-MIT-65090b722b3f6c56.txt new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/static.files/LICENSE-MIT-65090b722b3f6c56.txt @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 b/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 new file mode 100644 index 00000000..1866ad4b Binary files /dev/null and b/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 differ diff --git a/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt b/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt new file mode 100644 index 00000000..4b3edc29 --- /dev/null +++ b/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt @@ -0,0 +1,103 @@ +// REUSE-IgnoreStart + +Copyright (c) 2010, NAVER Corporation (https://www.navercorp.com/), + +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver NanumGothic, +NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver NanumBrush, NanumPen, +Naver NanumPen, Naver NanumGothicEco, NanumGothicEco, Naver NanumMyeongjoEco, +NanumMyeongjoEco, Naver NanumGothicLight, NanumGothicLight, NanumBarunGothic, +Naver NanumBarunGothic, NanumSquareRound, NanumBarunPen, MaruBuri + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 b/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 new file mode 100644 index 00000000..462c34ef Binary files /dev/null and b/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 differ diff --git a/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt b/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt new file mode 100644 index 00000000..0d2941e1 --- /dev/null +++ b/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt @@ -0,0 +1,97 @@ +// REUSE-IgnoreStart + +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 b/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 new file mode 100644 index 00000000..10b558e0 Binary files /dev/null and b/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 differ diff --git a/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 b/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 new file mode 100644 index 00000000..5ec64eef Binary files /dev/null and b/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 differ diff --git a/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 b/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 new file mode 100644 index 00000000..181a07f6 Binary files /dev/null and b/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 differ diff --git a/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 b/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 new file mode 100644 index 00000000..2ae08a7b Binary files /dev/null and b/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 differ diff --git a/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md b/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md new file mode 100644 index 00000000..175fa4f4 --- /dev/null +++ b/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md @@ -0,0 +1,98 @@ + + +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. +Copyright 2014 - 2023 Adobe (http://www.adobe.com/), with Reserved Font Name โ€˜Sourceโ€™. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + diff --git a/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 b/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 new file mode 100644 index 00000000..0263fc30 Binary files /dev/null and b/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 differ diff --git a/static.files/favicon-2c020d218678b618.svg b/static.files/favicon-2c020d218678b618.svg new file mode 100644 index 00000000..8b34b511 --- /dev/null +++ b/static.files/favicon-2c020d218678b618.svg @@ -0,0 +1,24 @@ + + + + + diff --git a/static.files/favicon-32x32-422f7d1d52889060.png b/static.files/favicon-32x32-422f7d1d52889060.png new file mode 100644 index 00000000..69b8613c Binary files /dev/null and b/static.files/favicon-32x32-422f7d1d52889060.png differ diff --git a/static.files/main-54bc299d2a5e4e43.js b/static.files/main-54bc299d2a5e4e43.js new file mode 100644 index 00000000..b4f20a41 --- /dev/null +++ b/static.files/main-54bc299d2a5e4e43.js @@ -0,0 +1,11 @@ +"use strict";window.RUSTDOC_TOOLTIP_HOVER_MS=300;window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS=450;function resourcePath(basename,extension){return getVar("root-path")+basename+getVar("resource-suffix")+extension}function hideMain(){addClass(document.getElementById(MAIN_ID),"hidden");const toggle=document.getElementById("toggle-all-docs");if(toggle){toggle.setAttribute("disabled","disabled")}}function showMain(){const main=document.getElementById(MAIN_ID);removeClass(main,"hidden");const mainHeading=main.querySelector(".main-heading");if(mainHeading&&searchState.rustdocToolbar){if(searchState.rustdocToolbar.parentElement){searchState.rustdocToolbar.parentElement.removeChild(searchState.rustdocToolbar)}mainHeading.appendChild(searchState.rustdocToolbar)}const toggle=document.getElementById("toggle-all-docs");if(toggle){toggle.removeAttribute("disabled")}}window.rootPath=getVar("root-path");window.currentCrate=getVar("current-crate");function setMobileTopbar(){const mobileTopbar=document.querySelector(".mobile-topbar");const locationTitle=document.querySelector(".sidebar h2.location");if(mobileTopbar){const mobileTitle=document.createElement("h2");mobileTitle.className="location";if(hasClass(document.querySelector(".rustdoc"),"crate")){mobileTitle.innerHTML=`Crate ${window.currentCrate}`}else if(locationTitle){mobileTitle.innerHTML=locationTitle.innerHTML}mobileTopbar.appendChild(mobileTitle)}}function getVirtualKey(ev){if("key"in ev&&typeof ev.key!=="undefined"){return ev.key}const c=ev.charCode||ev.keyCode;if(c===27){return"Escape"}return String.fromCharCode(c)}const MAIN_ID="main-content";const SETTINGS_BUTTON_ID="settings-menu";const ALTERNATIVE_DISPLAY_ID="alternative-display";const NOT_DISPLAYED_ID="not-displayed";const HELP_BUTTON_ID="help-button";function getSettingsButton(){return document.getElementById(SETTINGS_BUTTON_ID)}function getHelpButton(){return document.getElementById(HELP_BUTTON_ID)}function getNakedUrl(){return window.location.href.split("?")[0].split("#")[0]}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}function getOrCreateSection(id,classes){let el=document.getElementById(id);if(!el){el=document.createElement("section");el.id=id;el.className=classes;insertAfter(el,document.getElementById(MAIN_ID))}return el}function getAlternativeDisplayElem(){return getOrCreateSection(ALTERNATIVE_DISPLAY_ID,"content hidden")}function getNotDisplayedElem(){return getOrCreateSection(NOT_DISPLAYED_ID,"hidden")}function switchDisplayedElement(elemToDisplay){const el=getAlternativeDisplayElem();if(el.children.length>0){getNotDisplayedElem().appendChild(el.firstElementChild)}if(elemToDisplay===null){addClass(el,"hidden");showMain();return}el.appendChild(elemToDisplay);hideMain();removeClass(el,"hidden");const mainHeading=elemToDisplay.querySelector(".main-heading");if(mainHeading&&searchState.rustdocToolbar){if(searchState.rustdocToolbar.parentElement){searchState.rustdocToolbar.parentElement.removeChild(searchState.rustdocToolbar)}mainHeading.appendChild(searchState.rustdocToolbar)}}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}function preLoadCss(cssUrl){const link=document.createElement("link");link.href=cssUrl;link.rel="preload";link.as="style";document.getElementsByTagName("head")[0].appendChild(link)}(function(){const isHelpPage=window.location.pathname.endsWith("/help.html");function loadScript(url,errorCallback){const script=document.createElement("script");script.src=url;if(errorCallback!==undefined){script.onerror=errorCallback}document.head.append(script)}if(getSettingsButton()){getSettingsButton().onclick=event=>{if(event.ctrlKey||event.altKey||event.metaKey){return}window.hideAllModals(false);addClass(getSettingsButton(),"rotate");event.preventDefault();loadScript(getVar("static-root-path")+getVar("settings-js"));setTimeout(()=>{const themes=getVar("themes").split(",");for(const theme of themes){if(theme!==""){preLoadCss(getVar("root-path")+theme+".css")}}},0)}}window.searchState={rustdocToolbar:document.querySelector("rustdoc-toolbar"),loadingText:"Loading search results...",input:document.getElementsByClassName("search-input")[0],outputElement:()=>{let el=document.getElementById("search");if(!el){el=document.createElement("section");el.id="search";getNotDisplayedElem().appendChild(el)}return el},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:()=>{if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},isDisplayed:()=>searchState.outputElement().parentElement.id===ALTERNATIVE_DISPLAY_ID,focus:()=>{searchState.input.focus()},defocus:()=>{searchState.input.blur()},showResults:search=>{if(search===null||typeof search==="undefined"){search=searchState.outputElement()}switchDisplayedElement(search);searchState.mouseMovedAfterSearch=false;document.title=searchState.title},removeQueryParameters:()=>{document.title=searchState.titleBeforeSearch;if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.hash)}},hideResults:()=>{switchDisplayedElement(null);searchState.removeQueryParameters()},getQueryStringParams:()=>{const params={};window.location.search.substring(1).split("&").map(s=>{const pair=s.split("=").map(x=>x.replace(/\+/g," "));params[decodeURIComponent(pair[0])]=typeof pair[1]==="undefined"?null:decodeURIComponent(pair[1])});return params},setup:()=>{const search_input=searchState.input;if(!searchState.input){return}let searchLoaded=false;function sendSearchForm(){document.getElementsByClassName("search-form")[0].submit()}function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(getVar("static-root-path")+getVar("search-js"),sendSearchForm);loadScript(resourcePath("search-index",".js"),sendSearchForm)}}search_input.addEventListener("focus",()=>{search_input.origPlaceholder=search_input.placeholder;search_input.placeholder="Type your search here.";loadSearch()});if(search_input.value!==""){loadSearch()}const params=searchState.getQueryStringParams();if(params.search!==undefined){searchState.setLoadingSearch();loadSearch()}},setLoadingSearch:()=>{const search=searchState.outputElement();search.innerHTML="

"+searchState.loadingText+"

";searchState.showResults(search)},descShards:new Map(),loadDesc:async function({descShard,descIndex}){if(descShard.promise===null){descShard.promise=new Promise((resolve,reject)=>{descShard.resolve=resolve;const ds=descShard;const fname=`${ds.crate}-desc-${ds.shard}-`;const url=resourcePath(`search.desc/${descShard.crate}/${fname}`,".js",);loadScript(url,reject)})}const list=await descShard.promise;return list[descIndex]},loadedDescShard:function(crate,shard,data){this.descShards.get(crate)[shard].resolve(data.split("\n"))},};const toggleAllDocsId="toggle-all-docs";let savedHash="";function handleHashes(ev){if(ev!==null&&searchState.isDisplayed()&&ev.newURL){switchDisplayedElement(null);const hash=ev.newURL.slice(ev.newURL.indexOf("#")+1);if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.search+"#"+hash)}const elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}const pageId=window.location.hash.replace(/^#/,"");if(savedHash!==pageId){savedHash=pageId;if(pageId!==""){expandSection(pageId)}}if(savedHash.startsWith("impl-")){const splitAt=savedHash.indexOf("/");if(splitAt!==-1){const implId=savedHash.slice(0,splitAt);const assocId=savedHash.slice(splitAt+1);const implElems=document.querySelectorAll(`details > summary > section[id^="${implId}"]`,);onEachLazy(implElems,implElem=>{const numbered=/^(.+?)-([0-9]+)$/.exec(implElem.id);if(implElem.id!==implId&&(!numbered||numbered[1]!==implId)){return false}return onEachLazy(implElem.parentElement.parentElement.querySelectorAll(`[id^="${assocId}"]`),item=>{const numbered=/^(.+?)-([0-9]+)$/.exec(item.id);if(item.id===assocId||(numbered&&numbered[1]===assocId)){openParentDetails(item);item.scrollIntoView();setTimeout(()=>{window.location.replace("#"+item.id)},0);return true}},)})}}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName==="DETAILS"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function handleEscape(ev){searchState.clearInputTimeout();searchState.hideResults();ev.preventDefault();searchState.defocus();window.hideAllModals(true)}function handleShortcut(ev){const disableShortcuts=getSettingValue("disable-shortcuts")==="true";if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName==="INPUT"&&document.activeElement.type!=="checkbox"&&document.activeElement.type!=="radio"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break;case"s":case"S":case"/":ev.preventDefault();searchState.focus();break;case"+":ev.preventDefault();expandAllDocs();break;case"-":ev.preventDefault();collapseAllDocs();break;case"?":showHelp();break;default:break}}}document.addEventListener("keypress",handleShortcut);document.addEventListener("keydown",handleShortcut);function addSidebarItems(){if(!window.SIDEBAR_ITEMS){return}const sidebar=document.getElementById("rustdoc-modnav");function block(shortty,id,longty){const filtered=window.SIDEBAR_ITEMS[shortty];if(!filtered){return}const modpath=hasClass(document.querySelector(".rustdoc"),"mod")?"../":"";const h3=document.createElement("h3");h3.innerHTML=`${longty}`;const ul=document.createElement("ul");ul.className="block "+shortty;for(const name of filtered){let path;if(shortty==="mod"){path=`${modpath}${name}/index.html`}else{path=`${modpath}${shortty}.${name}.html`}let current_page=document.location.href.toString();if(current_page.endsWith("/")){current_page+="index.html"}const link=document.createElement("a");link.href=path;link.textContent=name;const li=document.createElement("li");if(link.href===current_page){li.classList.add("current")}li.appendChild(link);ul.appendChild(li)}sidebar.appendChild(h3);sidebar.appendChild(ul)}if(sidebar){block("primitive","primitives","Primitive Types");block("mod","modules","Modules");block("macro","macros","Macros");block("struct","structs","Structs");block("enum","enums","Enums");block("constant","constants","Constants");block("static","static","Statics");block("trait","traits","Traits");block("fn","functions","Functions");block("type","types","Type Aliases");block("union","unions","Unions");block("foreigntype","foreign-types","Foreign Types");block("keyword","keywords","Keywords");block("attr","attributes","Attribute Macros");block("derive","derives","Derive Macros");block("traitalias","trait-aliases","Trait Aliases")}}window.register_implementors=imp=>{const implementors=document.getElementById("implementors-list");const synthetic_implementors=document.getElementById("synthetic-implementors-list");const inlined_types=new Set();const TEXT_IDX=0;const SYNTHETIC_IDX=1;const TYPES_IDX=2;if(synthetic_implementors){onEachLazy(synthetic_implementors.getElementsByClassName("impl"),el=>{const aliases=el.getAttribute("data-aliases");if(!aliases){return}aliases.split(",").forEach(alias=>{inlined_types.add(alias)})})}let currentNbImpls=implementors.getElementsByClassName("impl").length;const traitName=document.querySelector(".main-heading h1 > .trait").textContent;const baseIdName="impl-"+traitName+"-";const libs=Object.getOwnPropertyNames(imp);const script=document.querySelector("script[data-ignore-extern-crates]");const ignoreExternCrates=new Set((script?script.getAttribute("data-ignore-extern-crates"):"").split(","),);for(const lib of libs){if(lib===window.currentCrate||ignoreExternCrates.has(lib)){continue}const structs=imp[lib];struct_loop:for(const struct of structs){const list=struct[SYNTHETIC_IDX]?synthetic_implementors:implementors;if(struct[SYNTHETIC_IDX]){for(const struct_type of struct[TYPES_IDX]){if(inlined_types.has(struct_type)){continue struct_loop}inlined_types.add(struct_type)}}const code=document.createElement("h3");code.innerHTML=struct[TEXT_IDX];addClass(code,"code-header");onEachLazy(code.getElementsByTagName("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});const currentId=baseIdName+currentNbImpls;const anchor=document.createElement("a");anchor.href="#"+currentId;addClass(anchor,"anchor");const display=document.createElement("div");display.id=currentId;addClass(display,"impl");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}window.register_type_impls=imp=>{if(!imp||!imp[window.currentCrate]){return}window.pending_type_impls=null;const idMap=new Map();let implementations=document.getElementById("implementations-list");let trait_implementations=document.getElementById("trait-implementations-list");let trait_implementations_header=document.getElementById("trait-implementations");const script=document.querySelector("script[data-self-path]");const selfPath=script?script.getAttribute("data-self-path"):null;const mainContent=document.querySelector("#main-content");const sidebarSection=document.querySelector(".sidebar section");let methods=document.querySelector(".sidebar .block.method");let associatedTypes=document.querySelector(".sidebar .block.associatedtype");let associatedConstants=document.querySelector(".sidebar .block.associatedconstant");let sidebarTraitList=document.querySelector(".sidebar .block.trait-implementation");for(const impList of imp[window.currentCrate]){const types=impList.slice(2);const text=impList[0];const isTrait=impList[1]!==0;const traitName=impList[1];if(types.indexOf(selfPath)===-1){continue}let outputList=isTrait?trait_implementations:implementations;if(outputList===null){const outputListName=isTrait?"Trait Implementations":"Implementations";const outputListId=isTrait?"trait-implementations-list":"implementations-list";const outputListHeaderId=isTrait?"trait-implementations":"implementations";const outputListHeader=document.createElement("h2");outputListHeader.id=outputListHeaderId;outputListHeader.innerText=outputListName;outputList=document.createElement("div");outputList.id=outputListId;if(isTrait){const link=document.createElement("a");link.href=`#${outputListHeaderId}`;link.innerText="Trait Implementations";const h=document.createElement("h3");h.appendChild(link);trait_implementations=outputList;trait_implementations_header=outputListHeader;sidebarSection.appendChild(h);sidebarTraitList=document.createElement("ul");sidebarTraitList.className="block trait-implementation";sidebarSection.appendChild(sidebarTraitList);mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}else{implementations=outputList;if(trait_implementations){mainContent.insertBefore(outputListHeader,trait_implementations_header);mainContent.insertBefore(outputList,trait_implementations_header)}else{const mainContent=document.querySelector("#main-content");mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}}}const template=document.createElement("template");template.innerHTML=text;onEachLazy(template.content.querySelectorAll("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});onEachLazy(template.content.querySelectorAll("[id]"),el=>{let i=0;if(idMap.has(el.id)){i=idMap.get(el.id)}else if(document.getElementById(el.id)){i=1;while(document.getElementById(`${el.id}-${2 * i}`)){i=2*i}while(document.getElementById(`${el.id}-${i}`)){i+=1}}if(i!==0){const oldHref=`#${el.id}`;const newHref=`#${el.id}-${i}`;el.id=`${el.id}-${i}`;onEachLazy(template.content.querySelectorAll("a[href]"),link=>{if(link.getAttribute("href")===oldHref){link.href=newHref}})}idMap.set(el.id,i+1)});const templateAssocItems=template.content.querySelectorAll("section.tymethod, "+"section.method, section.associatedtype, section.associatedconstant");if(isTrait){const li=document.createElement("li");const a=document.createElement("a");a.href=`#${template.content.querySelector(".impl").id}`;a.textContent=traitName;li.appendChild(a);sidebarTraitList.append(li)}else{onEachLazy(templateAssocItems,item=>{let block=hasClass(item,"associatedtype")?associatedTypes:(hasClass(item,"associatedconstant")?associatedConstants:(methods));if(!block){const blockTitle=hasClass(item,"associatedtype")?"Associated Types":(hasClass(item,"associatedconstant")?"Associated Constants":("Methods"));const blockClass=hasClass(item,"associatedtype")?"associatedtype":(hasClass(item,"associatedconstant")?"associatedconstant":("method"));const blockHeader=document.createElement("h3");const blockLink=document.createElement("a");blockLink.href="#implementations";blockLink.innerText=blockTitle;blockHeader.appendChild(blockLink);block=document.createElement("ul");block.className=`block ${blockClass}`;const insertionReference=methods||sidebarTraitList;if(insertionReference){const insertionReferenceH=insertionReference.previousElementSibling;sidebarSection.insertBefore(blockHeader,insertionReferenceH);sidebarSection.insertBefore(block,insertionReferenceH)}else{sidebarSection.appendChild(blockHeader);sidebarSection.appendChild(block)}if(hasClass(item,"associatedtype")){associatedTypes=block}else if(hasClass(item,"associatedconstant")){associatedConstants=block}else{methods=block}}const li=document.createElement("li");const a=document.createElement("a");a.innerText=item.id.split("-")[0].split(".")[1];a.href=`#${item.id}`;li.appendChild(a);block.appendChild(li)})}outputList.appendChild(template.content)}for(const list of[methods,associatedTypes,associatedConstants,sidebarTraitList]){if(!list){continue}const newChildren=Array.prototype.slice.call(list.children);newChildren.sort((a,b)=>{const aI=a.innerText;const bI=b.innerText;return aIbI?1:0});list.replaceChildren(...newChildren)}};if(window.pending_type_impls){window.register_type_impls(window.pending_type_impls)}function addSidebarCrates(){if(!window.ALL_CRATES){return}const sidebarElems=document.getElementById("rustdoc-modnav");if(!sidebarElems){return}const h3=document.createElement("h3");h3.innerHTML="Crates";const ul=document.createElement("ul");ul.className="block crate";for(const crate of window.ALL_CRATES){const link=document.createElement("a");link.href=window.rootPath+crate+"/index.html";link.textContent=crate;const li=document.createElement("li");if(window.rootPath!=="./"&&crate===window.currentCrate){li.className="current"}li.appendChild(link);ul.appendChild(li)}sidebarElems.appendChild(h3);sidebarElems.appendChild(ul)}function expandAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);removeClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hasClass(e,"type-contents-toggle")&&!hasClass(e,"more-examples-toggle")){e.open=true}});innerToggle.children[0].innerText="Summary"}function collapseAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);addClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(e.parentNode.id!=="implementations-list"||(!hasClass(e,"implementors-toggle")&&!hasClass(e,"type-contents-toggle"))){e.open=false}});innerToggle.children[0].innerText="Show all"}function toggleAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}if(hasClass(innerToggle,"will-expand")){expandAllDocs()}else{collapseAllDocs()}}(function(){const toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}const hideMethodDocs=getSettingValue("auto-hide-method-docs")==="true";const hideImplementations=getSettingValue("auto-hide-trait-implementations")==="true";const hideLargeItemContents=getSettingValue("auto-hide-large-items")!=="false";function setImplementorsTogglesOpen(id,open){const list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName("implementors-toggle"),e=>{e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen("trait-implementations-list",false);setImplementorsTogglesOpen("blanket-implementations-list",false)}onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hideLargeItemContents&&hasClass(e,"type-contents-toggle")){e.open=true}if(hideMethodDocs&&hasClass(e,"method-toggle")){e.open=false}})}());window.rustdoc_add_line_numbers_to_examples=()=>{if(document.querySelector(".rustdoc.src")){return}onEachLazy(document.querySelectorAll(":not(.scraped-example) > .example-wrap > pre:not(.example-line-numbers)",),x=>{const parent=x.parentNode;const line_numbers=parent.querySelectorAll(".example-line-numbers");if(line_numbers.length>0){return}const count=x.textContent.split("\n").length;const elems=[];for(let i=0;i{onEachLazy(document.querySelectorAll(".example-wrap > .example-line-numbers"),x=>{x.parentNode.removeChild(x)})};if(getSettingValue("line-numbers")==="true"){window.rustdoc_add_line_numbers_to_examples()}function showSidebar(){window.hideAllModals(false);const sidebar=document.getElementsByClassName("sidebar")[0];addClass(sidebar,"shown")}function hideSidebar(){const sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"shown")}window.addEventListener("resize",()=>{if(window.CURRENT_TOOLTIP_ELEMENT){const base=window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE;const force_visible=base.TOOLTIP_FORCE_VISIBLE;hideTooltip(false);if(force_visible){showTooltip(base);base.TOOLTIP_FORCE_VISIBLE=true}}});const mainElem=document.getElementById(MAIN_ID);if(mainElem){mainElem.addEventListener("click",hideSidebar)}onEachLazy(document.querySelectorAll("a[href^='#']"),el=>{el.addEventListener("click",()=>{expandSection(el.hash.slice(1));hideSidebar()})});onEachLazy(document.querySelectorAll(".toggle > summary:not(.hideme)"),el=>{el.addEventListener("click",e=>{if(e.target.tagName!=="SUMMARY"&&e.target.tagName!=="A"){e.preventDefault()}})});function showTooltip(e){const notable_ty=e.getAttribute("data-notable-ty");if(!window.NOTABLE_TRAITS&¬able_ty){const data=document.getElementById("notable-traits-data");if(data){window.NOTABLE_TRAITS=JSON.parse(data.innerText)}else{throw new Error("showTooltip() called with notable without any notable traits!")}}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE===e){clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);return}window.hideAllModals(false);const wrapper=document.createElement("div");if(notable_ty){wrapper.innerHTML="
"+window.NOTABLE_TRAITS[notable_ty]+"
"}else{if(e.getAttribute("title")!==null){e.setAttribute("data-title",e.getAttribute("title"));e.removeAttribute("title")}if(e.getAttribute("data-title")!==null){const titleContent=document.createElement("div");titleContent.className="content";titleContent.appendChild(document.createTextNode(e.getAttribute("data-title")));wrapper.appendChild(titleContent)}}wrapper.className="tooltip popover";const focusCatcher=document.createElement("div");focusCatcher.setAttribute("tabindex","0");focusCatcher.onfocus=hideTooltip;wrapper.appendChild(focusCatcher);const pos=e.getBoundingClientRect();wrapper.style.top=(pos.top+window.scrollY+pos.height)+"px";wrapper.style.left=0;wrapper.style.right="auto";wrapper.style.visibility="hidden";document.body.appendChild(wrapper);const wrapperPos=wrapper.getBoundingClientRect();const finalPos=pos.left+window.scrollX-wrapperPos.width+24;if(finalPos>0){wrapper.style.left=finalPos+"px"}else{wrapper.style.setProperty("--popover-arrow-offset",(wrapperPos.right-pos.right+4)+"px",)}wrapper.style.visibility="";window.CURRENT_TOOLTIP_ELEMENT=wrapper;window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE=e;clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);wrapper.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}clearTooltipHoverTimeout(e)};wrapper.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&!e.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(wrapper,"fade-out")}}}function setTooltipHoverTimeout(element,show){clearTooltipHoverTimeout(element);if(!show&&!window.CURRENT_TOOLTIP_ELEMENT){return}if(show&&window.CURRENT_TOOLTIP_ELEMENT){return}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE!==element){return}element.TOOLTIP_HOVER_TIMEOUT=setTimeout(()=>{if(show){showTooltip(element)}else if(!element.TOOLTIP_FORCE_VISIBLE){hideTooltip(false)}},show?window.RUSTDOC_TOOLTIP_HOVER_MS:window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS)}function clearTooltipHoverTimeout(element){if(element.TOOLTIP_HOVER_TIMEOUT!==undefined){removeClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out");clearTimeout(element.TOOLTIP_HOVER_TIMEOUT);delete element.TOOLTIP_HOVER_TIMEOUT}}function tooltipBlurHandler(event){if(window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.contains(event.relatedTarget)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(event.relatedTarget)){setTimeout(()=>hideTooltip(false),0)}}function hideTooltip(focus){if(window.CURRENT_TOOLTIP_ELEMENT){if(window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE){if(focus){window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.focus()}window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE=false}document.body.removeChild(window.CURRENT_TOOLTIP_ELEMENT);clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);window.CURRENT_TOOLTIP_ELEMENT=null}}onEachLazy(document.getElementsByClassName("tooltip"),e=>{e.onclick=()=>{e.TOOLTIP_FORCE_VISIBLE=e.TOOLTIP_FORCE_VISIBLE?false:true;if(window.CURRENT_TOOLTIP_ELEMENT&&!e.TOOLTIP_FORCE_VISIBLE){hideTooltip(true)}else{showTooltip(e);window.CURRENT_TOOLTIP_ELEMENT.setAttribute("tabindex","0");window.CURRENT_TOOLTIP_ELEMENT.focus();window.CURRENT_TOOLTIP_ELEMENT.onblur=tooltipBlurHandler}return false};e.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointermove=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out")}}});const sidebar_menu_toggle=document.getElementsByClassName("sidebar-menu-toggle")[0];if(sidebar_menu_toggle){sidebar_menu_toggle.addEventListener("click",()=>{const sidebar=document.getElementsByClassName("sidebar")[0];if(!hasClass(sidebar,"shown")){showSidebar()}else{hideSidebar()}})}function helpBlurHandler(event){if(!getHelpButton().contains(document.activeElement)&&!getHelpButton().contains(event.relatedTarget)&&!getSettingsButton().contains(document.activeElement)&&!getSettingsButton().contains(event.relatedTarget)){window.hidePopoverMenus()}}function buildHelpMenu(){const book_info=document.createElement("span");const channel=getVar("channel");book_info.className="top";book_info.innerHTML=`You can find more information in \ +the rustdoc book.`;const shortcuts=[["?","Show this help dialog"],["S / /","Focus the search field"],["โ†‘","Move up in search results"],["โ†“","Move down in search results"],["โ† / โ†’","Switch result tab (when results focused)"],["⏎","Go to active search result"],["+","Expand all sections"],["-","Collapse all sections"],].map(x=>"
"+x[0].split(" ").map((y,index)=>((index&1)===0?""+y+"":" "+y+" ")).join("")+"
"+x[1]+"
").join("");const div_shortcuts=document.createElement("div");addClass(div_shortcuts,"shortcuts");div_shortcuts.innerHTML="

Keyboard Shortcuts

"+shortcuts+"
";const infos=[`For a full list of all search features, take a look here.`,"Prefix searches with a type followed by a colon (e.g., fn:) to \ + restrict the search to a given item kind.","Accepted kinds are: fn, mod, struct, \ + enum, trait, type, macro, \ + and const.","Search functions by type signature (e.g., vec -> usize or \ + -> vec or String, enum:Cow -> bool)","You can look for items with an exact name by putting double quotes around \ + your request: \"string\"","Look for functions that accept or return \ + slices and \ + arrays by writing \ + square brackets (e.g., -> [u8] or [] -> Option)","Look for items inside another one by searching for a path: vec::Vec",].map(x=>"

"+x+"

").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="

Search Tricks

"+infos;const rustdoc_version=document.createElement("span");rustdoc_version.className="bottom";const rustdoc_version_code=document.createElement("code");rustdoc_version_code.innerText="rustdoc "+getVar("rustdoc-version");rustdoc_version.appendChild(rustdoc_version_code);const container=document.createElement("div");if(!isHelpPage){container.className="popover"}container.id="help";container.style.display="none";const side_by_side=document.createElement("div");side_by_side.className="side-by-side";side_by_side.appendChild(div_shortcuts);side_by_side.appendChild(div_infos);container.appendChild(book_info);container.appendChild(side_by_side);container.appendChild(rustdoc_version);if(isHelpPage){const help_section=document.createElement("section");help_section.appendChild(container);document.getElementById("main-content").appendChild(help_section);container.style.display="block"}else{const help_button=getHelpButton();help_button.appendChild(container);container.onblur=helpBlurHandler;help_button.onblur=helpBlurHandler;help_button.children[0].onblur=helpBlurHandler}return container}window.hideAllModals=switchFocus=>{hideSidebar();window.hidePopoverMenus();hideTooltip(switchFocus)};window.hidePopoverMenus=()=>{onEachLazy(document.querySelectorAll("rustdoc-toolbar .popover"),elem=>{elem.style.display="none"});const button=getHelpButton();if(button){removeClass(button,"help-open")}};function getHelpMenu(buildNeeded){let menu=getHelpButton().querySelector(".popover");if(!menu&&buildNeeded){menu=buildHelpMenu()}return menu}function showHelp(){const button=getHelpButton();addClass(button,"help-open");button.querySelector("a").focus();const menu=getHelpMenu(true);if(menu.style.display==="none"){window.hideAllModals();menu.style.display=""}}const helpLink=document.querySelector(`#${HELP_BUTTON_ID} > a`);if(isHelpPage){buildHelpMenu()}else if(helpLink){helpLink.addEventListener("click",event=>{if(!helpLink.contains(helpLink)||event.ctrlKey||event.altKey||event.metaKey){return}event.preventDefault();const menu=getHelpMenu(true);const shouldShowHelp=menu.style.display==="none";if(shouldShowHelp){showHelp()}else{window.hidePopoverMenus()}})}setMobileTopbar();addSidebarItems();addSidebarCrates();onHashChange(null);window.addEventListener("hashchange",onHashChange);searchState.setup()}());(function(){const SIDEBAR_MIN=100;const SIDEBAR_MAX=500;const RUSTDOC_MOBILE_BREAKPOINT=700;const BODY_MIN=400;const SIDEBAR_VANISH_THRESHOLD=SIDEBAR_MIN/2;const sidebarButton=document.getElementById("sidebar-button");if(sidebarButton){sidebarButton.addEventListener("click",e=>{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false");if(document.querySelector(".rustdoc.src")){window.rustdocToggleSrcSidebar()}e.preventDefault()})}let currentPointerId=null;let desiredSidebarSize=null;let pendingSidebarResizingFrame=false;const resizer=document.querySelector(".sidebar-resizer");const sidebar=document.querySelector(".sidebar");if(!resizer||!sidebar){return}const isSrcPage=hasClass(document.body,"src");function hideSidebar(){if(isSrcPage){window.rustdocCloseSourceSidebar();updateLocalStorage("src-sidebar-width",null);document.documentElement.style.removeProperty("--src-sidebar-width");sidebar.style.removeProperty("--src-sidebar-width");resizer.style.removeProperty("--src-sidebar-width")}else{addClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","true");updateLocalStorage("desktop-sidebar-width",null);document.documentElement.style.removeProperty("--desktop-sidebar-width");sidebar.style.removeProperty("--desktop-sidebar-width");resizer.style.removeProperty("--desktop-sidebar-width")}}function showSidebar(){if(isSrcPage){window.rustdocShowSourceSidebar()}else{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false")}}function changeSidebarSize(size){if(isSrcPage){updateLocalStorage("src-sidebar-width",size);sidebar.style.setProperty("--src-sidebar-width",size+"px");resizer.style.setProperty("--src-sidebar-width",size+"px")}else{updateLocalStorage("desktop-sidebar-width",size);sidebar.style.setProperty("--desktop-sidebar-width",size+"px");resizer.style.setProperty("--desktop-sidebar-width",size+"px")}}function isSidebarHidden(){return isSrcPage?!hasClass(document.documentElement,"src-sidebar-expanded"):hasClass(document.documentElement,"hide-sidebar")}function resize(e){if(currentPointerId===null||currentPointerId!==e.pointerId){return}e.preventDefault();const pos=e.clientX-3;if(pos=SIDEBAR_MIN){if(isSidebarHidden()){showSidebar()}const constrainedPos=Math.min(pos,window.innerWidth-BODY_MIN,SIDEBAR_MAX);changeSidebarSize(constrainedPos);desiredSidebarSize=constrainedPos;if(pendingSidebarResizingFrame!==false){clearTimeout(pendingSidebarResizingFrame)}pendingSidebarResizingFrame=setTimeout(()=>{if(currentPointerId===null||pendingSidebarResizingFrame===false){return}pendingSidebarResizingFrame=false;document.documentElement.style.setProperty("--resizing-sidebar-width",desiredSidebarSize+"px",)},100)}}window.addEventListener("resize",()=>{if(window.innerWidth=(window.innerWidth-BODY_MIN)){changeSidebarSize(window.innerWidth-BODY_MIN)}else if(desiredSidebarSize!==null&&desiredSidebarSize>SIDEBAR_MIN){changeSidebarSize(desiredSidebarSize)}});function stopResize(e){if(currentPointerId===null){return}if(e){e.preventDefault()}desiredSidebarSize=sidebar.getBoundingClientRect().width;removeClass(resizer,"active");window.removeEventListener("pointermove",resize,false);window.removeEventListener("pointerup",stopResize,false);removeClass(document.documentElement,"sidebar-resizing");document.documentElement.style.removeProperty("--resizing-sidebar-width");if(resizer.releasePointerCapture){resizer.releasePointerCapture(currentPointerId);currentPointerId=null}}function initResize(e){if(currentPointerId!==null||e.altKey||e.ctrlKey||e.metaKey||e.button!==0){return}if(resizer.setPointerCapture){resizer.setPointerCapture(e.pointerId);if(!resizer.hasPointerCapture(e.pointerId)){resizer.releasePointerCapture(e.pointerId);return}currentPointerId=e.pointerId}window.hideAllModals(false);e.preventDefault();window.addEventListener("pointermove",resize,false);window.addEventListener("pointercancel",stopResize,false);window.addEventListener("pointerup",stopResize,false);addClass(resizer,"active");addClass(document.documentElement,"sidebar-resizing");const pos=e.clientX-sidebar.offsetLeft-3;document.documentElement.style.setProperty("--resizing-sidebar-width",pos+"px");desiredSidebarSize=null}resizer.addEventListener("pointerdown",initResize,false)}());(function(){function copyContentToClipboard(content){const el=document.createElement("textarea");el.value=content;el.setAttribute("readonly","");el.style.position="absolute";el.style.left="-9999px";document.body.appendChild(el);el.select();document.execCommand("copy");document.body.removeChild(el)}function copyButtonAnimation(button){button.classList.add("clicked");if(button.reset_button_timeout!==undefined){window.clearTimeout(button.reset_button_timeout)}button.reset_button_timeout=window.setTimeout(()=>{button.reset_button_timeout=undefined;button.classList.remove("clicked")},1000)}const but=document.getElementById("copy-path");if(!but){return}but.onclick=()=>{const path=[];onEachLazy(document.querySelectorAll(".rustdoc-breadcrumbs a"),a=>{path.push(a.textContent)});path.push(document.querySelector("title").textContent.split(" ")[0]);copyContentToClipboard(path.join("::"));copyButtonAnimation(but)};function copyCode(codeElem){if(!codeElem){return}copyContentToClipboard(codeElem.textContent)}function getExampleWrap(event){let elem=event.target;while(!hasClass(elem,"example-wrap")){if(elem===document.body||elem.tagName==="A"||elem.tagName==="BUTTON"||hasClass(elem,"docblock")){return null}elem=elem.parentElement}return elem}function addCopyButton(event){const elem=getExampleWrap(event);if(elem===null){return}elem.removeEventListener("mouseover",addCopyButton);const parent=document.createElement("div");parent.className="button-holder";const runButton=elem.querySelector(".test-arrow");if(runButton!==null){parent.appendChild(runButton)}elem.appendChild(parent);const copyButton=document.createElement("button");copyButton.className="copy-button";copyButton.title="Copy code to clipboard";copyButton.addEventListener("click",()=>{copyCode(elem.querySelector("pre > code"));copyButtonAnimation(copyButton)});parent.appendChild(copyButton);if(!elem.parentElement.classList.contains("scraped-example")){return}const scrapedWrapped=elem.parentElement;window.updateScrapedExample(scrapedWrapped,parent)}function showHideCodeExampleButtons(event){const elem=getExampleWrap(event);if(elem===null){return}let buttons=elem.querySelector(".button-holder");if(buttons===null){addCopyButton(event);buttons=elem.querySelector(".button-holder");if(buttons===null){return}}buttons.classList.toggle("keep-visible")}onEachLazy(document.querySelectorAll(".docblock .example-wrap"),elem=>{elem.addEventListener("mouseover",addCopyButton);elem.addEventListener("click",showHideCodeExampleButtons)})}()) \ No newline at end of file diff --git a/static.files/normalize-76eba96aa4d2e634.css b/static.files/normalize-76eba96aa4d2e634.css new file mode 100644 index 00000000..469959f1 --- /dev/null +++ b/static.files/normalize-76eba96aa4d2e634.css @@ -0,0 +1,2 @@ + /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ +html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:0.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type="button"],[type="reset"],[type="submit"],button{-webkit-appearance:button}[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:0.35em 0.75em 0.625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none} \ No newline at end of file diff --git a/static.files/noscript-0111fcff984fae8f.css b/static.files/noscript-0111fcff984fae8f.css new file mode 100644 index 00000000..a6c18eca --- /dev/null +++ b/static.files/noscript-0111fcff984fae8f.css @@ -0,0 +1 @@ + #main-content .attributes{margin-left:0 !important;}#copy-path,#sidebar-button,.sidebar-resizer{display:none !important;}nav.sub{display:none;}.src .sidebar{display:none;}.notable-traits{display:none;}:root,:root:not([data-theme]){--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--mobile-sidebar-menu-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#595959;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}@media (prefers-color-scheme:dark){:root,:root:not([data-theme]){--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#a5a5a5;--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(65%);--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}} \ No newline at end of file diff --git a/static.files/rust-logo-151179464ae7ed46.svg b/static.files/rust-logo-151179464ae7ed46.svg new file mode 100644 index 00000000..62424d8f --- /dev/null +++ b/static.files/rust-logo-151179464ae7ed46.svg @@ -0,0 +1,61 @@ + + + diff --git a/static.files/rustdoc-b778ab399e080a4b.css b/static.files/rustdoc-b778ab399e080a4b.css new file mode 100644 index 00000000..8b90b805 --- /dev/null +++ b/static.files/rustdoc-b778ab399e080a4b.css @@ -0,0 +1,53 @@ + :root{--nav-sub-mobile-padding:8px;--search-typename-width:6.75rem;--desktop-sidebar-width:200px;--src-sidebar-width:300px;--desktop-sidebar-z-index:100;--sidebar-elems-left-padding:24px;--clipboard-image:url('data:image/svg+xml,\ +\ +\ +');--copy-path-height:34px;--copy-path-width:33px;--checkmark-image:url('data:image/svg+xml,\ +\ +');--button-left-margin:4px;--button-border-radius:2px;--toolbar-button-border-radius:6px;--code-block-border-radius:6px;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:400;src:local('Fira Sans'),url("FiraSans-Regular-018c141bf0843ffd.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:500;src:local('Fira Sans Medium'),url("FiraSans-Medium-8f9a781e4970d388.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:400;src:local('Source Serif 4'),url("SourceSerif4-Regular-46f98efaafac5295.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:italic;font-weight:400;src:local('Source Serif 4 Italic'),url("SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:700;src:local('Source Serif 4 Bold'),url("SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:400;src:url("SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:italic;font-weight:400;src:url("SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:600;src:url("SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'NanumBarunGothic';src:url("NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2") format("woff2");font-display:swap;unicode-range:U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF;}*{box-sizing:border-box;}body{font:1rem/1.5 "Source Serif 4",NanumBarunGothic,serif;margin:0;position:relative;overflow-wrap:break-word;overflow-wrap:anywhere;font-feature-settings:"kern","liga";background-color:var(--main-background-color);color:var(--main-color);}h1{font-size:1.5rem;}h2{font-size:1.375rem;}h3{font-size:1.25rem;}h1,h2,h3,h4,h5,h6{font-weight:500;}h1,h2,h3,h4{margin:25px 0 15px 0;padding-bottom:6px;}.docblock h3,.docblock h4,h5,h6{margin:15px 0 5px 0;}.docblock>h2:first-child,.docblock>h3:first-child,.docblock>h4:first-child,.docblock>h5:first-child,.docblock>h6:first-child{margin-top:0;}.main-heading h1{margin:0;padding:0;grid-area:main-heading-h1;overflow-wrap:break-word;overflow-wrap:anywhere;}.main-heading{position:relative;display:grid;grid-template-areas:"main-heading-breadcrumbs main-heading-breadcrumbs" "main-heading-h1 main-heading-toolbar" "main-heading-sub-heading main-heading-toolbar";grid-template-columns:1fr max-content;grid-template-rows:25px min-content min-content;padding-bottom:6px;margin-bottom:11px;}.rustdoc-breadcrumbs{grid-area:main-heading-breadcrumbs;height:25px;line-height:1.25;display:flex;align-items:end;}.rustdoc-breadcrumbs a{padding:4px 0;margin:-4px 0;z-index:1;}.content h2,.top-doc .docblock>h3,.top-doc .docblock>h4{border-bottom:1px solid var(--headings-border-bottom-color);}h1,h2{line-height:1.25;padding-top:3px;padding-bottom:9px;}h3.code-header{font-size:1.125rem;}h4.code-header{font-size:1rem;}.code-header{font-weight:600;margin:0;padding:0;white-space:pre-wrap;}#crate-search,h1,h2,h3,h4,h5,h6,.sidebar,.mobile-topbar,.search-input,.search-results .result-name,.item-name>a,.out-of-band,.sub-heading,span.since,a.src,rustdoc-toolbar,summary.hideme,.scraped-example-list,.rustdoc-breadcrumbs,ul.all-items{font-family:"Fira Sans",Arial,NanumBarunGothic,sans-serif;}#toggle-all-docs,a.anchor,.section-header a,#src-sidebar a,.rust a,.sidebar h2 a,.sidebar h3 a,.mobile-topbar h2 a,h1 a,.search-results a,.stab,.result-name i{color:var(--main-color);}span.enum,a.enum,span.struct,a.struct,span.union,a.union,span.primitive,a.primitive,span.type,a.type,span.foreigntype,a.foreigntype{color:var(--type-link-color);}span.trait,a.trait,span.traitalias,a.traitalias{color:var(--trait-link-color);}span.associatedtype,a.associatedtype,span.constant,a.constant,span.static,a.static{color:var(--assoc-item-link-color);}span.fn,a.fn,span.method,a.method,span.tymethod,a.tymethod{color:var(--function-link-color);}span.attr,a.attr,span.derive,a.derive,span.macro,a.macro{color:var(--macro-link-color);}span.mod,a.mod{color:var(--mod-link-color);}span.keyword,a.keyword{color:var(--keyword-link-color);}a{color:var(--link-color);text-decoration:none;}ol,ul{padding-left:24px;}ul ul,ol ul,ul ol,ol ol{margin-bottom:.625em;}p,.docblock>.warning{margin:0 0 .75em 0;}p:last-child,.docblock>.warning:last-child{margin:0;}button{padding:1px 6px;cursor:pointer;}button#toggle-all-docs{padding:0;background:none;border:none;-webkit-appearance:none;opacity:1;}.rustdoc{display:flex;flex-direction:row;flex-wrap:nowrap;}main{position:relative;flex-grow:1;padding:10px 15px 40px 45px;min-width:0;}.src main{padding:15px;}.width-limiter{max-width:960px;margin-right:auto;}details:not(.toggle) summary{margin-bottom:.6em;}code,pre,.code-header{font-family:"Source Code Pro",monospace;}.docblock code,.docblock-short code{border-radius:3px;padding:0 0.125em;}.docblock pre code,.docblock-short pre code{padding:0;}pre{padding:14px;line-height:1.5;}pre.item-decl{overflow-x:auto;}.item-decl .type-contents-toggle{contain:initial;}.src .content pre{padding:20px;}.rustdoc.src .example-wrap .src-line-numbers{padding:20px 0 20px 4px;}img{max-width:100%;}.logo-container{line-height:0;display:block;}.rust-logo{filter:var(--rust-logo-filter);}.sidebar{font-size:0.875rem;flex:0 0 var(--desktop-sidebar-width);width:var(--desktop-sidebar-width);overflow-y:scroll;overscroll-behavior:contain;position:sticky;height:100vh;top:0;left:0;z-index:var(--desktop-sidebar-z-index);}.rustdoc.src .sidebar{flex-basis:50px;width:50px;border-right:1px solid;overflow-x:hidden;overflow-y:hidden;}.hide-sidebar .sidebar,.hide-sidebar .sidebar-resizer{display:none;}.sidebar-resizer{touch-action:none;width:9px;cursor:col-resize;z-index:calc(var(--desktop-sidebar-z-index) + 1);position:fixed;height:100%;left:calc(var(--desktop-sidebar-width) + 1px);}.rustdoc.src .sidebar-resizer{left:49px;}.src-sidebar-expanded .src .sidebar-resizer{left:var(--src-sidebar-width);}.sidebar-resizing{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;}.sidebar-resizing*{cursor:col-resize !important;}.sidebar-resizing .sidebar{position:fixed;}.sidebar-resizing>body{padding-left:var(--resizing-sidebar-width);}.sidebar-resizer:hover,.sidebar-resizer:active,.sidebar-resizer:focus,.sidebar-resizer.active{width:10px;margin:0;left:var(--desktop-sidebar-width);border-left:solid 1px var(--sidebar-resizer-hover);}.src-sidebar-expanded .rustdoc.src .sidebar-resizer:hover,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:active,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:focus,.src-sidebar-expanded .rustdoc.src .sidebar-resizer.active{left:calc(var(--src-sidebar-width) - 1px);}@media (pointer:coarse){.sidebar-resizer{display:none !important;}}.sidebar-resizer.active{padding:0 140px;width:2px;margin-left:-140px;border-left:none;}.sidebar-resizer.active:before{border-left:solid 2px var(--sidebar-resizer-active);display:block;height:100%;content:"";}.sidebar,.mobile-topbar,.sidebar-menu-toggle,#src-sidebar{background-color:var(--sidebar-background-color);}.src .sidebar>*{visibility:hidden;}.src-sidebar-expanded .src .sidebar{overflow-y:auto;flex-basis:var(--src-sidebar-width);width:var(--src-sidebar-width);}.src-sidebar-expanded .src .sidebar>*{visibility:visible;}#all-types{margin-top:1em;}*{scrollbar-width:initial;scrollbar-color:var(--scrollbar-color);}.sidebar{scrollbar-width:thin;scrollbar-color:var(--scrollbar-color);}::-webkit-scrollbar{width:12px;}.sidebar::-webkit-scrollbar{width:8px;}::-webkit-scrollbar-track{-webkit-box-shadow:inset 0;background-color:var(--scrollbar-track-background-color);}.sidebar::-webkit-scrollbar-track{background-color:var(--scrollbar-track-background-color);}::-webkit-scrollbar-thumb,.sidebar::-webkit-scrollbar-thumb{background-color:var(--scrollbar-thumb-background-color);}.hidden{display:none !important;}.logo-container>img{height:48px;width:48px;}ul.block,.block li,.block ul{padding:0;margin:0;list-style:none;}.block ul a{padding-left:1rem;}.sidebar-elems a,.sidebar>h2 a{display:block;padding:0.25rem;margin-right:0.25rem;border-left:solid var(--sidebar-elems-left-padding) transparent;margin-left:calc(-0.25rem - var(--sidebar-elems-left-padding));background-clip:border-box;}.hide-toc #rustdoc-toc,.hide-toc .in-crate{display:none;}.hide-modnav #rustdoc-modnav{display:none;}.sidebar h2{text-wrap:balance;overflow-wrap:anywhere;padding:0;margin:0.7rem 0;}.sidebar h3{text-wrap:balance;overflow-wrap:anywhere;font-size:1.125rem;padding:0;margin:0;}.sidebar-elems,.sidebar>.version,.sidebar>h2{padding-left:var(--sidebar-elems-left-padding);}.sidebar a{color:var(--sidebar-link-color);}.sidebar .current,.sidebar .current a,.sidebar-crate a.logo-container:hover+h2 a,.sidebar a:hover:not(.logo-container){background-color:var(--sidebar-current-link-background-color);}.sidebar-elems .block{margin-bottom:2em;}.sidebar-elems .block li a{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;}.sidebar-crate{display:flex;align-items:center;justify-content:center;margin:14px 32px 1rem;row-gap:10px;column-gap:32px;flex-wrap:wrap;}.sidebar-crate h2{flex-grow:1;margin:0 -8px;align-self:start;}.sidebar-crate .logo-container{margin:0 calc(-16px - var(--sidebar-elems-left-padding));padding:0 var(--sidebar-elems-left-padding);text-align:center;}.sidebar-crate .logo-container img{margin-top:-16px;border-top:solid 16px transparent;box-sizing:content-box;position:relative;background-clip:border-box;z-index:1;}.sidebar-crate h2 a{display:block;border-left:solid var(--sidebar-elems-left-padding) transparent;background-clip:border-box;margin:0 calc(-24px + 0.25rem) 0 calc(-0.2rem - var(--sidebar-elems-left-padding));padding:calc((16px - 0.57rem ) / 2 ) 0.25rem;padding-left:0.2rem;}.sidebar-crate h2 .version{display:block;font-weight:normal;font-size:1rem;overflow-wrap:break-word;}.sidebar-crate+.version{margin-top:-1rem;margin-bottom:1rem;}.mobile-topbar{display:none;}.rustdoc .example-wrap{display:flex;position:relative;margin-bottom:10px;}.rustdoc .example-wrap>pre,.rustdoc .scraped-example .src-line-numbers,.rustdoc .scraped-example .src-line-numbers>pre{border-radius:6px;}.rustdoc .example-wrap>.example-line-numbers,.rustdoc .scraped-example .src-line-numbers,.rustdoc .scraped-example .src-line-numbers>pre{border-top-right-radius:0;border-bottom-right-radius:0;}.rustdoc .example-wrap>.example-line-numbers+pre,.rustdoc .scraped-example .rust{border-top-left-radius:0;border-bottom-left-radius:0;}.rustdoc .scraped-example{position:relative;}.rustdoc .example-wrap:last-child{margin-bottom:0px;}.rustdoc .example-wrap pre{margin:0;flex-grow:1;}.scraped-example:not(.expanded) .example-wrap{max-height:calc(1.5em * 5 + 10px);}.more-scraped-examples .scraped-example:not(.expanded) .example-wrap{max-height:calc(1.5em * 10 + 10px);}.rustdoc:not(.src) .scraped-example:not(.expanded) .src-line-numbers,.rustdoc:not(.src) .scraped-example:not(.expanded) .src-line-numbers>pre,.rustdoc:not(.src) .scraped-example:not(.expanded) pre.rust{padding-bottom:0;overflow:auto hidden;}.rustdoc:not(.src) .scraped-example .src-line-numbers{padding-top:0;}.rustdoc:not(.src) .scraped-example.expanded .src-line-numbers{padding-bottom:0;}.rustdoc:not(.src) .example-wrap pre{overflow:auto;}.rustdoc .example-wrap pre.example-line-numbers,.rustdoc .example-wrap .src-line-numbers{min-width:fit-content;flex-grow:0;text-align:right;-webkit-user-select:none;user-select:none;padding:14px 8px;padding-right:2px;color:var(--src-line-numbers-span-color);}.rustdoc .scraped-example .example-wrap .src-line-numbers{padding:0;}.rustdoc .src-line-numbers pre{padding:14px 0;}.src-line-numbers a,.src-line-numbers span{color:var(--src-line-numbers-span-color);padding:0 8px;}.src-line-numbers :target{background-color:transparent;border-right:none;padding:0 8px;}.src-line-numbers .line-highlighted{background-color:var(--src-line-number-highlighted-background-color);}.search-loading{text-align:center;}.docblock-short{overflow-wrap:break-word;overflow-wrap:anywhere;}.docblock :not(pre)>code,.docblock-short code{white-space:pre-wrap;}.top-doc .docblock h2{font-size:1.375rem;}.top-doc .docblock h3{font-size:1.25rem;}.top-doc .docblock h4,.top-doc .docblock h5{font-size:1.125rem;}.top-doc .docblock h6{font-size:1rem;}.docblock h5{font-size:1rem;}.docblock h6{font-size:0.875rem;}.docblock{margin-left:24px;position:relative;}.docblock>:not(.more-examples-toggle):not(.example-wrap){max-width:100%;overflow-x:auto;}.sub-heading{font-size:1rem;flex-grow:0;grid-area:main-heading-sub-heading;line-height:1.25;padding-bottom:4px;}.main-heading rustdoc-toolbar,.main-heading .out-of-band{grid-area:main-heading-toolbar;}rustdoc-toolbar{display:flex;flex-direction:row;flex-wrap:nowrap;}.docblock code,.docblock-short code,pre,.rustdoc.src .example-wrap,.example-wrap .src-line-numbers{background-color:var(--code-block-background-color);border-radius:var(--code-block-border-radius);}#main-content{position:relative;}.docblock table{margin:.5em 0;border-collapse:collapse;}.docblock table td,.docblock table th{padding:.5em;border:1px solid var(--border-color);}.docblock table tbody tr:nth-child(2n){background:var(--table-alt-row-background-color);}.docblock .stab,.docblock-short .stab{display:inline-block;}div.where{white-space:pre-wrap;font-size:0.875rem;}.item-info{display:block;margin-left:24px;}.item-info code{font-size:0.875rem;}#main-content>.item-info{margin-left:0;}nav.sub{flex-grow:1;flex-flow:row nowrap;margin:4px 0 0 0;display:flex;align-items:center;}.search-form{position:relative;display:flex;height:34px;flex-grow:1;}.src nav.sub{margin:0 0 -10px 0;}.section-header{display:block;position:relative;}.section-header:hover>.anchor,.impl:hover>.anchor,.trait-impl:hover>.anchor,.variant:hover>.anchor{display:initial;}.anchor{display:none;position:absolute;left:-0.5em;background:none !important;}.anchor.field{left:-5px;}.section-header>.anchor{left:-15px;padding-right:8px;}h2.section-header>.anchor{padding-right:6px;}a.doc-anchor{color:var(--main-color);display:none;position:absolute;left:-17px;padding-right:10px;padding-left:3px;}*:hover>.doc-anchor{display:block;}.top-doc>.docblock>*:first-child>.doc-anchor{display:none !important;}.main-heading a:hover,.example-wrap .rust a:hover,.all-items a:hover,.docblock a:not(.scrape-help):not(.tooltip):hover:not(.doc-anchor),.docblock-short a:not(.scrape-help):not(.tooltip):hover,.item-info a{text-decoration:underline;}.crate.block li.current a{font-weight:500;}table,.item-table{overflow-wrap:break-word;}.item-table{display:table;padding:0;margin:0;width:100%;}.item-table>li{display:table-row;}.item-table>li>div{display:table-cell;}.item-table>li>.item-name{padding-right:1.25rem;}.search-results-title{margin-top:0;white-space:nowrap;display:flex;align-items:baseline;}.search-results-title+.sub-heading{color:var(--main-color);display:flex;align-items:center;}#crate-search-div{position:relative;min-width:5em;}#crate-search{min-width:115px;padding:0 23px 0 4px;max-width:100%;text-overflow:ellipsis;border:1px solid var(--border-color);border-radius:4px;outline:none;cursor:pointer;-moz-appearance:none;-webkit-appearance:none;text-indent:0.01px;background-color:var(--main-background-color);color:inherit;line-height:1.5;font-weight:500;}#crate-search:hover,#crate-search:focus{border-color:var(--crate-search-hover-border);}#crate-search-div::after{pointer-events:none;width:100%;height:100%;position:absolute;top:0;left:0;content:"";background-repeat:no-repeat;background-size:20px;background-position:calc(100% - 2px) 56%;background-image:url('data:image/svg+xml, \ + ');filter:var(--crate-search-div-filter);}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:var(--crate-search-div-hover-filter);}#crate-search>option{font-size:1rem;}.search-input{-webkit-appearance:none;outline:none;border:1px solid var(--border-color);border-radius:2px;padding:8px;font-size:1rem;flex-grow:1;background-color:var(--button-background-color);color:var(--search-color);}.search-input:focus{border-color:var(--search-input-focused-border-color);}.search-results{display:none;}.search-results.active{display:block;}.search-results>a{display:flex;margin-left:2px;margin-right:2px;border-bottom:1px solid var(--search-result-border-color);gap:1em;}.search-results>a>div.desc{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;flex:2;}.search-results a:hover,.search-results a:focus{background-color:var(--search-result-link-focus-background-color);}.search-results .result-name{display:flex;align-items:center;justify-content:start;flex:3;}.search-results .result-name .alias{color:var(--search-results-alias-color);}.search-results .result-name .grey{color:var(--search-results-grey-color);}.search-results .result-name .typename{color:var(--search-results-grey-color);font-size:0.875rem;width:var(--search-typename-width);}.search-results .result-name .path{word-break:break-all;max-width:calc(100% - var(--search-typename-width));display:inline-block;}.search-results .result-name .path>*{display:inline;}.popover{position:absolute;top:100%;right:0;z-index:calc(var(--desktop-sidebar-z-index) + 1);margin-top:7px;border-radius:3px;border:1px solid var(--border-color);background-color:var(--main-background-color);color:var(--main-color);--popover-arrow-offset:11px;}.popover::before{content:'';position:absolute;right:var(--popover-arrow-offset);border:solid var(--border-color);border-width:1px 1px 0 0;background-color:var(--main-background-color);padding:4px;transform:rotate(-45deg);top:-5px;}.setting-line{margin:1.2em 0.6em;}.setting-radio input,.setting-check input{margin-right:0.3em;height:1.2rem;width:1.2rem;border:2px solid var(--settings-input-border-color);outline:none;-webkit-appearance:none;cursor:pointer;}.setting-radio input{border-radius:50%;}.setting-radio span,.setting-check span{padding-bottom:1px;}.setting-radio{margin-top:0.1em;margin-bottom:0.1em;min-width:3.8em;padding:0.3em;display:inline-flex;align-items:center;cursor:pointer;}.setting-radio+.setting-radio{margin-left:0.5em;}.setting-check{margin-right:20px;display:flex;align-items:center;cursor:pointer;}.setting-radio input:checked{box-shadow:inset 0 0 0 3px var(--main-background-color);background-color:var(--settings-input-color);}.setting-check input:checked{background-color:var(--settings-input-color);border-width:1px;content:url('data:image/svg+xml,\ + \ + ');}.setting-radio input:focus,.setting-check input:focus{box-shadow:0 0 1px 1px var(--settings-input-color);}.setting-radio input:checked:focus{box-shadow:inset 0 0 0 3px var(--main-background-color),0 0 2px 2px var(--settings-input-color);}.setting-radio input:hover,.setting-check input:hover{border-color:var(--settings-input-color) !important;}#settings.popover{--popover-arrow-offset:202px;top:calc(100% - 16px);}#help.popover{max-width:600px;--popover-arrow-offset:118px;top:calc(100% - 16px);}#help dt{float:left;clear:left;margin-right:0.5rem;}#help dd{margin-bottom:0.5rem;}#help span.top,#help span.bottom{text-align:center;display:block;font-size:1.125rem;padding:0 0.5rem;text-wrap-style:balance;}#help span.top{margin:10px 0;border-bottom:1px solid var(--border-color);padding-bottom:4px;margin-bottom:6px;}#help span.bottom{clear:both;border-top:1px solid var(--border-color);}.side-by-side{display:flex;margin-bottom:20px;}.side-by-side>div{width:50%;padding:0 20px 0 17px;}.item-info .stab{display:block;padding:3px;margin-bottom:5px;}.item-name .stab{margin-left:0.3125em;}.stab{padding:0 2px;font-size:0.875rem;font-weight:normal;color:var(--main-color);background-color:var(--stab-background-color);width:fit-content;white-space:pre-wrap;border-radius:3px;display:inline;vertical-align:baseline;}.stab.portability>code{background:none;color:var(--stab-code-color);}.stab .emoji,.item-info .stab::before{font-size:1.25rem;}.stab .emoji{margin-right:0.3rem;}.item-info .stab::before{content:"\0";width:0;display:inline-block;color:transparent;}.emoji{text-shadow:1px 0 0 black,-1px 0 0 black,0 1px 0 black,0 -1px 0 black;}.since{font-weight:normal;font-size:initial;}.rightside{padding-left:12px;float:right;}.rightside:not(a),.out-of-band,.sub-heading,rustdoc-toolbar{color:var(--right-side-color);}pre.rust{tab-size:4;-moz-tab-size:4;}pre.rust .kw{color:var(--code-highlight-kw-color);}pre.rust .kw-2{color:var(--code-highlight-kw-2-color);}pre.rust .lifetime{color:var(--code-highlight-lifetime-color);}pre.rust .prelude-ty{color:var(--code-highlight-prelude-color);}pre.rust .prelude-val{color:var(--code-highlight-prelude-val-color);}pre.rust .string{color:var(--code-highlight-string-color);}pre.rust .number{color:var(--code-highlight-number-color);}pre.rust .bool-val{color:var(--code-highlight-literal-color);}pre.rust .self{color:var(--code-highlight-self-color);}pre.rust .attr{color:var(--code-highlight-attribute-color);}pre.rust .macro,pre.rust .macro-nonterminal{color:var(--code-highlight-macro-color);}pre.rust .question-mark{font-weight:bold;color:var(--code-highlight-question-mark-color);}pre.rust .comment{color:var(--code-highlight-comment-color);}pre.rust .doccomment{color:var(--code-highlight-doc-comment-color);}.rustdoc.src .example-wrap pre.rust a{background:var(--codeblock-link-background);}.example-wrap.compile_fail,.example-wrap.should_panic{border-left:2px solid var(--codeblock-error-color);}.ignore.example-wrap{border-left:2px solid var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover,.example-wrap.should_panic:hover{border-left:2px solid var(--codeblock-error-hover-color);}.example-wrap.ignore:hover{border-left:2px solid var(--codeblock-ignore-hover-color);}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip{color:var(--codeblock-error-color);}.example-wrap.ignore .tooltip{color:var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover .tooltip,.example-wrap.should_panic:hover .tooltip{color:var(--codeblock-error-hover-color);}.example-wrap.ignore:hover .tooltip{color:var(--codeblock-ignore-hover-color);}.example-wrap .tooltip{position:absolute;display:block;left:-25px;top:5px;margin:0;line-height:1;}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip,.example-wrap.ignore .tooltip{font-weight:bold;font-size:1.25rem;}.content .docblock .warning{border-left:2px solid var(--warning-border-color);padding:14px;position:relative;overflow-x:visible !important;}.content .docblock .warning::before{color:var(--warning-border-color);content:"โ“˜";position:absolute;left:-25px;top:5px;font-weight:bold;font-size:1.25rem;}.top-doc>.docblock>.warning:first-child::before{top:20px;}.example-wrap>a.test-arrow,.example-wrap .button-holder{visibility:hidden;position:absolute;top:4px;right:4px;z-index:1;}a.test-arrow{height:var(--copy-path-height);padding:6px 4px 0 11px;}a.test-arrow::before{content:url('data:image/svg+xml,');}.example-wrap .button-holder{display:flex;}@media not (pointer:coarse){.example-wrap:hover>a.test-arrow,.example-wrap:hover>.button-holder{visibility:visible;}}.example-wrap .button-holder.keep-visible{visibility:visible;}.example-wrap .button-holder>*{background:var(--main-background-color);cursor:pointer;border-radius:var(--button-border-radius);height:var(--copy-path-height);width:var(--copy-path-width);border:0;color:var(--code-example-button-color);}.example-wrap .button-holder>*:hover{color:var(--code-example-button-hover-color);}.example-wrap .button-holder>*:not(:first-child){margin-left:var(--button-left-margin);}.example-wrap .button-holder .copy-button{padding:2px 0 0 4px;}.example-wrap .button-holder .copy-button::before,.example-wrap .test-arrow::before{filter:var(--copy-path-img-filter);}.example-wrap .button-holder .copy-button::before{content:var(--clipboard-image);}.example-wrap .button-holder .copy-button:hover::before,.example-wrap .test-arrow:hover::before{filter:var(--copy-path-img-hover-filter);}.example-wrap .button-holder .copy-button.clicked::before{content:var(--checkmark-image);padding-right:5px;}.code-attribute{font-weight:300;color:var(--code-attribute-color);}.item-spacer{width:100%;height:12px;display:block;}.main-heading span.since::before{content:"Since ";}.sub-variant h4{font-size:1rem;font-weight:400;margin-top:0;margin-bottom:0;}.sub-variant{margin-left:24px;margin-bottom:40px;}.sub-variant>.sub-variant-field{margin-left:24px;}@keyframes targetfadein{from{background-color:var(--main-background-color);}10%{background-color:var(--target-border-color);}to{background-color:var(--target-background-color);}}:target{padding-right:3px;background-color:var(--target-background-color);border-right:3px solid var(--target-border-color);}.code-header a.tooltip{color:inherit;margin-right:15px;position:relative;}.code-header a.tooltip:hover{color:var(--link-color);}a.tooltip:hover::after{position:absolute;top:calc(100% - 10px);left:-15px;right:-15px;height:20px;content:"\00a0";}@media not (prefers-reduced-motion){:target{animation:0.65s cubic-bezier(0,0,0.1,1.0) 0.1s targetfadein;}.fade-out{opacity:0;transition:opacity 0.45s cubic-bezier(0,0,0.1,1.0);}}.popover.tooltip .content{margin:0.25em 0.5em;}.popover.tooltip .content pre,.popover.tooltip .content code{background:transparent;margin:0;padding:0;font-size:1.25rem;white-space:pre-wrap;}.popover.tooltip .content>h3:first-child{margin:0 0 5px 0;}.search-failed{text-align:center;margin-top:20px;display:none;}.search-failed.active{display:block;}.search-failed>ul{text-align:left;max-width:570px;margin-left:auto;margin-right:auto;}#search-tabs{margin-top:0.25rem;display:flex;flex-direction:row;gap:1px;margin-bottom:4px;}#search-tabs button{text-align:center;font-size:1.125rem;border:0;border-top:2px solid;flex:1;line-height:1.5;color:inherit;}#search-tabs button:not(.selected){background-color:var(--search-tab-button-not-selected-background);border-top-color:var(--search-tab-button-not-selected-border-top-color);}#search-tabs button:hover,#search-tabs button.selected{background-color:var(--search-tab-button-selected-background);border-top-color:var(--search-tab-button-selected-border-top-color);}#search-tabs .count{font-size:1rem;font-variant-numeric:tabular-nums;color:var(--search-tab-title-count-color);}#search .error code{border-radius:3px;background-color:var(--search-error-code-background-color);}.search-corrections{font-weight:normal;}#src-sidebar{width:100%;overflow:auto;}#src-sidebar div.files>a:hover,details.dir-entry summary:hover,#src-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:var(--src-sidebar-background-hover);}#src-sidebar div.files>a.selected{background-color:var(--src-sidebar-background-selected);}.src-sidebar-title{position:sticky;top:0;display:flex;padding:8px 8px 0 48px;margin-bottom:7px;background:var(--sidebar-background-color);border-bottom:1px solid var(--border-color);}#settings-menu,#help-button,button#toggle-all-docs{margin-left:var(--button-left-margin);display:flex;line-height:1.25;}#sidebar-button{display:none;line-height:0;}.hide-sidebar #sidebar-button,.src #sidebar-button{display:flex;margin-right:4px;position:fixed;left:6px;height:34px;width:34px;background-color:var(--main-background-color);z-index:1;}.src #sidebar-button{left:8px;z-index:calc(var(--desktop-sidebar-z-index) + 1);}.hide-sidebar .src #sidebar-button{position:static;}#settings-menu>a,#help-button>a,#sidebar-button>a,button#toggle-all-docs{display:flex;align-items:center;justify-content:center;flex-direction:column;border:1px solid transparent;border-radius:var(--button-border-radius);color:var(--main-color);}#settings-menu>a,#help-button>a,button#toggle-all-docs{width:80px;border-radius:var(--toolbar-button-border-radius);}#sidebar-button>a{background-color:var(--button-background-color);border-color:var(--border-color);width:33px;}#settings-menu>a:hover,#settings-menu>a:focus-visible,#help-button>a:hover,#help-button>a:focus-visible,#sidebar-button>a:hover,#sidebar-button>a:focus-visible,button#toggle-all-docs:hover,button#toggle-all-docs:focus-visible{border-color:var(--settings-button-border-focus);text-decoration:none;}#settings-menu>a:before{content:url('data:image/svg+xml,\ + ');width:18px;height:18px;filter:var(--settings-menu-filter);}button#toggle-all-docs:before{content:url('data:image/svg+xml,\ + ');width:18px;height:18px;filter:var(--settings-menu-filter);}#help-button>a:before{content:url('data:image/svg+xml,\ + \ + ?');width:18px;height:18px;filter:var(--settings-menu-filter);}button#toggle-all-docs:before,#help-button>a:before,#settings-menu>a:before{filter:var(--settings-menu-filter);margin:8px;}@media not (pointer:coarse){button#toggle-all-docs:hover:before,#help-button>a:hover:before,#settings-menu>a:hover:before{filter:var(--settings-menu-hover-filter);}}button[disabled]#toggle-all-docs{opacity:0.25;border:solid 1px var(--main-background-color);background-size:cover;}button[disabled]#toggle-all-docs:hover{border:solid 1px var(--main-background-color);cursor:not-allowed;}rustdoc-toolbar span.label{font-size:1rem;flex-grow:1;padding-bottom:4px;}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}#copy-path{color:var(--copy-path-button-color);background:var(--main-background-color);height:var(--copy-path-height);width:var(--copy-path-width);margin-left:10px;padding:0;padding-left:2px;border:0;font-size:0;}#copy-path::before{filter:var(--copy-path-img-filter);content:var(--clipboard-image);}#copy-path:hover::before{filter:var(--copy-path-img-hover-filter);}#copy-path.clicked::before{content:var(--checkmark-image);}@keyframes rotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}#settings-menu.rotate>a img{animation:rotating 2s linear infinite;}kbd{display:inline-block;padding:3px 5px;font:15px monospace;line-height:10px;vertical-align:middle;border:solid 1px var(--border-color);border-radius:3px;color:var(--kbd-color);background-color:var(--kbd-background);box-shadow:inset 0 -1px 0 var(--kbd-box-shadow-color);}ul.all-items>li{list-style:none;}details.dir-entry{padding-left:4px;}details.dir-entry>summary{margin:0 0 0 -4px;padding:0 0 0 4px;cursor:pointer;}details.dir-entry div.folders,details.dir-entry div.files{padding-left:23px;}details.dir-entry a{display:block;}details.toggle{contain:layout;position:relative;}details.big-toggle{contain:inline-size;}details.toggle>summary.hideme{cursor:pointer;font-size:1rem;}details.toggle>summary{list-style:none;outline:none;}details.toggle>summary::-webkit-details-marker,details.toggle>summary::marker{display:none;}details.toggle>summary.hideme>span{margin-left:9px;}details.toggle>summary::before{background:url('data:image/svg+xml,\ + ');content:"";cursor:pointer;width:16px;height:16px;display:inline-block;vertical-align:middle;opacity:.5;filter:var(--toggle-filter);}details.toggle>summary.hideme>span,.more-examples-toggle summary,.more-examples-toggle .hide-more{color:var(--toggles-color);}details.toggle>summary::after{content:"Expand";overflow:hidden;width:0;height:0;position:absolute;}details.toggle>summary.hideme::after{content:"";}details.toggle>summary:focus::before,details.toggle>summary:hover::before{opacity:1;}details.toggle>summary:focus-visible::before{outline:1px dotted #000;outline-offset:1px;}details.non-exhaustive{margin-bottom:8px;}details.toggle>summary.hideme::before{position:relative;}details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;top:4px;}.impl-items>details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;}details.big-toggle>summary:not(.hideme)::before{left:-34px;top:9px;}details.toggle[open] >summary.hideme{position:absolute;}details.toggle[open] >summary.hideme>span{display:none;}details.toggle[open] >summary::before{background:url('data:image/svg+xml,\ + ');}details.toggle[open] >summary::after{content:"Collapse";}.docblock summary>*{display:inline-block;}.docblock>.example-wrap:first-child .tooltip{margin-top:16px;}.src #sidebar-button>a:before,.sidebar-menu-toggle:before{content:url('data:image/svg+xml,\ + ');opacity:0.75;}.sidebar-menu-toggle:hover:before,.sidebar-menu-toggle:active:before,.sidebar-menu-toggle:focus:before{opacity:1;}.src #sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');opacity:0.75;}@media (max-width:850px){#search-tabs .count{display:block;}.side-by-side{flex-direction:column-reverse;}.side-by-side>div{width:auto;}}@media (max-width:700px){*[id]{scroll-margin-top:45px;}#copy-path{display:none;}rustdoc-toolbar span.label{display:none;}#settings-menu>a,#help-button>a,button#toggle-all-docs{width:33px;}#settings.popover{--popover-arrow-offset:86px;}#help.popover{--popover-arrow-offset:48px;}.rustdoc{display:block;}main{padding-left:15px;padding-top:0px;}.sidebar .logo-container,.sidebar .location,.sidebar-resizer{display:none;}.sidebar{position:fixed;top:45px;left:-1000px;z-index:11;height:calc(100vh - 45px);width:200px;}.src main,.rustdoc.src .sidebar{top:0;padding:0;height:100vh;border:0;}.src .search-form{margin-left:40px;}.src .main-heading{margin-left:8px;}.hide-sidebar .search-form{margin-left:32px;}.hide-sidebar .src .search-form{margin-left:0;}.sidebar.shown,.src-sidebar-expanded .src .sidebar,.rustdoc:not(.src) .sidebar:focus-within{left:0;}.mobile-topbar h2{padding-bottom:0;margin:auto 0.5em auto auto;overflow:hidden;font-size:24px;white-space:nowrap;text-overflow:ellipsis;}.mobile-topbar .logo-container>img{max-width:35px;max-height:35px;margin:5px 0 5px 20px;}.mobile-topbar{display:flex;flex-direction:row;position:sticky;z-index:10;font-size:2rem;height:45px;width:100%;left:0;top:0;}.hide-sidebar .mobile-topbar{display:none;}.sidebar-menu-toggle{width:45px;border:none;line-height:0;}.hide-sidebar .sidebar-menu-toggle{display:none;}.sidebar-elems{margin-top:1em;}.anchor{display:none !important;}#main-content>details.toggle>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}.sidebar-menu-toggle:before{filter:var(--mobile-sidebar-menu-filter);}.sidebar-menu-toggle:hover{background:var(--main-background-color);}.item-table,.item-row,.item-table>li,.item-table>li>div,.search-results>a,.search-results>a>div{display:block;}.search-results>a{padding:5px 0px;}.search-results>a>div.desc,.item-table>li>div.desc{padding-left:2em;}.search-results .result-name{display:block;}.search-results .result-name .typename{width:initial;margin-right:0;}.search-results .result-name .typename,.search-results .result-name .path{display:inline;}.src-sidebar-expanded .src .sidebar{position:fixed;max-width:100vw;width:100vw;}.src .src-sidebar-title{padding-top:0;}details.toggle:not(.top-doc)>summary{margin-left:10px;}.impl-items>details.toggle>summary:not(.hideme)::before,#main-content>details.toggle:not(.top-doc)>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}.impl-items>.item-info{margin-left:34px;}.src nav.sub{margin:0 0 -25px 0;padding:var(--nav-sub-mobile-padding);}}@media (min-width:701px){.scraped-example-title{position:absolute;z-index:10;background:var(--main-background-color);bottom:8px;right:5px;padding:2px 4px;box-shadow:0 0 4px var(--main-background-color);}.item-table>li>.item-name{width:33%;}.item-table>li>div{overflow-wrap:anywhere;}}@media print{nav.sidebar,nav.sub,.out-of-band,a.src,#copy-path,details.toggle[open] >summary::before,details.toggle>summary::before,details.toggle.top-doc>summary{display:none;}.docblock{margin-left:0;}main{padding:10px;}}@media (max-width:464px){.docblock{margin-left:12px;}.docblock code{overflow-wrap:break-word;overflow-wrap:anywhere;}nav.sub{flex-direction:column;}.search-form{align-self:stretch;}}.variant,.implementors-toggle>summary,.impl,#implementors-list>.docblock,.impl-items>section,.impl-items>.toggle>summary,.methods>section,.methods>.toggle>summary{margin-bottom:0.75em;}.variants>.docblock,.implementors-toggle>.docblock,.impl-items>.toggle[open]:not(:last-child),.methods>.toggle[open]:not(:last-child),.implementors-toggle[open]:not(:last-child){margin-bottom:2em;}#trait-implementations-list .impl-items>.toggle:not(:last-child),#synthetic-implementations-list .impl-items>.toggle:not(:last-child),#blanket-implementations-list .impl-items>.toggle:not(:last-child){margin-bottom:1em;}.scraped-example-list .scrape-help{margin-left:10px;padding:0 4px;font-weight:normal;font-size:12px;position:relative;bottom:1px;border:1px solid var(--scrape-example-help-border-color);border-radius:50px;color:var(--scrape-example-help-color);}.scraped-example-list .scrape-help:hover{border-color:var(--scrape-example-help-hover-border-color);color:var(--scrape-example-help-hover-color);}.scraped-example:not(.expanded) .example-wrap::before,.scraped-example:not(.expanded) .example-wrap::after{content:" ";width:100%;height:5px;position:absolute;z-index:1;}.scraped-example:not(.expanded) .example-wrap::before{top:0;background:linear-gradient(to bottom,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example:not(.expanded) .example-wrap::after{bottom:0;background:linear-gradient(to top,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example:not(.expanded){width:100%;overflow-y:hidden;margin-bottom:0;}.scraped-example:not(.expanded){overflow-x:hidden;}.scraped-example .rust span.highlight{background:var(--scrape-example-code-line-highlight);}.scraped-example .rust span.highlight.focus{background:var(--scrape-example-code-line-highlight-focus);}.more-examples-toggle{max-width:calc(100% + 25px);margin-top:10px;margin-left:-25px;}.more-examples-toggle .hide-more{margin-left:25px;cursor:pointer;}.more-scraped-examples{margin-left:25px;position:relative;}.toggle-line{position:absolute;top:5px;bottom:0;right:calc(100% + 10px);padding:0 4px;cursor:pointer;}.toggle-line-inner{min-width:2px;height:100%;background:var(--scrape-example-toggle-line-background);}.toggle-line:hover .toggle-line-inner{background:var(--scrape-example-toggle-line-hover-background);}.more-scraped-examples .scraped-example,.example-links{margin-top:20px;}.more-scraped-examples .scraped-example:first-child{margin-top:5px;}.example-links ul{margin-bottom:0;}:root[data-theme="light"],:root:not([data-theme]){--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--mobile-sidebar-menu-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#595959;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="dark"]{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--code-example-button-color:#7f7f7f;--code-example-button-hover-color:#a5a5a5;--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--settings-menu-filter:invert(50%);--settings-menu-hover-filter:invert(65%);--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="ayu"]{--main-background-color:#0f1419;--main-color:#c5c5c5;--settings-input-color:#ffb454;--settings-input-border-color:#999;--settings-button-color:#fff;--settings-button-border-focus:#e0e0e0;--sidebar-background-color:#14191f;--sidebar-background-color-hover:rgba(70,70,70,0.33);--code-block-background-color:#191f26;--scrollbar-track-background-color:transparent;--scrollbar-thumb-background-color:#5c6773;--scrollbar-color:#5c6773 #24292f;--headings-border-bottom-color:#5c6773;--border-color:#5c6773;--button-background-color:#141920;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--mobile-sidebar-menu-filter:invert(100%);--search-input-focused-border-color:#5c6773;--copy-path-button-color:#fff;--copy-path-img-filter:invert(70%);--copy-path-img-hover-filter:invert(100%);--code-example-button-color:#b2b2b2;--code-example-button-hover-color:#fff;--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ffa0a5;--trait-link-color:#39afd7;--assoc-item-link-color:#39afd7;--function-link-color:#fdd687;--macro-link-color:#a37acc;--keyword-link-color:#39afd7;--mod-link-color:#39afd7;--link-color:#39afd7;--sidebar-link-color:#53b1db;--sidebar-current-link-background-color:transparent;--search-result-link-focus-background-color:#3c3c3c;--search-result-border-color:#aaa3;--search-color:#fff;--search-error-code-background-color:#4f4c4c;--search-results-alias-color:#c5c5c5;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:none;--search-tab-button-not-selected-background:transparent !important;--search-tab-button-selected-border-top-color:none;--search-tab-button-selected-background:#141920 !important;--settings-menu-filter:invert(70%);--settings-menu-hover-filter:invert(100%);--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ff7733;--code-highlight-kw-2-color:#ff7733;--code-highlight-lifetime-color:#ff7733;--code-highlight-prelude-color:#69f2df;--code-highlight-prelude-val-color:#ff7733;--code-highlight-number-color:#b8cc52;--code-highlight-string-color:#b8cc52;--code-highlight-literal-color:#ff7733;--code-highlight-attribute-color:#e6e1cf;--code-highlight-self-color:#36a3d9;--code-highlight-macro-color:#a37acc;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#788797;--code-highlight-doc-comment-color:#a1ac88;--src-line-numbers-span-color:#5c6773;--src-line-number-highlighted-background-color:rgba(255,236,164,0.06);--target-background-color:rgba(255,236,164,0.06);--target-border-color:rgba(255,180,76,0.85);--kbd-color:#c5c5c5;--kbd-background:#314559;--kbd-box-shadow-color:#5c6773;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(41%) sepia(12%) saturate(487%) hue-rotate(171deg) brightness(94%) contrast(94%);--crate-search-div-hover-filter:invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg) brightness(113%) contrast(76%);--crate-search-hover-border:#e0e0e0;--src-sidebar-background-selected:#14191f;--src-sidebar-background-hover:#14191f;--table-alt-row-background-color:#191f26;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(15,20,25,1);--scrape-example-code-wrapper-background-end:rgba(15,20,25,0);--sidebar-resizer-hover:hsl(34,50%,33%);--sidebar-resizer-active:hsl(34,100%,66%);}:root[data-theme="ayu"] h1,:root[data-theme="ayu"] h2,:root[data-theme="ayu"] h3,:root[data-theme="ayu"] h4,:where(:root[data-theme="ayu"]) h1 a,:root[data-theme="ayu"] .sidebar h2 a,:root[data-theme="ayu"] .sidebar h3 a{color:#fff;}:root[data-theme="ayu"] .docblock code{color:#ffb454;}:root[data-theme="ayu"] .docblock a>code{color:#39AFD7 !important;}:root[data-theme="ayu"] .code-header,:root[data-theme="ayu"] .docblock pre>code,:root[data-theme="ayu"] pre,:root[data-theme="ayu"] pre>code,:root[data-theme="ayu"] .item-info code,:root[data-theme="ayu"] .rustdoc.source .example-wrap{color:#e6e1cf;}:root[data-theme="ayu"] .sidebar .current,:root[data-theme="ayu"] .sidebar .current a,:root[data-theme="ayu"] .sidebar a:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:hover,:root[data-theme="ayu"] details.dir-entry summary:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:focus,:root[data-theme="ayu"] details.dir-entry summary:focus,:root[data-theme="ayu"] #src-sidebar div.files>a.selected{color:#ffb44c;}:root[data-theme="ayu"] .sidebar-elems .location{color:#ff7733;}:root[data-theme="ayu"] .src-line-numbers .line-highlighted{color:#708090;padding-right:7px;border-right:1px solid #ffb44c;}:root[data-theme="ayu"] .search-results a:hover,:root[data-theme="ayu"] .search-results a:focus{color:#fff !important;background-color:#3c3c3c;}:root[data-theme="ayu"] .search-results a{color:#0096cf;}:root[data-theme="ayu"] .search-results a div.desc{color:#c5c5c5;}:root[data-theme="ayu"] .result-name .primitive>i,:root[data-theme="ayu"] .result-name .keyword>i{color:#788797;}:root[data-theme="ayu"] #search-tabs>button.selected{border-bottom:1px solid #ffb44c !important;border-top:none;}:root[data-theme="ayu"] #search-tabs>button:not(.selected){border:none;background-color:transparent !important;}:root[data-theme="ayu"] #search-tabs>button:hover{border-bottom:1px solid rgba(242,151,24,0.3);}:root[data-theme="ayu"] #settings-menu>a img,:root[data-theme="ayu"] #sidebar-button>a:before{filter:invert(100);} \ No newline at end of file diff --git a/static.files/scrape-examples-46fc985aa763a438.js b/static.files/scrape-examples-46fc985aa763a438.js new file mode 100644 index 00000000..87b6065d --- /dev/null +++ b/static.files/scrape-examples-46fc985aa763a438.js @@ -0,0 +1 @@ +"use strict";(function(){const DEFAULT_MAX_LINES=5;const HIDDEN_MAX_LINES=10;function scrollToLoc(elt,loc,isHidden){const lines=elt.querySelector(".src-line-numbers > pre");let scrollOffset;const maxLines=isHidden?HIDDEN_MAX_LINES:DEFAULT_MAX_LINES;if(loc[1]-loc[0]>maxLines){const line=Math.max(0,loc[0]-1);scrollOffset=lines.children[line].offsetTop}else{const halfHeight=elt.offsetHeight/2;const offsetTop=lines.children[loc[0]].offsetTop;const lastLine=lines.children[loc[1]];const offsetBot=lastLine.offsetTop+lastLine.offsetHeight;const offsetMid=(offsetTop+offsetBot)/2;scrollOffset=offsetMid-halfHeight}lines.parentElement.scrollTo(0,scrollOffset);elt.querySelector(".rust").scrollTo(0,scrollOffset)}function createScrapeButton(parent,className,content){const button=document.createElement("button");button.className=className;button.innerText=content;parent.insertBefore(button,parent.firstChild);return button}window.updateScrapedExample=(example,buttonHolder)=>{let locIndex=0;const highlights=Array.prototype.slice.call(example.querySelectorAll(".highlight"));const link=example.querySelector(".scraped-example-title a");let expandButton=null;if(!example.classList.contains("expanded")){expandButton=createScrapeButton(buttonHolder,"expand","โ†•")}const isHidden=example.parentElement.classList.contains("more-scraped-examples");const locs=example.locs;if(locs.length>1){const next=createScrapeButton(buttonHolder,"next","โ‰ป");const prev=createScrapeButton(buttonHolder,"prev","โ‰บ");const onChangeLoc=changeIndex=>{removeClass(highlights[locIndex],"focus");changeIndex();scrollToLoc(example,locs[locIndex][0],isHidden);addClass(highlights[locIndex],"focus");const url=locs[locIndex][1];const title=locs[locIndex][2];link.href=url;link.innerHTML=title};prev.addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex-1+locs.length)%locs.length})});next.addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex+1)%locs.length})})}if(expandButton){expandButton.addEventListener("click",()=>{if(hasClass(example,"expanded")){removeClass(example,"expanded");scrollToLoc(example,locs[0][0],isHidden)}else{addClass(example,"expanded")}})}};function setupLoc(example,isHidden){example.locs=JSON.parse(example.attributes.getNamedItem("data-locs").textContent);scrollToLoc(example,example.locs[0][0],isHidden)}const firstExamples=document.querySelectorAll(".scraped-example-list > .scraped-example");onEachLazy(firstExamples,el=>setupLoc(el,false));onEachLazy(document.querySelectorAll(".more-examples-toggle"),toggle=>{onEachLazy(toggle.querySelectorAll(".toggle-line, .hide-more"),button=>{button.addEventListener("click",()=>{toggle.open=false})});const moreExamples=toggle.querySelectorAll(".scraped-example");toggle.querySelector("summary").addEventListener("click",()=>{setTimeout(()=>{onEachLazy(moreExamples,el=>setupLoc(el,true))})},{once:true})})})() \ No newline at end of file diff --git a/static.files/search-e056c65ede92db13.js b/static.files/search-e056c65ede92db13.js new file mode 100644 index 00000000..3e2c702e --- /dev/null +++ b/static.files/search-e056c65ede92db13.js @@ -0,0 +1,6 @@ +"use strict";if(!Array.prototype.toSpliced){Array.prototype.toSpliced=function(){const me=this.slice();Array.prototype.splice.apply(me,arguments);return me}}(function(){const itemTypes=["keyword","primitive","mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","associatedtype","constant","associatedconstant","union","foreigntype","existential","attr","derive","traitalias","generic",];const TY_GENERIC=itemTypes.indexOf("generic");const TY_IMPORT=itemTypes.indexOf("import");const ROOT_PATH=typeof window!=="undefined"?window.rootPath:"../";const UNBOXING_LIMIT=5;const REGEX_IDENT=/\p{ID_Start}\p{ID_Continue}*|_\p{ID_Continue}+/uy;const REGEX_INVALID_TYPE_FILTER=/[^a-z]/ui;const MAX_RESULTS=200;const NO_TYPE_FILTER=-1;const editDistanceState={current:[],prev:[],prevPrev:[],calculate:function calculate(a,b,limit){if(a.lengthlimit){return limit+1}while(b.length>0&&b[0]===a[0]){a=a.substring(1);b=b.substring(1)}while(b.length>0&&b[b.length-1]===a[a.length-1]){a=a.substring(0,a.length-1);b=b.substring(0,b.length-1)}if(b.length===0){return minDist}const aLength=a.length;const bLength=b.length;for(let i=0;i<=bLength;++i){this.current[i]=0;this.prev[i]=i;this.prevPrev[i]=Number.MAX_VALUE}for(let i=1;i<=aLength;++i){this.current[0]=i;const aIdx=i-1;for(let j=1;j<=bLength;++j){const bIdx=j-1;const substitutionCost=a[aIdx]===b[bIdx]?0:1;this.current[j]=Math.min(this.prev[j]+1,this.current[j-1]+1,this.prev[j-1]+substitutionCost,);if((i>1)&&(j>1)&&(a[aIdx]===b[bIdx-1])&&(a[aIdx-1]===b[bIdx])){this.current[j]=Math.min(this.current[j],this.prevPrev[j-2]+1,)}}const prevPrevTmp=this.prevPrev;this.prevPrev=this.prev;this.prev=this.current;this.current=prevPrevTmp}const distance=this.prev[bLength];return distance<=limit?distance:(limit+1)},};function editDistance(a,b,limit){return editDistanceState.calculate(a,b,limit)}function isEndCharacter(c){return"=,>-])".indexOf(c)!==-1}function isSeparatorCharacter(c){return c===","||c==="="}function isReturnArrow(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="->"}function skipWhitespace(parserState){while(parserState.pos0){const c=parserState.userQuery[pos-1];if(c===lookingFor){return true}else if(c!==" "){break}pos-=1}return false}function isLastElemGeneric(elems,parserState){return(elems.length>0&&elems[elems.length-1].generics.length>0)||prevIs(parserState,">")}function getFilteredNextElem(query,parserState,elems,isInGenerics){const start=parserState.pos;if(parserState.userQuery[parserState.pos]===":"&&!isPathStart(parserState)){throw["Expected type filter before ",":"]}getNextElem(query,parserState,elems,isInGenerics);if(parserState.userQuery[parserState.pos]===":"&&!isPathStart(parserState)){if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}if(elems.length===0){throw["Expected type filter before ",":"]}else if(query.literalSearch){throw["Cannot use quotes on type filter"]}const typeFilterElem=elems.pop();checkExtraTypeFilterCharacters(start,parserState);parserState.typeFilter=typeFilterElem.name;parserState.pos+=1;parserState.totalElems-=1;query.literalSearch=false;getNextElem(query,parserState,elems,isInGenerics)}}function getItemsBefore(query,parserState,elems,endChar){let foundStopChar=true;let foundSeparator=false;const oldTypeFilter=parserState.typeFilter;parserState.typeFilter=null;const oldIsInBinding=parserState.isInBinding;parserState.isInBinding=null;let hofParameters=null;let extra="";if(endChar===">"){extra="<"}else if(endChar==="]"){extra="["}else if(endChar===")"){extra="("}else if(endChar===""){extra="->"}else{extra=endChar}while(parserState.pos"," after ","="]}hofParameters=[...elems];elems.length=0;parserState.pos+=2;foundStopChar=true;foundSeparator=false;continue}else if(c===" "){parserState.pos+=1;continue}else if(isSeparatorCharacter(c)){parserState.pos+=1;foundStopChar=true;foundSeparator=true;continue}else if(c===":"&&isPathStart(parserState)){throw["Unexpected ","::",": paths cannot start with ","::"]}else if(isEndCharacter(c)){throw["Unexpected ",c," after ",extra]}if(!foundStopChar){let extra=[];if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(endChar!==""){throw["Expected ",",",", ","=",", or ",endChar,...extra,", found ",c,]}throw["Expected ",","," or ","=",...extra,", found ",c,]}const posBefore=parserState.pos;getFilteredNextElem(query,parserState,elems,endChar!=="");if(endChar!==""&&parserState.pos>=parserState.length){throw["Unclosed ",extra]}if(posBefore===parserState.pos){parserState.pos+=1}foundStopChar=false}if(parserState.pos>=parserState.length&&endChar!==""){throw["Unclosed ",extra]}parserState.pos+=1;if(hofParameters){foundSeparator=false;if([...elems,...hofParameters].some(x=>x.bindingName)||parserState.isInBinding){throw["Unexpected ","="," within ","->"]}const hofElem=makePrimitiveElement("->",{generics:hofParameters,bindings:new Map([["output",[...elems]]]),typeFilter:null,});elems.length=0;elems[0]=hofElem}parserState.typeFilter=oldTypeFilter;parserState.isInBinding=oldIsInBinding;return{foundSeparator}}function getNextElem(query,parserState,elems,isInGenerics){const generics=[];skipWhitespace(parserState);let start=parserState.pos;let end;if("[(".indexOf(parserState.userQuery[parserState.pos])!==-1){let endChar=")";let name="()";let friendlyName="tuple";if(parserState.userQuery[parserState.pos]==="["){endChar="]";name="[]";friendlyName="slice"}parserState.pos+=1;const{foundSeparator}=getItemsBefore(query,parserState,generics,endChar);const typeFilter=parserState.typeFilter;const bindingName=parserState.isInBinding;parserState.typeFilter=null;parserState.isInBinding=null;for(const gen of generics){if(gen.bindingName!==null){throw["Type parameter ","=",` cannot be within ${friendlyName} `,name]}}if(name==="()"&&!foundSeparator&&generics.length===1&&typeFilter===null){elems.push(generics[0])}else if(name==="()"&&generics.length===1&&generics[0].name==="->"){generics[0].typeFilter=typeFilter;elems.push(generics[0])}else{if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive ",name," and ",typeFilter," both specified",]}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}elems.push(makePrimitiveElement(name,{bindingName,generics}))}}else if(parserState.userQuery[parserState.pos]==="&"){if(parserState.typeFilter!==null&&parserState.typeFilter!=="primitive"){throw["Invalid search type: primitive ","&"," and ",parserState.typeFilter," both specified",]}parserState.typeFilter=null;parserState.pos+=1;let c=parserState.userQuery[parserState.pos];while(c===" "&&parserState.pos=end){throw["Found generics without a path"]}parserState.pos+=1;getItemsBefore(query,parserState,generics,">")}else if(parserState.pos=end){throw["Found generics without a path"]}if(parserState.isInBinding){throw["Unexpected ","("," after ","="]}parserState.pos+=1;const typeFilter=parserState.typeFilter;parserState.typeFilter=null;getItemsBefore(query,parserState,generics,")");skipWhitespace(parserState);if(isReturnArrow(parserState)){parserState.pos+=2;skipWhitespace(parserState);getFilteredNextElem(query,parserState,generics,isInGenerics);generics[generics.length-1].bindingName=makePrimitiveElement("output")}else{generics.push(makePrimitiveElement(null,{bindingName:makePrimitiveElement("output"),typeFilter:null,}))}parserState.typeFilter=typeFilter}if(isStringElem){skipWhitespace(parserState)}if(start>=end&&generics.length===0){return}if(parserState.userQuery[parserState.pos]==="="){if(parserState.isInBinding){throw["Cannot write ","="," twice in a binding"]}if(!isInGenerics){throw["Type parameter ","="," must be within generics list"]}const name=parserState.userQuery.slice(start,end).trim();if(name==="!"){throw["Type parameter ","="," key cannot be ","!"," never type"]}if(name.includes("!")){throw["Type parameter ","="," key cannot be ","!"," macro"]}if(name.includes("::")){throw["Type parameter ","="," key cannot contain ","::"," path"]}if(name.includes(":")){throw["Type parameter ","="," key cannot contain ",":"," type"]}parserState.isInBinding={name,generics}}else{elems.push(createQueryElement(query,parserState,parserState.userQuery.slice(start,end),generics,isInGenerics,),)}}}function checkExtraTypeFilterCharacters(start,parserState){const query=parserState.userQuery.slice(start,parserState.pos).trim();const match=query.match(REGEX_INVALID_TYPE_FILTER);if(match){throw["Unexpected ",match[0]," in type filter (before ",":",")",]}}function createQueryElement(query,parserState,name,generics,isInGenerics){const path=name.trim();if(path.length===0&&generics.length===0){throw["Unexpected ",parserState.userQuery[parserState.pos]]}if(query.literalSearch&&parserState.totalElems-parserState.genericsElems>0){throw["Cannot have more than one element if you use quotes"]}const typeFilter=parserState.typeFilter;parserState.typeFilter=null;if(name.trim()==="!"){if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive never type ","!"," and ",typeFilter," both specified",]}if(generics.length!==0){throw["Never type ","!"," does not accept generic parameters",]}const bindingName=parserState.isInBinding;parserState.isInBinding=null;return makePrimitiveElement("never",{bindingName})}const quadcolon=/::\s*::/.exec(path);if(path.startsWith("::")){throw["Paths cannot start with ","::"]}else if(path.endsWith("::")){throw["Paths cannot end with ","::"]}else if(quadcolon!==null){throw["Unexpected ",quadcolon[0]]}const pathSegments=path.split(/(?:::\s*)|(?:\s+(?:::\s*)?)/);if(pathSegments.length===0||(pathSegments.length===1&&pathSegments[0]==="")){if(generics.length>0||prevIs(parserState,">")){throw["Found generics without a path"]}else{throw["Unexpected ",parserState.userQuery[parserState.pos]]}}for(const[i,pathSegment]of pathSegments.entries()){if(pathSegment==="!"){if(i!==0){throw["Never type ","!"," is not associated item"]}pathSegments[i]="never"}}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}const bindingName=parserState.isInBinding;parserState.isInBinding=null;const bindings=new Map();const pathLast=pathSegments[pathSegments.length-1];return{name:name.trim(),id:null,fullPath:pathSegments,pathWithoutLast:pathSegments.slice(0,pathSegments.length-1),pathLast,normalizedPathLast:pathLast.replace(/_/g,""),generics:generics.filter(gen=>{if(gen.bindingName!==null){if(gen.name!==null){gen.bindingName.generics.unshift(gen)}bindings.set(gen.bindingName.name,gen.bindingName.generics);return false}return true}),bindings,typeFilter,bindingName,}}function makePrimitiveElement(name,extra){return Object.assign({name,id:null,fullPath:[name],pathWithoutLast:[],pathLast:name,normalizedPathLast:name,generics:[],bindings:new Map(),typeFilter:"primitive",bindingName:null,},extra)}function getStringElem(query,parserState,isInGenerics){if(isInGenerics){throw["Unexpected ","\""," in generics"]}else if(query.literalSearch){throw["Cannot have more than one literal search element"]}else if(parserState.totalElems-parserState.genericsElems>0){throw["Cannot use literal search when there is more than one element"]}parserState.pos+=1;const start=parserState.pos;const end=getIdentEndPosition(parserState);if(parserState.pos>=parserState.length){throw["Unclosed ","\""]}else if(parserState.userQuery[end]!=="\""){throw["Unexpected ",parserState.userQuery[end]," in a string element"]}else if(start===end){throw["Cannot have empty string element"]}parserState.pos+=1;query.literalSearch=true}function getIdentEndPosition(parserState){let afterIdent=consumeIdent(parserState);let end=parserState.pos;let macroExclamation=-1;while(parserState.pos0){throw["Unexpected ",c," after ",parserState.userQuery[parserState.pos-1]," (not a valid identifier)"]}else{throw["Unexpected ",c," (not a valid identifier)"]}parserState.pos+=1;afterIdent=consumeIdent(parserState);end=parserState.pos}if(macroExclamation!==-1){if(parserState.typeFilter===null){parserState.typeFilter="macro"}else if(parserState.typeFilter!=="macro"){throw["Invalid search type: macro ","!"," and ",parserState.typeFilter," both specified",]}end=macroExclamation}return end}function isSpecialStartCharacter(c){return"<\"".indexOf(c)!==-1}function isPathStart(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="::"}function consumeIdent(parserState){REGEX_IDENT.lastIndex=parserState.pos;const match=parserState.userQuery.match(REGEX_IDENT);if(match){parserState.pos+=match[0].length;return true}return false}function isPathSeparator(c){return c===":"||c===" "}class VlqHexDecoder{constructor(string,cons){this.string=string;this.cons=cons;this.offset=0;this.backrefQueue=[]}decodeList(){let c=this.string.charCodeAt(this.offset);const ret=[];while(c!==125){ret.push(this.decode());c=this.string.charCodeAt(this.offset)}this.offset+=1;return ret}decode(){let n=0;let c=this.string.charCodeAt(this.offset);if(c===123){this.offset+=1;return this.decodeList()}while(c<96){n=(n<<4)|(c&0xF);this.offset+=1;c=this.string.charCodeAt(this.offset)}n=(n<<4)|(c&0xF);const[sign,value]=[n&1,n>>1];this.offset+=1;return sign?-value:value}next(){const c=this.string.charCodeAt(this.offset);if(c>=48&&c<64){this.offset+=1;return this.backrefQueue[c-48]}if(c===96){this.offset+=1;return this.cons(0)}const result=this.cons(this.decode());this.backrefQueue.unshift(result);if(this.backrefQueue.length>16){this.backrefQueue.pop()}return result}}class RoaringBitmap{constructor(str){const strdecoded=atob(str);const u8array=new Uint8Array(strdecoded.length);for(let j=0;j=4){offsets=[];for(let j=0;j>3]&(1<<(j&0x7))){const runcount=(u8array[i]|(u8array[i+1]<<8));i+=2;this.containers.push(new RoaringBitmapRun(runcount,u8array.slice(i,i+(runcount*4)),));i+=runcount*4}else if(this.cardinalities[j]>=4096){this.containers.push(new RoaringBitmapBits(u8array.slice(i,i+8192)));i+=8192}else{const end=this.cardinalities[j]*2;this.containers.push(new RoaringBitmapArray(this.cardinalities[j],u8array.slice(i,i+end),));i+=end}}}contains(keyvalue){const key=keyvalue>>16;const value=keyvalue&0xFFFF;for(let i=0;i=start&&value<=(start+lenm1)){return true}}return false}}class RoaringBitmapArray{constructor(cardinality,array){this.cardinality=cardinality;this.array=array}contains(value){const l=this.cardinality*2;for(let i=0;i>3]&(1<<(value&7)))}}class DocSearch{constructor(rawSearchIndex,rootPath,searchState){this.searchIndexDeprecated=new Map();this.searchIndexEmptyDesc=new Map();this.functionTypeFingerprint=null;this.typeNameIdMap=new Map();this.ALIASES=new Map();this.rootPath=rootPath;this.searchState=searchState;this.typeNameIdOfArray=this.buildTypeMapIndex("array");this.typeNameIdOfSlice=this.buildTypeMapIndex("slice");this.typeNameIdOfArrayOrSlice=this.buildTypeMapIndex("[]");this.typeNameIdOfTuple=this.buildTypeMapIndex("tuple");this.typeNameIdOfUnit=this.buildTypeMapIndex("unit");this.typeNameIdOfTupleOrUnit=this.buildTypeMapIndex("()");this.typeNameIdOfFn=this.buildTypeMapIndex("fn");this.typeNameIdOfFnMut=this.buildTypeMapIndex("fnmut");this.typeNameIdOfFnOnce=this.buildTypeMapIndex("fnonce");this.typeNameIdOfHof=this.buildTypeMapIndex("->");this.EMPTY_BINDINGS_MAP=new Map();this.EMPTY_GENERICS_ARRAY=[];this.TYPES_POOL=new Map();this.searchIndex=this.buildIndex(rawSearchIndex)}buildTypeMapIndex(name,isAssocType){if(name===""||name===null){return null}if(this.typeNameIdMap.has(name)){const obj=this.typeNameIdMap.get(name);obj.assocOnly=isAssocType&&obj.assocOnly;return obj.id}else{const id=this.typeNameIdMap.size;this.typeNameIdMap.set(name,{id,assocOnly:isAssocType});return id}}buildItemSearchTypeAll(types,lowercasePaths){return types.length>0?types.map(type=>this.buildItemSearchType(type,lowercasePaths)):this.EMPTY_GENERICS_ARRAY}buildItemSearchType(type,lowercasePaths,isAssocType){const PATH_INDEX_DATA=0;const GENERICS_DATA=1;const BINDINGS_DATA=2;let pathIndex,generics,bindings;if(typeof type==="number"){pathIndex=type;generics=this.EMPTY_GENERICS_ARRAY;bindings=this.EMPTY_BINDINGS_MAP}else{pathIndex=type[PATH_INDEX_DATA];generics=this.buildItemSearchTypeAll(type[GENERICS_DATA],lowercasePaths,);if(type.length>BINDINGS_DATA&&type[BINDINGS_DATA].length>0){bindings=new Map(type[BINDINGS_DATA].map(binding=>{const[assocType,constraints]=binding;return[this.buildItemSearchType(assocType,lowercasePaths,true).id,this.buildItemSearchTypeAll(constraints,lowercasePaths),]}))}else{bindings=this.EMPTY_BINDINGS_MAP}}let result;if(pathIndex<0){result={id:pathIndex,ty:TY_GENERIC,path:null,exactPath:null,generics,bindings,}}else if(pathIndex===0){result={id:null,ty:null,path:null,exactPath:null,generics,bindings,}}else{const item=lowercasePaths[pathIndex-1];result={id:this.buildTypeMapIndex(item.name,isAssocType),ty:item.ty,path:item.path,exactPath:item.exactPath,generics,bindings,}}const cr=this.TYPES_POOL.get(result.id);if(cr){if(cr.generics.length===result.generics.length&&cr.generics!==result.generics&&cr.generics.every((x,i)=>result.generics[i]===x)){result.generics=cr.generics}if(cr.bindings.size===result.bindings.size&&cr.bindings!==result.bindings){let ok=true;for(const[k,v]of cr.bindings.entries()){const v2=result.bindings.get(v);if(!v2){ok=false;break}if(v!==v2&&v.length===v2.length&&v.every((x,i)=>v2[i]===x)){result.bindings.set(k,v)}else if(v!==v2){ok=false;break}}if(ok){result.bindings=cr.bindings}}if(cr.ty===result.ty&&cr.path===result.path&&cr.bindings===result.bindings&&cr.generics===result.generics&&cr.ty===result.ty){return cr}}this.TYPES_POOL.set(result.id,result);return result}buildFunctionTypeFingerprint(type,output,fps){let input=type.id;if(input===this.typeNameIdOfArray||input===this.typeNameIdOfSlice){input=this.typeNameIdOfArrayOrSlice}if(input===this.typeNameIdOfTuple||input===this.typeNameIdOfUnit){input=this.typeNameIdOfTupleOrUnit}if(input===this.typeNameIdOfFn||input===this.typeNameIdOfFnMut||input===this.typeNameIdOfFnOnce){input=this.typeNameIdOfHof}const hashint1=k=>{k=(~~k+0x7ed55d16)+(k<<12);k=(k ^ 0xc761c23c)^(k>>>19);k=(~~k+0x165667b1)+(k<<5);k=(~~k+0xd3a2646c)^(k<<9);k=(~~k+0xfd7046c5)+(k<<3);return(k ^ 0xb55a4f09)^(k>>>16)};const hashint2=k=>{k=~k+(k<<15);k ^=k>>>12;k+=k<<2;k ^=k>>>4;k=Math.imul(k,2057);return k ^(k>>16)};if(input!==null){const h0a=hashint1(input);const h0b=hashint2(input);const h1a=~~(h0a+Math.imul(h0b,2));const h1b=~~(h0a+Math.imul(h0b,3));const h2a=~~(h0a+Math.imul(h0b,4));const h2b=~~(h0a+Math.imul(h0b,5));output[0]|=(1<<(h0a%32))|(1<<(h1b%32));output[1]|=(1<<(h1a%32))|(1<<(h2b%32));output[2]|=(1<<(h2a%32))|(1<<(h0b%32));fps.add(input)}for(const g of type.generics){this.buildFunctionTypeFingerprint(g,output,fps)}const fb={id:null,ty:0,generics:this.EMPTY_GENERICS_ARRAY,bindings:this.EMPTY_BINDINGS_MAP,};for(const[k,v]of type.bindings.entries()){fb.id=k;fb.generics=v;this.buildFunctionTypeFingerprint(fb,output,fps)}output[3]=fps.size}buildIndex(rawSearchIndex){const buildFunctionSearchTypeCallback=lowercasePaths=>{return functionSearchType=>{if(functionSearchType===0){return null}const INPUTS_DATA=0;const OUTPUT_DATA=1;let inputs,output;if(typeof functionSearchType[INPUTS_DATA]==="number"){inputs=[this.buildItemSearchType(functionSearchType[INPUTS_DATA],lowercasePaths),]}else{inputs=this.buildItemSearchTypeAll(functionSearchType[INPUTS_DATA],lowercasePaths,)}if(functionSearchType.length>1){if(typeof functionSearchType[OUTPUT_DATA]==="number"){output=[this.buildItemSearchType(functionSearchType[OUTPUT_DATA],lowercasePaths,),]}else{output=this.buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA],lowercasePaths,)}}else{output=[]}const where_clause=[];const l=functionSearchType.length;for(let i=2;inoop);let descShard={crate,shard:0,start:0,len:itemDescShardDecoder.next(),promise:null,resolve:null,};const descShardList=[descShard];this.searchIndexDeprecated.set(crate,new RoaringBitmap(crateCorpus.c));this.searchIndexEmptyDesc.set(crate,new RoaringBitmap(crateCorpus.e));let descIndex=0;const crateRow={crate,ty:3,name:crate,path:"",descShard,descIndex,exactPath:"",desc:crateCorpus.doc,parent:undefined,type:null,id,word:crate,normalizedName:crate.indexOf("_")===-1?crate:crate.replace(/_/g,""),bitIndex:0,implDisambiguator:null,};id+=1;searchIndex.push(crateRow);currentIndex+=1;if(!this.searchIndexEmptyDesc.get(crate).contains(0)){descIndex+=1}const itemTypes=crateCorpus.t;const itemNames=crateCorpus.n;const itemPaths=new Map(crateCorpus.q);const itemReexports=new Map(crateCorpus.r);const itemParentIdxDecoder=new VlqHexDecoder(crateCorpus.i,noop=>noop);const implDisambiguator=new Map(crateCorpus.b);const paths=crateCorpus.p;const aliases=crateCorpus.a;const lowercasePaths=[];const itemFunctionDecoder=new VlqHexDecoder(crateCorpus.f,buildFunctionSearchTypeCallback(lowercasePaths),);let len=paths.length;let lastPath=itemPaths.get(0);for(let i=0;i2){path=itemPaths.has(elem[2])?itemPaths.get(elem[2]):lastPath;lastPath=path}const exactPath=elem.length>3?itemPaths.get(elem[3]):path;lowercasePaths.push({ty,name:name.toLowerCase(),path,exactPath});paths[i]={ty,name,path,exactPath}}lastPath="";len=itemTypes.length;let lastName="";let lastWord="";for(let i=0;i=descShard.len&&!this.searchIndexEmptyDesc.get(crate).contains(bitIndex)){descShard={crate,shard:descShard.shard+1,start:descShard.start+descShard.len,len:itemDescShardDecoder.next(),promise:null,resolve:null,};descIndex=0;descShardList.push(descShard)}const name=itemNames[i]===""?lastName:itemNames[i];const word=itemNames[i]===""?lastWord:itemNames[i].toLowerCase();const path=itemPaths.has(i)?itemPaths.get(i):lastPath;const type=itemFunctionDecoder.next();if(type!==null){if(type){const fp=this.functionTypeFingerprint.subarray(id*4,(id+1)*4);const fps=new Set();for(const t of type.inputs){this.buildFunctionTypeFingerprint(t,fp,fps)}for(const t of type.output){this.buildFunctionTypeFingerprint(t,fp,fps)}for(const w of type.where_clause){for(const t of w){this.buildFunctionTypeFingerprint(t,fp,fps)}}}}const itemParentIdx=itemParentIdxDecoder.next();const row={crate,ty:itemTypes.charCodeAt(i)-65,name,path,descShard,descIndex,exactPath:itemReexports.has(i)?itemPaths.get(itemReexports.get(i)):path,parent:itemParentIdx>0?paths[itemParentIdx-1]:undefined,type,id,word,normalizedName:word.indexOf("_")===-1?word:word.replace(/_/g,""),bitIndex,implDisambiguator:implDisambiguator.has(i)?implDisambiguator.get(i):null,};id+=1;searchIndex.push(row);lastPath=row.path;if(!this.searchIndexEmptyDesc.get(crate).contains(bitIndex)){descIndex+=1}lastName=name;lastWord=word}if(aliases){const currentCrateAliases=new Map();this.ALIASES.set(crate,currentCrateAliases);for(const alias_name in aliases){if(!Object.prototype.hasOwnProperty.call(aliases,alias_name)){continue}let currentNameAliases;if(currentCrateAliases.has(alias_name)){currentNameAliases=currentCrateAliases.get(alias_name)}else{currentNameAliases=[];currentCrateAliases.set(alias_name,currentNameAliases)}for(const local_alias of aliases[alias_name]){currentNameAliases.push(local_alias+currentIndex)}}}currentIndex+=itemTypes.length;this.searchState.descShards.set(crate,descShardList)}this.TYPES_POOL=new Map();return searchIndex}static parseQuery(userQuery){function itemTypeFromName(typename){const index=itemTypes.findIndex(i=>i===typename);if(index<0){throw["Unknown type filter ",typename]}return index}function convertTypeFilterOnElem(elem){if(elem.typeFilter!==null){let typeFilter=elem.typeFilter;if(typeFilter==="const"){typeFilter="constant"}elem.typeFilter=itemTypeFromName(typeFilter)}else{elem.typeFilter=NO_TYPE_FILTER}for(const elem2 of elem.generics){convertTypeFilterOnElem(elem2)}for(const constraints of elem.bindings.values()){for(const constraint of constraints){convertTypeFilterOnElem(constraint)}}}function newParsedQuery(userQuery){return{original:userQuery,userQuery:userQuery.toLowerCase(),elems:[],returned:[],foundElems:0,totalElems:0,literalSearch:false,hasReturnArrow:false,error:null,correction:null,proposeCorrectionFrom:null,proposeCorrectionTo:null,typeFingerprint:new Uint32Array(4),}}function parseInput(query,parserState){let foundStopChar=true;while(parserState.pos"){if(isReturnArrow(parserState)){query.hasReturnArrow=true;break}throw["Unexpected ",c," (did you mean ","->","?)"]}else if(parserState.pos>0){throw["Unexpected ",c," after ",parserState.userQuery[parserState.pos-1]]}throw["Unexpected ",c]}else if(c===" "){skipWhitespace(parserState);continue}if(!foundStopChar){let extra="";if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(parserState.typeFilter!==null){throw["Expected ",","," or ","->",...extra,", found ",c,]}throw["Expected ",",",", ",":"," or ","->",...extra,", found ",c,]}const before=query.elems.length;getFilteredNextElem(query,parserState,query.elems,false);if(query.elems.length===before){parserState.pos+=1}foundStopChar=false}if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}while(parserState.pos1}query.foundElems=query.elems.length+query.returned.length;query.totalElems=parserState.totalElems;return query}async execQuery(parsedQuery,filterCrates,currentCrate){const results_others=new Map(),results_in_args=new Map(),results_returned=new Map();function createQueryResults(results_in_args,results_returned,results_others,parsedQuery){return{"in_args":results_in_args,"returned":results_returned,"others":results_others,"query":parsedQuery,}}const buildHrefAndPath=item=>{let displayPath;let href;const type=itemTypes[item.ty];const name=item.name;let path=item.path;let exactPath=item.exactPath;if(type==="mod"){displayPath=path+"::";href=this.rootPath+path.replace(/::/g,"/")+"/"+name+"/index.html"}else if(type==="import"){displayPath=item.path+"::";href=this.rootPath+item.path.replace(/::/g,"/")+"/index.html#reexport."+name}else if(type==="primitive"||type==="keyword"){displayPath="";href=this.rootPath+path.replace(/::/g,"/")+"/"+type+"."+name+".html"}else if(type==="externcrate"){displayPath="";href=this.rootPath+name+"/index.html"}else if(item.parent!==undefined){const myparent=item.parent;let anchor=type+"."+name;const parentType=itemTypes[myparent.ty];let pageType=parentType;let pageName=myparent.name;exactPath=`${myparent.exactPath}::${myparent.name}`;if(parentType==="primitive"){displayPath=myparent.name+"::"}else if(type==="structfield"&&parentType==="variant"){const enumNameIdx=item.path.lastIndexOf("::");const enumName=item.path.substr(enumNameIdx+2);path=item.path.substr(0,enumNameIdx);displayPath=path+"::"+enumName+"::"+myparent.name+"::";anchor="variant."+myparent.name+".field."+name;pageType="enum";pageName=enumName}else{displayPath=path+"::"+myparent.name+"::"}if(item.implDisambiguator!==null){anchor=item.implDisambiguator+"/"+anchor}href=this.rootPath+path.replace(/::/g,"/")+"/"+pageType+"."+pageName+".html#"+anchor}else{displayPath=item.path+"::";href=this.rootPath+item.path.replace(/::/g,"/")+"/"+type+"."+name+".html"}return[displayPath,href,`${exactPath}::${name}`]};function pathSplitter(path){const tmp=""+path.replace(/::/g,"::");if(tmp.endsWith("")){return tmp.slice(0,tmp.length-6)}return tmp}const transformResults=results=>{const duplicates=new Set();const out=[];for(const result of results){if(result.id!==-1){const obj=this.searchIndex[result.id];obj.dist=result.dist;const res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=res[2]+"|"+obj.ty;if(duplicates.has(obj.fullPath)){continue}if(obj.ty===TY_IMPORT&&duplicates.has(res[2])){continue}if(duplicates.has(res[2]+"|"+TY_IMPORT)){continue}duplicates.add(obj.fullPath);duplicates.add(res[2]);obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}return out};const sortResults=async(results,isType,preferredCrate)=>{const userQuery=parsedQuery.userQuery;const casedUserQuery=parsedQuery.original;const result_list=[];for(const result of results.values()){result.item=this.searchIndex[result.id];result.word=this.searchIndex[result.id].word;result_list.push(result)}result_list.sort((aaa,bbb)=>{let a,b;a=(aaa.item.name!==casedUserQuery);b=(bbb.item.name!==casedUserQuery);if(a!==b){return a-b}a=(aaa.word!==userQuery);b=(bbb.word!==userQuery);if(a!==b){return a-b}a=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.path_dist;b=bbb.path_dist;if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}a=(aaa.dist);b=(bbb.dist);if(a!==b){return a-b}a=this.searchIndexDeprecated.get(aaa.item.crate).contains(aaa.item.bitIndex);b=this.searchIndexDeprecated.get(bbb.item.crate).contains(bbb.item.bitIndex);if(a!==b){return a-b}a=(aaa.item.crate!==preferredCrate);b=(bbb.item.crate!==preferredCrate);if(a!==b){return a-b}a=aaa.word.length;b=bbb.word.length;if(a!==b){return a-b}a=aaa.word;b=bbb.word;if(a!==b){return(a>b?+1:-1)}a=this.searchIndexEmptyDesc.get(aaa.item.crate).contains(aaa.item.bitIndex);b=this.searchIndexEmptyDesc.get(bbb.item.crate).contains(bbb.item.bitIndex);if(a!==b){return a-b}a=aaa.item.ty;b=bbb.item.ty;if(a!==b){return a-b}a=aaa.item.path;b=bbb.item.path;if(a!==b){return(a>b?+1:-1)}return 0});return transformResults(result_list)};function unifyFunctionTypes(fnTypesIn,queryElems,whereClause,mgensIn,solutionCb,unboxingDepth,){if(unboxingDepth>=UNBOXING_LIMIT){return false}const mgens=mgensIn===null?null:new Map(mgensIn);if(queryElems.length===0){return!solutionCb||solutionCb(mgens)}if(!fnTypesIn||fnTypesIn.length===0){return false}const ql=queryElems.length;const fl=fnTypesIn.length;if(ql===1&&queryElems[0].generics.length===0&&queryElems[0].bindings.size===0){const queryElem=queryElems[0];for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgens)){continue}if(fnType.id<0&&queryElem.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==queryElem.id){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,queryElem.id);if(!solutionCb||solutionCb(mgensScratch)){return true}}else if(!solutionCb||solutionCb(mgens?new Map(mgens):null)){return true}}for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth+1,)){continue}if(fnType.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,0);if(unifyFunctionTypes(whereClause[(-fnType.id)-1],queryElems,whereClause,mgensScratch,solutionCb,unboxingDepth+1,)){return true}}else if(unifyFunctionTypes([...fnType.generics,...Array.from(fnType.bindings.values()).flat()],queryElems,whereClause,mgens?new Map(mgens):null,solutionCb,unboxingDepth+1,)){return true}}return false}const fnTypes=fnTypesIn.slice();const flast=fl-1;const qlast=ql-1;const queryElem=queryElems[qlast];let queryElemsTmp=null;for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,mgens)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==queryElem.id){continue}mgensScratch.set(fnType.id,queryElem.id)}else{mgensScratch=mgens}fnTypes[i]=fnTypes[flast];fnTypes.length=flast;if(!queryElemsTmp){queryElemsTmp=queryElems.slice(0,qlast)}const passesUnification=unifyFunctionTypes(fnTypes,queryElemsTmp,whereClause,mgensScratch,mgensScratch=>{if(fnType.generics.length===0&&queryElem.generics.length===0&&fnType.bindings.size===0&&queryElem.bindings.size===0){return!solutionCb||solutionCb(mgensScratch)}const solution=unifyFunctionTypeCheckBindings(fnType,queryElem,whereClause,mgensScratch,unboxingDepth,);if(!solution){return false}const simplifiedGenerics=solution.simplifiedGenerics;for(const simplifiedMgens of solution.mgens){const passesUnification=unifyFunctionTypes(simplifiedGenerics,queryElem.generics,whereClause,simplifiedMgens,solutionCb,unboxingDepth,);if(passesUnification){return true}}return false},unboxingDepth,);if(passesUnification){return true}fnTypes[flast]=fnTypes[i];fnTypes[i]=fnType;fnTypes.length=fl}for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth+1,)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==0){continue}mgensScratch.set(fnType.id,0)}else{mgensScratch=mgens}const generics=fnType.id<0?whereClause[(-fnType.id)-1]:fnType.generics;const bindings=fnType.bindings?Array.from(fnType.bindings.values()).flat():[];const passesUnification=unifyFunctionTypes(fnTypes.toSpliced(i,1,...generics,...bindings),queryElems,whereClause,mgensScratch,solutionCb,unboxingDepth+1,);if(passesUnification){return true}}return false}const unifyFunctionTypeIsMatchCandidate=(fnType,queryElem,mgensIn)=>{if(!typePassesFilter(queryElem.typeFilter,fnType.ty)){return false}if(fnType.id<0&&queryElem.id<0){if(mgensIn){if(mgensIn.has(fnType.id)&&mgensIn.get(fnType.id)!==queryElem.id){return false}for(const[fid,qid]of mgensIn.entries()){if(fnType.id!==fid&&queryElem.id===qid){return false}if(fnType.id===fid&&queryElem.id!==qid){return false}}}return true}else{if(queryElem.id===this.typeNameIdOfArrayOrSlice&&(fnType.id===this.typeNameIdOfSlice||fnType.id===this.typeNameIdOfArray)){}else if(queryElem.id===this.typeNameIdOfTupleOrUnit&&(fnType.id===this.typeNameIdOfTuple||fnType.id===this.typeNameIdOfUnit)){}else if(queryElem.id===this.typeNameIdOfHof&&(fnType.id===this.typeNameIdOfFn||fnType.id===this.typeNameIdOfFnMut||fnType.id===this.typeNameIdOfFnOnce)){}else if(fnType.id!==queryElem.id||queryElem.id===null){return false}if((fnType.generics.length+fnType.bindings.size)===0&&queryElem.generics.length!==0){return false}if(fnType.bindings.size0){const fnTypePath=fnType.path!==undefined&&fnType.path!==null?fnType.path.split("::"):[];if(queryElemPathLength>fnTypePath.length){return false}let i=0;for(const path of fnTypePath){if(path===queryElem.pathWithoutLast[i]){i+=1;if(i>=queryElemPathLength){break}}}if(i0){let mgensSolutionSet=[mgensIn];for(const[name,constraints]of queryElem.bindings.entries()){if(mgensSolutionSet.length===0){return false}if(!fnType.bindings.has(name)){return false}const fnTypeBindings=fnType.bindings.get(name);mgensSolutionSet=mgensSolutionSet.flatMap(mgens=>{const newSolutions=[];unifyFunctionTypes(fnTypeBindings,constraints,whereClause,mgens,newMgens=>{newSolutions.push(newMgens);return false},unboxingDepth,);return newSolutions})}if(mgensSolutionSet.length===0){return false}const binds=Array.from(fnType.bindings.entries()).flatMap(entry=>{const[name,constraints]=entry;if(queryElem.bindings.has(name)){return[]}else{return constraints}});if(simplifiedGenerics.length>0){simplifiedGenerics=[...simplifiedGenerics,...binds]}else{simplifiedGenerics=binds}return{simplifiedGenerics,mgens:mgensSolutionSet}}return{simplifiedGenerics,mgens:[mgensIn]}}function unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens,unboxingDepth,){if(unboxingDepth>=UNBOXING_LIMIT){return false}if(fnType.id<0&&queryElem.id>=0){if(!whereClause){return false}if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){return false}const mgensTmp=new Map(mgens);mgensTmp.set(fnType.id,null);return checkIfInList(whereClause[(-fnType.id)-1],queryElem,whereClause,mgensTmp,unboxingDepth,)}else if(fnType.generics.length>0||fnType.bindings.size>0){const simplifiedGenerics=[...fnType.generics,...Array.from(fnType.bindings.values()).flat(),];return checkIfInList(simplifiedGenerics,queryElem,whereClause,mgens,unboxingDepth,)}return false}function checkIfInList(list,elem,whereClause,mgens,unboxingDepth){for(const entry of list){if(checkType(entry,elem,whereClause,mgens,unboxingDepth)){return true}}return false}const checkType=(row,elem,whereClause,mgens,unboxingDepth)=>{if(unboxingDepth>=UNBOXING_LIMIT){return false}if(row.bindings.size===0&&elem.bindings.size===0){if(elem.id<0&&mgens===null){return row.id<0||checkIfInList(row.generics,elem,whereClause,mgens,unboxingDepth+1,)}if(row.id>0&&elem.id>0&&elem.pathWithoutLast.length===0&&typePassesFilter(elem.typeFilter,row.ty)&&elem.generics.length===0&&elem.id!==this.typeNameIdOfArrayOrSlice&&elem.id!==this.typeNameIdOfTupleOrUnit&&elem.id!==this.typeNameIdOfHof){return row.id===elem.id||checkIfInList(row.generics,elem,whereClause,mgens,unboxingDepth,)}}return unifyFunctionTypes([row],[elem],whereClause,mgens,null,unboxingDepth)};function checkPath(contains,ty){if(contains.length===0){return 0}const maxPathEditDistance=Math.floor(contains.reduce((acc,next)=>acc+next.length,0)/3,);let ret_dist=maxPathEditDistance+1;const path=ty.path.split("::");if(ty.parent&&ty.parent.name){path.push(ty.parent.name.toLowerCase())}const length=path.length;const clength=contains.length;pathiter:for(let i=length-clength;i>=0;i-=1){let dist_total=0;for(let x=0;xmaxPathEditDistance){continue pathiter}dist_total+=dist}}ret_dist=Math.min(ret_dist,Math.round(dist_total/clength))}return ret_dist>maxPathEditDistance?null:ret_dist}function typePassesFilter(filter,type){if(filter<=NO_TYPE_FILTER||filter===type)return true;const name=itemTypes[type];switch(itemTypes[filter]){case"constant":return name==="associatedconstant";case"fn":return name==="method"||name==="tymethod";case"type":return name==="primitive"||name==="associatedtype";case"trait":return name==="traitalias"}return false}function createAliasFromItem(item){return{crate:item.crate,name:item.name,path:item.path,descShard:item.descShard,descIndex:item.descIndex,exactPath:item.exactPath,ty:item.ty,parent:item.parent,type:item.type,is_alias:true,bitIndex:item.bitIndex,implDisambiguator:item.implDisambiguator,}}const handleAliases=async(ret,query,filterCrates,currentCrate)=>{const lowerQuery=query.toLowerCase();const aliases=[];const crateAliases=[];if(filterCrates!==null){if(this.ALIASES.has(filterCrates)&&this.ALIASES.get(filterCrates).has(lowerQuery)){const query_aliases=this.ALIASES.get(filterCrates).get(lowerQuery);for(const alias of query_aliases){aliases.push(createAliasFromItem(this.searchIndex[alias]))}}}else{for(const[crate,crateAliasesIndex]of this.ALIASES){if(crateAliasesIndex.has(lowerQuery)){const pushTo=crate===currentCrate?crateAliases:aliases;const query_aliases=crateAliasesIndex.get(lowerQuery);for(const alias of query_aliases){pushTo.push(createAliasFromItem(this.searchIndex[alias]))}}}}const sortFunc=(aaa,bbb)=>{if(aaa.path{return this.searchIndexEmptyDesc.get(alias.crate).contains(alias.bitIndex)?"":this.searchState.loadDesc(alias)};const[crateDescs,descs]=await Promise.all([Promise.all(crateAliases.map(fetchDesc)),Promise.all(aliases.map(fetchDesc)),]);const pushFunc=alias=>{alias.alias=query;const res=buildHrefAndPath(alias);alias.displayPath=pathSplitter(res[0]);alias.fullPath=alias.displayPath+alias.name;alias.href=res[1];ret.others.unshift(alias);if(ret.others.length>MAX_RESULTS){ret.others.pop()}};aliases.forEach((alias,i)=>{alias.desc=descs[i]});aliases.forEach(pushFunc);crateAliases.forEach((alias,i)=>{alias.desc=crateDescs[i]});crateAliases.forEach(pushFunc)};function addIntoResults(results,fullId,id,index,dist,path_dist,maxEditDistance){if(dist<=maxEditDistance||index!==-1){if(results.has(fullId)){const result=results.get(fullId);if(result.dontValidate||result.dist<=dist){return}}results.set(fullId,{id:id,index:index,dontValidate:parsedQuery.literalSearch,dist:dist,path_dist:path_dist,})}}function handleSingleArg(row,pos,elem,results_others,results_in_args,results_returned,maxEditDistance,){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let path_dist=0;const fullId=row.id;const tfpDist=compareTypeFingerprints(fullId,parsedQuery.typeFingerprint,);if(tfpDist!==null){const in_args=row.type&&row.type.inputs&&checkIfInList(row.type.inputs,elem,row.type.where_clause,null,0);const returned=row.type&&row.type.output&&checkIfInList(row.type.output,elem,row.type.where_clause,null,0);if(in_args){results_in_args.max_dist=Math.max(results_in_args.max_dist||0,tfpDist);const maxDist=results_in_args.sizenormalizedIndex&&normalizedIndex!==-1)){index=normalizedIndex}if(elem.fullPath.length>1){path_dist=checkPath(elem.pathWithoutLast,row);if(path_dist===null){return}}if(parsedQuery.literalSearch){if(row.word===elem.pathLast){addIntoResults(results_others,fullId,pos,index,0,path_dist)}return}const dist=editDistance(row.normalizedName,elem.normalizedPathLast,maxEditDistance);if(index===-1&&dist>maxEditDistance){return}addIntoResults(results_others,fullId,pos,index,dist,path_dist,maxEditDistance)}function handleArgs(row,pos,results){if(!row||(filterCrates!==null&&row.crate!==filterCrates)||!row.type){return}const tfpDist=compareTypeFingerprints(row.id,parsedQuery.typeFingerprint,);if(tfpDist===null){return}if(results.size>=MAX_RESULTS&&tfpDist>results.max_dist){return}if(!unifyFunctionTypes(row.type.inputs,parsedQuery.elems,row.type.where_clause,null,mgens=>{return unifyFunctionTypes(row.type.output,parsedQuery.returned,row.type.where_clause,mgens,null,0,)},0,)){return}results.max_dist=Math.max(results.max_dist||0,tfpDist);addIntoResults(results,row.id,pos,0,tfpDist,0,Number.MAX_VALUE)}const compareTypeFingerprints=(fullId,queryFingerprint)=>{const fh0=this.functionTypeFingerprint[fullId*4];const fh1=this.functionTypeFingerprint[(fullId*4)+1];const fh2=this.functionTypeFingerprint[(fullId*4)+2];const[qh0,qh1,qh2]=queryFingerprint;const[in0,in1,in2]=[fh0&qh0,fh1&qh1,fh2&qh2];if((in0 ^ qh0)||(in1 ^ qh1)||(in2 ^ qh2)){return null}return this.functionTypeFingerprint[(fullId*4)+3]};const innerRunQuery=()=>{const queryLen=parsedQuery.elems.reduce((acc,next)=>acc+next.pathLast.length,0)+parsedQuery.returned.reduce((acc,next)=>acc+next.pathLast.length,0);const maxEditDistance=Math.floor(queryLen/3);const genericSymbols=new Map();const convertNameToId=(elem,isAssocType)=>{const loweredName=elem.pathLast.toLowerCase();if(this.typeNameIdMap.has(loweredName)&&(isAssocType||!this.typeNameIdMap.get(loweredName).assocOnly)){elem.id=this.typeNameIdMap.get(loweredName).id}else if(!parsedQuery.literalSearch){let match=null;let matchDist=maxEditDistance+1;let matchName="";for(const[name,{id,assocOnly}]of this.typeNameIdMap){const dist=Math.min(editDistance(name,loweredName,maxEditDistance),editDistance(name,elem.normalizedPathLast,maxEditDistance),);if(dist<=matchDist&&dist<=maxEditDistance&&(isAssocType||!assocOnly)){if(dist===matchDist&&matchName>name){continue}match=id;matchDist=dist;matchName=name}}if(match!==null){parsedQuery.correction=matchName}elem.id=match}if((elem.id===null&&parsedQuery.totalElems>1&&elem.typeFilter===-1&&elem.generics.length===0&&elem.bindings.size===0)||elem.typeFilter===TY_GENERIC){if(genericSymbols.has(elem.name)){elem.id=genericSymbols.get(elem.name)}else{elem.id=-(genericSymbols.size+1);genericSymbols.set(elem.name,elem.id)}if(elem.typeFilter===-1&&elem.name.length>=3){const maxPartDistance=Math.floor(elem.name.length/3);let matchDist=maxPartDistance+1;let matchName="";for(const name of this.typeNameIdMap.keys()){const dist=editDistance(name,elem.name,maxPartDistance);if(dist<=matchDist&&dist<=maxPartDistance){if(dist===matchDist&&matchName>name){continue}matchDist=dist;matchName=name}}if(matchName!==""){parsedQuery.proposeCorrectionFrom=elem.name;parsedQuery.proposeCorrectionTo=matchName}}elem.typeFilter=TY_GENERIC}if(elem.generics.length>0&&elem.typeFilter===TY_GENERIC){parsedQuery.error=["Generic type parameter ",elem.name," does not accept generic parameters",]}for(const elem2 of elem.generics){convertNameToId(elem2)}elem.bindings=new Map(Array.from(elem.bindings.entries()).map(entry=>{const[name,constraints]=entry;if(!this.typeNameIdMap.has(name)){parsedQuery.error=["Type parameter ",name," does not exist",];return[null,[]]}for(const elem2 of constraints){convertNameToId(elem2)}return[this.typeNameIdMap.get(name).id,constraints]}),)};const fps=new Set();for(const elem of parsedQuery.elems){convertNameToId(elem);this.buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}for(const elem of parsedQuery.returned){convertNameToId(elem);this.buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}if(parsedQuery.foundElems===1&&!parsedQuery.hasReturnArrow){if(parsedQuery.elems.length===1){const elem=parsedQuery.elems[0];const length=this.searchIndex.length;for(let i=0,nSearchIndex=length;i0){const sortQ=(a,b)=>{const ag=a.generics.length===0&&a.bindings.size===0;const bg=b.generics.length===0&&b.bindings.size===0;if(ag!==bg){return ag-bg}const ai=a.id>0;const bi=b.id>0;return ai-bi};parsedQuery.elems.sort(sortQ);parsedQuery.returned.sort(sortQ);for(let i=0,nSearchIndex=this.searchIndex.length;i{const descs=await Promise.all(list.map(result=>{return this.searchIndexEmptyDesc.get(result.crate).contains(result.bitIndex)?"":this.searchState.loadDesc(result)}));for(const[i,result]of list.entries()){result.desc=descs[i]}}));if(parsedQuery.error!==null&&ret.others.length!==0){ret.query.error=null}return ret}}let rawSearchIndex;let docSearch;const longItemTypes=["keyword","primitive type","module","extern crate","re-export","struct","enum","function","type alias","static","trait","","trait method","method","struct field","enum variant","macro","assoc type","constant","assoc const","union","foreign type","existential type","attribute macro","derive macro","trait alias",];let currentResults;function printTab(nb){let iter=0;let foundCurrentTab=false;let foundCurrentResultSet=false;onEachLazy(document.getElementById("search-tabs").childNodes,elem=>{if(nb===iter){addClass(elem,"selected");foundCurrentTab=true}else{removeClass(elem,"selected")}iter+=1});const isTypeSearch=(nb>0||iter===1);iter=0;onEachLazy(document.getElementById("results").childNodes,elem=>{if(nb===iter){addClass(elem,"active");foundCurrentResultSet=true}else{removeClass(elem,"active")}iter+=1});if(foundCurrentTab&&foundCurrentResultSet){searchState.currentTab=nb;const correctionsElem=document.getElementsByClassName("search-corrections");if(isTypeSearch){removeClass(correctionsElem[0],"hidden")}else{addClass(correctionsElem[0],"hidden")}}else if(nb!==0){printTab(0)}}function buildUrl(search,filterCrates){let extra="?search="+encodeURIComponent(search);if(filterCrates!==null){extra+="&filter-crate="+encodeURIComponent(filterCrates)}return getNakedUrl()+extra+window.location.hash}function getFilterCrates(){const elem=document.getElementById("crate-search");if(elem&&elem.value!=="all crates"&&window.searchIndex.has(elem.value)){return elem.value}return null}function nextTab(direction){const next=(searchState.currentTab+direction+3)%searchState.focusedByTab.length;searchState.focusedByTab[searchState.currentTab]=document.activeElement;printTab(next);focusSearchResult()}function focusSearchResult(){const target=searchState.focusedByTab[searchState.currentTab]||document.querySelectorAll(".search-results.active a").item(0)||document.querySelectorAll("#search-tabs button").item(searchState.currentTab);searchState.focusedByTab[searchState.currentTab]=null;if(target){target.focus()}}async function addTab(array,query,display){const extraClass=display?" active":"";const output=document.createElement("div");if(array.length>0){output.className="search-results "+extraClass;for(const item of array){const name=item.name;const type=itemTypes[item.ty];const longType=longItemTypes[item.ty];const typeName=longType.length!==0?`${longType}`:"?";const link=document.createElement("a");link.className="result-"+type;link.href=item.href;const resultName=document.createElement("div");resultName.className="result-name";resultName.insertAdjacentHTML("beforeend",`${typeName}`);link.appendChild(resultName);let alias=" ";if(item.is_alias){alias=`
\ +${item.alias} - see \ +
`}resultName.insertAdjacentHTML("beforeend",`
${alias}\ +${item.displayPath}${name}\ +
`);const description=document.createElement("div");description.className="desc";description.insertAdjacentHTML("beforeend",item.desc);link.appendChild(description);output.appendChild(link)}}else if(query.error===null){output.className="search-failed"+extraClass;output.innerHTML="No results :(
"+"Try on DuckDuckGo?

"+"Or try looking in one of these:"}return[output,array.length]}function makeTabHeader(tabNb,text,nbElems){const fmtNbElems=nbElems<10?`\u{2007}(${nbElems})\u{2007}\u{2007}`:nbElems<100?`\u{2007}(${nbElems})\u{2007}`:`\u{2007}(${nbElems})`;if(searchState.currentTab===tabNb){return""}return""}async function showResults(results,go_to_first,filterCrates){const search=searchState.outputElement();if(go_to_first||(results.others.length===1&&getSettingValue("go-to-only-result")==="true")){window.onunload=()=>{};searchState.removeQueryParameters();const elem=document.createElement("a");elem.href=results.others[0].href;removeClass(elem,"active");document.body.appendChild(elem);elem.click();return}if(results.query===undefined){results.query=DocSearch.parseQuery(searchState.input.value)}currentResults=results.query.userQuery;const[ret_others,ret_in_args,ret_returned]=await Promise.all([addTab(results.others,results.query,true),addTab(results.in_args,results.query,false),addTab(results.returned,results.query,false),]);let currentTab=searchState.currentTab;if((currentTab===0&&ret_others[1]===0)||(currentTab===1&&ret_in_args[1]===0)||(currentTab===2&&ret_returned[1]===0)){if(ret_others[1]!==0){currentTab=0}else if(ret_in_args[1]!==0){currentTab=1}else if(ret_returned[1]!==0){currentTab=2}}let crates="";if(rawSearchIndex.size>1){crates="
in 
"+"
"}let output=`
\ +

Results

${crates}
`;if(results.query.error!==null){const error=results.query.error;error.forEach((value,index)=>{value=value.split("<").join("<").split(">").join(">");if(index%2!==0){error[index]=`${value.replaceAll(" ", " ")}`}else{error[index]=value}});output+=`

Query parser error: "${error.join("")}".

`;output+="
"+makeTabHeader(0,"In Names",ret_others[1])+"
";currentTab=0}else if(results.query.foundElems<=1&&results.query.returned.length===0){output+="
"+makeTabHeader(0,"In Names",ret_others[1])+makeTabHeader(1,"In Parameters",ret_in_args[1])+makeTabHeader(2,"In Return Types",ret_returned[1])+"
"}else{const signatureTabTitle=results.query.elems.length===0?"In Function Return Types":results.query.returned.length===0?"In Function Parameters":"In Function Signatures";output+="
"+makeTabHeader(0,signatureTabTitle,ret_others[1])+"
";currentTab=0}if(results.query.correction!==null){const orig=results.query.returned.length>0?results.query.returned[0].name:results.query.elems[0].name;output+="

"+`Type "${orig}" not found. `+"Showing results for closest type name "+`"${results.query.correction}" instead.

`}if(results.query.proposeCorrectionFrom!==null){const orig=results.query.proposeCorrectionFrom;const targ=results.query.proposeCorrectionTo;output+="

"+`Type "${orig}" not found and used as generic parameter. `+`Consider searching for "${targ}" instead.

`}const resultsElem=document.createElement("div");resultsElem.id="results";resultsElem.appendChild(ret_others[0]);resultsElem.appendChild(ret_in_args[0]);resultsElem.appendChild(ret_returned[0]);search.innerHTML=output;if(searchState.rustdocToolbar){search.querySelector(".main-heading").appendChild(searchState.rustdocToolbar)}const crateSearch=document.getElementById("crate-search");if(crateSearch){crateSearch.addEventListener("input",updateCrate)}search.appendChild(resultsElem);searchState.showResults(search);const elems=document.getElementById("search-tabs").childNodes;searchState.focusedByTab=[];let i=0;for(const elem of elems){const j=i;elem.onclick=()=>printTab(j);searchState.focusedByTab.push(null);i+=1}printTab(currentTab)}function updateSearchHistory(url){if(!browserSupportsHistoryApi()){return}const params=searchState.getQueryStringParams();if(!history.state&&!params.search){history.pushState(null,"",url)}else{history.replaceState(null,"",url)}}async function search(forced){const query=DocSearch.parseQuery(searchState.input.value.trim());let filterCrates=getFilterCrates();if(!forced&&query.userQuery===currentResults){if(query.userQuery.length>0){putBackSearch()}return}searchState.setLoadingSearch();const params=searchState.getQueryStringParams();if(filterCrates===null&¶ms["filter-crate"]!==undefined){filterCrates=params["filter-crate"]}searchState.title="\""+query.original+"\" Search - Rust";updateSearchHistory(buildUrl(query.original,filterCrates));await showResults(await docSearch.execQuery(query,filterCrates,window.currentCrate),params.go_to_first,filterCrates)}function onSearchSubmit(e){e.preventDefault();searchState.clearInputTimeout();search()}function putBackSearch(){const search_input=searchState.input;if(!searchState.input){return}if(search_input.value!==""&&!searchState.isDisplayed()){searchState.showResults();if(browserSupportsHistoryApi()){history.replaceState(null,"",buildUrl(search_input.value,getFilterCrates()))}document.title=searchState.title}}function registerSearchEvents(){const params=searchState.getQueryStringParams();if(searchState.input.value===""){searchState.input.value=params.search||""}const searchAfter500ms=()=>{searchState.clearInputTimeout();if(searchState.input.value.length===0){searchState.hideResults()}else{searchState.timeout=setTimeout(search,500)}};searchState.input.onkeyup=searchAfter500ms;searchState.input.oninput=searchAfter500ms;document.getElementsByClassName("search-form")[0].onsubmit=onSearchSubmit;searchState.input.onchange=e=>{if(e.target!==document.activeElement){return}searchState.clearInputTimeout();setTimeout(search,0)};searchState.input.onpaste=searchState.input.onchange;searchState.outputElement().addEventListener("keydown",e=>{if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey){return}if(e.which===38){const previous=document.activeElement.previousElementSibling;if(previous){previous.focus()}else{searchState.focus()}e.preventDefault()}else if(e.which===40){const next=document.activeElement.nextElementSibling;if(next){next.focus()}const rect=document.activeElement.getBoundingClientRect();if(window.innerHeight-rect.bottom{if(e.which===40){focusSearchResult();e.preventDefault()}});searchState.input.addEventListener("focus",()=>{putBackSearch()});searchState.input.addEventListener("blur",()=>{searchState.input.placeholder=searchState.input.origPlaceholder});if(browserSupportsHistoryApi()){const previousTitle=document.title;window.addEventListener("popstate",e=>{const params=searchState.getQueryStringParams();document.title=previousTitle;currentResults=null;if(params.search&¶ms.search.length>0){searchState.input.value=params.search;e.preventDefault();search()}else{searchState.input.value="";searchState.hideResults()}})}window.onpageshow=()=>{const qSearch=searchState.getQueryStringParams().search;if(searchState.input.value===""&&qSearch){searchState.input.value=qSearch}search()}}function updateCrate(ev){if(ev.target.value==="all crates"){const query=searchState.input.value.trim();updateSearchHistory(buildUrl(query,null))}currentResults=null;search(true)}function initSearch(searchIndx){rawSearchIndex=searchIndx;if(typeof window!=="undefined"){docSearch=new DocSearch(rawSearchIndex,ROOT_PATH,searchState);registerSearchEvents();if(window.searchState.getQueryStringParams().search){search()}}else if(typeof exports!=="undefined"){docSearch=new DocSearch(rawSearchIndex,ROOT_PATH,searchState);exports.docSearch=docSearch;exports.parseQuery=DocSearch.parseQuery}}if(typeof exports!=="undefined"){exports.initSearch=initSearch}if(typeof window!=="undefined"){window.initSearch=initSearch;if(window.searchIndex!==undefined){initSearch(window.searchIndex)}}else{initSearch(new Map())}})() \ No newline at end of file diff --git a/static.files/settings-805db61a62df4bd2.js b/static.files/settings-805db61a62df4bd2.js new file mode 100644 index 00000000..4a30479d --- /dev/null +++ b/static.files/settings-805db61a62df4bd2.js @@ -0,0 +1,17 @@ +"use strict";(function(){const isSettingsPage=window.location.pathname.endsWith("/settings.html");function changeSetting(settingName,value){if(settingName==="theme"){const useSystem=value==="system preference"?"true":"false";updateLocalStorage("use-system-theme",useSystem)}updateLocalStorage(settingName,value);switch(settingName){case"theme":case"preferred-dark-theme":case"preferred-light-theme":updateTheme();updateLightAndDark();break;case"line-numbers":if(value===true){window.rustdoc_add_line_numbers_to_examples()}else{window.rustdoc_remove_line_numbers_from_examples()}break;case"hide-sidebar":if(value===true){addClass(document.documentElement,"hide-sidebar")}else{removeClass(document.documentElement,"hide-sidebar")}break;case"hide-toc":if(value===true){addClass(document.documentElement,"hide-toc")}else{removeClass(document.documentElement,"hide-toc")}break;case"hide-modnav":if(value===true){addClass(document.documentElement,"hide-modnav")}else{removeClass(document.documentElement,"hide-modnav")}break}}function showLightAndDark(){removeClass(document.getElementById("preferred-light-theme"),"hidden");removeClass(document.getElementById("preferred-dark-theme"),"hidden")}function hideLightAndDark(){addClass(document.getElementById("preferred-light-theme"),"hidden");addClass(document.getElementById("preferred-dark-theme"),"hidden")}function updateLightAndDark(){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||(useSystem===null&&getSettingValue("theme")===null)){showLightAndDark()}else{hideLightAndDark()}}function setEvents(settingsElement){updateLightAndDark();onEachLazy(settingsElement.querySelectorAll("input[type=\"checkbox\"]"),toggle=>{const settingId=toggle.id;const settingValue=getSettingValue(settingId);if(settingValue!==null){toggle.checked=settingValue==="true"}toggle.onchange=()=>{changeSetting(toggle.id,toggle.checked)}});onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"),elem=>{const settingId=elem.name;let settingValue=getSettingValue(settingId);if(settingId==="theme"){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||settingValue===null){settingValue=useSystem==="false"?"light":"system preference"}}if(settingValue!==null&&settingValue!=="null"){elem.checked=settingValue===elem.value}elem.addEventListener("change",ev=>{changeSetting(ev.target.name,ev.target.value)})})}function buildSettingsPageSections(settings){let output="";for(const setting of settings){if(setting==="hr"){output+="
";continue}const js_data_name=setting["js_name"];const setting_name=setting["name"];if(setting["options"]!==undefined){output+=`\ +
+
${setting_name}
+
`;onEach(setting["options"],option=>{const checked=option===setting["default"]?" checked":"";const full=`${js_data_name}-${option.replace(/ /g,"-")}`;output+=`\ + `});output+=`\ +
+
`}else{const checked=setting["default"]===true?" checked":"";output+=`\ +
\ + \ +
`}}return output}function buildSettingsPage(){const theme_names=getVar("themes").split(",").filter(t=>t);theme_names.push("light","dark","ayu");const settings=[{"name":"Theme","js_name":"theme","default":"system preference","options":theme_names.concat("system preference"),},{"name":"Preferred light theme","js_name":"preferred-light-theme","default":"light","options":theme_names,},{"name":"Preferred dark theme","js_name":"preferred-dark-theme","default":"dark","options":theme_names,},{"name":"Auto-hide item contents for large items","js_name":"auto-hide-large-items","default":true,},{"name":"Auto-hide item methods' documentation","js_name":"auto-hide-method-docs","default":false,},{"name":"Auto-hide trait implementation documentation","js_name":"auto-hide-trait-implementations","default":false,},{"name":"Directly go to item in search if there is only one result","js_name":"go-to-only-result","default":false,},{"name":"Show line numbers on code examples","js_name":"line-numbers","default":false,},{"name":"Hide persistent navigation bar","js_name":"hide-sidebar","default":false,},{"name":"Hide table of contents","js_name":"hide-toc","default":false,},{"name":"Hide module navigation","js_name":"hide-modnav","default":false,},{"name":"Disable keyboard shortcuts","js_name":"disable-shortcuts","default":false,},];const elementKind=isSettingsPage?"section":"div";const innerHTML=`
${buildSettingsPageSections(settings)}
`;const el=document.createElement(elementKind);el.id="settings";if(!isSettingsPage){el.className="popover"}el.innerHTML=innerHTML;if(isSettingsPage){document.getElementById(MAIN_ID).appendChild(el)}else{el.setAttribute("tabindex","-1");getSettingsButton().appendChild(el)}return el}const settingsMenu=buildSettingsPage();function displaySettings(){settingsMenu.style.display="";onEachLazy(settingsMenu.querySelectorAll("input[type='checkbox']"),el=>{const val=getSettingValue(el.id);const checked=val==="true";if(checked!==el.checked&&val!==null){el.checked=checked}})}function settingsBlurHandler(event){if(!getHelpButton().contains(document.activeElement)&&!getHelpButton().contains(event.relatedTarget)&&!getSettingsButton().contains(document.activeElement)&&!getSettingsButton().contains(event.relatedTarget)){window.hidePopoverMenus()}}if(!isSettingsPage){const settingsButton=getSettingsButton();const settingsMenu=document.getElementById("settings");settingsButton.onclick=event=>{if(settingsMenu.contains(event.target)){return}event.preventDefault();const shouldDisplaySettings=settingsMenu.style.display==="none";window.hideAllModals();if(shouldDisplaySettings){displaySettings()}};settingsButton.onblur=settingsBlurHandler;settingsButton.querySelector("a").onblur=settingsBlurHandler;onEachLazy(settingsMenu.querySelectorAll("input"),el=>{el.onblur=settingsBlurHandler});settingsMenu.onblur=settingsBlurHandler}setTimeout(()=>{setEvents(settingsMenu);if(!isSettingsPage){displaySettings()}removeClass(getSettingsButton(),"rotate")},0)})() \ No newline at end of file diff --git a/static.files/src-script-e66d777a5a92e9b2.js b/static.files/src-script-e66d777a5a92e9b2.js new file mode 100644 index 00000000..d0aebb85 --- /dev/null +++ b/static.files/src-script-e66d777a5a92e9b2.js @@ -0,0 +1 @@ +"use strict";(function(){const rootPath=getVar("root-path");const NAME_OFFSET=0;const DIRS_OFFSET=1;const FILES_OFFSET=2;const RUSTDOC_MOBILE_BREAKPOINT=700;function closeSidebarIfMobile(){if(window.innerWidth{removeClass(document.documentElement,"src-sidebar-expanded");updateLocalStorage("source-sidebar-show","false")};window.rustdocShowSourceSidebar=()=>{addClass(document.documentElement,"src-sidebar-expanded");updateLocalStorage("source-sidebar-show","true")};window.rustdocToggleSrcSidebar=()=>{if(document.documentElement.classList.contains("src-sidebar-expanded")){window.rustdocCloseSourceSidebar()}else{window.rustdocShowSourceSidebar()}};function createSrcSidebar(){const container=document.querySelector("nav.sidebar");const sidebar=document.createElement("div");sidebar.id="src-sidebar";let hasFoundFile=false;for(const[key,source]of srcIndex){source[NAME_OFFSET]=key;hasFoundFile=createDirEntry(source,sidebar,"",hasFoundFile)}container.appendChild(sidebar);const selected_elem=sidebar.getElementsByClassName("selected")[0];if(typeof selected_elem!=="undefined"){selected_elem.focus()}}function highlightSrcLines(){const match=window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);if(!match){return}let from=parseInt(match[1],10);let to=from;if(typeof match[2]!=="undefined"){to=parseInt(match[2],10)}if(to{onEachLazy(e.getElementsByTagName("a"),i_e=>{removeClass(i_e,"line-highlighted")})});for(let i=from;i<=to;++i){elem=document.getElementById(i);if(!elem){break}addClass(elem,"line-highlighted")}}const handleSrcHighlight=(function(){let prev_line_id=0;const set_fragment=name=>{const x=window.scrollX,y=window.scrollY;if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);highlightSrcLines()}else{location.replace("#"+name)}window.scrollTo(x,y)};return ev=>{let cur_line_id=parseInt(ev.target.id,10);if(isNaN(cur_line_id)||ev.ctrlKey||ev.altKey||ev.metaKey){return}ev.preventDefault();if(ev.shiftKey&&prev_line_id){if(prev_line_id>cur_line_id){const tmp=prev_line_id;prev_line_id=cur_line_id;cur_line_id=tmp}set_fragment(prev_line_id+"-"+cur_line_id)}else{prev_line_id=cur_line_id;set_fragment(cur_line_id)}}}());window.addEventListener("hashchange",highlightSrcLines);onEachLazy(document.getElementsByClassName("src-line-numbers"),el=>{el.addEventListener("click",handleSrcHighlight)});highlightSrcLines();window.createSrcSidebar=createSrcSidebar})() \ No newline at end of file diff --git a/static.files/storage-1d39b6787ed640ff.js b/static.files/storage-1d39b6787ed640ff.js new file mode 100644 index 00000000..5aac776b --- /dev/null +++ b/static.files/storage-1d39b6787ed640ff.js @@ -0,0 +1,23 @@ +"use strict";const builtinThemes=["light","dark","ayu"];const darkThemes=["dark","ayu"];window.currentTheme=document.getElementById("themeStyle");const settingsDataset=(function(){const settingsElement=document.getElementById("default-settings");return settingsElement&&settingsElement.dataset?settingsElement.dataset:null})();function getSettingValue(settingName){const current=getCurrentValue(settingName);if(current===null&&settingsDataset!==null){const def=settingsDataset[settingName.replace(/-/g,"_")];if(def!==undefined){return def}}return current}const localStoredTheme=getSettingValue("theme");function hasClass(elem,className){return elem&&elem.classList&&elem.classList.contains(className)}function addClass(elem,className){if(elem&&elem.classList){elem.classList.add(className)}}function removeClass(elem,className){if(elem&&elem.classList){elem.classList.remove(className)}}function onEach(arr,func){for(const elem of arr){if(func(elem)){return true}}return false}function onEachLazy(lazyArray,func){return onEach(Array.prototype.slice.call(lazyArray),func)}function updateLocalStorage(name,value){try{window.localStorage.setItem("rustdoc-"+name,value)}catch(e){}}function getCurrentValue(name){try{return window.localStorage.getItem("rustdoc-"+name)}catch(e){return null}}const getVar=(function getVar(name){const el=document.querySelector("head > meta[name='rustdoc-vars']");return el?el.attributes["data-"+name].value:null});function switchTheme(newThemeName,saveTheme){const themeNames=getVar("themes").split(",").filter(t=>t);themeNames.push(...builtinThemes);if(themeNames.indexOf(newThemeName)===-1){return}if(saveTheme){updateLocalStorage("theme",newThemeName)}document.documentElement.setAttribute("data-theme",newThemeName);if(builtinThemes.indexOf(newThemeName)!==-1){if(window.currentTheme){window.currentTheme.parentNode.removeChild(window.currentTheme);window.currentTheme=null}}else{const newHref=getVar("root-path")+encodeURIComponent(newThemeName)+getVar("resource-suffix")+".css";if(!window.currentTheme){if(document.readyState==="loading"){document.write(``);window.currentTheme=document.getElementById("themeStyle")}else{window.currentTheme=document.createElement("link");window.currentTheme.rel="stylesheet";window.currentTheme.id="themeStyle";window.currentTheme.href=newHref;document.documentElement.appendChild(window.currentTheme)}}else if(newHref!==window.currentTheme.href){window.currentTheme.href=newHref}}}const updateTheme=(function(){const mql=window.matchMedia("(prefers-color-scheme: dark)");function updateTheme(){if(getSettingValue("use-system-theme")!=="false"){const lightTheme=getSettingValue("preferred-light-theme")||"light";const darkTheme=getSettingValue("preferred-dark-theme")||"dark";updateLocalStorage("use-system-theme","true");switchTheme(mql.matches?darkTheme:lightTheme,true)}else{switchTheme(getSettingValue("theme"),false)}}mql.addEventListener("change",updateTheme);return updateTheme})();if(getSettingValue("use-system-theme")!=="false"&&window.matchMedia){if(getSettingValue("use-system-theme")===null&&getSettingValue("preferred-dark-theme")===null&&darkThemes.indexOf(localStoredTheme)>=0){updateLocalStorage("preferred-dark-theme",localStoredTheme)}}updateTheme();if(getSettingValue("source-sidebar-show")==="true"){addClass(document.documentElement,"src-sidebar-expanded")}if(getSettingValue("hide-sidebar")==="true"){addClass(document.documentElement,"hide-sidebar")}if(getSettingValue("hide-toc")==="true"){addClass(document.documentElement,"hide-toc")}if(getSettingValue("hide-modnav")==="true"){addClass(document.documentElement,"hide-modnav")}function updateSidebarWidth(){const desktopSidebarWidth=getSettingValue("desktop-sidebar-width");if(desktopSidebarWidth&&desktopSidebarWidth!=="null"){document.documentElement.style.setProperty("--desktop-sidebar-width",desktopSidebarWidth+"px",)}const srcSidebarWidth=getSettingValue("src-sidebar-width");if(srcSidebarWidth&&srcSidebarWidth!=="null"){document.documentElement.style.setProperty("--src-sidebar-width",srcSidebarWidth+"px",)}}updateSidebarWidth();window.addEventListener("pageshow",ev=>{if(ev.persisted){setTimeout(updateTheme,0);setTimeout(updateSidebarWidth,0)}});class RustdocSearchElement extends HTMLElement{constructor(){super()}connectedCallback(){const rootPath=getVar("root-path");const currentCrate=getVar("current-crate");this.innerHTML=``}}window.customElements.define("rustdoc-search",RustdocSearchElement);class RustdocToolbarElement extends HTMLElement{constructor(){super()}connectedCallback(){if(this.firstElementChild){return}const rootPath=getVar("root-path");this.innerHTML=` +
+ Settings +
+
+ Help +
+ `}}window.customElements.define("rustdoc-toolbar",RustdocToolbarElement) \ No newline at end of file diff --git a/trait.impl/actix_service/ext/trait.ServiceExt.js b/trait.impl/actix_service/ext/trait.ServiceExt.js new file mode 100644 index 00000000..bbaf644c --- /dev/null +++ b/trait.impl/actix_service/ext/trait.ServiceExt.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20]} \ No newline at end of file diff --git a/trait.impl/actix_service/ext/trait.ServiceFactoryExt.js b/trait.impl/actix_service/ext/trait.ServiceFactoryExt.js new file mode 100644 index 00000000..bbaf644c --- /dev/null +++ b/trait.impl/actix_service/ext/trait.ServiceFactoryExt.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20]} \ No newline at end of file diff --git a/trait.impl/actix_service/ext/trait.TransformExt.js b/trait.impl/actix_service/ext/trait.TransformExt.js new file mode 100644 index 00000000..bbaf644c --- /dev/null +++ b/trait.impl/actix_service/ext/trait.TransformExt.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20]} \ No newline at end of file diff --git a/trait.impl/actix_service/trait.IntoService.js b/trait.impl/actix_service/trait.IntoService.js new file mode 100644 index 00000000..bbaf644c --- /dev/null +++ b/trait.impl/actix_service/trait.IntoService.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20]} \ No newline at end of file diff --git a/trait.impl/actix_service/trait.IntoServiceFactory.js b/trait.impl/actix_service/trait.IntoServiceFactory.js new file mode 100644 index 00000000..bbaf644c --- /dev/null +++ b/trait.impl/actix_service/trait.IntoServiceFactory.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20]} \ No newline at end of file diff --git a/trait.impl/actix_service/trait.Service.js b/trait.impl/actix_service/trait.Service.js new file mode 100644 index 00000000..01aea7d8 --- /dev/null +++ b/trait.impl/actix_service/trait.Service.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]],["actix_tls",[["impl<IO: ActixStream + 'static> Service<IO> for AcceptorService"],["impl<IO: ActixStream> Service<IO> for AcceptorService"],["impl<IO: ActixStream> Service<IO> for AcceptorService"],["impl<IO: ActixStream> Service<IO> for AcceptorService"],["impl<IO: ActixStream> Service<IO> for AcceptorService"],["impl<IO: ActixStream> Service<IO> for AcceptorService"],["impl<R, IO> Service<Connection<R, IO>> for TlsConnector
where\n R: Host,\n IO: ActixStream + 'static,
"],["impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where\n R: Host,\n IO: ActixStream,
"],["impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where\n R: Host,\n IO: ActixStream,
"],["impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where\n R: Host,\n IO: ActixStream,
"],["impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where\n R: Host,\n IO: ActixStream,
"],["impl<R, IO> Service<Connection<R, IO>> for TlsConnectorService
where\n R: Host,\n IO: ActixStream,
"],["impl<R: Host> Service<ConnectInfo<R>> for ConnectorService"],["impl<R: Host> Service<ConnectInfo<R>> for ResolverService"],["impl<R: Host> Service<ConnectInfo<R>> for TcpConnectorService"]]],["actix_tracing",[["impl<S, Req, F> Service<Req> for TracingService<S, F>
where\n S: Service<Req>,\n F: Fn(&Req) -> Option<Span>,
"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20,5980,691]} \ No newline at end of file diff --git a/trait.impl/actix_service/trait.ServiceFactory.js b/trait.impl/actix_service/trait.ServiceFactory.js new file mode 100644 index 00000000..0054159c --- /dev/null +++ b/trait.impl/actix_service/trait.ServiceFactory.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]],["actix_tls",[["impl<IO: ActixStream + 'static> ServiceFactory<IO> for Acceptor"],["impl<IO: ActixStream> ServiceFactory<IO> for Acceptor"],["impl<IO: ActixStream> ServiceFactory<IO> for Acceptor"],["impl<IO: ActixStream> ServiceFactory<IO> for Acceptor"],["impl<IO: ActixStream> ServiceFactory<IO> for Acceptor"],["impl<IO: ActixStream> ServiceFactory<IO> for Acceptor"],["impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where\n R: Host,\n IO: ActixStream + 'static,
"],["impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where\n R: Host,\n IO: ActixStream + 'static,
"],["impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where\n R: Host,\n IO: ActixStream + 'static,
"],["impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where\n R: Host,\n IO: ActixStream + 'static,
"],["impl<R, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where\n R: Host,\n IO: ActixStream + 'static,
"],["impl<R: Host> ServiceFactory<ConnectInfo<R>> for Connector"],["impl<R: Host> ServiceFactory<ConnectInfo<R>> for Resolver"],["impl<R: Host> ServiceFactory<ConnectInfo<R>> for TcpConnector"],["impl<R: Host, IO> ServiceFactory<Connection<R, IO>> for TlsConnector
where\n IO: ActixStream + 'static,
"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20,5833]} \ No newline at end of file diff --git a/trait.impl/actix_service/transform/trait.Transform.js b/trait.impl/actix_service/transform/trait.Transform.js new file mode 100644 index 00000000..eef6101e --- /dev/null +++ b/trait.impl/actix_service/transform/trait.Transform.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_service",[]],["actix_tracing",[["impl<S, Req, U, F> Transform<S, Req> for TracingTransform<S, U, F>
where\n S: Service<Req>,\n U: ServiceFactory<Req, Response = S::Response, Error = S::Error, Service = S>,\n F: Fn(&Req) -> Option<Span> + Clone,
"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[20,935]} \ No newline at end of file diff --git a/trait.impl/actix_tls/connect/host/trait.Host.js b/trait.impl/actix_tls/connect/host/trait.Host.js new file mode 100644 index 00000000..6aa325a1 --- /dev/null +++ b/trait.impl/actix_tls/connect/host/trait.Host.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[16]} \ No newline at end of file diff --git a/trait.impl/core/borrow/trait.Borrow.js b/trait.impl/core/borrow/trait.Borrow.js new file mode 100644 index 00000000..f1cd78f0 --- /dev/null +++ b/trait.impl/core/borrow/trait.Borrow.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl Borrow<str> for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[391]} \ No newline at end of file diff --git a/trait.impl/core/clone/trait.Clone.js b/trait.impl/core/clone/trait.Clone.js new file mode 100644 index 00000000..3d22b999 --- /dev/null +++ b/trait.impl/core/clone/trait.Clone.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Clone for BytesCodec"],["impl Clone for LinesCodec"]]],["actix_rt",[["impl Clone for ArbiterHandle"],["impl Clone for System"]]],["actix_server",[["impl Clone for MpTcp"],["impl Clone for ServerHandle"]]],["actix_service",[["impl<T, S, Req> Clone for ApplyTransform<T, S, Req>"]]],["actix_tls",[["impl Clone for Acceptor"],["impl Clone for Acceptor"],["impl Clone for Acceptor"],["impl Clone for Acceptor"],["impl Clone for Acceptor"],["impl Clone for Acceptor"],["impl Clone for TlsConnector"],["impl Clone for TlsConnector"],["impl Clone for TlsConnectorService"],["impl Clone for TlsConnector"],["impl Clone for TlsConnectorService"],["impl Clone for TlsConnector"],["impl Clone for TlsConnectorService"],["impl Clone for TlsConnector"],["impl Clone for TlsConnectorService"],["impl Clone for TlsConnector"],["impl Clone for TlsConnectorService"],["impl Clone for Connector"],["impl Clone for ConnectorService"],["impl Clone for Resolver"],["impl Clone for ResolverService"],["impl Clone for TcpConnector"],["impl Clone for TcpConnectorService"]]],["actix_tracing",[["impl<S: Clone, F: Clone> Clone for TracingService<S, F>"]]],["actix_utils",[["impl Clone for Counter"],["impl<L: Clone, R: Clone> Clone for Either<L, R>"],["impl<T: Clone> Clone for Ready<T>"]]],["bytestring",[["impl Clone for ByteString"]]],["local_channel",[["impl<T> Clone for Sender<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[553,536,544,338,7074,600,1277,283,309]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.Eq.js b/trait.impl/core/cmp/trait.Eq.js new file mode 100644 index 00000000..6bb2dca3 --- /dev/null +++ b/trait.impl/core/cmp/trait.Eq.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl<R: Eq> Eq for ConnectInfo<R>"]]],["bytestring",[["impl Eq for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[427,270]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.Ord.js b/trait.impl/core/cmp/trait.Ord.js new file mode 100644 index 00000000..bf42acf6 --- /dev/null +++ b/trait.impl/core/cmp/trait.Ord.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl Ord for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[272]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.PartialEq.js b/trait.impl/core/cmp/trait.PartialEq.js new file mode 100644 index 00000000..53822bb6 --- /dev/null +++ b/trait.impl/core/cmp/trait.PartialEq.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl<R: PartialEq> PartialEq for ConnectInfo<R>"]]],["bytestring",[["impl PartialEq<str> for ByteString"],["impl<T: AsRef<str>> PartialEq<T> for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[469,931]} \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.PartialOrd.js b/trait.impl/core/cmp/trait.PartialOrd.js new file mode 100644 index 00000000..3ce73da2 --- /dev/null +++ b/trait.impl/core/cmp/trait.PartialOrd.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl PartialOrd for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[293]} \ No newline at end of file diff --git a/trait.impl/core/convert/trait.AsRef.js b/trait.impl/core/convert/trait.AsRef.js new file mode 100644 index 00000000..5860abce --- /dev/null +++ b/trait.impl/core/convert/trait.AsRef.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl AsRef<str> for ByteString"],["impl AsRef<ByteString> for ByteString"],["impl AsRef<[u8]> for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1159]} \ No newline at end of file diff --git a/trait.impl/core/convert/trait.From.js b/trait.impl/core/convert/trait.From.js new file mode 100644 index 00000000..0c9d413e --- /dev/null +++ b/trait.impl/core/convert/trait.From.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_rt",[["impl From<Runtime> for Runtime"]]],["actix_tls",[["impl<IO> From<TlsStream<IO>> for TlsStream<IO>"],["impl<IO> From<SslStream<IO>> for TlsStream<IO>"],["impl<IO> From<TlsStream<IO>> for TlsStream<IO>"],["impl<IO> From<TlsStream<IO>> for TlsStream<IO>"],["impl<IO> From<TlsStream<IO>> for TlsStream<IO>"],["impl<IO> From<TlsStream<IO>> for TlsStream<IO>"],["impl<R: Host> From<R> for ConnectInfo<R>"]]],["bytestring",[["impl From<&str> for ByteString"],["impl From<ByteString> for String"],["impl From<Box<str>> for ByteString"],["impl From<String> for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[283,2867,1743]} \ No newline at end of file diff --git a/trait.impl/core/convert/trait.TryFrom.js b/trait.impl/core/convert/trait.TryFrom.js new file mode 100644 index 00000000..c1333171 --- /dev/null +++ b/trait.impl/core/convert/trait.TryFrom.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl TryFrom<&[u8; 0]> for ByteString"],["impl TryFrom<&[u8; 10]> for ByteString"],["impl TryFrom<&[u8; 11]> for ByteString"],["impl TryFrom<&[u8; 12]> for ByteString"],["impl TryFrom<&[u8; 13]> for ByteString"],["impl TryFrom<&[u8; 14]> for ByteString"],["impl TryFrom<&[u8; 15]> for ByteString"],["impl TryFrom<&[u8; 16]> for ByteString"],["impl TryFrom<&[u8; 17]> for ByteString"],["impl TryFrom<&[u8; 18]> for ByteString"],["impl TryFrom<&[u8; 19]> for ByteString"],["impl TryFrom<&[u8; 1]> for ByteString"],["impl TryFrom<&[u8; 20]> for ByteString"],["impl TryFrom<&[u8; 21]> for ByteString"],["impl TryFrom<&[u8; 22]> for ByteString"],["impl TryFrom<&[u8; 23]> for ByteString"],["impl TryFrom<&[u8; 24]> for ByteString"],["impl TryFrom<&[u8; 25]> for ByteString"],["impl TryFrom<&[u8; 26]> for ByteString"],["impl TryFrom<&[u8; 27]> for ByteString"],["impl TryFrom<&[u8; 28]> for ByteString"],["impl TryFrom<&[u8; 29]> for ByteString"],["impl TryFrom<&[u8; 2]> for ByteString"],["impl TryFrom<&[u8; 30]> for ByteString"],["impl TryFrom<&[u8; 31]> for ByteString"],["impl TryFrom<&[u8; 32]> for ByteString"],["impl TryFrom<&[u8; 3]> for ByteString"],["impl TryFrom<&[u8; 4]> for ByteString"],["impl TryFrom<&[u8; 5]> for ByteString"],["impl TryFrom<&[u8; 6]> for ByteString"],["impl TryFrom<&[u8; 7]> for ByteString"],["impl TryFrom<&[u8; 8]> for ByteString"],["impl TryFrom<&[u8; 9]> for ByteString"],["impl TryFrom<&[u8]> for ByteString"],["impl TryFrom<Vec<u8>> for ByteString"],["impl TryFrom<Bytes> for ByteString"],["impl TryFrom<BytesMut> for ByteString"],["impl TryFrom<[u8; 0]> for ByteString"],["impl TryFrom<[u8; 10]> for ByteString"],["impl TryFrom<[u8; 11]> for ByteString"],["impl TryFrom<[u8; 12]> for ByteString"],["impl TryFrom<[u8; 13]> for ByteString"],["impl TryFrom<[u8; 14]> for ByteString"],["impl TryFrom<[u8; 15]> for ByteString"],["impl TryFrom<[u8; 16]> for ByteString"],["impl TryFrom<[u8; 17]> for ByteString"],["impl TryFrom<[u8; 18]> for ByteString"],["impl TryFrom<[u8; 19]> for ByteString"],["impl TryFrom<[u8; 1]> for ByteString"],["impl TryFrom<[u8; 20]> for ByteString"],["impl TryFrom<[u8; 21]> for ByteString"],["impl TryFrom<[u8; 22]> for ByteString"],["impl TryFrom<[u8; 23]> for ByteString"],["impl TryFrom<[u8; 24]> for ByteString"],["impl TryFrom<[u8; 25]> for ByteString"],["impl TryFrom<[u8; 26]> for ByteString"],["impl TryFrom<[u8; 27]> for ByteString"],["impl TryFrom<[u8; 28]> for ByteString"],["impl TryFrom<[u8; 29]> for ByteString"],["impl TryFrom<[u8; 2]> for ByteString"],["impl TryFrom<[u8; 30]> for ByteString"],["impl TryFrom<[u8; 31]> for ByteString"],["impl TryFrom<[u8; 32]> for ByteString"],["impl TryFrom<[u8; 3]> for ByteString"],["impl TryFrom<[u8; 4]> for ByteString"],["impl TryFrom<[u8; 5]> for ByteString"],["impl TryFrom<[u8; 6]> for ByteString"],["impl TryFrom<[u8; 7]> for ByteString"],["impl TryFrom<[u8; 8]> for ByteString"],["impl TryFrom<[u8; 9]> for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[33256]} \ No newline at end of file diff --git a/trait.impl/core/default/trait.Default.js b/trait.impl/core/default/trait.Default.js new file mode 100644 index 00000000..d5338313 --- /dev/null +++ b/trait.impl/core/default/trait.Default.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Default for LinesCodec"]]],["actix_server",[["impl Default for ServerBuilder"]]],["actix_tls",[["impl Default for Connector"],["impl Default for ConnectorService"],["impl Default for Resolver"],["impl Default for ResolverService"],["impl Default for TcpConnector"],["impl Default for TcpConnectorService"]]],["bytestring",[["impl Default for ByteString"]]],["local_waker",[["impl Default for LocalWaker"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[295,308,1837,293,296]} \ No newline at end of file diff --git a/trait.impl/core/error/trait.Error.js b/trait.impl/core/error/trait.Error.js new file mode 100644 index 00000000..4f17a97c --- /dev/null +++ b/trait.impl/core/error/trait.Error.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl Error for ConnectError"],["impl<TlsErr, SvcErr> Error for TlsError<TlsErr, SvcErr>
where\n TlsErr: Error + 'static,\n SvcErr: Error + 'static,
"]]],["local_channel",[["impl<T> Error for SendError<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[957,318]} \ No newline at end of file diff --git a/trait.impl/core/fmt/trait.Debug.js b/trait.impl/core/fmt/trait.Debug.js new file mode 100644 index 00000000..11f4712d --- /dev/null +++ b/trait.impl/core/fmt/trait.Debug.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Debug for BytesCodec"],["impl Debug for LinesCodec"],["impl<T, U> Debug for Framed<T, U>
where\n T: Debug,\n U: Debug,
"],["impl<T: Debug, U: Debug> Debug for FramedParts<T, U>"]]],["actix_rt",[["impl Debug for Arbiter"],["impl Debug for ArbiterHandle"],["impl Debug for Runtime"],["impl Debug for System"],["impl Debug for SystemRunner"]]],["actix_server",[["impl Debug for MpTcp"],["impl Debug for ServerHandle"]]],["actix_tls",[["impl Debug for ConnectError"],["impl Debug for TcpConnector"],["impl Debug for TcpConnectorService"],["impl<R: Debug> Debug for ConnectInfo<R>"],["impl<R: Debug, IO: Debug> Debug for Connection<R, IO>"],["impl<TlsErr: Debug, SvcErr: Debug> Debug for TlsError<TlsErr, SvcErr>"]]],["actix_utils",[["impl Debug for Counter"],["impl Debug for CounterGuard"],["impl<F> Debug for PollFn<F>"],["impl<L: Debug, R: Debug> Debug for Either<L, R>"],["impl<T: Debug> Debug for Ready<T>"]]],["bytestring",[["impl Debug for ByteString"]]],["local_channel",[["impl<T> Debug for SendError<T>"],["impl<T: Debug> Debug for Receiver<T>"],["impl<T: Debug> Debug for Sender<T>"]]],["local_waker",[["impl Debug for LocalWaker"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1688,1290,536,2466,1825,279,1154,282]} \ No newline at end of file diff --git a/trait.impl/core/fmt/trait.Display.js b/trait.impl/core/fmt/trait.Display.js new file mode 100644 index 00000000..d9ad4658 --- /dev/null +++ b/trait.impl/core/fmt/trait.Display.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl Display for ConnectError"],["impl<R: Host> Display for ConnectInfo<R>"],["impl<TlsErr, SvcErr> Display for TlsError<TlsErr, SvcErr>"]]],["bytestring",[["impl Display for ByteString"]]],["local_channel",[["impl<T> Display for SendError<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1028,285,320]} \ No newline at end of file diff --git a/trait.impl/core/future/future/trait.Future.js b/trait.impl/core/future/future/trait.Future.js new file mode 100644 index 00000000..d0b554c5 --- /dev/null +++ b/trait.impl/core/future/future/trait.Future.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_server",[["impl Future for Server"]]],["actix_utils",[["impl<F, T> Future for PollFn<F>
where\n F: FnMut(&mut Context<'_>) -> Poll<T>,
"],["impl<L, R> Future for Either<L, R>
where\n L: Future,\n R: Future<Output = L::Output>,
"],["impl<T> Future for Ready<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[296,2034]} \ No newline at end of file diff --git a/trait.impl/core/hash/trait.Hash.js b/trait.impl/core/hash/trait.Hash.js new file mode 100644 index 00000000..c2e92598 --- /dev/null +++ b/trait.impl/core/hash/trait.Hash.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl<R: Hash> Hash for ConnectInfo<R>"]]],["bytestring",[["impl Hash for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[443,278]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Copy.js b/trait.impl/core/marker/trait.Copy.js new file mode 100644 index 00000000..60a6b3dc --- /dev/null +++ b/trait.impl/core/marker/trait.Copy.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Copy for BytesCodec"],["impl Copy for LinesCodec"]]],["actix_tls",[["impl Copy for TcpConnector"],["impl Copy for TcpConnectorService"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[551,627]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Freeze.js b/trait.impl/core/marker/trait.Freeze.js new file mode 100644 index 00000000..d66a37ad --- /dev/null +++ b/trait.impl/core/marker/trait.Freeze.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Freeze for BytesCodec",1,["actix_codec::bcodec::BytesCodec"]],["impl Freeze for LinesCodec",1,["actix_codec::lines::LinesCodec"]],["impl<T, U> Freeze for Framed<T, U>
where\n T: Freeze,\n U: Freeze,
",1,["actix_codec::framed::Framed"]],["impl<T, U> Freeze for FramedParts<T, U>
where\n T: Freeze,\n U: Freeze,
",1,["actix_codec::framed::FramedParts"]]]],["actix_rt",[["impl !Freeze for Runtime",1,["actix_rt::runtime::Runtime"]],["impl Freeze for Arbiter",1,["actix_rt::arbiter::Arbiter"]],["impl Freeze for ArbiterHandle",1,["actix_rt::arbiter::ArbiterHandle"]],["impl Freeze for System",1,["actix_rt::system::System"]],["impl Freeze for SystemRunner",1,["actix_rt::system::SystemRunner"]]]],["actix_server",[["impl Freeze for MpTcp",1,["actix_server::builder::MpTcp"]],["impl Freeze for Server",1,["actix_server::server::Server"]],["impl Freeze for ServerBuilder",1,["actix_server::builder::ServerBuilder"]],["impl Freeze for ServerHandle",1,["actix_server::handle::ServerHandle"]],["impl Freeze for TestServer",1,["actix_server::test_server::TestServer"]]]],["actix_service",[["impl<Cfg, Req, Res, Err, InitErr> Freeze for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>",1,["actix_service::boxed::BoxServiceFactory"]],["impl<T, S, Req> Freeze for ApplyTransform<T, S, Req>",1,["actix_service::transform::ApplyTransform"]]]],["actix_tls",[["impl Freeze for ConnectError",1,["actix_tls::connect::error::ConnectError"]],["impl Freeze for Acceptor",1,["actix_tls::accept::native_tls::Acceptor"]],["impl Freeze for AcceptorService",1,["actix_tls::accept::native_tls::AcceptorService"]],["impl Freeze for Acceptor",1,["actix_tls::accept::openssl::Acceptor"]],["impl Freeze for AcceptorService",1,["actix_tls::accept::openssl::AcceptorService"]],["impl Freeze for Acceptor",1,["actix_tls::accept::rustls_0_20::Acceptor"]],["impl Freeze for AcceptorService",1,["actix_tls::accept::rustls_0_20::AcceptorService"]],["impl Freeze for Acceptor",1,["actix_tls::accept::rustls_0_21::Acceptor"]],["impl Freeze for AcceptorService",1,["actix_tls::accept::rustls_0_21::AcceptorService"]],["impl Freeze for Acceptor",1,["actix_tls::accept::rustls_0_22::Acceptor"]],["impl Freeze for AcceptorService",1,["actix_tls::accept::rustls_0_22::AcceptorService"]],["impl Freeze for Acceptor",1,["actix_tls::accept::rustls_0_23::Acceptor"]],["impl Freeze for AcceptorService",1,["actix_tls::accept::rustls_0_23::AcceptorService"]],["impl Freeze for TlsConnector",1,["actix_tls::connect::native_tls::TlsConnector"]],["impl Freeze for TlsConnector",1,["actix_tls::connect::openssl::TlsConnector"]],["impl Freeze for TlsConnectorService",1,["actix_tls::connect::openssl::TlsConnectorService"]],["impl Freeze for TlsConnector",1,["actix_tls::connect::rustls_0_20::TlsConnector"]],["impl Freeze for TlsConnectorService",1,["actix_tls::connect::rustls_0_20::TlsConnectorService"]],["impl Freeze for TlsConnector",1,["actix_tls::connect::rustls_0_21::TlsConnector"]],["impl Freeze for TlsConnectorService",1,["actix_tls::connect::rustls_0_21::TlsConnectorService"]],["impl Freeze for TlsConnector",1,["actix_tls::connect::rustls_0_22::TlsConnector"]],["impl Freeze for TlsConnectorService",1,["actix_tls::connect::rustls_0_22::TlsConnectorService"]],["impl Freeze for TlsConnector",1,["actix_tls::connect::rustls_0_23::TlsConnector"]],["impl Freeze for TlsConnectorService",1,["actix_tls::connect::rustls_0_23::TlsConnectorService"]],["impl Freeze for Connector",1,["actix_tls::connect::connector::Connector"]],["impl Freeze for ConnectorService",1,["actix_tls::connect::connector::ConnectorService"]],["impl Freeze for Resolver",1,["actix_tls::connect::resolver::Resolver"]],["impl Freeze for ResolverService",1,["actix_tls::connect::resolver::ResolverService"]],["impl Freeze for TcpConnector",1,["actix_tls::connect::tcp::TcpConnector"]],["impl Freeze for TcpConnectorService",1,["actix_tls::connect::tcp::TcpConnectorService"]],["impl<IO> Freeze for TlsStream<IO>",1,["actix_tls::accept::native_tls::TlsStream"]],["impl<IO> Freeze for TlsStream<IO>",1,["actix_tls::accept::openssl::TlsStream"]],["impl<IO> Freeze for TlsStream<IO>
where\n IO: Freeze,
",1,["actix_tls::accept::rustls_0_20::TlsStream"]],["impl<IO> Freeze for TlsStream<IO>
where\n IO: Freeze,
",1,["actix_tls::accept::rustls_0_21::TlsStream"]],["impl<IO> Freeze for TlsStream<IO>
where\n IO: Freeze,
",1,["actix_tls::accept::rustls_0_22::TlsStream"]],["impl<IO> Freeze for TlsStream<IO>
where\n IO: Freeze,
",1,["actix_tls::accept::rustls_0_23::TlsStream"]],["impl<R> Freeze for ConnectInfo<R>
where\n R: Freeze,
",1,["actix_tls::connect::info::ConnectInfo"]],["impl<R, IO> Freeze for Connection<R, IO>
where\n R: Freeze,\n IO: Freeze,
",1,["actix_tls::connect::connection::Connection"]],["impl<TlsErr, SvcErr> Freeze for TlsError<TlsErr, SvcErr>
where\n TlsErr: Freeze,\n SvcErr: Freeze,
",1,["actix_tls::accept::TlsError"]]]],["actix_tracing",[["impl<S, F> Freeze for TracingService<S, F>
where\n S: Freeze,\n F: Freeze,
",1,["actix_tracing::TracingService"]],["impl<S, U, F> Freeze for TracingTransform<S, U, F>
where\n F: Freeze,
",1,["actix_tracing::TracingTransform"]]]],["actix_utils",[["impl Freeze for Counter",1,["actix_utils::counter::Counter"]],["impl Freeze for CounterGuard",1,["actix_utils::counter::CounterGuard"]],["impl<F> Freeze for PollFn<F>
where\n F: Freeze,
",1,["actix_utils::future::poll_fn::PollFn"]],["impl<L, R> Freeze for Either<L, R>
where\n L: Freeze,\n R: Freeze,
",1,["actix_utils::future::either::Either"]],["impl<T> Freeze for Ready<T>
where\n T: Freeze,
",1,["actix_utils::future::ready::Ready"]]]],["bytestring",[["impl !Freeze for ByteString",1,["bytestring::ByteString"]]]],["local_channel",[["impl<T> Freeze for Receiver<T>",1,["local_channel::mpsc::Receiver"]],["impl<T> Freeze for SendError<T>
where\n T: Freeze,
",1,["local_channel::mpsc::SendError"]],["impl<T> Freeze for Sender<T>",1,["local_channel::mpsc::Sender"]]]],["local_waker",[["impl !Freeze for LocalWaker",1,["local_waker::LocalWaker"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1956,1509,1574,817,15813,1243,2368,318,1205,322]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Send.js b/trait.impl/core/marker/trait.Send.js new file mode 100644 index 00000000..60f022c7 --- /dev/null +++ b/trait.impl/core/marker/trait.Send.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Send for BytesCodec",1,["actix_codec::bcodec::BytesCodec"]],["impl Send for LinesCodec",1,["actix_codec::lines::LinesCodec"]],["impl<T, U> Send for Framed<T, U>
where\n T: Send,\n U: Send,
",1,["actix_codec::framed::Framed"]],["impl<T, U> Send for FramedParts<T, U>
where\n T: Send,\n U: Send,
",1,["actix_codec::framed::FramedParts"]]]],["actix_rt",[["impl !Send for Runtime",1,["actix_rt::runtime::Runtime"]],["impl Send for Arbiter",1,["actix_rt::arbiter::Arbiter"]],["impl Send for ArbiterHandle",1,["actix_rt::arbiter::ArbiterHandle"]],["impl Send for System",1,["actix_rt::system::System"]],["impl Send for SystemRunner",1,["actix_rt::system::SystemRunner"]]]],["actix_server",[["impl Send for MpTcp",1,["actix_server::builder::MpTcp"]],["impl Send for Server",1,["actix_server::server::Server"]],["impl Send for ServerBuilder",1,["actix_server::builder::ServerBuilder"]],["impl Send for ServerHandle",1,["actix_server::handle::ServerHandle"]],["impl Send for TestServer",1,["actix_server::test_server::TestServer"]]]],["actix_service",[["impl<Cfg, Req, Res, Err, InitErr> !Send for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>",1,["actix_service::boxed::BoxServiceFactory"]],["impl<T, S, Req> !Send for ApplyTransform<T, S, Req>",1,["actix_service::transform::ApplyTransform"]]]],["actix_tls",[["impl !Send for ConnectError",1,["actix_tls::connect::error::ConnectError"]],["impl !Send for AcceptorService",1,["actix_tls::accept::native_tls::AcceptorService"]],["impl !Send for AcceptorService",1,["actix_tls::accept::openssl::AcceptorService"]],["impl !Send for AcceptorService",1,["actix_tls::accept::rustls_0_20::AcceptorService"]],["impl !Send for AcceptorService",1,["actix_tls::accept::rustls_0_21::AcceptorService"]],["impl !Send for AcceptorService",1,["actix_tls::accept::rustls_0_22::AcceptorService"]],["impl !Send for AcceptorService",1,["actix_tls::accept::rustls_0_23::AcceptorService"]],["impl !Send for Connector",1,["actix_tls::connect::connector::Connector"]],["impl !Send for ConnectorService",1,["actix_tls::connect::connector::ConnectorService"]],["impl !Send for Resolver",1,["actix_tls::connect::resolver::Resolver"]],["impl !Send for ResolverService",1,["actix_tls::connect::resolver::ResolverService"]],["impl Send for Acceptor",1,["actix_tls::accept::native_tls::Acceptor"]],["impl Send for Acceptor",1,["actix_tls::accept::openssl::Acceptor"]],["impl Send for Acceptor",1,["actix_tls::accept::rustls_0_20::Acceptor"]],["impl Send for Acceptor",1,["actix_tls::accept::rustls_0_21::Acceptor"]],["impl Send for Acceptor",1,["actix_tls::accept::rustls_0_22::Acceptor"]],["impl Send for Acceptor",1,["actix_tls::accept::rustls_0_23::Acceptor"]],["impl Send for TlsConnector",1,["actix_tls::connect::native_tls::TlsConnector"]],["impl Send for TlsConnector",1,["actix_tls::connect::openssl::TlsConnector"]],["impl Send for TlsConnectorService",1,["actix_tls::connect::openssl::TlsConnectorService"]],["impl Send for TlsConnector",1,["actix_tls::connect::rustls_0_20::TlsConnector"]],["impl Send for TlsConnectorService",1,["actix_tls::connect::rustls_0_20::TlsConnectorService"]],["impl Send for TlsConnector",1,["actix_tls::connect::rustls_0_21::TlsConnector"]],["impl Send for TlsConnectorService",1,["actix_tls::connect::rustls_0_21::TlsConnectorService"]],["impl Send for TlsConnector",1,["actix_tls::connect::rustls_0_22::TlsConnector"]],["impl Send for TlsConnectorService",1,["actix_tls::connect::rustls_0_22::TlsConnectorService"]],["impl Send for TlsConnector",1,["actix_tls::connect::rustls_0_23::TlsConnector"]],["impl Send for TlsConnectorService",1,["actix_tls::connect::rustls_0_23::TlsConnectorService"]],["impl Send for TcpConnector",1,["actix_tls::connect::tcp::TcpConnector"]],["impl Send for TcpConnectorService",1,["actix_tls::connect::tcp::TcpConnectorService"]],["impl<IO> Send for TlsStream<IO>
where\n IO: Send,
",1,["actix_tls::accept::native_tls::TlsStream"]],["impl<IO> Send for TlsStream<IO>
where\n IO: Send,
",1,["actix_tls::accept::openssl::TlsStream"]],["impl<IO> Send for TlsStream<IO>
where\n IO: Send,
",1,["actix_tls::accept::rustls_0_20::TlsStream"]],["impl<IO> Send for TlsStream<IO>
where\n IO: Send,
",1,["actix_tls::accept::rustls_0_21::TlsStream"]],["impl<IO> Send for TlsStream<IO>
where\n IO: Send,
",1,["actix_tls::accept::rustls_0_22::TlsStream"]],["impl<IO> Send for TlsStream<IO>
where\n IO: Send,
",1,["actix_tls::accept::rustls_0_23::TlsStream"]],["impl<R> Send for ConnectInfo<R>
where\n R: Send,
",1,["actix_tls::connect::info::ConnectInfo"]],["impl<R, IO> Send for Connection<R, IO>
where\n R: Send,\n IO: Send,
",1,["actix_tls::connect::connection::Connection"]],["impl<TlsErr, SvcErr> Send for TlsError<TlsErr, SvcErr>
where\n TlsErr: Send,\n SvcErr: Send,
",1,["actix_tls::accept::TlsError"]]]],["actix_tracing",[["impl<S, F> Send for TracingService<S, F>
where\n S: Send,\n F: Send,
",1,["actix_tracing::TracingService"]],["impl<S, U, F> Send for TracingTransform<S, U, F>
where\n F: Send,
",1,["actix_tracing::TracingTransform"]]]],["actix_utils",[["impl !Send for Counter",1,["actix_utils::counter::Counter"]],["impl !Send for CounterGuard",1,["actix_utils::counter::CounterGuard"]],["impl<F> Send for PollFn<F>
where\n F: Send,
",1,["actix_utils::future::poll_fn::PollFn"]],["impl<L, R> Send for Either<L, R>
where\n L: Send,\n R: Send,
",1,["actix_utils::future::either::Either"]],["impl<T> Send for Ready<T>
where\n T: Send,
",1,["actix_utils::future::ready::Ready"]]]],["bytestring",[["impl Send for ByteString",1,["bytestring::ByteString"]]]],["local_channel",[["impl<T> !Send for Receiver<T>",1,["local_channel::mpsc::Receiver"]],["impl<T> !Send for Sender<T>",1,["local_channel::mpsc::Sender"]],["impl<T> Send for SendError<T>
where\n T: Send,
",1,["local_channel::mpsc::SendError"]]]],["local_waker",[["impl !Send for LocalWaker",1,["local_waker::LocalWaker"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1908,1479,1544,807,15888,1213,2316,311,1183,316]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.StructuralPartialEq.js b/trait.impl/core/marker/trait.StructuralPartialEq.js new file mode 100644 index 00000000..6093cbc9 --- /dev/null +++ b/trait.impl/core/marker/trait.StructuralPartialEq.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl<R> StructuralPartialEq for ConnectInfo<R>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[361]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Sync.js b/trait.impl/core/marker/trait.Sync.js new file mode 100644 index 00000000..4f5430bc --- /dev/null +++ b/trait.impl/core/marker/trait.Sync.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Sync for BytesCodec",1,["actix_codec::bcodec::BytesCodec"]],["impl Sync for LinesCodec",1,["actix_codec::lines::LinesCodec"]],["impl<T, U> Sync for Framed<T, U>
where\n T: Sync,\n U: Sync,
",1,["actix_codec::framed::Framed"]],["impl<T, U> Sync for FramedParts<T, U>
where\n T: Sync,\n U: Sync,
",1,["actix_codec::framed::FramedParts"]]]],["actix_rt",[["impl !Sync for Runtime",1,["actix_rt::runtime::Runtime"]],["impl Sync for Arbiter",1,["actix_rt::arbiter::Arbiter"]],["impl Sync for ArbiterHandle",1,["actix_rt::arbiter::ArbiterHandle"]],["impl Sync for System",1,["actix_rt::system::System"]],["impl Sync for SystemRunner",1,["actix_rt::system::SystemRunner"]]]],["actix_server",[["impl !Sync for Server",1,["actix_server::server::Server"]],["impl !Sync for ServerBuilder",1,["actix_server::builder::ServerBuilder"]],["impl Sync for MpTcp",1,["actix_server::builder::MpTcp"]],["impl Sync for ServerHandle",1,["actix_server::handle::ServerHandle"]],["impl Sync for TestServer",1,["actix_server::test_server::TestServer"]]]],["actix_service",[["impl<Cfg, Req, Res, Err, InitErr> !Sync for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>",1,["actix_service::boxed::BoxServiceFactory"]],["impl<T, S, Req> !Sync for ApplyTransform<T, S, Req>",1,["actix_service::transform::ApplyTransform"]]]],["actix_tls",[["impl !Sync for ConnectError",1,["actix_tls::connect::error::ConnectError"]],["impl !Sync for AcceptorService",1,["actix_tls::accept::native_tls::AcceptorService"]],["impl !Sync for AcceptorService",1,["actix_tls::accept::openssl::AcceptorService"]],["impl !Sync for AcceptorService",1,["actix_tls::accept::rustls_0_20::AcceptorService"]],["impl !Sync for AcceptorService",1,["actix_tls::accept::rustls_0_21::AcceptorService"]],["impl !Sync for AcceptorService",1,["actix_tls::accept::rustls_0_22::AcceptorService"]],["impl !Sync for AcceptorService",1,["actix_tls::accept::rustls_0_23::AcceptorService"]],["impl !Sync for Connector",1,["actix_tls::connect::connector::Connector"]],["impl !Sync for ConnectorService",1,["actix_tls::connect::connector::ConnectorService"]],["impl !Sync for Resolver",1,["actix_tls::connect::resolver::Resolver"]],["impl !Sync for ResolverService",1,["actix_tls::connect::resolver::ResolverService"]],["impl Sync for Acceptor",1,["actix_tls::accept::native_tls::Acceptor"]],["impl Sync for Acceptor",1,["actix_tls::accept::openssl::Acceptor"]],["impl Sync for Acceptor",1,["actix_tls::accept::rustls_0_20::Acceptor"]],["impl Sync for Acceptor",1,["actix_tls::accept::rustls_0_21::Acceptor"]],["impl Sync for Acceptor",1,["actix_tls::accept::rustls_0_22::Acceptor"]],["impl Sync for Acceptor",1,["actix_tls::accept::rustls_0_23::Acceptor"]],["impl Sync for TlsConnector",1,["actix_tls::connect::native_tls::TlsConnector"]],["impl Sync for TlsConnector",1,["actix_tls::connect::openssl::TlsConnector"]],["impl Sync for TlsConnectorService",1,["actix_tls::connect::openssl::TlsConnectorService"]],["impl Sync for TlsConnector",1,["actix_tls::connect::rustls_0_20::TlsConnector"]],["impl Sync for TlsConnectorService",1,["actix_tls::connect::rustls_0_20::TlsConnectorService"]],["impl Sync for TlsConnector",1,["actix_tls::connect::rustls_0_21::TlsConnector"]],["impl Sync for TlsConnectorService",1,["actix_tls::connect::rustls_0_21::TlsConnectorService"]],["impl Sync for TlsConnector",1,["actix_tls::connect::rustls_0_22::TlsConnector"]],["impl Sync for TlsConnectorService",1,["actix_tls::connect::rustls_0_22::TlsConnectorService"]],["impl Sync for TlsConnector",1,["actix_tls::connect::rustls_0_23::TlsConnector"]],["impl Sync for TlsConnectorService",1,["actix_tls::connect::rustls_0_23::TlsConnectorService"]],["impl Sync for TcpConnector",1,["actix_tls::connect::tcp::TcpConnector"]],["impl Sync for TcpConnectorService",1,["actix_tls::connect::tcp::TcpConnectorService"]],["impl<IO> Sync for TlsStream<IO>
where\n IO: Sync,
",1,["actix_tls::accept::native_tls::TlsStream"]],["impl<IO> Sync for TlsStream<IO>
where\n IO: Sync,
",1,["actix_tls::accept::openssl::TlsStream"]],["impl<IO> Sync for TlsStream<IO>
where\n IO: Sync,
",1,["actix_tls::accept::rustls_0_20::TlsStream"]],["impl<IO> Sync for TlsStream<IO>
where\n IO: Sync,
",1,["actix_tls::accept::rustls_0_21::TlsStream"]],["impl<IO> Sync for TlsStream<IO>
where\n IO: Sync,
",1,["actix_tls::accept::rustls_0_22::TlsStream"]],["impl<IO> Sync for TlsStream<IO>
where\n IO: Sync,
",1,["actix_tls::accept::rustls_0_23::TlsStream"]],["impl<R> Sync for ConnectInfo<R>
where\n R: Sync,
",1,["actix_tls::connect::info::ConnectInfo"]],["impl<R, IO> Sync for Connection<R, IO>
where\n R: Sync,\n IO: Sync,
",1,["actix_tls::connect::connection::Connection"]],["impl<TlsErr, SvcErr> Sync for TlsError<TlsErr, SvcErr>
where\n TlsErr: Sync,\n SvcErr: Sync,
",1,["actix_tls::accept::TlsError"]]]],["actix_tracing",[["impl<S, F> Sync for TracingService<S, F>
where\n S: Sync,\n F: Sync,
",1,["actix_tracing::TracingService"]],["impl<S, U, F> Sync for TracingTransform<S, U, F>
where\n F: Sync,
",1,["actix_tracing::TracingTransform"]]]],["actix_utils",[["impl !Sync for Counter",1,["actix_utils::counter::Counter"]],["impl !Sync for CounterGuard",1,["actix_utils::counter::CounterGuard"]],["impl<F> Sync for PollFn<F>
where\n F: Sync,
",1,["actix_utils::future::poll_fn::PollFn"]],["impl<L, R> Sync for Either<L, R>
where\n L: Sync,\n R: Sync,
",1,["actix_utils::future::either::Either"]],["impl<T> Sync for Ready<T>
where\n T: Sync,
",1,["actix_utils::future::ready::Ready"]]]],["bytestring",[["impl Sync for ByteString",1,["bytestring::ByteString"]]]],["local_channel",[["impl<T> !Sync for Receiver<T>",1,["local_channel::mpsc::Receiver"]],["impl<T> !Sync for Sender<T>",1,["local_channel::mpsc::Sender"]],["impl<T> Sync for SendError<T>
where\n T: Sync,
",1,["local_channel::mpsc::SendError"]]]],["local_waker",[["impl !Sync for LocalWaker",1,["local_waker::LocalWaker"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1908,1479,1546,807,15888,1213,2316,311,1183,316]} \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Unpin.js b/trait.impl/core/marker/trait.Unpin.js new file mode 100644 index 00000000..385995cb --- /dev/null +++ b/trait.impl/core/marker/trait.Unpin.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Unpin for BytesCodec",1,["actix_codec::bcodec::BytesCodec"]],["impl Unpin for LinesCodec",1,["actix_codec::lines::LinesCodec"]],["impl<'__pin, T, U> Unpin for Framed<T, U>
where\n __Origin<'__pin, T, U>: Unpin,
"],["impl<T, U> Unpin for FramedParts<T, U>
where\n T: Unpin,\n U: Unpin,
",1,["actix_codec::framed::FramedParts"]]]],["actix_rt",[["impl Unpin for Arbiter",1,["actix_rt::arbiter::Arbiter"]],["impl Unpin for ArbiterHandle",1,["actix_rt::arbiter::ArbiterHandle"]],["impl Unpin for Runtime",1,["actix_rt::runtime::Runtime"]],["impl Unpin for System",1,["actix_rt::system::System"]],["impl Unpin for SystemRunner",1,["actix_rt::system::SystemRunner"]]]],["actix_server",[["impl Unpin for MpTcp",1,["actix_server::builder::MpTcp"]],["impl Unpin for Server",1,["actix_server::server::Server"]],["impl Unpin for ServerBuilder",1,["actix_server::builder::ServerBuilder"]],["impl Unpin for ServerHandle",1,["actix_server::handle::ServerHandle"]],["impl Unpin for TestServer",1,["actix_server::test_server::TestServer"]]]],["actix_service",[["impl<Cfg, Req, Res, Err, InitErr> Unpin for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>",1,["actix_service::boxed::BoxServiceFactory"]],["impl<T, S, Req> Unpin for ApplyTransform<T, S, Req>
where\n Req: Unpin,
",1,["actix_service::transform::ApplyTransform"]]]],["actix_tls",[["impl Unpin for ConnectError",1,["actix_tls::connect::error::ConnectError"]],["impl Unpin for Acceptor",1,["actix_tls::accept::native_tls::Acceptor"]],["impl Unpin for AcceptorService",1,["actix_tls::accept::native_tls::AcceptorService"]],["impl Unpin for Acceptor",1,["actix_tls::accept::openssl::Acceptor"]],["impl Unpin for AcceptorService",1,["actix_tls::accept::openssl::AcceptorService"]],["impl Unpin for Acceptor",1,["actix_tls::accept::rustls_0_20::Acceptor"]],["impl Unpin for AcceptorService",1,["actix_tls::accept::rustls_0_20::AcceptorService"]],["impl Unpin for Acceptor",1,["actix_tls::accept::rustls_0_21::Acceptor"]],["impl Unpin for AcceptorService",1,["actix_tls::accept::rustls_0_21::AcceptorService"]],["impl Unpin for Acceptor",1,["actix_tls::accept::rustls_0_22::Acceptor"]],["impl Unpin for AcceptorService",1,["actix_tls::accept::rustls_0_22::AcceptorService"]],["impl Unpin for Acceptor",1,["actix_tls::accept::rustls_0_23::Acceptor"]],["impl Unpin for AcceptorService",1,["actix_tls::accept::rustls_0_23::AcceptorService"]],["impl Unpin for TlsConnector",1,["actix_tls::connect::native_tls::TlsConnector"]],["impl Unpin for TlsConnector",1,["actix_tls::connect::openssl::TlsConnector"]],["impl Unpin for TlsConnectorService",1,["actix_tls::connect::openssl::TlsConnectorService"]],["impl Unpin for TlsConnector",1,["actix_tls::connect::rustls_0_20::TlsConnector"]],["impl Unpin for TlsConnectorService",1,["actix_tls::connect::rustls_0_20::TlsConnectorService"]],["impl Unpin for TlsConnector",1,["actix_tls::connect::rustls_0_21::TlsConnector"]],["impl Unpin for TlsConnectorService",1,["actix_tls::connect::rustls_0_21::TlsConnectorService"]],["impl Unpin for TlsConnector",1,["actix_tls::connect::rustls_0_22::TlsConnector"]],["impl Unpin for TlsConnectorService",1,["actix_tls::connect::rustls_0_22::TlsConnectorService"]],["impl Unpin for TlsConnector",1,["actix_tls::connect::rustls_0_23::TlsConnector"]],["impl Unpin for TlsConnectorService",1,["actix_tls::connect::rustls_0_23::TlsConnectorService"]],["impl Unpin for Connector",1,["actix_tls::connect::connector::Connector"]],["impl Unpin for ConnectorService",1,["actix_tls::connect::connector::ConnectorService"]],["impl Unpin for Resolver",1,["actix_tls::connect::resolver::Resolver"]],["impl Unpin for ResolverService",1,["actix_tls::connect::resolver::ResolverService"]],["impl Unpin for TcpConnector",1,["actix_tls::connect::tcp::TcpConnector"]],["impl Unpin for TcpConnectorService",1,["actix_tls::connect::tcp::TcpConnectorService"]],["impl<IO> Unpin for TlsStream<IO>
where\n IO: Unpin,
",1,["actix_tls::accept::native_tls::TlsStream"]],["impl<IO> Unpin for TlsStream<IO>
where\n IO: Unpin,
",1,["actix_tls::accept::openssl::TlsStream"]],["impl<IO> Unpin for TlsStream<IO>
where\n IO: Unpin,
",1,["actix_tls::accept::rustls_0_20::TlsStream"]],["impl<IO> Unpin for TlsStream<IO>
where\n IO: Unpin,
",1,["actix_tls::accept::rustls_0_21::TlsStream"]],["impl<IO> Unpin for TlsStream<IO>
where\n IO: Unpin,
",1,["actix_tls::accept::rustls_0_22::TlsStream"]],["impl<IO> Unpin for TlsStream<IO>
where\n IO: Unpin,
",1,["actix_tls::accept::rustls_0_23::TlsStream"]],["impl<R> Unpin for ConnectInfo<R>
where\n R: Unpin,
",1,["actix_tls::connect::info::ConnectInfo"]],["impl<R, IO> Unpin for Connection<R, IO>
where\n R: Unpin,\n IO: Unpin,
",1,["actix_tls::connect::connection::Connection"]],["impl<TlsErr, SvcErr> Unpin for TlsError<TlsErr, SvcErr>
where\n TlsErr: Unpin,\n SvcErr: Unpin,
",1,["actix_tls::accept::TlsError"]]]],["actix_tracing",[["impl<S, F> Unpin for TracingService<S, F>
where\n S: Unpin,\n F: Unpin,
",1,["actix_tracing::TracingService"]],["impl<S, U, F> Unpin for TracingTransform<S, U, F>
where\n F: Unpin,
",1,["actix_tracing::TracingTransform"]]]],["actix_utils",[["impl Unpin for Counter",1,["actix_utils::counter::Counter"]],["impl Unpin for CounterGuard"],["impl<'__pin, L, R> Unpin for Either<L, R>
where\n __Origin<'__pin, L, R>: Unpin,
"],["impl<F> Unpin for PollFn<F>
where\n F: Unpin,
",1,["actix_utils::future::poll_fn::PollFn"]],["impl<T> Unpin for Ready<T>"]]],["bytestring",[["impl Unpin for ByteString",1,["bytestring::ByteString"]]]],["local_channel",[["impl<T> Unpin for Receiver<T>"],["impl<T> Unpin for SendError<T>
where\n T: Unpin,
",1,["local_channel::mpsc::SendError"]],["impl<T> Unpin for Sender<T>"]]],["local_waker",[["impl Unpin for LocalWaker",1,["local_waker::LocalWaker"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[1787,1493,1559,991,16027,1228,1929,314,1123,318]} \ No newline at end of file diff --git a/trait.impl/core/ops/deref/trait.Deref.js b/trait.impl/core/ops/deref/trait.Deref.js new file mode 100644 index 00000000..e78095d4 --- /dev/null +++ b/trait.impl/core/ops/deref/trait.Deref.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl<IO> Deref for TlsStream<IO>"],["impl<IO> Deref for TlsStream<IO>"],["impl<IO> Deref for TlsStream<IO>"],["impl<IO> Deref for TlsStream<IO>"],["impl<IO> Deref for TlsStream<IO>"],["impl<IO> Deref for TlsStream<IO>"],["impl<R, IO> Deref for Connection<R, IO>"]]],["bytestring",[["impl Deref for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2301,292]} \ No newline at end of file diff --git a/trait.impl/core/ops/deref/trait.DerefMut.js b/trait.impl/core/ops/deref/trait.DerefMut.js new file mode 100644 index 00000000..a5d71413 --- /dev/null +++ b/trait.impl/core/ops/deref/trait.DerefMut.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_tls",[["impl<IO> DerefMut for TlsStream<IO>"],["impl<IO> DerefMut for TlsStream<IO>"],["impl<IO> DerefMut for TlsStream<IO>"],["impl<IO> DerefMut for TlsStream<IO>"],["impl<IO> DerefMut for TlsStream<IO>"],["impl<IO> DerefMut for TlsStream<IO>"],["impl<R, IO> DerefMut for Connection<R, IO>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2364]} \ No newline at end of file diff --git a/trait.impl/core/ops/drop/trait.Drop.js b/trait.impl/core/ops/drop/trait.Drop.js new file mode 100644 index 00000000..0e124f06 --- /dev/null +++ b/trait.impl/core/ops/drop/trait.Drop.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_utils",[["impl Drop for CounterGuard"]]],["local_channel",[["impl<T> Drop for Receiver<T>"],["impl<T> Drop for Sender<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[312,612]} \ No newline at end of file diff --git a/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js new file mode 100644 index 00000000..e03021db --- /dev/null +++ b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl RefUnwindSafe for BytesCodec",1,["actix_codec::bcodec::BytesCodec"]],["impl RefUnwindSafe for LinesCodec",1,["actix_codec::lines::LinesCodec"]],["impl<T, U> RefUnwindSafe for Framed<T, U>
where\n T: RefUnwindSafe,\n U: RefUnwindSafe,
",1,["actix_codec::framed::Framed"]],["impl<T, U> RefUnwindSafe for FramedParts<T, U>
where\n T: RefUnwindSafe,\n U: RefUnwindSafe,
",1,["actix_codec::framed::FramedParts"]]]],["actix_rt",[["impl !RefUnwindSafe for Arbiter",1,["actix_rt::arbiter::Arbiter"]],["impl !RefUnwindSafe for Runtime",1,["actix_rt::runtime::Runtime"]],["impl RefUnwindSafe for ArbiterHandle",1,["actix_rt::arbiter::ArbiterHandle"]],["impl RefUnwindSafe for System",1,["actix_rt::system::System"]],["impl RefUnwindSafe for SystemRunner",1,["actix_rt::system::SystemRunner"]]]],["actix_server",[["impl !RefUnwindSafe for Server",1,["actix_server::server::Server"]],["impl !RefUnwindSafe for ServerBuilder",1,["actix_server::builder::ServerBuilder"]],["impl RefUnwindSafe for MpTcp",1,["actix_server::builder::MpTcp"]],["impl RefUnwindSafe for ServerHandle",1,["actix_server::handle::ServerHandle"]],["impl RefUnwindSafe for TestServer",1,["actix_server::test_server::TestServer"]]]],["actix_service",[["impl<Cfg, Req, Res, Err, InitErr> !RefUnwindSafe for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>",1,["actix_service::boxed::BoxServiceFactory"]],["impl<T, S, Req> RefUnwindSafe for ApplyTransform<T, S, Req>
where\n Req: RefUnwindSafe,\n T: RefUnwindSafe,\n S: RefUnwindSafe,
",1,["actix_service::transform::ApplyTransform"]]]],["actix_tls",[["impl !RefUnwindSafe for ConnectError",1,["actix_tls::connect::error::ConnectError"]],["impl !RefUnwindSafe for AcceptorService",1,["actix_tls::accept::native_tls::AcceptorService"]],["impl !RefUnwindSafe for AcceptorService",1,["actix_tls::accept::openssl::AcceptorService"]],["impl !RefUnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_20::Acceptor"]],["impl !RefUnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_20::AcceptorService"]],["impl !RefUnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_21::Acceptor"]],["impl !RefUnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_21::AcceptorService"]],["impl !RefUnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_22::Acceptor"]],["impl !RefUnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_22::AcceptorService"]],["impl !RefUnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_23::Acceptor"]],["impl !RefUnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_23::AcceptorService"]],["impl !RefUnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_20::TlsConnector"]],["impl !RefUnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_20::TlsConnectorService"]],["impl !RefUnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_21::TlsConnector"]],["impl !RefUnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_21::TlsConnectorService"]],["impl !RefUnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_22::TlsConnector"]],["impl !RefUnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_22::TlsConnectorService"]],["impl !RefUnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_23::TlsConnector"]],["impl !RefUnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_23::TlsConnectorService"]],["impl !RefUnwindSafe for Connector",1,["actix_tls::connect::connector::Connector"]],["impl !RefUnwindSafe for ConnectorService",1,["actix_tls::connect::connector::ConnectorService"]],["impl !RefUnwindSafe for Resolver",1,["actix_tls::connect::resolver::Resolver"]],["impl !RefUnwindSafe for ResolverService",1,["actix_tls::connect::resolver::ResolverService"]],["impl RefUnwindSafe for Acceptor",1,["actix_tls::accept::native_tls::Acceptor"]],["impl RefUnwindSafe for Acceptor",1,["actix_tls::accept::openssl::Acceptor"]],["impl RefUnwindSafe for TlsConnector",1,["actix_tls::connect::native_tls::TlsConnector"]],["impl RefUnwindSafe for TlsConnector",1,["actix_tls::connect::openssl::TlsConnector"]],["impl RefUnwindSafe for TlsConnectorService",1,["actix_tls::connect::openssl::TlsConnectorService"]],["impl RefUnwindSafe for TcpConnector",1,["actix_tls::connect::tcp::TcpConnector"]],["impl RefUnwindSafe for TcpConnectorService",1,["actix_tls::connect::tcp::TcpConnectorService"]],["impl<IO> !RefUnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_20::TlsStream"]],["impl<IO> !RefUnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_21::TlsStream"]],["impl<IO> !RefUnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_22::TlsStream"]],["impl<IO> !RefUnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_23::TlsStream"]],["impl<IO> RefUnwindSafe for TlsStream<IO>
where\n IO: RefUnwindSafe,
",1,["actix_tls::accept::native_tls::TlsStream"]],["impl<IO> RefUnwindSafe for TlsStream<IO>
where\n IO: RefUnwindSafe,
",1,["actix_tls::accept::openssl::TlsStream"]],["impl<R> RefUnwindSafe for ConnectInfo<R>
where\n R: RefUnwindSafe,
",1,["actix_tls::connect::info::ConnectInfo"]],["impl<R, IO> RefUnwindSafe for Connection<R, IO>
where\n R: RefUnwindSafe,\n IO: RefUnwindSafe,
",1,["actix_tls::connect::connection::Connection"]],["impl<TlsErr, SvcErr> RefUnwindSafe for TlsError<TlsErr, SvcErr>
where\n TlsErr: RefUnwindSafe,\n SvcErr: RefUnwindSafe,
",1,["actix_tls::accept::TlsError"]]]],["actix_tracing",[["impl<S, F> RefUnwindSafe for TracingService<S, F>
where\n S: RefUnwindSafe,\n F: RefUnwindSafe,
",1,["actix_tracing::TracingService"]],["impl<S, U, F> RefUnwindSafe for TracingTransform<S, U, F>
where\n F: RefUnwindSafe,
",1,["actix_tracing::TracingTransform"]]]],["actix_utils",[["impl !RefUnwindSafe for Counter",1,["actix_utils::counter::Counter"]],["impl !RefUnwindSafe for CounterGuard",1,["actix_utils::counter::CounterGuard"]],["impl<F> RefUnwindSafe for PollFn<F>
where\n F: RefUnwindSafe,
",1,["actix_utils::future::poll_fn::PollFn"]],["impl<L, R> RefUnwindSafe for Either<L, R>
where\n L: RefUnwindSafe,\n R: RefUnwindSafe,
",1,["actix_utils::future::either::Either"]],["impl<T> RefUnwindSafe for Ready<T>
where\n T: RefUnwindSafe,
",1,["actix_utils::future::ready::Ready"]]]],["bytestring",[["impl RefUnwindSafe for ByteString",1,["bytestring::ByteString"]]]],["local_channel",[["impl<T> !RefUnwindSafe for Receiver<T>",1,["local_channel::mpsc::Receiver"]],["impl<T> !RefUnwindSafe for Sender<T>",1,["local_channel::mpsc::Sender"]],["impl<T> RefUnwindSafe for SendError<T>
where\n T: RefUnwindSafe,
",1,["local_channel::mpsc::SendError"]]]],["local_waker",[["impl !RefUnwindSafe for LocalWaker",1,["local_waker::LocalWaker"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2308,1730,1796,1519,17500,1463,2766,361,1383,366]} \ No newline at end of file diff --git a/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js new file mode 100644 index 00000000..1ae42e49 --- /dev/null +++ b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl UnwindSafe for BytesCodec",1,["actix_codec::bcodec::BytesCodec"]],["impl UnwindSafe for LinesCodec",1,["actix_codec::lines::LinesCodec"]],["impl<T, U> UnwindSafe for Framed<T, U>
where\n T: UnwindSafe,\n U: UnwindSafe,
",1,["actix_codec::framed::Framed"]],["impl<T, U> UnwindSafe for FramedParts<T, U>
where\n T: UnwindSafe,\n U: UnwindSafe,
",1,["actix_codec::framed::FramedParts"]]]],["actix_rt",[["impl !UnwindSafe for Arbiter",1,["actix_rt::arbiter::Arbiter"]],["impl !UnwindSafe for Runtime",1,["actix_rt::runtime::Runtime"]],["impl UnwindSafe for ArbiterHandle",1,["actix_rt::arbiter::ArbiterHandle"]],["impl UnwindSafe for System",1,["actix_rt::system::System"]],["impl UnwindSafe for SystemRunner",1,["actix_rt::system::SystemRunner"]]]],["actix_server",[["impl !UnwindSafe for Server",1,["actix_server::server::Server"]],["impl !UnwindSafe for ServerBuilder",1,["actix_server::builder::ServerBuilder"]],["impl UnwindSafe for MpTcp",1,["actix_server::builder::MpTcp"]],["impl UnwindSafe for ServerHandle",1,["actix_server::handle::ServerHandle"]],["impl UnwindSafe for TestServer",1,["actix_server::test_server::TestServer"]]]],["actix_service",[["impl<Cfg, Req, Res, Err, InitErr> !UnwindSafe for BoxServiceFactory<Cfg, Req, Res, Err, InitErr>",1,["actix_service::boxed::BoxServiceFactory"]],["impl<T, S, Req> UnwindSafe for ApplyTransform<T, S, Req>
where\n Req: UnwindSafe,\n T: RefUnwindSafe,\n S: RefUnwindSafe,
",1,["actix_service::transform::ApplyTransform"]]]],["actix_tls",[["impl !UnwindSafe for ConnectError",1,["actix_tls::connect::error::ConnectError"]],["impl !UnwindSafe for AcceptorService",1,["actix_tls::accept::native_tls::AcceptorService"]],["impl !UnwindSafe for AcceptorService",1,["actix_tls::accept::openssl::AcceptorService"]],["impl !UnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_20::Acceptor"]],["impl !UnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_20::AcceptorService"]],["impl !UnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_21::Acceptor"]],["impl !UnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_21::AcceptorService"]],["impl !UnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_22::Acceptor"]],["impl !UnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_22::AcceptorService"]],["impl !UnwindSafe for Acceptor",1,["actix_tls::accept::rustls_0_23::Acceptor"]],["impl !UnwindSafe for AcceptorService",1,["actix_tls::accept::rustls_0_23::AcceptorService"]],["impl !UnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_20::TlsConnector"]],["impl !UnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_20::TlsConnectorService"]],["impl !UnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_21::TlsConnector"]],["impl !UnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_21::TlsConnectorService"]],["impl !UnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_22::TlsConnector"]],["impl !UnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_22::TlsConnectorService"]],["impl !UnwindSafe for TlsConnector",1,["actix_tls::connect::rustls_0_23::TlsConnector"]],["impl !UnwindSafe for TlsConnectorService",1,["actix_tls::connect::rustls_0_23::TlsConnectorService"]],["impl !UnwindSafe for Connector",1,["actix_tls::connect::connector::Connector"]],["impl !UnwindSafe for ConnectorService",1,["actix_tls::connect::connector::ConnectorService"]],["impl !UnwindSafe for Resolver",1,["actix_tls::connect::resolver::Resolver"]],["impl !UnwindSafe for ResolverService",1,["actix_tls::connect::resolver::ResolverService"]],["impl UnwindSafe for Acceptor",1,["actix_tls::accept::native_tls::Acceptor"]],["impl UnwindSafe for Acceptor",1,["actix_tls::accept::openssl::Acceptor"]],["impl UnwindSafe for TlsConnector",1,["actix_tls::connect::native_tls::TlsConnector"]],["impl UnwindSafe for TlsConnector",1,["actix_tls::connect::openssl::TlsConnector"]],["impl UnwindSafe for TlsConnectorService",1,["actix_tls::connect::openssl::TlsConnectorService"]],["impl UnwindSafe for TcpConnector",1,["actix_tls::connect::tcp::TcpConnector"]],["impl UnwindSafe for TcpConnectorService",1,["actix_tls::connect::tcp::TcpConnectorService"]],["impl<IO> !UnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_20::TlsStream"]],["impl<IO> !UnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_21::TlsStream"]],["impl<IO> !UnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_22::TlsStream"]],["impl<IO> !UnwindSafe for TlsStream<IO>",1,["actix_tls::accept::rustls_0_23::TlsStream"]],["impl<IO> UnwindSafe for TlsStream<IO>
where\n IO: UnwindSafe,
",1,["actix_tls::accept::native_tls::TlsStream"]],["impl<IO> UnwindSafe for TlsStream<IO>
where\n IO: UnwindSafe,
",1,["actix_tls::accept::openssl::TlsStream"]],["impl<R> UnwindSafe for ConnectInfo<R>
where\n R: UnwindSafe,
",1,["actix_tls::connect::info::ConnectInfo"]],["impl<R, IO> UnwindSafe for Connection<R, IO>
where\n R: UnwindSafe,\n IO: UnwindSafe,
",1,["actix_tls::connect::connection::Connection"]],["impl<TlsErr, SvcErr> UnwindSafe for TlsError<TlsErr, SvcErr>
where\n TlsErr: UnwindSafe,\n SvcErr: UnwindSafe,
",1,["actix_tls::accept::TlsError"]]]],["actix_tracing",[["impl<S, F> UnwindSafe for TracingService<S, F>
where\n S: UnwindSafe,\n F: UnwindSafe,
",1,["actix_tracing::TracingService"]],["impl<S, U, F> UnwindSafe for TracingTransform<S, U, F>
where\n F: UnwindSafe,
",1,["actix_tracing::TracingTransform"]]]],["actix_utils",[["impl !UnwindSafe for Counter",1,["actix_utils::counter::Counter"]],["impl !UnwindSafe for CounterGuard",1,["actix_utils::counter::CounterGuard"]],["impl<F> UnwindSafe for PollFn<F>
where\n F: UnwindSafe,
",1,["actix_utils::future::poll_fn::PollFn"]],["impl<L, R> UnwindSafe for Either<L, R>
where\n L: UnwindSafe,\n R: UnwindSafe,
",1,["actix_utils::future::either::Either"]],["impl<T> UnwindSafe for Ready<T>
where\n T: UnwindSafe,
",1,["actix_utils::future::ready::Ready"]]]],["bytestring",[["impl UnwindSafe for ByteString",1,["bytestring::ByteString"]]]],["local_channel",[["impl<T> !UnwindSafe for Receiver<T>",1,["local_channel::mpsc::Receiver"]],["impl<T> !UnwindSafe for Sender<T>",1,["local_channel::mpsc::Sender"]],["impl<T> UnwindSafe for SendError<T>
where\n T: UnwindSafe,
",1,["local_channel::mpsc::SendError"]]]],["local_waker",[["impl UnwindSafe for LocalWaker",1,["local_waker::LocalWaker"]]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[2236,1685,1751,1492,17086,1418,2685,352,1347,356]} \ No newline at end of file diff --git a/trait.impl/futures_core/stream/trait.Stream.js b/trait.impl/futures_core/stream/trait.Stream.js new file mode 100644 index 00000000..a71b2f73 --- /dev/null +++ b/trait.impl/futures_core/stream/trait.Stream.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl<T, U> Stream for Framed<T, U>
where\n T: AsyncRead,\n U: Decoder,
"]]],["local_channel",[["impl<T> Stream for Receiver<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[441,187]} \ No newline at end of file diff --git a/trait.impl/futures_sink/trait.Sink.js b/trait.impl/futures_sink/trait.Sink.js new file mode 100644 index 00000000..987a44a9 --- /dev/null +++ b/trait.impl/futures_sink/trait.Sink.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl<T, U, I> Sink<I> for Framed<T, U>
where\n T: AsyncWrite,\n U: Encoder<I>,\n U::Error: From<Error>,
"]]],["local_channel",[["impl<T> Sink<T> for Sender<T>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[901,188]} \ No newline at end of file diff --git a/trait.impl/serde/de/trait.Deserialize.js b/trait.impl/serde/de/trait.Deserialize.js new file mode 100644 index 00000000..882baec1 --- /dev/null +++ b/trait.impl/serde/de/trait.Deserialize.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl<'de> Deserialize<'de> for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[314]} \ No newline at end of file diff --git a/trait.impl/serde/ser/trait.Serialize.js b/trait.impl/serde/ser/trait.Serialize.js new file mode 100644 index 00000000..d66c5e4e --- /dev/null +++ b/trait.impl/serde/ser/trait.Serialize.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["bytestring",[["impl Serialize for ByteString"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[288]} \ No newline at end of file diff --git a/trait.impl/tokio/io/async_read/trait.AsyncRead.js b/trait.impl/tokio/io/async_read/trait.AsyncRead.js new file mode 100644 index 00000000..1e1349f5 --- /dev/null +++ b/trait.impl/tokio/io/async_read/trait.AsyncRead.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[]],["actix_tls",[["impl<IO: ActixStream> AsyncRead for TlsStream<IO>"],["impl<IO: ActixStream> AsyncRead for TlsStream<IO>"],["impl<IO: ActixStream> AsyncRead for TlsStream<IO>"],["impl<IO: ActixStream> AsyncRead for TlsStream<IO>"],["impl<IO: ActixStream> AsyncRead for TlsStream<IO>"],["impl<IO: ActixStream> AsyncRead for TlsStream<IO>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[18,1260]} \ No newline at end of file diff --git a/trait.impl/tokio/io/async_write/trait.AsyncWrite.js b/trait.impl/tokio/io/async_write/trait.AsyncWrite.js new file mode 100644 index 00000000..2a0f23f7 --- /dev/null +++ b/trait.impl/tokio/io/async_write/trait.AsyncWrite.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[]],["actix_tls",[["impl<IO: ActixStream> AsyncWrite for TlsStream<IO>"],["impl<IO: ActixStream> AsyncWrite for TlsStream<IO>"],["impl<IO: ActixStream> AsyncWrite for TlsStream<IO>"],["impl<IO: ActixStream> AsyncWrite for TlsStream<IO>"],["impl<IO: ActixStream> AsyncWrite for TlsStream<IO>"],["impl<IO: ActixStream> AsyncWrite for TlsStream<IO>"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[18,1266]} \ No newline at end of file diff --git a/trait.impl/tokio_util/codec/decoder/trait.Decoder.js b/trait.impl/tokio_util/codec/decoder/trait.Decoder.js new file mode 100644 index 00000000..dcb5f8ef --- /dev/null +++ b/trait.impl/tokio_util/codec/decoder/trait.Decoder.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Decoder for BytesCodec"],["impl Decoder for LinesCodec"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[499]} \ No newline at end of file diff --git a/trait.impl/tokio_util/codec/encoder/trait.Encoder.js b/trait.impl/tokio_util/codec/encoder/trait.Encoder.js new file mode 100644 index 00000000..bb567de5 --- /dev/null +++ b/trait.impl/tokio_util/codec/encoder/trait.Encoder.js @@ -0,0 +1,9 @@ +(function() { + var implementors = Object.fromEntries([["actix_codec",[["impl Encoder<Bytes> for BytesCodec"],["impl<T: AsRef<str>> Encoder<T> for LinesCodec"]]]]); + if (window.register_implementors) { + window.register_implementors(implementors); + } else { + window.pending_implementors = implementors; + } +})() +//{"start":57,"fragment_lengths":[774]} \ No newline at end of file diff --git a/type.impl/alloc/boxed/struct.Box.js b/type.impl/alloc/boxed/struct.Box.js new file mode 100644 index 00000000..610a0906 --- /dev/null +++ b/type.impl/alloc/boxed/struct.Box.js @@ -0,0 +1,9 @@ +(function() { + var type_impls = Object.fromEntries([["actix_service",[["
1.66.0 ยท sourceยง

impl<T> AsFd for Box<T>
where\n T: AsFd + ?Sized,

sourceยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
","AsFd","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> AsMut<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
","AsMut","actix_service::boxed::BoxService"],["
1.66.0 ยท sourceยง

impl<T> AsRawFd for Box<T>
where\n T: AsRawFd,

sourceยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
","AsRawFd","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> AsRef<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","actix_service::boxed::BoxService"],["
sourceยง

impl<Args, F, A> AsyncFn<Args> for Box<F, A>
where\n Args: Tuple,\n F: AsyncFn<Args> + ?Sized,\n A: Allocator,

sourceยง

extern "rust-call" fn async_call(\n &self,\n args: Args,\n) -> <Box<F, A> as AsyncFnMut<Args>>::CallRefFuture<'_>

๐Ÿ”ฌThis is a nightly-only experimental API. (async_fn_traits)
Call the AsyncFn, returning a future which may borrow from the called closure.
","AsyncFn","actix_service::boxed::BoxService"],["
sourceยง

impl<Args, F, A> AsyncFnMut<Args> for Box<F, A>
where\n Args: Tuple,\n F: AsyncFnMut<Args> + ?Sized,\n A: Allocator,

sourceยง

type CallRefFuture<'a> = <F as AsyncFnMut<Args>>::CallRefFuture<'a>\nwhere\n Box<F, A>: 'a

๐Ÿ”ฌThis is a nightly-only experimental API. (async_fn_traits)
sourceยง

extern "rust-call" fn async_call_mut(\n &mut self,\n args: Args,\n) -> <Box<F, A> as AsyncFnMut<Args>>::CallRefFuture<'_>

๐Ÿ”ฌThis is a nightly-only experimental API. (async_fn_traits)
Call the AsyncFnMut, returning a future which may borrow from the called closure.
","AsyncFnMut","actix_service::boxed::BoxService"],["
sourceยง

impl<Args, F, A> AsyncFnOnce<Args> for Box<F, A>
where\n Args: Tuple,\n F: AsyncFnOnce<Args> + ?Sized,\n A: Allocator,

sourceยง

type Output = <F as AsyncFnOnce<Args>>::Output

๐Ÿ”ฌThis is a nightly-only experimental API. (async_fn_traits)
Output type of the called closureโ€™s future.
sourceยง

type CallOnceFuture = <F as AsyncFnOnce<Args>>::CallOnceFuture

๐Ÿ”ฌThis is a nightly-only experimental API. (async_fn_traits)
Future returned by AsyncFnOnce::async_call_once.
sourceยง

extern "rust-call" fn async_call_once(\n self,\n args: Args,\n) -> <Box<F, A> as AsyncFnOnce<Args>>::CallOnceFuture

๐Ÿ”ฌThis is a nightly-only experimental API. (async_fn_traits)
Call the AsyncFnOnce, returning a future which may move out of the called closure.
","AsyncFnOnce","actix_service::boxed::BoxService"],["
sourceยง

impl<S> AsyncIterator for Box<S>
where\n S: AsyncIterator + Unpin + ?Sized,

sourceยง

type Item = <S as AsyncIterator>::Item

๐Ÿ”ฌThis is a nightly-only experimental API. (async_iterator)
The type of items yielded by the async iterator.
sourceยง

fn poll_next(\n self: Pin<&mut Box<S>>,\n cx: &mut Context<'_>,\n) -> Poll<Option<<Box<S> as AsyncIterator>::Item>>

๐Ÿ”ฌThis is a nightly-only experimental API. (async_iterator)
Attempts to pull out the next value of this async iterator, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the async iterator is exhausted. Read more
sourceยง

fn size_hint(&self) -> (usize, Option<usize>)

๐Ÿ”ฌThis is a nightly-only experimental API. (async_iterator)
Returns the bounds on the remaining length of the async iterator. Read more
","AsyncIterator","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Borrow<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
","Borrow","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> BorrowMut<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
","BorrowMut","actix_service::boxed::BoxService"],["
sourceยง

impl<T> Box<T>
where\n T: ?Sized,

1.36.0 ยท source

pub unsafe fn from_raw(raw: *mut T) -> Box<T>

Constructs a box from a raw pointer.

\n

After calling this function, the raw pointer is owned by the\nresulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
ยงSafety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n

The safety conditions are described in the memory layout section.

\n
ยงExamples
\n

Recreate a Box which was previously converted to a raw pointer\nusing Box::into_raw:

\n\n
let x = Box::new(5);\nlet ptr = Box::into_raw(x);\nlet x = unsafe { Box::from_raw(ptr) };
\n

Manually create a Box from scratch by using the global allocator:

\n\n
use std::alloc::{alloc, Layout};\n\nunsafe {\n    let ptr = alloc(Layout::new::<i32>()) as *mut i32;\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `ptr`, though for this\n    // simple example `*ptr = 5` would have worked as well.\n    ptr.write(5);\n    let x = Box::from_raw(ptr);\n}
\n
source

pub unsafe fn from_non_null(ptr: NonNull<T>) -> Box<T>

๐Ÿ”ฌThis is a nightly-only experimental API. (box_vec_non_null)

Constructs a box from a NonNull pointer.

\n

After calling this function, the NonNull pointer is owned by\nthe resulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
ยงSafety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same NonNull pointer.

\n

The safety conditions are described in the memory layout section.

\n
ยงExamples
\n

Recreate a Box which was previously converted to a NonNull\npointer using Box::into_non_null:

\n\n
#![feature(box_vec_non_null)]\n\nlet x = Box::new(5);\nlet non_null = Box::into_non_null(x);\nlet x = unsafe { Box::from_non_null(non_null) };
\n

Manually create a Box from scratch by using the global allocator:

\n\n
#![feature(box_vec_non_null)]\n\nuse std::alloc::{alloc, Layout};\nuse std::ptr::NonNull;\n\nunsafe {\n    let non_null = NonNull::new(alloc(Layout::new::<i32>()).cast::<i32>())\n        .expect(\"allocation failed\");\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `non_null`.\n    non_null.write(5);\n    let x = Box::from_non_null(non_null);\n}
\n
",0,"actix_service::boxed::BoxService"],["
sourceยง

impl<T> Box<T>

1.36.0 ยท source

pub fn new(x: T) -> Box<T>

Allocates memory on the heap and then places x into it.

\n

This doesnโ€™t actually allocate if T is zero-sized.

\n
ยงExamples
\n
let five = Box::new(5);
\n
1.82.0 ยท source

pub fn new_uninit() -> Box<MaybeUninit<T>>

Constructs a new box with uninitialized contents.

\n
ยงExamples
\n
let mut five = Box::<u32>::new_uninit();\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed() -> Box<MaybeUninit<T>>

๐Ÿ”ฌThis is a nightly-only experimental API. (new_zeroed_alloc)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
ยงExamples
\n
#![feature(new_zeroed_alloc)]\n\nlet zero = Box::<u32>::new_zeroed();\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
1.36.0 ยท source

pub fn pin(x: T) -> Pin<Box<T>>

Constructs a new Pin<Box<T>>. If T does not implement Unpin, then\nx will be pinned in memory and unable to be moved.

\n

Constructing and pinning of the Box can also be done in two steps: Box::pin(x)\ndoes the same as Box::into_pin(Box::new(x)). Consider using\ninto_pin if you already have a Box<T>, or if you want to\nconstruct a (pinned) Box in a different way than with Box::new.

\n
source

pub fn try_new(x: T) -> Result<Box<T>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Allocates memory on the heap then places x into it,\nreturning an error if the allocation fails

\n

This doesnโ€™t actually allocate if T is zero-sized.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nlet five = Box::try_new(5)?;
\n
source

pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents on the heap,\nreturning an error if the allocation fails

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nlet mut five = Box::<u32>::try_new_uninit()?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes on the heap

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nlet zero = Box::<u32>::try_new_zeroed()?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
",0,"actix_service::boxed::BoxService"],["
sourceยง

impl<T, A> Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source

pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box<T, A>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a box from a raw pointer in the given allocator.

\n

After calling this function, the raw pointer is owned by the\nresulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
ยงSafety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n
ยงExamples
\n

Recreate a Box which was previously converted to a raw pointer\nusing Box::into_raw_with_allocator:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(5, System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nlet x = unsafe { Box::from_raw_in(ptr, alloc) };
\n

Manually create a Box from scratch by using the system allocator:

\n\n
#![feature(allocator_api, slice_ptr_get)]\n\nuse std::alloc::{Allocator, Layout, System};\n\nunsafe {\n    let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `ptr`, though for this\n    // simple example `*ptr = 5` would have worked as well.\n    ptr.write(5);\n    let x = Box::from_raw_in(ptr, System);\n}
\n
source

pub const unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Box<T, A>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a box from a NonNull pointer in the given allocator.

\n

After calling this function, the NonNull pointer is owned by\nthe resulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
ยงSafety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n
ยงExamples
\n

Recreate a Box which was previously converted to a NonNull pointer\nusing Box::into_non_null_with_allocator:

\n\n
#![feature(allocator_api, box_vec_non_null)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(5, System);\nlet (non_null, alloc) = Box::into_non_null_with_allocator(x);\nlet x = unsafe { Box::from_non_null_in(non_null, alloc) };
\n

Manually create a Box from scratch by using the system allocator:

\n\n
#![feature(allocator_api, box_vec_non_null, slice_ptr_get)]\n\nuse std::alloc::{Allocator, Layout, System};\n\nunsafe {\n    let non_null = System.allocate(Layout::new::<i32>())?.cast::<i32>();\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `non_null`.\n    non_null.write(5);\n    let x = Box::from_non_null_in(non_null, System);\n}
\n
1.36.0 ยท source

pub fn into_raw(b: Box<T, A>) -> *mut T

Consumes the Box, returning a wrapped raw pointer.

\n

The pointer will be properly aligned and non-null.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the raw pointer back into a Box with the\nBox::from_raw function, allowing the Box destructor to perform\nthe cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_raw(b) instead of b.into_raw(). This\nis so that there is no conflict with a method on the inner type.

\n
ยงExamples
\n

Converting the raw pointer back into a Box with Box::from_raw\nfor automatic cleanup:

\n\n
let x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nlet x = unsafe { Box::from_raw(ptr) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
use std::alloc::{dealloc, Layout};\nuse std::ptr;\n\nlet x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nunsafe {\n    ptr::drop_in_place(ptr);\n    dealloc(ptr as *mut u8, Layout::new::<String>());\n}
\n

Note: This is equivalent to the following:

\n\n
let x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nunsafe {\n    drop(Box::from_raw(ptr));\n}
\n
source

pub fn into_non_null(b: Box<T, A>) -> NonNull<T>

๐Ÿ”ฌThis is a nightly-only experimental API. (box_vec_non_null)

Consumes the Box, returning a wrapped NonNull pointer.

\n

The pointer will be properly aligned.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the NonNull pointer back into a Box with the\nBox::from_non_null function, allowing the Box destructor to\nperform the cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_non_null(b) instead of b.into_non_null().\nThis is so that there is no conflict with a method on the inner type.

\n
ยงExamples
\n

Converting the NonNull pointer back into a Box with Box::from_non_null\nfor automatic cleanup:

\n\n
#![feature(box_vec_non_null)]\n\nlet x = Box::new(String::from(\"Hello\"));\nlet non_null = Box::into_non_null(x);\nlet x = unsafe { Box::from_non_null(non_null) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
#![feature(box_vec_non_null)]\n\nuse std::alloc::{dealloc, Layout};\n\nlet x = Box::new(String::from(\"Hello\"));\nlet non_null = Box::into_non_null(x);\nunsafe {\n    non_null.drop_in_place();\n    dealloc(non_null.as_ptr().cast::<u8>(), Layout::new::<String>());\n}
\n

Note: This is equivalent to the following:

\n\n
#![feature(box_vec_non_null)]\n\nlet x = Box::new(String::from(\"Hello\"));\nlet non_null = Box::into_non_null(x);\nunsafe {\n    drop(Box::from_non_null(non_null));\n}
\n
source

pub fn into_raw_with_allocator(b: Box<T, A>) -> (*mut T, A)

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Consumes the Box, returning a wrapped raw pointer and the allocator.

\n

The pointer will be properly aligned and non-null.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the raw pointer back into a Box with the\nBox::from_raw_in function, allowing the Box destructor to perform\nthe cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_raw_with_allocator(b) instead of b.into_raw_with_allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
ยงExamples
\n

Converting the raw pointer back into a Box with Box::from_raw_in\nfor automatic cleanup:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nlet x = unsafe { Box::from_raw_in(ptr, alloc) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::{Allocator, Layout, System};\nuse std::ptr::{self, NonNull};\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nunsafe {\n    ptr::drop_in_place(ptr);\n    let non_null = NonNull::new_unchecked(ptr);\n    alloc.deallocate(non_null.cast(), Layout::new::<String>());\n}
\n
source

pub fn into_non_null_with_allocator(b: Box<T, A>) -> (NonNull<T>, A)

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Consumes the Box, returning a wrapped NonNull pointer and the allocator.

\n

The pointer will be properly aligned.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the NonNull pointer back into a Box with the\nBox::from_non_null_in function, allowing the Box destructor to\nperform the cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_non_null_with_allocator(b) instead of\nb.into_non_null_with_allocator(). This is so that there is no\nconflict with a method on the inner type.

\n
ยงExamples
\n

Converting the NonNull pointer back into a Box with\nBox::from_non_null_in for automatic cleanup:

\n\n
#![feature(allocator_api, box_vec_non_null)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (non_null, alloc) = Box::into_non_null_with_allocator(x);\nlet x = unsafe { Box::from_non_null_in(non_null, alloc) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
#![feature(allocator_api, box_vec_non_null)]\n\nuse std::alloc::{Allocator, Layout, System};\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (non_null, alloc) = Box::into_non_null_with_allocator(x);\nunsafe {\n    non_null.drop_in_place();\n    alloc.deallocate(non_null.cast::<u8>(), Layout::new::<String>());\n}
\n
source

pub fn as_mut_ptr(b: &mut Box<T, A>) -> *mut T

๐Ÿ”ฌThis is a nightly-only experimental API. (box_as_ptr)

Returns a raw mutable pointer to the Boxโ€™s contents.

\n

The caller must ensure that the Box outlives the pointer this\nfunction returns, or else it will end up dangling.

\n

This method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying memory, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr and as_mut_ptr.\nNote that calling other methods that materialize references to the memory\nmay still invalidate this pointer.\nSee the example below for how this guarantee can be used.

\n
ยงExamples
\n

Due to the aliasing guarantee, the following code is legal:

\n\n
#![feature(box_as_ptr)]\n\nunsafe {\n    let mut b = Box::new(0);\n    let ptr1 = Box::as_mut_ptr(&mut b);\n    ptr1.write(1);\n    let ptr2 = Box::as_mut_ptr(&mut b);\n    ptr2.write(2);\n    // Notably, the write to `ptr2` did *not* invalidate `ptr1`:\n    ptr1.write(3);\n}
\n
source

pub fn as_ptr(b: &Box<T, A>) -> *const T

๐Ÿ”ฌThis is a nightly-only experimental API. (box_as_ptr)

Returns a raw pointer to the Boxโ€™s contents.

\n

The caller must ensure that the Box outlives the pointer this\nfunction returns, or else it will end up dangling.

\n

The caller must also ensure that the memory the pointer (non-transitively) points to\nis never written to (except inside an UnsafeCell) using this pointer or any pointer\nderived from it. If you need to mutate the contents of the Box, use as_mut_ptr.

\n

This method guarantees that for the purpose of the aliasing model, this method\ndoes not materialize a reference to the underlying memory, and thus the returned pointer\nwill remain valid when mixed with other calls to as_ptr and as_mut_ptr.\nNote that calling other methods that materialize mutable references to the memory,\nas well as writing to this memory, may still invalidate this pointer.\nSee the example below for how this guarantee can be used.

\n
ยงExamples
\n

Due to the aliasing guarantee, the following code is legal:

\n\n
#![feature(box_as_ptr)]\n\nunsafe {\n    let mut v = Box::new(0);\n    let ptr1 = Box::as_ptr(&v);\n    let ptr2 = Box::as_mut_ptr(&mut v);\n    let _val = ptr2.read();\n    // No write to this memory has happened yet, so `ptr1` is still valid.\n    let _val = ptr1.read();\n    // However, once we do a write...\n    ptr2.write(1);\n    // ... `ptr1` is no longer valid.\n    // This would be UB: let _val = ptr1.read();\n}
\n
source

pub const fn allocator(b: &Box<T, A>) -> &A

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

\n

Note: this is an associated function, which means that you have\nto call it as Box::allocator(&b) instead of b.allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
1.36.0 ยท source

pub fn leak<'a>(b: Box<T, A>) -> &'a mut T
where\n A: 'a,

Consumes and leaks the Box, returning a mutable reference,\n&'a mut T.

\n

Note that the type T must outlive the chosen lifetime 'a. If the type\nhas only static references, or none at all, then this may be chosen to be\n'static.

\n

This function is mainly useful for data that lives for the remainder of\nthe programโ€™s life. Dropping the returned reference will cause a memory\nleak. If this is not acceptable, the reference should first be wrapped\nwith the Box::from_raw function producing a Box. This Box can\nthen be dropped which will properly destroy T and release the\nallocated memory.

\n

Note: this is an associated function, which means that you have\nto call it as Box::leak(b) instead of b.leak(). This\nis so that there is no conflict with a method on the inner type.

\n
ยงExamples
\n

Simple usage:

\n\n
let x = Box::new(41);\nlet static_ref: &'static mut usize = Box::leak(x);\n*static_ref += 1;\nassert_eq!(*static_ref, 42);
\n

Unsized data:

\n\n
let x = vec![1, 2, 3].into_boxed_slice();\nlet static_ref = Box::leak(x);\nstatic_ref[0] = 4;\nassert_eq!(*static_ref, [4, 2, 3]);
\n
1.63.0 (const: unstable) ยท source

pub fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>>
where\n A: 'static,

Converts a Box<T> into a Pin<Box<T>>. If T does not implement Unpin, then\n*boxed will be pinned in memory and unable to be moved.

\n

This conversion does not allocate on the heap and happens in place.

\n

This is also available via From.

\n

Constructing and pinning a Box with Box::into_pin(Box::new(x))\ncan also be written more concisely using Box::pin(x).\nThis into_pin method is useful if you already have a Box<T>, or you are\nconstructing a (pinned) Box in a different way than with Box::new.

\n
ยงNotes
\n

Itโ€™s not recommended that crates add an impl like From<Box<T>> for Pin<T>,\nas itโ€™ll introduce an ambiguity when calling Pin::from.\nA demonstration of such a poor impl is shown below.

\n\n
โ“˜
struct Foo; // A type defined in this crate.\nimpl From<Box<()>> for Pin<Foo> {\n    fn from(_: Box<()>) -> Pin<Foo> {\n        Pin::new(Foo)\n    }\n}\n\nlet foo = Box::new(());\nlet bar = Pin::from(foo);
\n
",0,"actix_service::boxed::BoxService"],["
sourceยง

impl<T, A> Box<T, A>
where\n A: Allocator,

source

pub fn new_in(x: T, alloc: A) -> Box<T, A>
where\n A: Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Allocates memory in the given allocator then places x into it.

\n

This doesnโ€™t actually allocate if T is zero-sized.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet five = Box::new_in(5, System);
\n
source

pub fn try_new_in(x: T, alloc: A) -> Result<Box<T, A>, AllocError>
where\n A: Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Allocates memory in the given allocator then places x into it,\nreturning an error if the allocation fails

\n

This doesnโ€™t actually allocate if T is zero-sized.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet five = Box::try_new_in(5, System)?;
\n
source

pub fn new_uninit_in(alloc: A) -> Box<MaybeUninit<T>, A>
where\n A: Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents in the provided allocator.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut five = Box::<u32, _>::new_uninit_in(System);\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn try_new_uninit_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>
where\n A: Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents in the provided allocator,\nreturning an error if the allocation fails

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet mut five = Box::<u32, _>::try_new_uninit_in(System)?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn new_zeroed_in(alloc: A) -> Box<MaybeUninit<T>, A>
where\n A: Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes in the provided allocator.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet zero = Box::<u32, _>::new_zeroed_in(System);\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn try_new_zeroed_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>
where\n A: Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes in the provided allocator,\nreturning an error if the allocation fails,

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet zero = Box::<u32, _>::try_new_zeroed_in(System)?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
source

pub fn pin_in(x: T, alloc: A) -> Pin<Box<T, A>>
where\n A: 'static + Allocator,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Box<T, A>>. If T does not implement Unpin, then\nx will be pinned in memory and unable to be moved.

\n

Constructing and pinning of the Box can also be done in two steps: Box::pin_in(x, alloc)\ndoes the same as Box::into_pin(Box::new_in(x, alloc)). Consider using\ninto_pin if you already have a Box<T, A>, or if you want to\nconstruct a (pinned) Box in a different way than with Box::new_in.

\n
source

pub fn into_boxed_slice(boxed: Box<T, A>) -> Box<[T], A>

๐Ÿ”ฌThis is a nightly-only experimental API. (box_into_boxed_slice)

Converts a Box<T> into a Box<[T]>

\n

This conversion does not allocate on the heap and happens in place.

\n
source

pub fn into_inner(boxed: Box<T, A>) -> T

๐Ÿ”ฌThis is a nightly-only experimental API. (box_into_inner)

Consumes the Box, returning the wrapped value.

\n
ยงExamples
\n
#![feature(box_into_inner)]\n\nlet c = Box::new(5);\n\nassert_eq!(Box::into_inner(c), 5);
\n
",0,"actix_service::boxed::BoxService"],["
1.0.0 ยท sourceยง

impl<B> BufRead for Box<B>
where\n B: BufRead + ?Sized,

sourceยง

fn fill_buf(&mut self) -> Result<&[u8], Error>

Returns the contents of the internal buffer, filling it with more data\nfrom the inner reader if it is empty. Read more
sourceยง

fn consume(&mut self, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer,\nso they should no longer be returned in calls to read. Read more
sourceยง

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
sourceยง

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until a newline (the 0xA byte) is reached, and append\nthem to the provided String buffer. Read more
sourceยง

fn has_data_left(&mut self) -> Result<bool, Error>

๐Ÿ”ฌThis is a nightly-only experimental API. (buf_read_has_data_left)
Checks if the underlying Read has any data left to be read. Read more
sourceยง

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

๐Ÿ”ฌThis is a nightly-only experimental API. (bufread_skip_until)
Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 ยท sourceยง

fn split(self, byte: u8) -> Split<Self>
where\n Self: Sized,

Returns an iterator over the contents of this reader split on the byte\nbyte. Read more
1.0.0 ยท sourceยง

fn lines(self) -> Lines<Self>
where\n Self: Sized,

Returns an iterator over the lines of this reader. Read more
","BufRead","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Clone for Box<T, A>
where\n T: Clone,\n A: Allocator + Clone,

sourceยง

fn clone(&self) -> Box<T, A>

Returns a new box with a clone() of this boxโ€™s contents.

\n
ยงExamples
\n
let x = Box::new(5);\nlet y = x.clone();\n\n// The value is the same\nassert_eq!(x, y);\n\n// But they are unique objects\nassert_ne!(&*x as *const i32, &*y as *const i32);
\n
sourceยง

fn clone_from(&mut self, source: &Box<T, A>)

Copies sourceโ€™s contents into self without creating a new allocation.

\n
ยงExamples
\n
let x = Box::new(5);\nlet mut y = Box::new(10);\nlet yp: *const i32 = &*y;\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no allocation occurred\nassert_eq!(yp, &*y);
\n
","Clone","actix_service::boxed::BoxService"],["
sourceยง

impl<G, R, A> Coroutine<R> for Box<G, A>
where\n G: Coroutine<R> + Unpin + ?Sized,\n A: Allocator,

sourceยง

type Yield = <G as Coroutine<R>>::Yield

๐Ÿ”ฌThis is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine yields. Read more
sourceยง

type Return = <G as Coroutine<R>>::Return

๐Ÿ”ฌThis is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine returns. Read more
sourceยง

fn resume(\n self: Pin<&mut Box<G, A>>,\n arg: R,\n) -> CoroutineState<<Box<G, A> as Coroutine<R>>::Yield, <Box<G, A> as Coroutine<R>>::Return>

๐Ÿ”ฌThis is a nightly-only experimental API. (coroutine_trait)
Resumes the execution of this coroutine. Read more
","Coroutine","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Debug for Box<T, A>
where\n T: Debug + ?Sized,\n A: Allocator,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T> Default for Box<T>
where\n T: Default,

sourceยง

fn default() -> Box<T>

Creates a Box<T>, with the Default value for T.

\n
","Default","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Deref for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

type Target = T

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &T

Dereferences the value.
","Deref","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> DerefMut for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn deref_mut(&mut self) -> &mut T

Mutably dereferences the value.
","DerefMut","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Display for Box<T, A>
where\n T: Display + ?Sized,\n A: Allocator,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<I, A> DoubleEndedIterator for Box<I, A>
where\n I: DoubleEndedIterator + ?Sized,\n A: Allocator,

sourceยง

fn next_back(&mut self) -> Option<<I as Iterator>::Item>

Removes and returns an element from the end of the iterator. Read more
sourceยง

fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item>

Returns the nth element from the end of the iterator. Read more
sourceยง

fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>>

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_advance_by)
Advances the iterator from the back by n elements. Read more
1.27.0 ยท sourceยง

fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> R,\n R: Try<Output = B>,

This is the reverse version of Iterator::try_fold(): it takes\nelements starting from the back of the iterator. Read more
1.27.0 ยท sourceยง

fn rfold<B, F>(self, init: B, f: F) -> B
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> B,

An iterator method that reduces the iteratorโ€™s elements to a single,\nfinal value, starting from the back. Read more
1.27.0 ยท sourceยง

fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator from the back that satisfies a predicate. Read more
","DoubleEndedIterator","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Drop for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn drop(&mut self)

Executes the destructor for this type. Read more
","Drop","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T> Error for Box<T>
where\n T: Error,

sourceยง

fn description(&self) -> &str

๐Ÿ‘ŽDeprecated since 1.42.0: use the Display impl or to_string()
sourceยง

fn cause(&self) -> Option<&dyn Error>

๐Ÿ‘ŽDeprecated since 1.33.0: replaced by Error::source, which can support downcasting
sourceยง

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
sourceยง

fn provide<'b>(&'b self, request: &mut Request<'b>)

๐Ÿ”ฌThis is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
","Error","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<I, A> ExactSizeIterator for Box<I, A>
where\n I: ExactSizeIterator + ?Sized,\n A: Allocator,

sourceยง

fn len(&self) -> usize

Returns the exact remaining length of the iterator. Read more
sourceยง

fn is_empty(&self) -> bool

๐Ÿ”ฌThis is a nightly-only experimental API. (exact_size_is_empty)
Returns true if the iterator is empty. Read more
","ExactSizeIterator","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<Args, F, A> Fn<Args> for Box<F, A>
where\n Args: Tuple,\n F: Fn<Args> + ?Sized,\n A: Allocator,

sourceยง

extern "rust-call" fn call(\n &self,\n args: Args,\n) -> <Box<F, A> as FnOnce<Args>>::Output

๐Ÿ”ฌThis is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","Fn","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<Args, F, A> FnMut<Args> for Box<F, A>
where\n Args: Tuple,\n F: FnMut<Args> + ?Sized,\n A: Allocator,

sourceยง

extern "rust-call" fn call_mut(\n &mut self,\n args: Args,\n) -> <Box<F, A> as FnOnce<Args>>::Output

๐Ÿ”ฌThis is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","FnMut","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<Args, F, A> FnOnce<Args> for Box<F, A>
where\n Args: Tuple,\n F: FnOnce<Args> + ?Sized,\n A: Allocator,

sourceยง

type Output = <F as FnOnce<Args>>::Output

The returned type after the call operator is used.
sourceยง

extern "rust-call" fn call_once(\n self,\n args: Args,\n) -> <Box<F, A> as FnOnce<Args>>::Output

๐Ÿ”ฌThis is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","FnOnce","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T> From<T> for Box<T>

sourceยง

fn from(t: T) -> Box<T>

Converts a T into a Box<T>

\n

The conversion allocates on the heap and moves t\nfrom the stack into it.

\n
ยงExamples
\n
let x = 5;\nlet boxed = Box::new(5);\n\nassert_eq!(Box::from(x), boxed);
\n
","From","actix_service::boxed::BoxService"],["
ยง

impl<F> FusedFuture for Box<F>
where\n F: FusedFuture + Unpin + ?Sized,

ยง

fn is_terminated(&self) -> bool

Returns true if the underlying future should no longer be polled.
","FusedFuture","actix_service::boxed::BoxService"],["
ยง

impl<S> FusedStream for Box<S>
where\n S: FusedStream + Unpin + ?Sized,

ยง

fn is_terminated(&self) -> bool

Returns true if the stream should no longer be polled.
","FusedStream","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<F, A> Future for Box<F, A>
where\n F: Future + Unpin + ?Sized,\n A: Allocator,

sourceยง

type Output = <F as Future>::Output

The type of value produced on completion.
sourceยง

fn poll(\n self: Pin<&mut Box<F, A>>,\n cx: &mut Context<'_>,\n) -> Poll<<Box<F, A> as Future>::Output>

Attempts to resolve the future to a final value, registering\nthe current task for wakeup if the value is not yet available. Read more
","Future","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Hash for Box<T, A>
where\n T: Hash + ?Sized,\n A: Allocator,

sourceยง

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Hasher for Box<T, A>
where\n T: Hasher + ?Sized,\n A: Allocator,

sourceยง

fn finish(&self) -> u64

Returns the hash value for the values written so far. Read more
sourceยง

fn write(&mut self, bytes: &[u8])

Writes some data into this Hasher. Read more
sourceยง

fn write_u8(&mut self, i: u8)

Writes a single u8 into this hasher.
sourceยง

fn write_u16(&mut self, i: u16)

Writes a single u16 into this hasher.
sourceยง

fn write_u32(&mut self, i: u32)

Writes a single u32 into this hasher.
sourceยง

fn write_u64(&mut self, i: u64)

Writes a single u64 into this hasher.
sourceยง

fn write_u128(&mut self, i: u128)

Writes a single u128 into this hasher.
sourceยง

fn write_usize(&mut self, i: usize)

Writes a single usize into this hasher.
sourceยง

fn write_i8(&mut self, i: i8)

Writes a single i8 into this hasher.
sourceยง

fn write_i16(&mut self, i: i16)

Writes a single i16 into this hasher.
sourceยง

fn write_i32(&mut self, i: i32)

Writes a single i32 into this hasher.
sourceยง

fn write_i64(&mut self, i: i64)

Writes a single i64 into this hasher.
sourceยง

fn write_i128(&mut self, i: i128)

Writes a single i128 into this hasher.
sourceยง

fn write_isize(&mut self, i: isize)

Writes a single isize into this hasher.
sourceยง

fn write_length_prefix(&mut self, len: usize)

๐Ÿ”ฌThis is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a length prefix into this hasher, as part of being prefix-free. Read more
sourceยง

fn write_str(&mut self, s: &str)

๐Ÿ”ฌThis is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a single str into this hasher. Read more
","Hasher","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<I, A> Iterator for Box<I, A>
where\n I: Iterator + ?Sized,\n A: Allocator,

sourceยง

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
sourceยง

fn next(&mut self) -> Option<<I as Iterator>::Item>

Advances the iterator and returns the next value. Read more
sourceยง

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
sourceยง

fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item>

Returns the nth element of the iterator. Read more
sourceยง

fn last(self) -> Option<<I as Iterator>::Item>

Consumes the iterator, returning the last element. Read more
sourceยง

fn next_chunk<const N: usize>(\n &mut self,\n) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>
where\n Self: Sized,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.6.0 ยท sourceยง

fn count(self) -> usize
where\n Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
sourceยง

fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.28.0 ยท sourceยง

fn step_by(self, step: usize) -> StepBy<Self>
where\n Self: Sized,

Creates an iterator starting at the same point, but stepping by\nthe given amount at each iteration. Read more
1.6.0 ยท sourceยง

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>
where\n Self: Sized,\n U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.6.0 ยท sourceยง

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>
where\n Self: Sized,\n U: IntoIterator,

โ€˜Zips upโ€™ two iterators into a single iterator of pairs. Read more
sourceยง

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
where\n Self: Sized,\n G: FnMut() -> Self::Item,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator\nbetween adjacent items of the original iterator. Read more
1.6.0 ยท sourceยง

fn map<B, F>(self, f: F) -> Map<Self, F>
where\n Self: Sized,\n F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each\nelement. Read more
1.21.0 ยท sourceยง

fn for_each<F>(self, f: F)
where\n Self: Sized,\n F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.6.0 ยท sourceยง

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element\nshould be yielded. Read more
1.6.0 ยท sourceยง

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
where\n Self: Sized,\n F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.6.0 ยท sourceยง

fn enumerate(self) -> Enumerate<Self>
where\n Self: Sized,

Creates an iterator which gives the current iteration count as well as\nthe next value. Read more
1.6.0 ยท sourceยง

fn peekable(self) -> Peekable<Self>
where\n Self: Sized,

Creates an iterator which can use the peek and peek_mut methods\nto look at the next element of the iterator without consuming it. See\ntheir documentation for more information. Read more
1.6.0 ยท sourceยง

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.6.0 ยท sourceยง

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0 ยท sourceยง

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
where\n Self: Sized,\n P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.6.0 ยท sourceยง

fn skip(self, n: usize) -> Skip<Self>
where\n Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.6.0 ยท sourceยง

fn take(self, n: usize) -> Take<Self>
where\n Self: Sized,

Creates an iterator that yields the first n elements, or fewer\nif the underlying iterator ends sooner. Read more
1.6.0 ยท sourceยง

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where\n Self: Sized,\n F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but\nunlike fold, produces a new iterator. Read more
1.6.0 ยท sourceยง

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where\n Self: Sized,\n U: IntoIterator,\n F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
sourceยง

fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
where\n Self: Sized,\n F: FnMut(&[Self::Item; N]) -> R,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_map_windows)
Calls the given function f for each contiguous window of size N over\nself and returns an iterator over the outputs of f. Like slice::windows(),\nthe windows during mapping overlap as well. Read more
1.6.0 ยท sourceยง

fn fuse(self) -> Fuse<Self>
where\n Self: Sized,

Creates an iterator which ends after the first None. Read more
1.6.0 ยท sourceยง

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where\n Self: Sized,\n F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.6.0 ยท sourceยง

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.6.0 ยท sourceยง

fn collect<B>(self) -> B
where\n B: FromIterator<Self::Item>,\n Self: Sized,

Transforms an iterator into a collection. Read more
sourceยง

fn collect_into<E>(self, collection: &mut E) -> &mut E
where\n E: Extend<Self::Item>,\n Self: Sized,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.6.0 ยท sourceยง

fn partition<B, F>(self, f: F) -> (B, B)
where\n Self: Sized,\n B: Default + Extend<Self::Item>,\n F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
sourceยง

fn is_partitioned<P>(self, predicate: P) -> bool
where\n Self: Sized,\n P: FnMut(Self::Item) -> bool,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate,\nsuch that all those that return true precede all those that return false. Read more
1.27.0 ยท sourceยง

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> R,\n R: Try<Output = B>,

An iterator method that applies a function as long as it returns\nsuccessfully, producing a single, final value. Read more
1.27.0 ยท sourceยง

fn try_for_each<F, R>(&mut self, f: F) -> R
where\n Self: Sized,\n F: FnMut(Self::Item) -> R,\n R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the\niterator, stopping at the first error and returning that error. Read more
1.6.0 ยท sourceยง

fn fold<B, F>(self, init: B, f: F) -> B
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation,\nreturning the final result. Read more
1.51.0 ยท sourceยง

fn reduce<F>(self, f: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing\noperation. Read more
sourceยง

fn try_reduce<R>(\n &mut self,\n f: impl FnMut(Self::Item, Self::Item) -> R,\n) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
where\n Self: Sized,\n R: Try<Output = Self::Item>,\n <R as Try>::Residual: Residual<Option<Self::Item>>,

๐Ÿ”ฌThis is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the\nclosure returns a failure, the failure is propagated back to the caller immediately. Read more
1.6.0 ยท sourceยง

fn all<F>(&mut self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.6.0 ยท sourceยง

fn any<F>(&mut self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.6.0 ยท sourceยง

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0 ยท sourceยง

fn find_map<B, F>(&mut self, f: F) -> Option<B>
where\n Self: Sized,\n F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns\nthe first non-none result. Read more
sourceยง

fn try_find<R>(\n &mut self,\n f: impl FnMut(&Self::Item) -> R,\n) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
where\n Self: Sized,\n R: Try<Output = bool>,\n <R as Try>::Residual: Residual<Option<Self::Item>>,

๐Ÿ”ฌThis is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns\nthe first true result or the first error. Read more
1.6.0 ยท sourceยง

fn position<P>(&mut self, predicate: P) -> Option<usize>
where\n Self: Sized,\n P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0 ยท sourceยง

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
where\n B: Ord,\n Self: Sized,\n F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the\nspecified function. Read more
1.15.0 ยท sourceยง

fn max_by<F>(self, compare: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the\nspecified comparison function. Read more
1.6.0 ยท sourceยง

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
where\n B: Ord,\n Self: Sized,\n F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the\nspecified function. Read more
1.15.0 ยท sourceยง

fn min_by<F>(self, compare: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the\nspecified comparison function. Read more
1.6.0 ยท sourceยง

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
where\n FromA: Default + Extend<A>,\n FromB: Default + Extend<B>,\n Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0 ยท sourceยง

fn copied<'a, T>(self) -> Copied<Self>
where\n T: 'a + Copy,\n Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.6.0 ยท sourceยง

fn cloned<'a, T>(self) -> Cloned<Self>
where\n T: 'a + Clone,\n Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
sourceยง

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
where\n Self: Sized,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0 ยท sourceยง

fn sum<S>(self) -> S
where\n Self: Sized,\n S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0 ยท sourceยง

fn product<P>(self) -> P
where\n Self: Sized,\n P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
sourceยง

fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those\nof another with respect to the specified comparison function. Read more
1.6.0 ยท sourceยง

fn partial_cmp<I>(self, other: I) -> Option<Ordering>
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Lexicographically compares the PartialOrd elements of\nthis Iterator with those of another. The comparison works like short-circuit\nevaluation, returning a result without comparing the remaining elements.\nAs soon as an order can be determined, the evaluation stops and a result is returned. Read more
sourceยง

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those\nof another with respect to the specified comparison function. Read more
1.6.0 ยท sourceยง

fn eq<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialEq<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are equal to those of\nanother. Read more
sourceยง

fn eq_by<I, F>(self, other: I, eq: F) -> bool
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

๐Ÿ”ฌThis is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this Iterator are equal to those of\nanother with respect to the specified equality function. Read more
1.6.0 ยท sourceยง

fn ne<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialEq<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are not equal to those of\nanother. Read more
1.6.0 ยท sourceยง

fn lt<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\nless than those of another. Read more
1.6.0 ยท sourceยง

fn le<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\nless or equal to those of another. Read more
1.6.0 ยท sourceยง

fn gt<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\ngreater than those of another. Read more
1.6.0 ยท sourceยง

fn ge<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\ngreater than or equal to those of another. Read more
1.82.0 ยท sourceยง

fn is_sorted_by<F>(self, compare: F) -> bool
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> bool,

Checks if the elements of this iterator are sorted using the given comparator function. Read more
1.82.0 ยท sourceยง

fn is_sorted_by_key<F, K>(self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> K,\n K: PartialOrd,

Checks if the elements of this iterator are sorted using the given key extraction\nfunction. Read more
","Iterator","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Ord for Box<T, A>
where\n T: Ord + ?Sized,\n A: Allocator,

sourceยง

fn cmp(&self, other: &Box<T, A>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized,

Restrict a value to a certain interval. Read more
","Ord","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> PartialEq for Box<T, A>
where\n T: PartialEq + ?Sized,\n A: Allocator,

sourceยง

fn eq(&self, other: &Box<T, A>) -> bool

Tests for self and other values to be equal, and is used by ==.
sourceยง

fn ne(&self, other: &Box<T, A>) -> bool

Tests for !=. The default implementation is almost always sufficient,\nand should not be overridden without very good reason.
","PartialEq","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> PartialOrd for Box<T, A>
where\n T: PartialOrd + ?Sized,\n A: Allocator,

sourceยง

fn partial_cmp(&self, other: &Box<T, A>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
sourceยง

fn lt(&self, other: &Box<T, A>) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
sourceยง

fn le(&self, other: &Box<T, A>) -> bool

Tests less than or equal to (for self and other) and is used by the\n<= operator. Read more
sourceยง

fn ge(&self, other: &Box<T, A>) -> bool

Tests greater than or equal to (for self and other) and is used by\nthe >= operator. Read more
sourceยง

fn gt(&self, other: &Box<T, A>) -> bool

Tests greater than (for self and other) and is used by the >\noperator. Read more
","PartialOrd","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Pointer for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Pointer","actix_service::boxed::BoxService"],["
1.0.0 ยท sourceยง

impl<R> Read for Box<R>
where\n R: Read + ?Sized,

sourceยง

fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>

Pull some bytes from this source into the specified buffer, returning\nhow many bytes were read. Read more
sourceยง

fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

๐Ÿ”ฌThis is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
sourceยง

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
sourceยง

fn is_read_vectored(&self) -> bool

๐Ÿ”ฌThis is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored\nimplementation. Read more
sourceยง

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
sourceยง

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
sourceยง

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
sourceยง

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

๐Ÿ”ฌThis is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 ยท sourceยง

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Creates a โ€œby referenceโ€ adaptor for this instance of Read. Read more
1.0.0 ยท sourceยง

fn bytes(self) -> Bytes<Self>
where\n Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 ยท sourceยง

fn chain<R>(self, next: R) -> Chain<Self, R>
where\n R: Read,\n Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 ยท sourceยง

fn take(self, limit: u64) -> Take<Self>
where\n Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
","Read","actix_service::boxed::BoxService"],["
1.0.0 ยท sourceยง

impl<S> Seek for Box<S>
where\n S: Seek + ?Sized,

sourceยง

fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>

Seek to an offset, in bytes, in a stream. Read more
sourceยง

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.55.0 ยท sourceยง

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
sourceยง

fn stream_len(&mut self) -> Result<u64, Error>

๐Ÿ”ฌThis is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.80.0 ยท sourceยง

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
","Seek","actix_service::boxed::BoxService"],["
sourceยง

impl<S, Req> Service<Req> for Box<S>
where\n S: Service<Req> + ?Sized,

sourceยง

type Response = <S as Service<Req>>::Response

Responses given by the service.
sourceยง

type Error = <S as Service<Req>>::Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = <S as Service<Req>>::Future

The future response value.
sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), S::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, request: Req) -> S::Future

Process the request and return the response asynchronously. Read more
","Service","actix_service::boxed::BoxService"],["
ยง

impl<S> Stream for Box<S>
where\n S: Stream + Unpin + ?Sized,

ยง

type Item = <S as Stream>::Item

Values yielded by the stream.
ยง

fn poll_next(\n self: Pin<&mut Box<S>>,\n cx: &mut Context<'_>,\n) -> Poll<Option<<Box<S> as Stream>::Item>>

Attempt to pull out the next value of this stream, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the stream is exhausted. Read more
ยง

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
","Stream","actix_service::boxed::BoxService"],["
1.0.0 ยท sourceยง

impl<W> Write for Box<W>
where\n W: Write + ?Sized,

sourceยง

fn write(&mut self, buf: &[u8]) -> Result<usize, Error>

Writes a buffer into this writer, returning how many bytes were written. Read more
sourceยง

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
sourceยง

fn is_write_vectored(&self) -> bool

๐Ÿ”ฌThis is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored\nimplementation. Read more
sourceยง

fn flush(&mut self) -> Result<(), Error>

Flushes this output stream, ensuring that all intermediately buffered\ncontents reach their destination. Read more
sourceยง

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
sourceยง

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error\nencountered. Read more
sourceยง

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

๐Ÿ”ฌThis is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 ยท sourceยง

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Creates a โ€œby referenceโ€ adapter for this instance of Write. Read more
","Write","actix_service::boxed::BoxService"],["
sourceยง

impl<T, U, A> CoerceUnsized<Box<U, A>> for Box<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","actix_service::boxed::BoxService"],["
sourceยง

impl<T, A> DerefPure for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

","DerefPure","actix_service::boxed::BoxService"],["
sourceยง

impl<T, U> DispatchFromDyn<Box<U>> for Box<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Eq for Box<T, A>
where\n T: Eq + ?Sized,\n A: Allocator,

","Eq","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<I, A> FusedIterator for Box<I, A>
where\n I: FusedIterator + ?Sized,\n A: Allocator,

","FusedIterator","actix_service::boxed::BoxService"],["
sourceยง

impl<T, A> PinCoerceUnsized for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

","PinCoerceUnsized","actix_service::boxed::BoxService"],["
1.36.0 ยท sourceยง

impl<T, A> Unpin for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

","Unpin","actix_service::boxed::BoxService"]]]]); + if (window.register_type_impls) { + window.register_type_impls(type_impls); + } else { + window.pending_type_impls = type_impls; + } +})() +//{"start":55,"fragment_lengths":[386806]} \ No newline at end of file diff --git a/type.impl/alloc/rc/struct.Rc.js b/type.impl/alloc/rc/struct.Rc.js new file mode 100644 index 00000000..7a0c8440 --- /dev/null +++ b/type.impl/alloc/rc/struct.Rc.js @@ -0,0 +1,9 @@ +(function() { + var type_impls = Object.fromEntries([["actix_service",[["
1.69.0 ยท sourceยง

impl<T> AsFd for Rc<T>
where\n T: AsFd + ?Sized,

sourceยง

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
","AsFd","actix_service::boxed::RcService"],["
1.69.0 ยท sourceยง

impl<T> AsRawFd for Rc<T>
where\n T: AsRawFd,

sourceยง

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
","AsRawFd","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> AsRef<T> for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Borrow<T> for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
","Borrow","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Clone for Rc<T, A>
where\n A: Allocator + Clone,\n T: ?Sized,

sourceยง

fn clone(&self) -> Rc<T, A>

Makes a clone of the Rc pointer.

\n

This creates another pointer to the same allocation, increasing the\nstrong reference count.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nlet _ = Rc::clone(&five);
\n
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Debug for Rc<T, A>
where\n T: Debug + ?Sized,\n A: Allocator,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T> Default for Rc<T>
where\n T: Default,

sourceยง

fn default() -> Rc<T>

Creates a new Rc<T>, with the Default value for T.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet x: Rc<i32> = Default::default();\nassert_eq!(*x, 0);
\n
","Default","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Deref for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

type Target = T

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &T

Dereferences the value.
","Deref","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Display for Rc<T, A>
where\n T: Display + ?Sized,\n A: Allocator,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Drop for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn drop(&mut self)

Drops the Rc.

\n

This will decrement the strong reference count. If the strong reference\ncount reaches zero then the only other references (if any) are\nWeak, so we drop the inner value.

\n
ยงExamples
\n
use std::rc::Rc;\n\nstruct Foo;\n\nimpl Drop for Foo {\n    fn drop(&mut self) {\n        println!(\"dropped!\");\n    }\n}\n\nlet foo  = Rc::new(Foo);\nlet foo2 = Rc::clone(&foo);\n\ndrop(foo);    // Doesn't print anything\ndrop(foo2);   // Prints \"dropped!\"
\n
","Drop","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> From<Box<T, A>> for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn from(v: Box<T, A>) -> Rc<T, A>

Move a boxed object to a new, reference counted, allocation.

\n
ยงExample
\n
let original: Box<i32> = Box::new(1);\nlet shared: Rc<i32> = Rc::from(original);\nassert_eq!(1, *shared);
\n
","From>","actix_service::boxed::RcService"],["
1.45.0 ยท sourceยง

impl<'a, B> From<Cow<'a, B>> for Rc<B>
where\n B: ToOwned + ?Sized,\n Rc<B>: From<&'a B> + From<<B as ToOwned>::Owned>,

sourceยง

fn from(cow: Cow<'a, B>) -> Rc<B>

Creates a reference-counted pointer from a clone-on-write pointer by\ncopying its content.

\n
ยงExample
\n
let cow: Cow<'_, str> = Cow::Borrowed(\"eggplant\");\nlet shared: Rc<str> = Rc::from(cow);\nassert_eq!(\"eggplant\", &shared[..]);
\n
","From>","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T> From<T> for Rc<T>

sourceยง

fn from(t: T) -> Rc<T>

Converts a generic type T into an Rc<T>

\n

The conversion allocates on the heap and moves t\nfrom the stack into it.

\n
ยงExample
\n
let x = 5;\nlet rc = Rc::new(5);\n\nassert_eq!(Rc::from(x), rc);
\n
","From","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Hash for Rc<T, A>
where\n T: Hash + ?Sized,\n A: Allocator,

sourceยง

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Ord for Rc<T, A>
where\n T: Ord + ?Sized,\n A: Allocator,

sourceยง

fn cmp(&self, other: &Rc<T, A>) -> Ordering

Comparison for two Rcs.

\n

The two are compared by calling cmp() on their inner values.

\n
ยงExamples
\n
use std::rc::Rc;\nuse std::cmp::Ordering;\n\nlet five = Rc::new(5);\n\nassert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
\n
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized,

Restrict a value to a certain interval. Read more
","Ord","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> PartialEq for Rc<T, A>
where\n T: PartialEq + ?Sized,\n A: Allocator,

sourceยง

fn eq(&self, other: &Rc<T, A>) -> bool

Equality for two Rcs.

\n

Two Rcs are equal if their inner values are equal, even if they are\nstored in different allocation.

\n

If T also implements Eq (implying reflexivity of equality),\ntwo Rcs that point to the same allocation are\nalways equal.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nassert!(five == Rc::new(5));
\n
sourceยง

fn ne(&self, other: &Rc<T, A>) -> bool

Inequality for two Rcs.

\n

Two Rcs are not equal if their inner values are not equal.

\n

If T also implements Eq (implying reflexivity of equality),\ntwo Rcs that point to the same allocation are\nalways equal.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nassert!(five != Rc::new(6));
\n
","PartialEq","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> PartialOrd for Rc<T, A>
where\n T: PartialOrd + ?Sized,\n A: Allocator,

sourceยง

fn partial_cmp(&self, other: &Rc<T, A>) -> Option<Ordering>

Partial comparison for two Rcs.

\n

The two are compared by calling partial_cmp() on their inner values.

\n
ยงExamples
\n
use std::rc::Rc;\nuse std::cmp::Ordering;\n\nlet five = Rc::new(5);\n\nassert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
\n
sourceยง

fn lt(&self, other: &Rc<T, A>) -> bool

Less-than comparison for two Rcs.

\n

The two are compared by calling < on their inner values.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nassert!(five < Rc::new(6));
\n
sourceยง

fn le(&self, other: &Rc<T, A>) -> bool

โ€˜Less than or equal toโ€™ comparison for two Rcs.

\n

The two are compared by calling <= on their inner values.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nassert!(five <= Rc::new(5));
\n
sourceยง

fn gt(&self, other: &Rc<T, A>) -> bool

Greater-than comparison for two Rcs.

\n

The two are compared by calling > on their inner values.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nassert!(five > Rc::new(4));
\n
sourceยง

fn ge(&self, other: &Rc<T, A>) -> bool

โ€˜Greater than or equal toโ€™ comparison for two Rcs.

\n

The two are compared by calling >= on their inner values.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nassert!(five >= Rc::new(5));
\n
","PartialOrd","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Pointer for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Pointer","actix_service::boxed::RcService"],["
sourceยง

impl<T> Rc<T>
where\n T: ?Sized,

1.36.0 ยท source

pub unsafe fn from_raw(ptr: *const T) -> Rc<T>

Constructs an Rc<T> from a raw pointer.

\n

The raw pointer must have been previously returned by a call to\nRc<U>::into_raw with the following requirements:

\n
    \n
  • If U is sized, it must have the same size and alignment as T. This\nis trivially true if U is T.
  • \n
  • If U is unsized, its data pointer must have the same size and\nalignment as T. This is trivially true if Rc<U> was constructed\nthrough Rc<T> and then converted to Rc<U> through an unsized\ncoercion.
  • \n
\n

Note that if U or Uโ€™s data pointer is not T but has the same size\nand alignment, this is basically like transmuting references of\ndifferent types. See mem::transmute for more information\non what restrictions apply in this case.

\n

The raw pointer must point to a block of memory allocated by the global allocator

\n

The user of from_raw has to make sure a specific value of T is only\ndropped once.

\n

This function is unsafe because improper use may lead to memory unsafety,\neven if the returned Rc<T> is never accessed.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet x = Rc::new(\"hello\".to_owned());\nlet x_ptr = Rc::into_raw(x);\n\nunsafe {\n    // Convert back to an `Rc` to prevent leak.\n    let x = Rc::from_raw(x_ptr);\n    assert_eq!(&*x, \"hello\");\n\n    // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.\n}\n\n// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
\n

Convert a slice back into its original array:

\n\n
use std::rc::Rc;\n\nlet x: Rc<[u32]> = Rc::new([1, 2, 3]);\nlet x_ptr: *const [u32] = Rc::into_raw(x);\n\nunsafe {\n    let x: Rc<[u32; 3]> = Rc::from_raw(x_ptr.cast::<[u32; 3]>());\n    assert_eq!(&*x, &[1, 2, 3]);\n}
\n
1.53.0 ยท source

pub unsafe fn increment_strong_count(ptr: *const T)

Increments the strong reference count on the Rc<T> associated with the\nprovided pointer by one.

\n
ยงSafety
\n

The pointer must have been obtained through Rc::into_raw, the\nassociated Rc instance must be valid (i.e. the strong count must be at\nleast 1) for the duration of this method, and ptr must point to a block of memory\nallocated by the global allocator.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nunsafe {\n    let ptr = Rc::into_raw(five);\n    Rc::increment_strong_count(ptr);\n\n    let five = Rc::from_raw(ptr);\n    assert_eq!(2, Rc::strong_count(&five));\n}
\n
1.53.0 ยท source

pub unsafe fn decrement_strong_count(ptr: *const T)

Decrements the strong reference count on the Rc<T> associated with the\nprovided pointer by one.

\n
ยงSafety
\n

The pointer must have been obtained through Rc::into_raw, the\nassociated Rc instance must be valid (i.e. the strong count must be at\nleast 1) when invoking this method, and ptr must point to a block of memory\nallocated by the global allocator. This method can be used to release the final Rc and\nbacking storage, but should not be called after the final Rc has been released.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nunsafe {\n    let ptr = Rc::into_raw(five);\n    Rc::increment_strong_count(ptr);\n\n    let five = Rc::from_raw(ptr);\n    assert_eq!(2, Rc::strong_count(&five));\n    Rc::decrement_strong_count(ptr);\n    assert_eq!(1, Rc::strong_count(&five));\n}
\n
",0,"actix_service::boxed::RcService"],["
sourceยง

impl<T> Rc<T>

1.36.0 ยท source

pub fn new(value: T) -> Rc<T>

Constructs a new Rc<T>.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);
\n
1.60.0 ยท source

pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
where\n F: FnOnce(&Weak<T>) -> T,

Constructs a new Rc<T> while giving you a Weak<T> to the allocation,\nto allow you to construct a T which holds a weak pointer to itself.

\n

Generally, a structure circularly referencing itself, either directly or\nindirectly, should not hold a strong reference to itself to prevent a memory leak.\nUsing this function, you get access to the weak pointer during the\ninitialization of T, before the Rc<T> is created, such that you can\nclone and store it inside the T.

\n

new_cyclic first allocates the managed allocation for the Rc<T>,\nthen calls your closure, giving it a Weak<T> to this allocation,\nand only afterwards completes the construction of the Rc<T> by placing\nthe T returned from your closure into the allocation.

\n

Since the new Rc<T> is not fully-constructed until Rc<T>::new_cyclic\nreturns, calling upgrade on the weak reference inside your closure will\nfail and result in a None value.

\n
ยงPanics
\n

If data_fn panics, the panic is propagated to the caller, and the\ntemporary Weak<T> is dropped normally.

\n
ยงExamples
\n
use std::rc::{Rc, Weak};\n\nstruct Gadget {\n    me: Weak<Gadget>,\n}\n\nimpl Gadget {\n    /// Constructs a reference counted Gadget.\n    fn new() -> Rc<Self> {\n        // `me` is a `Weak<Gadget>` pointing at the new allocation of the\n        // `Rc` we're constructing.\n        Rc::new_cyclic(|me| {\n            // Create the actual struct here.\n            Gadget { me: me.clone() }\n        })\n    }\n\n    /// Returns a reference counted pointer to Self.\n    fn me(&self) -> Rc<Self> {\n        self.me.upgrade().unwrap()\n    }\n}
\n
1.82.0 ยท source

pub fn new_uninit() -> Rc<MaybeUninit<T>>

Constructs a new Rc with uninitialized contents.

\n
ยงExamples
\n
#![feature(get_mut_unchecked)]\n\nuse std::rc::Rc;\n\nlet mut five = Rc::<u32>::new_uninit();\n\n// Deferred initialization:\nRc::get_mut(&mut five).unwrap().write(5);\n\nlet five = unsafe { five.assume_init() };\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed() -> Rc<MaybeUninit<T>>

๐Ÿ”ฌThis is a nightly-only experimental API. (new_zeroed_alloc)

Constructs a new Rc with uninitialized contents, with the memory\nbeing filled with 0 bytes.

\n

See MaybeUninit::zeroed for examples of correct and\nincorrect usage of this method.

\n
ยงExamples
\n
#![feature(new_zeroed_alloc)]\n\nuse std::rc::Rc;\n\nlet zero = Rc::<u32>::new_zeroed();\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn try_new(value: T) -> Result<Rc<T>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc<T>, returning an error if the allocation fails

\n
ยงExamples
\n
#![feature(allocator_api)]\nuse std::rc::Rc;\n\nlet five = Rc::try_new(5);
\n
source

pub fn try_new_uninit() -> Result<Rc<MaybeUninit<T>>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc with uninitialized contents, returning an error if the allocation fails

\n
ยงExamples
\n
#![feature(allocator_api)]\n#![feature(get_mut_unchecked)]\n\nuse std::rc::Rc;\n\nlet mut five = Rc::<u32>::try_new_uninit()?;\n\n// Deferred initialization:\nRc::get_mut(&mut five).unwrap().write(5);\n\nlet five = unsafe { five.assume_init() };\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed() -> Result<Rc<MaybeUninit<T>>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc with uninitialized contents, with the memory\nbeing filled with 0 bytes, returning an error if the allocation fails

\n

See MaybeUninit::zeroed for examples of correct and\nincorrect usage of this method.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\n\nlet zero = Rc::<u32>::try_new_zeroed()?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
1.36.0 ยท source

pub fn pin(value: T) -> Pin<Rc<T>>

Constructs a new Pin<Rc<T>>. If T does not implement Unpin, then\nvalue will be pinned in memory and unable to be moved.

\n
",0,"actix_service::boxed::RcService"],["
sourceยง

impl<T, A> Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

source

pub fn allocator(this: &Rc<T, A>) -> &A

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

\n

Note: this is an associated function, which means that you have\nto call it as Rc::allocator(&r) instead of r.allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
1.36.0 ยท source

pub fn into_raw(this: Rc<T, A>) -> *const T

Consumes the Rc, returning the wrapped pointer.

\n

To avoid a memory leak the pointer must be converted back to an Rc using\nRc::from_raw.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet x = Rc::new(\"hello\".to_owned());\nlet x_ptr = Rc::into_raw(x);\nassert_eq!(unsafe { &*x_ptr }, \"hello\");
\n
source

pub fn into_raw_with_allocator(this: Rc<T, A>) -> (*const T, A)

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Consumes the Rc, returning the wrapped pointer and allocator.

\n

To avoid a memory leak the pointer must be converted back to an Rc using\nRc::from_raw_in.

\n
ยงExamples
\n
#![feature(allocator_api)]\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet x = Rc::new_in(\"hello\".to_owned(), System);\nlet (ptr, alloc) = Rc::into_raw_with_allocator(x);\nassert_eq!(unsafe { &*ptr }, \"hello\");\nlet x = unsafe { Rc::from_raw_in(ptr, alloc) };\nassert_eq!(&*x, \"hello\");
\n
1.45.0 ยท source

pub fn as_ptr(this: &Rc<T, A>) -> *const T

Provides a raw pointer to the data.

\n

The counts are not affected in any way and the Rc is not consumed. The pointer is valid\nfor as long there are strong counts in the Rc.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet x = Rc::new(\"hello\".to_owned());\nlet y = Rc::clone(&x);\nlet x_ptr = Rc::as_ptr(&x);\nassert_eq!(x_ptr, Rc::as_ptr(&y));\nassert_eq!(unsafe { &*x_ptr }, \"hello\");
\n
source

pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Rc<T, A>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs an Rc<T, A> from a raw pointer in the provided allocator.

\n

The raw pointer must have been previously returned by a call to Rc<U, A>::into_raw with the following requirements:

\n
    \n
  • If U is sized, it must have the same size and alignment as T. This\nis trivially true if U is T.
  • \n
  • If U is unsized, its data pointer must have the same size and\nalignment as T. This is trivially true if Rc<U> was constructed\nthrough Rc<T> and then converted to Rc<U> through an unsized\ncoercion.
  • \n
\n

Note that if U or Uโ€™s data pointer is not T but has the same size\nand alignment, this is basically like transmuting references of\ndifferent types. See mem::transmute for more information\non what restrictions apply in this case.

\n

The raw pointer must point to a block of memory allocated by alloc

\n

The user of from_raw has to make sure a specific value of T is only\ndropped once.

\n

This function is unsafe because improper use may lead to memory unsafety,\neven if the returned Rc<T> is never accessed.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet x = Rc::new_in(\"hello\".to_owned(), System);\nlet x_ptr = Rc::into_raw(x);\n\nunsafe {\n    // Convert back to an `Rc` to prevent leak.\n    let x = Rc::from_raw_in(x_ptr, System);\n    assert_eq!(&*x, \"hello\");\n\n    // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.\n}\n\n// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
\n

Convert a slice back into its original array:

\n\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet x: Rc<[u32], _> = Rc::new_in([1, 2, 3], System);\nlet x_ptr: *const [u32] = Rc::into_raw(x);\n\nunsafe {\n    let x: Rc<[u32; 3], _> = Rc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System);\n    assert_eq!(&*x, &[1, 2, 3]);\n}
\n
1.36.0 ยท source

pub fn downgrade(this: &Rc<T, A>) -> Weak<T, A>
where\n A: Clone,

Creates a new Weak pointer to this allocation.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\n\nlet weak_five = Rc::downgrade(&five);
\n
1.36.0 ยท source

pub fn weak_count(this: &Rc<T, A>) -> usize

Gets the number of Weak pointers to this allocation.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\nlet _weak_five = Rc::downgrade(&five);\n\nassert_eq!(1, Rc::weak_count(&five));
\n
1.36.0 ยท source

pub fn strong_count(this: &Rc<T, A>) -> usize

Gets the number of strong (Rc) pointers to this allocation.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\nlet _also_five = Rc::clone(&five);\n\nassert_eq!(2, Rc::strong_count(&five));
\n
source

pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A)
where\n A: Clone,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Increments the strong reference count on the Rc<T> associated with the\nprovided pointer by one.

\n
ยงSafety
\n

The pointer must have been obtained through Rc::into_raw, the\nassociated Rc instance must be valid (i.e. the strong count must be at\nleast 1) for the duration of this method, and ptr must point to a block of memory\nallocated by alloc

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet five = Rc::new_in(5, System);\n\nunsafe {\n    let ptr = Rc::into_raw(five);\n    Rc::increment_strong_count_in(ptr, System);\n\n    let five = Rc::from_raw_in(ptr, System);\n    assert_eq!(2, Rc::strong_count(&five));\n}
\n
source

pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A)

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Decrements the strong reference count on the Rc<T> associated with the\nprovided pointer by one.

\n
ยงSafety
\n

The pointer must have been obtained through Rc::into_raw, the\nassociated Rc instance must be valid (i.e. the strong count must be at\nleast 1) when invoking this method, and ptr must point to a block of memory\nallocated by alloc. This method can be used to release the final Rc and backing storage,\nbut should not be called after the final Rc has been released.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet five = Rc::new_in(5, System);\n\nunsafe {\n    let ptr = Rc::into_raw(five);\n    Rc::increment_strong_count_in(ptr, System);\n\n    let five = Rc::from_raw_in(ptr, System);\n    assert_eq!(2, Rc::strong_count(&five));\n    Rc::decrement_strong_count_in(ptr, System);\n    assert_eq!(1, Rc::strong_count(&five));\n}
\n
1.36.0 ยท source

pub fn get_mut(this: &mut Rc<T, A>) -> Option<&mut T>

Returns a mutable reference into the given Rc, if there are\nno other Rc or Weak pointers to the same allocation.

\n

Returns None otherwise, because it is not safe to\nmutate a shared value.

\n

See also make_mut, which will clone\nthe inner value when there are other Rc pointers.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet mut x = Rc::new(3);\n*Rc::get_mut(&mut x).unwrap() = 4;\nassert_eq!(*x, 4);\n\nlet _y = Rc::clone(&x);\nassert!(Rc::get_mut(&mut x).is_none());
\n
source

pub unsafe fn get_mut_unchecked(this: &mut Rc<T, A>) -> &mut T

๐Ÿ”ฌThis is a nightly-only experimental API. (get_mut_unchecked)

Returns a mutable reference into the given Rc,\nwithout any check.

\n

See also get_mut, which is safe and does appropriate checks.

\n
ยงSafety
\n

If any other Rc or Weak pointers to the same allocation exist, then\nthey must not be dereferenced or have active borrows for the duration\nof the returned borrow, and their inner type must be exactly the same as the\ninner type of this Rc (including lifetimes). This is trivially the case if no\nsuch pointers exist, for example immediately after Rc::new.

\n
ยงExamples
\n
#![feature(get_mut_unchecked)]\n\nuse std::rc::Rc;\n\nlet mut x = Rc::new(String::new());\nunsafe {\n    Rc::get_mut_unchecked(&mut x).push_str(\"foo\")\n}\nassert_eq!(*x, \"foo\");
\n

Other Rc pointers to the same allocation must be to the same type.

\n\n
#![feature(get_mut_unchecked)]\n\nuse std::rc::Rc;\n\nlet x: Rc<str> = Rc::from(\"Hello, world!\");\nlet mut y: Rc<[u8]> = x.clone().into();\nunsafe {\n    // this is Undefined Behavior, because x's inner type is str, not [u8]\n    Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8\n}\nprintln!(\"{}\", &*x); // Invalid UTF-8 in a str
\n

Other Rc pointers to the same allocation must be to the exact same type, including lifetimes.

\n\n
#![feature(get_mut_unchecked)]\n\nuse std::rc::Rc;\n\nlet x: Rc<&str> = Rc::new(\"Hello, world!\");\n{\n    let s = String::from(\"Oh, no!\");\n    let mut y: Rc<&str> = x.clone().into();\n    unsafe {\n        // this is Undefined Behavior, because x's inner type\n        // is &'long str, not &'short str\n        *Rc::get_mut_unchecked(&mut y) = &s;\n    }\n}\nprintln!(\"{}\", &*x); // Use-after-free
\n
1.36.0 ยท source

pub fn ptr_eq(this: &Rc<T, A>, other: &Rc<T, A>) -> bool

Returns true if the two Rcs point to the same allocation in a vein similar to\nptr::eq. This function ignores the metadata of dyn Trait pointers.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet five = Rc::new(5);\nlet same_five = Rc::clone(&five);\nlet other_five = Rc::new(5);\n\nassert!(Rc::ptr_eq(&five, &same_five));\nassert!(!Rc::ptr_eq(&five, &other_five));
\n
",0,"actix_service::boxed::RcService"],["
sourceยง

impl<T, A> Rc<T, A>
where\n T: CloneToUninit + ?Sized,\n A: Allocator + Clone,

1.36.0 ยท source

pub fn make_mut(this: &mut Rc<T, A>) -> &mut T

Makes a mutable reference into the given Rc.

\n

If there are other Rc pointers to the same allocation, then make_mut will\nclone the inner value to a new allocation to ensure unique ownership. This is also\nreferred to as clone-on-write.

\n

However, if there are no other Rc pointers to this allocation, but some Weak\npointers, then the Weak pointers will be disassociated and the inner value will not\nbe cloned.

\n

See also get_mut, which will fail rather than cloning the inner value\nor disassociating Weak pointers.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet mut data = Rc::new(5);\n\n*Rc::make_mut(&mut data) += 1;         // Won't clone anything\nlet mut other_data = Rc::clone(&data); // Won't clone inner data\n*Rc::make_mut(&mut data) += 1;         // Clones inner data\n*Rc::make_mut(&mut data) += 1;         // Won't clone anything\n*Rc::make_mut(&mut other_data) *= 2;   // Won't clone anything\n\n// Now `data` and `other_data` point to different allocations.\nassert_eq!(*data, 8);\nassert_eq!(*other_data, 12);
\n

Weak pointers will be disassociated:

\n\n
use std::rc::Rc;\n\nlet mut data = Rc::new(75);\nlet weak = Rc::downgrade(&data);\n\nassert!(75 == *data);\nassert!(75 == *weak.upgrade().unwrap());\n\n*Rc::make_mut(&mut data) += 1;\n\nassert!(76 == *data);\nassert!(weak.upgrade().is_none());
\n
",0,"actix_service::boxed::RcService"],["
sourceยง

impl<T, A> Rc<T, A>
where\n T: Clone,\n A: Allocator,

1.76.0 ยท source

pub fn unwrap_or_clone(this: Rc<T, A>) -> T

If we have the only reference to T then unwrap it. Otherwise, clone T and return the\nclone.

\n

Assuming rc_t is of type Rc<T>, this function is functionally equivalent to\n(*rc_t).clone(), but will avoid cloning the inner value where possible.

\n
ยงExamples
\n
let inner = String::from(\"test\");\nlet ptr = inner.as_ptr();\n\nlet rc = Rc::new(inner);\nlet inner = Rc::unwrap_or_clone(rc);\n// The inner value was not cloned\nassert!(ptr::eq(ptr, inner.as_ptr()));\n\nlet rc = Rc::new(inner);\nlet rc2 = rc.clone();\nlet inner = Rc::unwrap_or_clone(rc);\n// Because there were 2 references, we had to clone the inner value.\nassert!(!ptr::eq(ptr, inner.as_ptr()));\n// `rc2` is the last reference, so when we unwrap it we get back\n// the original `String`.\nlet inner = Rc::unwrap_or_clone(rc2);\nassert!(ptr::eq(ptr, inner.as_ptr()));
\n
",0,"actix_service::boxed::RcService"],["
sourceยง

impl<T, A> Rc<T, A>
where\n A: Allocator,

source

pub fn new_in(value: T, alloc: A) -> Rc<T, A>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc in the provided allocator.

\n
ยงExamples
\n
#![feature(allocator_api)]\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet five = Rc::new_in(5, System);
\n
source

pub fn new_uninit_in(alloc: A) -> Rc<MaybeUninit<T>, A>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc with uninitialized contents in the provided allocator.

\n
ยงExamples
\n
#![feature(get_mut_unchecked)]\n#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet mut five = Rc::<u32, _>::new_uninit_in(System);\n\nlet five = unsafe {\n    // Deferred initialization:\n    Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed_in(alloc: A) -> Rc<MaybeUninit<T>, A>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc with uninitialized contents, with the memory\nbeing filled with 0 bytes, in the provided allocator.

\n

See MaybeUninit::zeroed for examples of correct and\nincorrect usage of this method.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet zero = Rc::<u32, _>::new_zeroed_in(System);\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn new_cyclic_in<F>(data_fn: F, alloc: A) -> Rc<T, A>
where\n F: FnOnce(&Weak<T, A>) -> T,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc<T, A> in the given allocator while giving you a Weak<T, A> to the allocation,\nto allow you to construct a T which holds a weak pointer to itself.

\n

Generally, a structure circularly referencing itself, either directly or\nindirectly, should not hold a strong reference to itself to prevent a memory leak.\nUsing this function, you get access to the weak pointer during the\ninitialization of T, before the Rc<T, A> is created, such that you can\nclone and store it inside the T.

\n

new_cyclic_in first allocates the managed allocation for the Rc<T, A>,\nthen calls your closure, giving it a Weak<T, A> to this allocation,\nand only afterwards completes the construction of the Rc<T, A> by placing\nthe T returned from your closure into the allocation.

\n

Since the new Rc<T, A> is not fully-constructed until Rc<T, A>::new_cyclic_in\nreturns, calling upgrade on the weak reference inside your closure will\nfail and result in a None value.

\n
ยงPanics
\n

If data_fn panics, the panic is propagated to the caller, and the\ntemporary Weak<T, A> is dropped normally.

\n
ยงExamples
\n

See new_cyclic.

\n
source

pub fn try_new_in(value: T, alloc: A) -> Result<Rc<T, A>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc<T> in the provided allocator, returning an error if the allocation\nfails

\n
ยงExamples
\n
#![feature(allocator_api)]\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet five = Rc::try_new_in(5, System);
\n
source

pub fn try_new_uninit_in(alloc: A) -> Result<Rc<MaybeUninit<T>, A>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc with uninitialized contents, in the provided allocator, returning an\nerror if the allocation fails

\n
ยงExamples
\n
#![feature(allocator_api)]\n#![feature(get_mut_unchecked)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet mut five = Rc::<u32, _>::try_new_uninit_in(System)?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed_in(alloc: A) -> Result<Rc<MaybeUninit<T>, A>, AllocError>

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Rc with uninitialized contents, with the memory\nbeing filled with 0 bytes, in the provided allocator, returning an error if the allocation\nfails

\n

See MaybeUninit::zeroed for examples of correct and\nincorrect usage of this method.

\n
ยงExamples
\n
#![feature(allocator_api)]\n\nuse std::rc::Rc;\nuse std::alloc::System;\n\nlet zero = Rc::<u32, _>::try_new_zeroed_in(System)?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
source

pub fn pin_in(value: T, alloc: A) -> Pin<Rc<T, A>>
where\n A: 'static,

๐Ÿ”ฌThis is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Rc<T>> in the provided allocator. If T does not implement Unpin, then\nvalue will be pinned in memory and unable to be moved.

\n
1.36.0 ยท source

pub fn try_unwrap(this: Rc<T, A>) -> Result<T, Rc<T, A>>

Returns the inner value, if the Rc has exactly one strong reference.

\n

Otherwise, an Err is returned with the same Rc that was\npassed in.

\n

This will succeed even if there are outstanding weak references.

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet x = Rc::new(3);\nassert_eq!(Rc::try_unwrap(x), Ok(3));\n\nlet x = Rc::new(4);\nlet _y = Rc::clone(&x);\nassert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
\n
1.70.0 ยท source

pub fn into_inner(this: Rc<T, A>) -> Option<T>

Returns the inner value, if the Rc has exactly one strong reference.

\n

Otherwise, None is returned and the Rc is dropped.

\n

This will succeed even if there are outstanding weak references.

\n

If Rc::into_inner is called on every clone of this Rc,\nit is guaranteed that exactly one of the calls returns the inner value.\nThis means in particular that the inner value is not dropped.

\n

Rc::try_unwrap is conceptually similar to Rc::into_inner.\nAnd while they are meant for different use-cases, Rc::into_inner(this)\nis in fact equivalent to Rc::try_unwrap(this).ok().\n(Note that the same kind of equivalence does not hold true for\nArc, due to race conditions that do not apply to Rc!)

\n
ยงExamples
\n
use std::rc::Rc;\n\nlet x = Rc::new(3);\nassert_eq!(Rc::into_inner(x), Some(3));\n\nlet x = Rc::new(4);\nlet y = Rc::clone(&x);\n\nassert_eq!(Rc::into_inner(y), None);\nassert_eq!(Rc::into_inner(x), Some(4));
\n
",0,"actix_service::boxed::RcService"],["
sourceยง

impl<S, Req> Service<Req> for Rc<S>
where\n S: Service<Req> + ?Sized,

sourceยง

type Response = <S as Service<Req>>::Response

Responses given by the service.
sourceยง

type Error = <S as Service<Req>>::Error

Errors produced by the service when polling readiness or executing call.
sourceยง

type Future = <S as Service<Req>>::Future

The future response value.
sourceยง

fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Ready when the service is able to process requests. Read more
sourceยง

fn call(&self, request: Req) -> S::Future

Process the request and return the response asynchronously. Read more
","Service","actix_service::boxed::RcService"],["
sourceยง

impl<S, Req> ServiceFactory<Req> for Rc<S>
where\n S: ServiceFactory<Req>,

sourceยง

type Response = <S as ServiceFactory<Req>>::Response

Responses given by the created services.
sourceยง

type Error = <S as ServiceFactory<Req>>::Error

Errors produced by the created services.
sourceยง

type Config = <S as ServiceFactory<Req>>::Config

Service factory configuration.
sourceยง

type Service = <S as ServiceFactory<Req>>::Service

The kind of Service created by this factory.
sourceยง

type InitError = <S as ServiceFactory<Req>>::InitError

Errors potentially raised while building a service.
sourceยง

type Future = <S as ServiceFactory<Req>>::Future

The future of the Service instance.g
sourceยง

fn new_service(&self, cfg: S::Config) -> S::Future

Create and return a new service asynchronously.
","ServiceFactory","actix_service::boxed::RcService"],["
sourceยง

impl<T, S, Req> Transform<S, Req> for Rc<T>
where\n T: Transform<S, Req>,

sourceยง

type Response = <T as Transform<S, Req>>::Response

Responses produced by the service.
sourceยง

type Error = <T as Transform<S, Req>>::Error

Errors produced by the service.
sourceยง

type Transform = <T as Transform<S, Req>>::Transform

The TransformService value created by this factory
sourceยง

type InitError = <T as Transform<S, Req>>::InitError

Errors produced while building a transform service.
sourceยง

type Future = <T as Transform<S, Req>>::Future

The future response value.
sourceยง

fn new_transform(&self, service: S) -> T::Future

Creates and returns a new Transform component, asynchronously
","Transform","actix_service::boxed::RcService"],["
sourceยง

impl<T, U, A> CoerceUnsized<Rc<U, A>> for Rc<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","actix_service::boxed::RcService"],["
sourceยง

impl<T, A> DerefPure for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

","DerefPure","actix_service::boxed::RcService"],["
sourceยง

impl<T, U> DispatchFromDyn<Rc<U>> for Rc<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Eq for Rc<T, A>
where\n T: Eq + ?Sized,\n A: Allocator,

","Eq","actix_service::boxed::RcService"],["
sourceยง

impl<T, A> PinCoerceUnsized for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

","PinCoerceUnsized","actix_service::boxed::RcService"],["
1.58.0 ยท sourceยง

impl<T, A> RefUnwindSafe for Rc<T, A>
where\n T: RefUnwindSafe + ?Sized,\n A: Allocator + UnwindSafe,

","RefUnwindSafe","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> !Send for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

","Send","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> !Sync for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

","Sync","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> Unpin for Rc<T, A>
where\n A: Allocator,\n T: ?Sized,

","Unpin","actix_service::boxed::RcService"],["
1.36.0 ยท sourceยง

impl<T, A> UnwindSafe for Rc<T, A>
where\n T: RefUnwindSafe + ?Sized,\n A: Allocator + UnwindSafe,

","UnwindSafe","actix_service::boxed::RcService"]]]]); + if (window.register_type_impls) { + window.register_type_impls(type_impls); + } else { + window.pending_type_impls = type_impls; + } +})() +//{"start":55,"fragment_lengths":[171694]} \ No newline at end of file diff --git a/type.impl/core/pin/struct.Pin.js b/type.impl/core/pin/struct.Pin.js new file mode 100644 index 00000000..80e68a19 --- /dev/null +++ b/type.impl/core/pin/struct.Pin.js @@ -0,0 +1,9 @@ +(function() { + var type_impls = Object.fromEntries([["actix_service",[["
sourceยง

impl<P> AsyncIterator for Pin<P>
where\n P: DerefMut,\n <P as Deref>::Target: AsyncIterator,

sourceยง

type Item = <<P as Deref>::Target as AsyncIterator>::Item

๐Ÿ”ฌThis is a nightly-only experimental API. (async_iterator)
The type of items yielded by the async iterator.
sourceยง

fn poll_next(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n) -> Poll<Option<<Pin<P> as AsyncIterator>::Item>>

๐Ÿ”ฌThis is a nightly-only experimental API. (async_iterator)
Attempts to pull out the next value of this async iterator, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the async iterator is exhausted. Read more
sourceยง

fn size_hint(&self) -> (usize, Option<usize>)

๐Ÿ”ฌThis is a nightly-only experimental API. (async_iterator)
Returns the bounds on the remaining length of the async iterator. Read more
","AsyncIterator","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> Clone for Pin<Ptr>
where\n Ptr: Clone,

sourceยง

fn clone(&self) -> Pin<Ptr>

Returns a copy of the value. Read more
1.6.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","actix_service::boxed::BoxFuture"],["
sourceยง

impl<G, R, A> Coroutine<R> for Pin<Box<G, A>>
where\n G: Coroutine<R> + ?Sized,\n A: Allocator + 'static,

sourceยง

type Yield = <G as Coroutine<R>>::Yield

๐Ÿ”ฌThis is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine yields. Read more
sourceยง

type Return = <G as Coroutine<R>>::Return

๐Ÿ”ฌThis is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine returns. Read more
sourceยง

fn resume(\n self: Pin<&mut Pin<Box<G, A>>>,\n arg: R,\n) -> CoroutineState<<Pin<Box<G, A>> as Coroutine<R>>::Yield, <Pin<Box<G, A>> as Coroutine<R>>::Return>

๐Ÿ”ฌThis is a nightly-only experimental API. (coroutine_trait)
Resumes the execution of this coroutine. Read more
","Coroutine","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> Debug for Pin<Ptr>
where\n Ptr: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> Deref for Pin<Ptr>
where\n Ptr: Deref,

sourceยง

type Target = <Ptr as Deref>::Target

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &<Ptr as Deref>::Target

Dereferences the value.
","Deref","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> DerefMut for Pin<Ptr>
where\n Ptr: DerefMut,\n <Ptr as Deref>::Target: Unpin,

sourceยง

fn deref_mut(&mut self) -> &mut <Ptr as Deref>::Target

Mutably dereferences the value.
","DerefMut","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> Display for Pin<Ptr>
where\n Ptr: Display,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","actix_service::boxed::BoxFuture"],["
1.36.0 ยท sourceยง

impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>
where\n A: Allocator + 'static,\n T: ?Sized,

sourceยง

fn from(boxed: Box<T, A>) -> Pin<Box<T, A>>

Converts a Box<T> into a Pin<Box<T>>. If T does not implement Unpin, then\n*boxed will be pinned in memory and unable to be moved.

\n

This conversion does not allocate on the heap and happens in place.

\n

This is also available via Box::into_pin.

\n

Constructing and pinning a Box with <Pin<Box<T>>>::from(Box::new(x))\ncan also be written more concisely using Box::pin(x).\nThis From implementation is useful if you already have a Box<T>, or you are\nconstructing a (pinned) Box in a different way than with Box::new.

\n
","From>","actix_service::boxed::BoxFuture"],["
ยง

impl<P> FusedFuture for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: FusedFuture,

ยง

fn is_terminated(&self) -> bool

Returns true if the underlying future should no longer be polled.
","FusedFuture","actix_service::boxed::BoxFuture"],["
ยง

impl<P> FusedStream for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: FusedStream,

ยง

fn is_terminated(&self) -> bool

Returns true if the stream should no longer be polled.
","FusedStream","actix_service::boxed::BoxFuture"],["
1.36.0 ยท sourceยง

impl<P> Future for Pin<P>
where\n P: DerefMut,\n <P as Deref>::Target: Future,

sourceยง

type Output = <<P as Deref>::Target as Future>::Output

The type of value produced on completion.
sourceยง

fn poll(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n) -> Poll<<Pin<P> as Future>::Output>

Attempts to resolve the future to a final value, registering\nthe current task for wakeup if the value is not yet available. Read more
","Future","actix_service::boxed::BoxFuture"],["
1.41.0 ยท sourceยง

impl<Ptr> Hash for Pin<Ptr>
where\n Ptr: Deref,\n <Ptr as Deref>::Target: Hash,

sourceยง

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.6.0 ยท sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","actix_service::boxed::BoxFuture"],["
1.41.0 ยท sourceยง

impl<Ptr> Ord for Pin<Ptr>
where\n Ptr: Deref,\n <Ptr as Deref>::Target: Ord,

sourceยง

fn cmp(&self, other: &Pin<Ptr>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized,

Restrict a value to a certain interval. Read more
","Ord","actix_service::boxed::BoxFuture"],["
1.41.0 ยท sourceยง

impl<Ptr, Q> PartialEq<Pin<Q>> for Pin<Ptr>
where\n Ptr: Deref,\n Q: Deref,\n <Ptr as Deref>::Target: PartialEq<<Q as Deref>::Target>,

sourceยง

fn eq(&self, other: &Pin<Q>) -> bool

Tests for self and other values to be equal, and is used by ==.
sourceยง

fn ne(&self, other: &Pin<Q>) -> bool

Tests for !=. The default implementation is almost always sufficient,\nand should not be overridden without very good reason.
","PartialEq>","actix_service::boxed::BoxFuture"],["
1.41.0 ยท sourceยง

impl<Ptr, Q> PartialOrd<Pin<Q>> for Pin<Ptr>
where\n Ptr: Deref,\n Q: Deref,\n <Ptr as Deref>::Target: PartialOrd<<Q as Deref>::Target>,

sourceยง

fn partial_cmp(&self, other: &Pin<Q>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
sourceยง

fn lt(&self, other: &Pin<Q>) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
sourceยง

fn le(&self, other: &Pin<Q>) -> bool

Tests less than or equal to (for self and other) and is used by the\n<= operator. Read more
sourceยง

fn gt(&self, other: &Pin<Q>) -> bool

Tests greater than (for self and other) and is used by the >\noperator. Read more
sourceยง

fn ge(&self, other: &Pin<Q>) -> bool

Tests greater than or equal to (for self and other) and is used by\nthe >= operator. Read more
","PartialOrd>","actix_service::boxed::BoxFuture"],["
sourceยง

impl<Ptr> Pin<Ptr>
where\n Ptr: Deref,\n <Ptr as Deref>::Target: Unpin,

1.33.0 (const: unstable) ยท source

pub fn new(pointer: Ptr) -> Pin<Ptr>

Constructs a new Pin<Ptr> around a pointer to some data of a type that\nimplements Unpin.

\n

Unlike Pin::new_unchecked, this method is safe because the pointer\nPtr dereferences to an Unpin type, which cancels the pinning guarantees.

\n
ยงExamples
\n
use std::pin::Pin;\n\nlet mut val: u8 = 5;\n\n// Since `val` doesn't care about being moved, we can safely create a \"facade\" `Pin`\n// which will allow `val` to participate in `Pin`-bound apis  without checking that\n// pinning guarantees are actually upheld.\nlet mut pinned: Pin<&mut u8> = Pin::new(&mut val);
\n
1.39.0 (const: unstable) ยท source

pub fn into_inner(pin: Pin<Ptr>) -> Ptr

Unwraps this Pin<Ptr>, returning the underlying pointer.

\n

Doing this operation safely requires that the data pointed at by this pinning pointer\nimplements Unpin so that we can ignore the pinning invariants when unwrapping it.

\n
ยงExamples
\n
use std::pin::Pin;\n\nlet mut val: u8 = 5;\nlet pinned: Pin<&mut u8> = Pin::new(&mut val);\n\n// Unwrap the pin to get the underlying mutable reference to the value. We can do\n// this because `val` doesn't care about being moved, so the `Pin` was just\n// a \"facade\" anyway.\nlet r = Pin::into_inner(pinned);\nassert_eq!(*r, 5);
\n
",0,"actix_service::boxed::BoxFuture"],["
sourceยง

impl<Ptr> Pin<Ptr>
where\n Ptr: Deref,

1.33.0 (const: unstable) ยท source

pub unsafe fn new_unchecked(pointer: Ptr) -> Pin<Ptr>

Constructs a new Pin<Ptr> around a reference to some data of a type that\nmay or may not implement Unpin.

\n

If pointer dereferences to an Unpin type, Pin::new should be used\ninstead.

\n
ยงSafety
\n

This constructor is unsafe because we cannot guarantee that the data\npointed to by pointer is pinned. At its core, pinning a value means making the\nguarantee that the valueโ€™s data will not be moved nor have its storage invalidated until\nit gets dropped. For a more thorough explanation of pinning, see the pin module docs.

\n

If the caller that is constructing this Pin<Ptr> does not ensure that the data Ptr\npoints to is pinned, that is a violation of the API contract and may lead to undefined\nbehavior in later (even safe) operations.

\n

By using this method, you are also making a promise about the Deref and\nDerefMut implementations of Ptr, if they exist. Most importantly, they\nmust not move out of their self arguments: Pin::as_mut and Pin::as_ref\nwill call DerefMut::deref_mut and Deref::deref on the pointer type Ptr\nand expect these methods to uphold the pinning invariants.\nMoreover, by calling this method you promise that the reference Ptr\ndereferences to will not be moved out of again; in particular, it\nmust not be possible to obtain a &mut Ptr::Target and then\nmove out of that reference (using, for example mem::swap).

\n

For example, calling Pin::new_unchecked on an &'a mut T is unsafe because\nwhile you are able to pin it for the given lifetime 'a, you have no control\nover whether it is kept pinned once 'a ends, and therefore cannot uphold the\nguarantee that a value, once pinned, remains pinned until it is dropped:

\n\n
use std::mem;\nuse std::pin::Pin;\n\nfn move_pinned_ref<T>(mut a: T, mut b: T) {\n    unsafe {\n        let p: Pin<&mut T> = Pin::new_unchecked(&mut a);\n        // This should mean the pointee `a` can never move again.\n    }\n    mem::swap(&mut a, &mut b); // Potential UB down the road โš ๏ธ\n    // The address of `a` changed to `b`'s stack slot, so `a` got moved even\n    // though we have previously pinned it! We have violated the pinning API contract.\n}
\n

A value, once pinned, must remain pinned until it is dropped (unless its type implements\nUnpin). Because Pin<&mut T> does not own the value, dropping the Pin will not drop\nthe value and will not end the pinning contract. So moving the value after dropping the\nPin<&mut T> is still a violation of the API contract.

\n

Similarly, calling Pin::new_unchecked on an Rc<T> is unsafe because there could be\naliases to the same data that are not subject to the pinning restrictions:

\n\n
use std::rc::Rc;\nuse std::pin::Pin;\n\nfn move_pinned_rc<T>(mut x: Rc<T>) {\n    // This should mean the pointee can never move again.\n    let pin = unsafe { Pin::new_unchecked(Rc::clone(&x)) };\n    {\n        let p: Pin<&T> = pin.as_ref();\n        // ...\n    }\n    drop(pin);\n\n    let content = Rc::get_mut(&mut x).unwrap(); // Potential UB down the road โš ๏ธ\n    // Now, if `x` was the only reference, we have a mutable reference to\n    // data that we pinned above, which we could use to move it as we have\n    // seen in the previous example. We have violated the pinning API contract.\n}
\n
ยงPinning of closure captures
\n

Particular care is required when using Pin::new_unchecked in a closure:\nPin::new_unchecked(&mut var) where var is a by-value (moved) closure capture\nimplicitly makes the promise that the closure itself is pinned, and that all uses\nof this closure capture respect that pinning.

\n\n
use std::pin::Pin;\nuse std::task::Context;\nuse std::future::Future;\n\nfn move_pinned_closure(mut x: impl Future, cx: &mut Context<'_>) {\n    // Create a closure that moves `x`, and then internally uses it in a pinned way.\n    let mut closure = move || unsafe {\n        let _ignore = Pin::new_unchecked(&mut x).poll(cx);\n    };\n    // Call the closure, so the future can assume it has been pinned.\n    closure();\n    // Move the closure somewhere else. This also moves `x`!\n    let mut moved = closure;\n    // Calling it again means we polled the future from two different locations,\n    // violating the pinning API contract.\n    moved(); // Potential UB โš ๏ธ\n}
\n

When passing a closure to another API, it might be moving the closure any time, so\nPin::new_unchecked on closure captures may only be used if the API explicitly documents\nthat the closure is pinned.

\n

The better alternative is to avoid all that trouble and do the pinning in the outer function\ninstead (here using the pin! macro):

\n\n
use std::pin::pin;\nuse std::task::Context;\nuse std::future::Future;\n\nfn move_pinned_closure(mut x: impl Future, cx: &mut Context<'_>) {\n    let mut x = pin!(x);\n    // Create a closure that captures `x: Pin<&mut _>`, which is safe to move.\n    let mut closure = move || {\n        let _ignore = x.as_mut().poll(cx);\n    };\n    // Call the closure, so the future can assume it has been pinned.\n    closure();\n    // Move the closure somewhere else.\n    let mut moved = closure;\n    // Calling it again here is fine (except that we might be polling a future that already\n    // returned `Poll::Ready`, but that is a separate problem).\n    moved();\n}
\n
1.33.0 ยท source

pub fn as_ref(&self) -> Pin<&<Ptr as Deref>::Target>

Gets a shared reference to the pinned value this Pin points to.

\n

This is a generic method to go from &Pin<Pointer<T>> to Pin<&T>.\nIt is safe because, as part of the contract of Pin::new_unchecked,\nthe pointee cannot move after Pin<Pointer<T>> got created.\nโ€œMaliciousโ€ implementations of Pointer::Deref are likewise\nruled out by the contract of Pin::new_unchecked.

\n
",0,"actix_service::boxed::BoxFuture"],["
sourceยง

impl<Ptr> Pin<Ptr>
where\n Ptr: DerefMut,

1.33.0 ยท source

pub fn as_mut(&mut self) -> Pin<&mut <Ptr as Deref>::Target>

Gets a mutable reference to the pinned value this Pin<Ptr> points to.

\n

This is a generic method to go from &mut Pin<Pointer<T>> to Pin<&mut T>.\nIt is safe because, as part of the contract of Pin::new_unchecked,\nthe pointee cannot move after Pin<Pointer<T>> got created.\nโ€œMaliciousโ€ implementations of Pointer::DerefMut are likewise\nruled out by the contract of Pin::new_unchecked.

\n

This method is useful when doing multiple calls to functions that consume the\npinning pointer.

\n
ยงExample
\n
use std::pin::Pin;\n\nimpl Type {\n    fn method(self: Pin<&mut Self>) {\n        // do something\n    }\n\n    fn call_method_twice(mut self: Pin<&mut Self>) {\n        // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`.\n        self.as_mut().method();\n        self.as_mut().method();\n    }\n}
\n
source

pub fn as_deref_mut(\n self: Pin<&mut Pin<Ptr>>,\n) -> Pin<&mut <Ptr as Deref>::Target>

๐Ÿ”ฌThis is a nightly-only experimental API. (pin_deref_mut)

Gets Pin<&mut T> to the underlying pinned value from this nested Pin-pointer.

\n

This is a generic method to go from Pin<&mut Pin<Pointer<T>>> to Pin<&mut T>. It is\nsafe because the existence of a Pin<Pointer<T>> ensures that the pointee, T, cannot\nmove in the future, and this method does not enable the pointee to move. โ€œMaliciousโ€\nimplementations of Ptr::DerefMut are likewise ruled out by the contract of\nPin::new_unchecked.

\n
1.33.0 ยท source

pub fn set(&mut self, value: <Ptr as Deref>::Target)
where\n <Ptr as Deref>::Target: Sized,

Assigns a new value to the memory location pointed to by the Pin<Ptr>.

\n

This overwrites pinned data, but that is okay: the original pinned valueโ€™s destructor gets\nrun before being overwritten and the new value is also a valid value of the same type, so\nno pinning invariant is violated. See the pin module documentation\nfor more information on how this upholds the pinning invariants.

\n
ยงExample
\n
use std::pin::Pin;\n\nlet mut val: u8 = 5;\nlet mut pinned: Pin<&mut u8> = Pin::new(&mut val);\nprintln!(\"{}\", pinned); // 5\npinned.set(10);\nprintln!(\"{}\", pinned); // 10
\n
",0,"actix_service::boxed::BoxFuture"],["
sourceยง

impl<Ptr> Pin<Ptr>
where\n Ptr: Deref,

1.39.0 (const: unstable) ยท source

pub unsafe fn into_inner_unchecked(pin: Pin<Ptr>) -> Ptr

Unwraps this Pin<Ptr>, returning the underlying Ptr.

\n
ยงSafety
\n

This function is unsafe. You must guarantee that you will continue to\ntreat the pointer Ptr as pinned after you call this function, so that\nthe invariants on the Pin type can be upheld. If the code using the\nresulting Ptr does not continue to maintain the pinning invariants that\nis a violation of the API contract and may lead to undefined behavior in\nlater (safe) operations.

\n

Note that you must be able to guarantee that the data pointed to by Ptr\nwill be treated as pinned all the way until its drop handler is complete!

\n

For more information, see the pin module docs

\n

If the underlying data is Unpin, Pin::into_inner should be used\ninstead.

\n
",0,"actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> Pointer for Pin<Ptr>
where\n Ptr: Pointer,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Pointer","actix_service::boxed::BoxFuture"],["
ยง

impl<P> Stream for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: Stream,

ยง

type Item = <<P as Deref>::Target as Stream>::Item

Values yielded by the stream.
ยง

fn poll_next(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n) -> Poll<Option<<Pin<P> as Stream>::Item>>

Attempt to pull out the next value of this stream, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the stream is exhausted. Read more
ยง

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
","Stream","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr, U> CoerceUnsized<Pin<U>> for Pin<Ptr>

","CoerceUnsized>","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr> Copy for Pin<Ptr>
where\n Ptr: Copy,

","Copy","actix_service::boxed::BoxFuture"],["
sourceยง

impl<Ptr> DerefPure for Pin<Ptr>
where\n Ptr: DerefPure,

","DerefPure","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<Ptr, U> DispatchFromDyn<Pin<U>> for Pin<Ptr>

","DispatchFromDyn>","actix_service::boxed::BoxFuture"],["
1.41.0 ยท sourceยง

impl<Ptr> Eq for Pin<Ptr>
where\n Ptr: Deref,\n <Ptr as Deref>::Target: Eq,

","Eq","actix_service::boxed::BoxFuture"],["
1.33.0 ยท sourceยง

impl<T> PinCoerceUnsized for Pin<T>
where\n T: PinCoerceUnsized,

","PinCoerceUnsized","actix_service::boxed::BoxFuture"]]]]); + if (window.register_type_impls) { + window.register_type_impls(type_impls); + } else { + window.pending_type_impls = type_impls; + } +})() +//{"start":55,"fragment_lengths":[100168]} \ No newline at end of file