From a71774896478788930e0ca07ee5e2160724cd3c5 Mon Sep 17 00:00:00 2001 From: robjtede Date: Wed, 24 Aug 2022 17:10:06 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20=20@=201e682?= =?UTF-8?q?e7a594b6a9d7557012f93f060db597c1a33=20=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- actix_cors/all.html | 2 +- actix_cors/enum.CorsError.html | 30 +- actix_cors/index.html | 46 +- actix_cors/struct.Cors.html | 32 +- actix_identity/all.html | 2 +- .../config/enum.LogoutBehaviour.html | 16 +- actix_identity/config/index.html | 2 +- .../struct.IdentityMiddlewareBuilder.html | 16 +- actix_identity/index.html | 88 +- actix_identity/struct.Identity.html | 132 +- actix_identity/struct.IdentityMiddleware.html | 46 +- actix_identity/trait.IdentityExt.html | 6 +- actix_limitation/all.html | 2 +- .../constant.DEFAULT_COOKIE_NAME.html | 2 +- .../constant.DEFAULT_PERIOD_SECS.html | 2 +- .../constant.DEFAULT_REQUEST_LIMIT.html | 2 +- .../constant.DEFAULT_SESSION_KEY.html | 2 +- actix_limitation/enum.Error.html | 30 +- actix_limitation/index.html | 52 +- actix_limitation/struct.Builder.html | 16 +- actix_limitation/struct.Limiter.html | 16 +- actix_limitation/struct.RateLimiter.html | 16 +- actix_limitation/struct.Status.html | 16 +- actix_protobuf/all.html | 2 +- actix_protobuf/enum.ProtoBufPayloadError.html | 28 +- actix_protobuf/index.html | 4 +- actix_protobuf/struct.ProtoBuf.html | 30 +- actix_protobuf/struct.ProtoBufConfig.html | 16 +- actix_protobuf/struct.ProtoBufMessage.html | 24 +- .../trait.ProtoBufResponseBuilder.html | 6 +- actix_redis/all.html | 2 +- actix_redis/enum.Error.html | 30 +- actix_redis/enum.RespError.html | 34 +- actix_redis/enum.RespValue.html | 33 +- actix_redis/index.html | 2 +- actix_redis/macro.resp_array.html | 26 +- actix_redis/struct.Command.html | 16 +- actix_redis/struct.RedisActor.html | 16 +- actix_session/all.html | 2 +- .../config/enum.CookieContentSecurity.html | 16 +- .../config/enum.SessionLifecycle.html | 16 +- .../config/enum.TtlExtensionPolicy.html | 16 +- actix_session/config/index.html | 2 +- .../config/struct.BrowserSession.html | 16 +- .../config/struct.PersistentSession.html | 36 +- .../struct.SessionMiddlewareBuilder.html | 34 +- actix_session/enum.SessionStatus.html | 19 +- actix_session/index.html | 62 +- actix_session/storage/enum.LoadError.html | 38 +- actix_session/storage/enum.SaveError.html | 38 +- actix_session/storage/enum.UpdateError.html | 38 +- actix_session/storage/index.html | 2 +- .../storage/struct.CookieSessionStore.html | 54 +- .../struct.RedisActorSessionStore.html | 64 +- .../struct.RedisActorSessionStoreBuilder.html | 16 +- .../storage/struct.RedisSessionStore.html | 72 +- .../struct.RedisSessionStoreBuilder.html | 18 +- actix_session/storage/struct.SessionKey.html | 27 +- actix_session/storage/trait.SessionStore.html | 10 +- actix_session/struct.Session.html | 56 +- actix_session/struct.SessionGetError.html | 32 +- actix_session/struct.SessionInsertError.html | 32 +- actix_session/struct.SessionMiddleware.html | 116 +- actix_session/trait.SessionExt.html | 2 +- actix_settings/all.html | 2 +- actix_settings/enum.Backlog.html | 21 +- actix_settings/enum.Error.html | 16 +- actix_settings/enum.KeepAlive.html | 21 +- actix_settings/enum.MaxConnectionRate.html | 21 +- actix_settings/enum.MaxConnections.html | 21 +- actix_settings/enum.Mode.html | 21 +- actix_settings/enum.NumWorkers.html | 21 +- actix_settings/enum.Timeout.html | 21 +- actix_settings/index.html | 60 +- actix_settings/struct.ActixSettings.html | 21 +- actix_settings/struct.Address.html | 21 +- actix_settings/struct.BasicSettings.html | 45 +- actix_settings/struct.NoSettings.html | 21 +- actix_settings/struct.Tls.html | 21 +- actix_settings/trait.ApplySettings.html | 6 +- actix_settings/trait.Parse.html | 2 +- actix_settings/type.Settings.html | 2 +- actix_web_httpauth/all.html | 2 +- .../extractors/basic/index.html | 2 +- .../extractors/basic/struct.BasicAuth.html | 36 +- .../extractors/basic/struct.Config.html | 16 +- .../extractors/bearer/enum.Error.html | 35 +- .../extractors/bearer/index.html | 2 +- .../extractors/bearer/struct.BearerAuth.html | 42 +- .../extractors/bearer/struct.Config.html | 16 +- actix_web_httpauth/extractors/index.html | 2 +- .../struct.AuthenticationError.html | 30 +- .../extractors/trait.AuthExtractorConfig.html | 2 +- .../authorization/enum.ParseError.html | 30 +- .../headers/authorization/index.html | 2 +- .../authorization/struct.Authorization.html | 43 +- .../headers/authorization/struct.Basic.html | 37 +- .../headers/authorization/struct.Bearer.html | 37 +- .../headers/authorization/trait.Scheme.html | 2 +- actix_web_httpauth/headers/index.html | 2 +- .../headers/www_authenticate/basic/index.html | 2 +- .../www_authenticate/basic/struct.Basic.html | 57 +- .../www_authenticate/bearer/enum.Error.html | 35 +- .../www_authenticate/bearer/index.html | 2 +- .../bearer/struct.Bearer.html | 71 +- .../bearer/struct.BearerBuilder.html | 16 +- .../headers/www_authenticate/index.html | 2 +- .../struct.WwwAuthenticate.html | 33 +- .../www_authenticate/trait.Challenge.html | 2 +- actix_web_httpauth/index.html | 2 +- actix_web_httpauth/middleware/index.html | 2 +- .../middleware/struct.HttpAuthentication.html | 62 +- ayu.css | 2 +- dark.css | 2 +- down-arrow.svg | 2 +- .../actix_web/extract/trait.FromRequest.js | 2 +- .../response/responder/trait.Responder.js | 2 +- implementors/core/convert/trait.From.js | 4 +- implementors/core/error/trait.Error.js | 7 + implementors/core/fmt/trait.Debug.js | 2 +- implementors/core/fmt/trait.Display.js | 2 +- .../core/future/future/trait.Future.js | 2 +- implementors/core/ops/deref/trait.Deref.js | 2 +- implementors/core/ops/deref/trait.DerefMut.js | 2 +- implementors/serde/de/trait.Deserialize.js | 2 +- implementors/std/error/trait.Error.js | 7 - light.css | 2 +- main.js | 2 +- rustdoc.css | 2 +- search-index.js | 12 +- search.js | 2 +- settings.html | 4 +- source-script.js | 2 +- src/actix_cors/all_or_some.rs.html | 74 +- src/actix_cors/builder.rs.html | 940 ++++++------- src/actix_cors/error.rs.html | 72 +- src/actix_cors/inner.rs.html | 544 ++++---- src/actix_cors/lib.rs.html | 116 +- src/actix_cors/middleware.rs.html | 344 ++--- src/actix_identity/config.rs.html | 160 +-- src/actix_identity/identity.rs.html | 428 +++--- src/actix_identity/identity_ext.rs.html | 32 +- src/actix_identity/lib.rs.html | 196 +-- src/actix_identity/middleware.rs.html | 350 ++--- src/actix_limitation/builder.rs.html | 190 +-- src/actix_limitation/errors.rs.html | 62 +- src/actix_limitation/lib.rs.html | 260 ++-- src/actix_limitation/middleware.rs.html | 144 +- src/actix_limitation/status.rs.html | 166 +-- src/actix_protobuf/lib.rs.html | 454 +++---- src/actix_redis/lib.rs.html | 44 +- src/actix_redis/redis.rs.html | 190 +-- src/actix_session/config.rs.html | 662 ++++----- src/actix_session/lib.rs.html | 1194 ++++++++--------- src/actix_session/middleware.rs.html | 698 +++++----- src/actix_session/session.rs.html | 452 +++---- src/actix_session/session_ext.rs.html | 46 +- src/actix_session/storage/cookie.rs.html | 186 +-- src/actix_session/storage/interface.rs.html | 164 +-- src/actix_session/storage/mod.rs.html | 40 +- src/actix_session/storage/redis_actor.rs.html | 462 +++---- src/actix_session/storage/redis_rs.rs.html | 520 +++---- src/actix_session/storage/session_key.rs.html | 86 +- src/actix_session/storage/utils.rs.html | 30 +- src/actix_settings/error.rs.html | 170 +-- src/actix_settings/lib.rs.html | 1128 ++++++++-------- src/actix_settings/parse.rs.html | 46 +- src/actix_settings/settings/address.rs.html | 88 +- src/actix_settings/settings/backlog.rs.html | 90 +- .../settings/keep_alive.rs.html | 124 +- .../settings/max_connection_rate.rs.html | 84 +- .../settings/max_connections.rs.html | 84 +- src/actix_settings/settings/mod.rs.html | 100 +- src/actix_settings/settings/mode.rs.html | 38 +- .../settings/num_workers.rs.html | 82 +- src/actix_settings/settings/timeout.rs.html | 116 +- src/actix_settings/settings/tls.rs.html | 28 +- .../extractors/basic.rs.html | 192 +-- .../extractors/bearer.rs.html | 248 ++-- .../extractors/config.rs.html | 30 +- .../extractors/errors.rs.html | 106 +- src/actix_web_httpauth/extractors/mod.rs.html | 16 +- .../headers/authorization/errors.rs.html | 96 +- .../headers/authorization/header.rs.html | 136 +- .../headers/authorization/mod.rs.html | 16 +- .../authorization/scheme/basic.rs.html | 258 ++-- .../authorization/scheme/bearer.rs.html | 174 +-- .../headers/authorization/scheme/mod.rs.html | 20 +- src/actix_web_httpauth/headers/mod.rs.html | 8 +- .../www_authenticate/challenge/basic.rs.html | 204 +-- .../challenge/bearer/builder.rs.html | 118 +- .../challenge/bearer/challenge.rs.html | 214 +-- .../challenge/bearer/errors.rs.html | 72 +- .../challenge/bearer/mod.rs.html | 36 +- .../www_authenticate/challenge/mod.rs.html | 18 +- .../headers/www_authenticate/header.rs.html | 46 +- .../headers/www_authenticate/mod.rs.html | 12 +- src/actix_web_httpauth/lib.rs.html | 46 +- src/actix_web_httpauth/middleware.rs.html | 592 ++++---- src/actix_web_httpauth/utils.rs.html | 140 +- 200 files changed, 8532 insertions(+), 8481 deletions(-) create mode 100644 implementors/core/error/trait.Error.js delete mode 100644 implementors/std/error/trait.Error.js diff --git a/actix_cors/all.html b/actix_cors/all.html index 48a1c7723..f3b58d676 100644 --- a/actix_cors/all.html +++ b/actix_cors/all.html @@ -1,3 +1,3 @@ List of all items in this crate

List of all items

Structs

Enums

\ No newline at end of file + logo

List of all items

Structs

Enums

\ No newline at end of file diff --git a/actix_cors/enum.CorsError.html b/actix_cors/enum.CorsError.html index 0519752ed..4bef3cee1 100644 --- a/actix_cors/enum.CorsError.html +++ b/actix_cors/enum.CorsError.html @@ -1,5 +1,5 @@ CorsError in actix_cors - Rust

CorsError

logo
#[non_exhaustive]
 pub enum CorsError {
     WildcardOrigin,
@@ -23,34 +23,36 @@ pub enum CorsError {
 

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Returns appropriate status code for error. Read more

Creates full response for error. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_cors/index.html b/actix_cors/index.html index 083807c9a..8aac3fe58 100644 --- a/actix_cors/index.html +++ b/actix_cors/index.html @@ -6,37 +6,37 @@ Scope::wrap(), or Resource::wrap() methods.

This CORS middleware automatically handles OPTIONS preflight requests.

Example

-
use actix_cors::Cors;
-use actix_web::{get, http, web, App, HttpRequest, HttpResponse, HttpServer};
+
use actix_cors::Cors;
+use actix_web::{get, http, web, App, HttpRequest, HttpResponse, HttpServer};
 
-#[get("/index.html")]
-async fn index(req: HttpRequest) -> &'static str {
-    "<p>Hello World!</p>"
-}
+#[get("/index.html")]
+async fn index(req: HttpRequest) -> &'static str {
+    "<p>Hello World!</p>"
+}
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    HttpServer::new(|| {
-        let cors = Cors::default()
-              .allowed_origin("https://www.rust-lang.org/")
-              .allowed_origin_fn(|origin, _req_head| {
-                  origin.as_bytes().ends_with(b".rust-lang.org")
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    HttpServer::new(|| {
+        let cors = Cors::default()
+              .allowed_origin("https://www.rust-lang.org/")
+              .allowed_origin_fn(|origin, _req_head| {
+                  origin.as_bytes().ends_with(b".rust-lang.org")
               })
-              .allowed_methods(vec!["GET", "POST"])
-              .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
-              .allowed_header(http::header::CONTENT_TYPE)
-              .max_age(3600);
+              .allowed_methods(vec!["GET", "POST"])
+              .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
+              .allowed_header(http::header::CONTENT_TYPE)
+              .max_age(3600);
 
-        App::new()
-            .wrap(cors)
-            .service(index)
+        App::new()
+            .wrap(cors)
+            .service(index)
     })
-    .bind(("127.0.0.1", 8080))?
-    .run()
+    .bind(("127.0.0.1", 8080))?
+    .run()
     .await;
 
     Ok(())
 }

Structs

Builder for CORS middleware.

Enums

Errors that can occur when processing CORS guarded requests.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_cors/struct.Cors.html b/actix_cors/struct.Cors.html index 7907db976..366b090b1 100644 --- a/actix_cors/struct.Cors.html +++ b/actix_cors/struct.Cors.html @@ -11,15 +11,15 @@ in Actix Web (using env_logger or other crate that exposes logs fro messages will outline what is wrong with the CORS configuration in the server logs and the server will fail to start up or serve requests.

Example

-
use actix_cors::Cors;
-use actix_web::http::header;
+
use actix_cors::Cors;
+use actix_web::http::header;
 
-let cors = Cors::default()
-    .allowed_origin("https://www.rust-lang.org")
-    .allowed_methods(vec!["GET", "POST"])
-    .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
-    .allowed_header(header::CONTENT_TYPE)
-    .max_age(3600);
+let cors = Cors::default()
+    .allowed_origin("https://www.rust-lang.org")
+    .allowed_methods(vec!["GET", "POST"])
+    .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
+    .allowed_header(header::CONTENT_TYPE)
+    .max_age(3600);
 
 // `cors` can now be used in `App::wrap`.

Implementations

A very permissive set of default for quick development. Not recommended for production use.

@@ -114,24 +114,24 @@ not supported. No max age (will use browser’s default).

The TransformService value created by this factory

The future response value.

Creates and returns a new Transform component, asynchronously

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/all.html b/actix_identity/all.html index 17b4b1d5e..c2e14a67b 100644 --- a/actix_identity/all.html +++ b/actix_identity/all.html @@ -1 +1 @@ -List of all items in this crate
\ No newline at end of file +List of all items in this crate
\ No newline at end of file diff --git a/actix_identity/config/enum.LogoutBehaviour.html b/actix_identity/config/enum.LogoutBehaviour.html index 2f87c447f..b8ad2cbc1 100644 --- a/actix_identity/config/enum.LogoutBehaviour.html +++ b/actix_identity/config/enum.LogoutBehaviour.html @@ -14,27 +14,27 @@ is not tied to the user’s identity and should be retained after logout.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/config/index.html b/actix_identity/config/index.html index b7ae20931..6b49bd351 100644 --- a/actix_identity/config/index.html +++ b/actix_identity/config/index.html @@ -3,4 +3,4 @@ parameters.

Enums

LogoutBehaviour controls what actions are going to be performed when Identity::logout is invoked.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/config/struct.IdentityMiddlewareBuilder.html b/actix_identity/config/struct.IdentityMiddlewareBuilder.html index eacff7d20..ed4e1ff32 100644 --- a/actix_identity/config/struct.IdentityMiddlewareBuilder.html +++ b/actix_identity/config/struct.IdentityMiddlewareBuilder.html @@ -25,27 +25,27 @@ has passed since their last visit.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/index.html b/actix_identity/index.html index d1d7f18ec..c4f33417a 100644 --- a/actix_identity/index.html +++ b/actix_identity/index.html @@ -5,64 +5,64 @@ on top of HTTP sessions, via actix

To start using identity management in your Actix Web application you must register IdentityMiddleware and SessionMiddleware as middleware on your App:

-
use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
-use actix_identity::IdentityMiddleware;
-use actix_session::{storage::RedisSessionStore, SessionMiddleware};
+
use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
+use actix_identity::IdentityMiddleware;
+use actix_session::{storage::RedisSessionStore, SessionMiddleware};
 
-#[actix_web::main]
-async fn main() {
-    let secret_key = Key::generate();
-    let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
-        .await
-        .unwrap();
+#[actix_web::main]
+async fn main() {
+    let secret_key = Key::generate();
+    let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
+        .await
+        .unwrap();
 
-    HttpServer::new(move || {
-        App::new()
-            // Install the identity framework first.
-            .wrap(IdentityMiddleware::default())
-            // The identity system is built on top of sessions. You must install the session
-            // middleware to leverage `actix-identity`. The session middleware must be mounted
-            // AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
-            // order of registration when it receives an incoming request.
-            .wrap(SessionMiddleware::new(
-                 redis_store.clone(),
-                 secret_key.clone()
+    HttpServer::new(move || {
+        App::new()
+            // Install the identity framework first.
+            .wrap(IdentityMiddleware::default())
+            // The identity system is built on top of sessions. You must install the session
+            // middleware to leverage `actix-identity`. The session middleware must be mounted
+            // AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
+            // order of registration when it receives an incoming request.
+            .wrap(SessionMiddleware::new(
+                 redis_store.clone(),
+                 secret_key.clone()
             ))
-            // Your request handlers [...]
-    })
+            // Your request handlers [...]
+    })
 }

User identities can be created, accessed and destroyed using the Identity extractor in your request handlers:

-
use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
-use actix_identity::Identity;
-use actix_session::storage::RedisSessionStore;
+
use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
+use actix_identity::Identity;
+use actix_session::storage::RedisSessionStore;
 
-#[get("/")]
-async fn index(user: Option<Identity>) -> impl Responder {
-    if let Some(user) = user {
-        format!("Welcome! {}", user.id().unwrap())
-    } else {
-        "Welcome Anonymous!".to_owned()
+#[get("/")]
+async fn index(user: Option<Identity>) -> impl Responder {
+    if let Some(user) = user {
+        format!("Welcome! {}", user.id().unwrap())
+    } else {
+        "Welcome Anonymous!".to_owned()
     }
 }
 
-#[post("/login")]
-async fn login(request: HttpRequest) -> impl Responder {
-    // Some kind of authentication should happen here
-    // e.g. password-based, biometric, etc.
-    // [...]
+#[post("/login")]
+async fn login(request: HttpRequest) -> impl Responder {
+    // Some kind of authentication should happen here
+    // e.g. password-based, biometric, etc.
+    // [...]
 
-    // attach a verified user identity to the active session
-    Identity::login(&request.extensions(), "User1".into()).unwrap();
+    // attach a verified user identity to the active session
+    Identity::login(&request.extensions(), "User1".into()).unwrap();
 
-    HttpResponse::Ok()
+    HttpResponse::Ok()
 }
 
-#[post("/logout")]
-async fn logout(user: Identity) -> impl Responder {
-    user.logout();
-    HttpResponse::Ok()
+#[post("/logout")]
+async fn logout(user: Identity) -> impl Responder {
+    user.logout();
+    HttpResponse::Ok()
 }

Advanced configuration

By default, actix-identity does not automatically log out users. You can change this behaviour @@ -76,4 +76,4 @@ by customising the configuration for

Structs

A verified user identity. It can be used as a request extractor.

Identity management middleware.

Traits

Helper trait to retrieve an Identity instance from various actix-web’s types.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/struct.Identity.html b/actix_identity/struct.Identity.html index 69782aefb..682d48650 100644 --- a/actix_identity/struct.Identity.html +++ b/actix_identity/struct.Identity.html @@ -3,30 +3,30 @@ session is destroyed (e.g. the session expired), the user identity will be forgotten, de-facto forcing a user log out.

Examples

-
use actix_web::{
-    get, post, Responder, HttpRequest, HttpMessage, HttpResponse
+
use actix_web::{
+    get, post, Responder, HttpRequest, HttpMessage, HttpResponse
 };
-use actix_identity::Identity;
+use actix_identity::Identity;
 
-#[get("/")]
-async fn index(user: Option<Identity>) -> impl Responder {
-    if let Some(user) = user {
-        format!("Welcome! {}", user.id().unwrap())
-    } else {
-        "Welcome Anonymous!".to_owned()
+#[get("/")]
+async fn index(user: Option<Identity>) -> impl Responder {
+    if let Some(user) = user {
+        format!("Welcome! {}", user.id().unwrap())
+    } else {
+        "Welcome Anonymous!".to_owned()
     }
 }
 
-#[post("/login")]
-async fn login(request: HttpRequest) -> impl Responder {
-    Identity::login(&request.extensions(), "User1".into());
-    HttpResponse::Ok()
+#[post("/login")]
+async fn login(request: HttpRequest) -> impl Responder {
+    Identity::login(&request.extensions(), "User1".into());
+    HttpResponse::Ok()
 }
 
-#[post("/logout")]
-async fn logout(user: Identity) -> impl Responder {
-    user.logout();
-    HttpResponse::Ok()
+#[post("/logout")]
+async fn logout(user: Identity) -> impl Responder {
+    user.logout();
+    HttpResponse::Ok()
 }

Extractor Behaviour

What happens if you try to extract an Identity out of a request that does not have a valid @@ -35,94 +35,94 @@ identity attached? The API will return a 401 UNAUTHORIZED to the ca Result<Identity, actix_web::Error> instead of a bare Identity: you will then be fully in control of the error path.

Examples

-
use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
-use actix_identity::Identity;
+
use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
+use actix_identity::Identity;
 
-#[get("/")]
-async fn index(user: Option<Identity>) -> impl Responder {
-    if let Some(user) = user {
-        HttpResponse::Ok().finish()
-    } else {
-        // Redirect to login page if unauthenticated
-        HttpResponse::TemporaryRedirect()
-            .insert_header((LOCATION, "/login"))
-            .finish()
+#[get("/")]
+async fn index(user: Option<Identity>) -> impl Responder {
+    if let Some(user) = user {
+        HttpResponse::Ok().finish()
+    } else {
+        // Redirect to login page if unauthenticated
+        HttpResponse::TemporaryRedirect()
+            .insert_header((LOCATION, "/login"))
+            .finish()
     }
 }
-

Implementations

Return the user id associated to the current session.

+

Implementations

Return the user id associated to the current session.

Examples
-
use actix_web::{get, Responder};
-use actix_identity::Identity;
+
use actix_web::{get, Responder};
+use actix_identity::Identity;
 
-#[get("/")]
-async fn index(user: Option<Identity>) -> impl Responder {
-    if let Some(user) = user {
-        format!("Welcome! {}", user.id().unwrap())
-    } else {
-        "Welcome Anonymous!".to_owned()
+#[get("/")]
+async fn index(user: Option<Identity>) -> impl Responder {
+    if let Some(user) = user {
+        format!("Welcome! {}", user.id().unwrap())
+    } else {
+        "Welcome Anonymous!".to_owned()
     }
 }
-

Attach a valid user identity to the current session.

+

Attach a valid user identity to the current session.

This method should be called after you have successfully authenticated the user. After login has been called, the user will be able to access all routes that require a valid Identity.

Examples
-
use actix_web::{post, Responder, HttpRequest, HttpMessage, HttpResponse};
-use actix_identity::Identity;
+
use actix_web::{post, Responder, HttpRequest, HttpMessage, HttpResponse};
+use actix_identity::Identity;
 
-#[post("/login")]
-async fn login(request: HttpRequest) -> impl Responder {
-    Identity::login(&request.extensions(), "User1".into());
-    HttpResponse::Ok()
+#[post("/login")]
+async fn login(request: HttpRequest) -> impl Responder {
+    Identity::login(&request.extensions(), "User1".into());
+    HttpResponse::Ok()
 }

Remove the user identity from the current session.

After logout has been called, the user will no longer be able to access routes that require a valid Identity.

The behaviour on logout is determined by IdentityMiddlewareBuilder::logout_behaviour.

Examples
-
use actix_web::{post, Responder, HttpResponse};
-use actix_identity::Identity;
+
use actix_web::{post, Responder, HttpResponse};
+use actix_identity::Identity;
 
-#[post("/logout")]
-async fn logout(user: Identity) -> impl Responder {
-    user.logout();
-    HttpResponse::Ok()
+#[post("/logout")]
+async fn logout(user: Identity) -> impl Responder {
+    user.logout();
+    HttpResponse::Ok()
 }

Trait Implementations

Extractor implementation for Identity.

Examples

-
use actix_web::{get, Responder};
-use actix_identity::Identity;
+
use actix_web::{get, Responder};
+use actix_identity::Identity;
 
-#[get("/")]
-async fn index(user: Option<Identity>) -> impl Responder {
-    if let Some(user) = user {
-        format!("Welcome! {}", user.id().unwrap())
-    } else {
-        "Welcome Anonymous!".to_owned()
+#[get("/")]
+async fn index(user: Option<Identity>) -> impl Responder {
+    if let Some(user) = user {
+        format!("Welcome! {}", user.id().unwrap())
+    } else {
+        "Welcome Anonymous!".to_owned()
     }
 }

The associated error which can be returned.

Future that resolves to a Self. Read more

Create a Self from request parts asynchronously.

Create a Self from request head asynchronously. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/struct.IdentityMiddleware.html b/actix_identity/struct.IdentityMiddleware.html index 29f4af25f..dcf9797f0 100644 --- a/actix_identity/struct.IdentityMiddleware.html +++ b/actix_identity/struct.IdentityMiddleware.html @@ -1,22 +1,22 @@ IdentityMiddleware in actix_identity - Rust
pub struct IdentityMiddleware { /* private fields */ }
Expand description

Identity management middleware.

-
use actix_web::{cookie::Key, App, HttpServer};
-use actix_session::storage::RedisSessionStore;
-use actix_identity::{Identity, IdentityMiddleware};
-use actix_session::{Session, SessionMiddleware};
+
use actix_web::{cookie::Key, App, HttpServer};
+use actix_session::storage::RedisSessionStore;
+use actix_identity::{Identity, IdentityMiddleware};
+use actix_session::{Session, SessionMiddleware};
 
-#[actix_web::main]
-async fn main() {
-    let secret_key = Key::generate();
-    let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379").await.unwrap();
+#[actix_web::main]
+async fn main() {
+    let secret_key = Key::generate();
+    let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379").await.unwrap();
 
-    HttpServer::new(move || {
-       App::new()
-           // Install the identity framework first.
-           .wrap(IdentityMiddleware::default())
-           // The identity system is built on top of sessions.
-           // You must install the session middleware to leverage `actix-identity`.
-           .wrap(SessionMiddleware::new(redis_store.clone(), secret_key.clone()))
+    HttpServer::new(move || {
+       App::new()
+           // Install the identity framework first.
+           .wrap(IdentityMiddleware::default())
+           // The identity system is built on top of sessions.
+           // You must install the session middleware to leverage `actix-identity`.
+           .wrap(SessionMiddleware::new(redis_store.clone(), secret_key.clone()))
     })
 }

Implementations

A fluent API to configure IdentityMiddleware.

@@ -29,27 +29,27 @@

Errors produced while building a transform service.

The future response value.

Creates and returns a new Transform component, asynchronously

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_identity/trait.IdentityExt.html b/actix_identity/trait.IdentityExt.html index 8f9892a08..5595fc897 100644 --- a/actix_identity/trait.IdentityExt.html +++ b/actix_identity/trait.IdentityExt.html @@ -1,5 +1,5 @@ IdentityExt in actix_identity - Rust
pub trait IdentityExt {
-    fn get_identity(&self) -> Result<Identity, Error>;
+    fn get_identity(&self) -> Result<Identity, Error>;
 }
Expand description

Helper trait to retrieve an Identity instance from various actix-web’s types.

-

Required Methods

Retrieve the identity attached to the current session, if available.

-

Implementations on Foreign Types

Implementors

\ No newline at end of file +

Required Methods

Retrieve the identity attached to the current session, if available.

+

Implementations on Foreign Types

Implementors

\ No newline at end of file diff --git a/actix_limitation/all.html b/actix_limitation/all.html index 2db5bb31d..694ef1d3c 100644 --- a/actix_limitation/all.html +++ b/actix_limitation/all.html @@ -1,3 +1,3 @@ List of all items in this crate
\ No newline at end of file + logo

List of all items

Structs

Enums

Constants

\ No newline at end of file diff --git a/actix_limitation/constant.DEFAULT_COOKIE_NAME.html b/actix_limitation/constant.DEFAULT_COOKIE_NAME.html index b9e8ea9c9..4f66d1cbc 100644 --- a/actix_limitation/constant.DEFAULT_COOKIE_NAME.html +++ b/actix_limitation/constant.DEFAULT_COOKIE_NAME.html @@ -1,4 +1,4 @@ DEFAULT_COOKIE_NAME in actix_limitation - Rust
logo
pub const DEFAULT_COOKIE_NAME: &'static str = "sid";
Expand description

Default cookie name.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/constant.DEFAULT_PERIOD_SECS.html b/actix_limitation/constant.DEFAULT_PERIOD_SECS.html index 58a7d90a3..6598e6453 100644 --- a/actix_limitation/constant.DEFAULT_PERIOD_SECS.html +++ b/actix_limitation/constant.DEFAULT_PERIOD_SECS.html @@ -1,4 +1,4 @@ DEFAULT_PERIOD_SECS in actix_limitation - Rust
logo
pub const DEFAULT_PERIOD_SECS: u64 = 3600;
Expand description

Default period (in seconds).

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/constant.DEFAULT_REQUEST_LIMIT.html b/actix_limitation/constant.DEFAULT_REQUEST_LIMIT.html index 7a65f7276..56abdea95 100644 --- a/actix_limitation/constant.DEFAULT_REQUEST_LIMIT.html +++ b/actix_limitation/constant.DEFAULT_REQUEST_LIMIT.html @@ -1,4 +1,4 @@ DEFAULT_REQUEST_LIMIT in actix_limitation - Rust
logo
pub const DEFAULT_REQUEST_LIMIT: usize = 5000;
Expand description

Default request limit.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/constant.DEFAULT_SESSION_KEY.html b/actix_limitation/constant.DEFAULT_SESSION_KEY.html index 5bed6d646..d446d06d8 100644 --- a/actix_limitation/constant.DEFAULT_SESSION_KEY.html +++ b/actix_limitation/constant.DEFAULT_SESSION_KEY.html @@ -1,4 +1,4 @@ DEFAULT_SESSION_KEY in actix_limitation - Rust
logo
pub const DEFAULT_SESSION_KEY: &'static str = "rate-api-id";
Expand description

Default session key.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/enum.Error.html b/actix_limitation/enum.Error.html index a3d95b557..d042f8433 100644 --- a/actix_limitation/enum.Error.html +++ b/actix_limitation/enum.Error.html @@ -1,5 +1,5 @@ Error in actix_limitation - Rust

Error

logo
pub enum Error {
     Client(RedisError),
     LimitExceeded(Status),
@@ -12,31 +12,33 @@
 

Other(String)

Generic error.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Converts to this type from the input type.

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/index.html b/actix_limitation/index.html index 89a180933..6ae60e336 100644 --- a/actix_limitation/index.html +++ b/actix_limitation/index.html @@ -4,37 +4,37 @@
[dependencies]
 actix-web = "4"
 actix-limitation = "0.3"
-
use std::time::Duration;
-use actix_web::{get, web, App, HttpServer, Responder};
-use actix_limitation::{Limiter, RateLimiter};
+
use std::time::Duration;
+use actix_web::{get, web, App, HttpServer, Responder};
+use actix_limitation::{Limiter, RateLimiter};
 
-#[get("/{id}/{name}")]
-async fn index(info: web::Path<(u32, String)>) -> impl Responder {
-    format!("Hello {}! id:{}", info.1, info.0)
+#[get("/{id}/{name}")]
+async fn index(info: web::Path<(u32, String)>) -> impl Responder {
+    format!("Hello {}! id:{}", info.1, info.0)
 }
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let limiter = web::Data::new(
-        Limiter::builder("redis://127.0.0.1")
-            .cookie_name("session-id".to_owned())
-            .session_key("rate-api-id".to_owned())
-            .limit(5000)
-            .period(Duration::from_secs(3600)) // 60 minutes
-            .build()
-            .unwrap(),
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    let limiter = web::Data::new(
+        Limiter::builder("redis://127.0.0.1")
+            .cookie_name("session-id".to_owned())
+            .session_key("rate-api-id".to_owned())
+            .limit(5000)
+            .period(Duration::from_secs(3600)) // 60 minutes
+            .build()
+            .unwrap(),
     );
 
-    HttpServer::new(move || {
-        App::new()
-            .wrap(RateLimiter::default())
-            .app_data(limiter.clone())
-            .service(index)
+    HttpServer::new(move || {
+        App::new()
+            .wrap(RateLimiter::default())
+            .app_data(limiter.clone())
+            .service(index)
     })
-    .bind(("127.0.0.1", 8080))?
-    .run()
-    .await
-}
+ .bind(("127.0.0.1", 8080))? + .run() + .await +}

Structs

Rate limiter builder.

Rate limiter.

Rate limit middleware.

@@ -44,4 +44,4 @@ actix-limitation = "0.3"

Default period (in seconds).

Default request limit.

Default session key.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/struct.Builder.html b/actix_limitation/struct.Builder.html index b54fb26e8..5892646dc 100644 --- a/actix_limitation/struct.Builder.html +++ b/actix_limitation/struct.Builder.html @@ -9,24 +9,24 @@

Note that this method will connect to the Redis server to test its connection which is a synchronous operation.

Trait Implementations

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/struct.Limiter.html b/actix_limitation/struct.Limiter.html index c7145c219..71397a581 100644 --- a/actix_limitation/struct.Limiter.html +++ b/actix_limitation/struct.Limiter.html @@ -8,27 +8,27 @@ parameters for how to set the Redis URL.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/struct.RateLimiter.html b/actix_limitation/struct.RateLimiter.html index 0b04935f8..29a978a2c 100644 --- a/actix_limitation/struct.RateLimiter.html +++ b/actix_limitation/struct.RateLimiter.html @@ -9,24 +9,24 @@

Errors produced while building a transform service.

The future response value.

Creates and returns a new Transform component, asynchronously

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_limitation/struct.Status.html b/actix_limitation/struct.Status.html index f991928d4..566a1079a 100644 --- a/actix_limitation/struct.Status.html +++ b/actix_limitation/struct.Status.html @@ -7,27 +7,27 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_protobuf/all.html b/actix_protobuf/all.html index 5f42f67b8..8e4f94b77 100644 --- a/actix_protobuf/all.html +++ b/actix_protobuf/all.html @@ -1 +1 @@ -List of all items in this crate
\ No newline at end of file +List of all items in this crate
\ No newline at end of file diff --git a/actix_protobuf/enum.ProtoBufPayloadError.html b/actix_protobuf/enum.ProtoBufPayloadError.html index 59cf96359..b825bd65a 100644 --- a/actix_protobuf/enum.ProtoBufPayloadError.html +++ b/actix_protobuf/enum.ProtoBufPayloadError.html @@ -1,39 +1,39 @@ ProtoBufPayloadError in actix_protobuf - Rust
pub enum ProtoBufPayloadError {
     Overflow,
     ContentType,
-    Serialize(ProtoBufEncodeError),
-    Deserialize(ProtoBufDecodeError),
+    Serialize(ProtoBufEncodeError),
+    Deserialize(ProtoBufDecodeError),
     Payload(PayloadError),
 }

Variants

Overflow

Payload size is bigger than 256k

ContentType

Content type error

-

Serialize(ProtoBufEncodeError)

Serialize error

-

Deserialize(ProtoBufDecodeError)

Deserialize error

+

Serialize(ProtoBufEncodeError)

Serialize error

+

Deserialize(ProtoBufDecodeError)

Deserialize error

Payload(PayloadError)

Payload error

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

Converts to this type from the input type.

+

Converts to this type from the input type.

Converts to this type from the input type.

Creates full response for error. Read more

Returns appropriate status code for error. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_protobuf/index.html b/actix_protobuf/index.html index a72396014..9f55fa05c 100644 --- a/actix_protobuf/index.html +++ b/actix_protobuf/index.html @@ -1,2 +1,2 @@ -actix_protobuf - Rust
\ No newline at end of file +actix_protobuf - Rust
\ No newline at end of file diff --git a/actix_protobuf/struct.ProtoBuf.html b/actix_protobuf/struct.ProtoBuf.html index 56eace411..706f7e98e 100644 --- a/actix_protobuf/struct.ProtoBuf.html +++ b/actix_protobuf/struct.ProtoBuf.html @@ -1,34 +1,34 @@ -ProtoBuf in actix_protobuf - Rust
pub struct ProtoBuf<T: Message>(pub T);

Tuple Fields

0: T

Trait Implementations

Formats the value using the given formatter. Read more

-

The resulting type after dereferencing.

+ProtoBuf in actix_protobuf - Rust
pub struct ProtoBuf<T: Message>(pub T);

Tuple Fields

0: T

Trait Implementations

Formats the value using the given formatter. Read more

+

The resulting type after dereferencing.

Dereferences the value.

-

Mutably dereferences the value.

-

Formats the value using the given formatter. Read more

-

The associated error which can be returned.

+

Mutably dereferences the value.

+

Formats the value using the given formatter. Read more

+

The associated error which can be returned.

Future that resolves to a Self. Read more

Create a Self from request parts asynchronously.

Create a Self from request head asynchronously. Read more

-

Convert self to HttpResponse.

+

Convert self to HttpResponse.

Wraps responder to allow alteration of its response. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Type of resource’s path returned in resource_path.

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_protobuf/struct.ProtoBufConfig.html b/actix_protobuf/struct.ProtoBufConfig.html index 55d50cea2..34fcaa93d 100644 --- a/actix_protobuf/struct.ProtoBufConfig.html +++ b/actix_protobuf/struct.ProtoBufConfig.html @@ -1,23 +1,23 @@ ProtoBufConfig in actix_protobuf - Rust
pub struct ProtoBufConfig { /* private fields */ }

Implementations

Change max size of payload. By default max size is 256Kb

Trait Implementations

Returns the “default value” for a type. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_protobuf/struct.ProtoBufMessage.html b/actix_protobuf/struct.ProtoBufMessage.html index cfa8eeabc..0f33bee1b 100644 --- a/actix_protobuf/struct.ProtoBufMessage.html +++ b/actix_protobuf/struct.ProtoBufMessage.html @@ -1,12 +1,12 @@ -ProtoBufMessage in actix_protobuf - Rust
pub struct ProtoBufMessage<T: Message + Default> { /* private fields */ }

Implementations

Create ProtoBufMessage for request.

-

Change max size of payload. By default max size is 256Kb

-

Trait Implementations

The type of value produced on completion.

-

Attempt to resolve the future to a final value, registering +ProtoBufMessage in actix_protobuf - Rust

pub struct ProtoBufMessage<T: Message + Default> { /* private fields */ }

Implementations

Create ProtoBufMessage for request.

+

Change max size of payload. By default max size is 256Kb

+

Trait Implementations

The type of value produced on completion.

+

Attempt 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

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Map this future’s output to a different type, returning a new future of the resulting type. Read more

Map this future’s output to a different type, returning a new future of @@ -44,15 +44,15 @@ the future is ready after the first call to Future::poll. Read m Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

The output that the future will produce on completion.

Which kind of future are we turning this into?

Creates a future from a value. Read more

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

The type of successful values yielded by this future

The type of failures yielded by this future

Poll this TryFuture as if it were a Future. Read more

@@ -82,10 +82,10 @@ future is a stream. Read more

Future. Read more

A convenience method for calling [TryFuture::try_poll] on Unpin future types. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_protobuf/trait.ProtoBufResponseBuilder.html b/actix_protobuf/trait.ProtoBufResponseBuilder.html index 08579d509..2d82bcb3b 100644 --- a/actix_protobuf/trait.ProtoBufResponseBuilder.html +++ b/actix_protobuf/trait.ProtoBufResponseBuilder.html @@ -1,3 +1,3 @@ -ProtoBufResponseBuilder in actix_protobuf - Rust
pub trait ProtoBufResponseBuilder {
-    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
-}

Required Methods

Implementations on Foreign Types

Implementors

\ No newline at end of file +ProtoBufResponseBuilder in actix_protobuf - Rust
pub trait ProtoBufResponseBuilder {
+    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
+}

Required Methods

Implementations on Foreign Types

Implementors

\ No newline at end of file diff --git a/actix_redis/all.html b/actix_redis/all.html index 65d98c747..7336ffda3 100644 --- a/actix_redis/all.html +++ b/actix_redis/all.html @@ -1 +1 @@ -List of all items in this crate

List of all items

Structs

Enums

Macros

\ No newline at end of file +List of all items in this crate

List of all items

Structs

Enums

Macros

\ No newline at end of file diff --git a/actix_redis/enum.Error.html b/actix_redis/enum.Error.html index 16e750c76..cdb723aae 100644 --- a/actix_redis/enum.Error.html +++ b/actix_redis/enum.Error.html @@ -1,4 +1,4 @@ -Error in actix_redis - Rust
pub enum Error {
+Error in actix_redis - Rust
pub enum Error {
     Redis(Error),
     NotConnected,
     Disconnected,
@@ -7,32 +7,34 @@
 

Disconnected

Cancel all waiters when connection is dropped.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Converts to this type from the input type.

Returns appropriate status code for error. Read more

Creates full response for error. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_redis/enum.RespError.html b/actix_redis/enum.RespError.html index 9666d70f1..5666418cf 100644 --- a/actix_redis/enum.RespError.html +++ b/actix_redis/enum.RespError.html @@ -1,4 +1,4 @@ -RespError in actix_redis - Rust
pub enum RespError {
+RespError in actix_redis - Rust
pub enum RespError {
     Internal(String),
     IO(Error),
     Resp(StringOption<RespValue>),
@@ -16,34 +16,36 @@ chains of futures; but it occurring at runtime should be considered a catastroph
 failure.

If any error is propagated this way that needs to be handled, then it should be made into a proper option.

-

Trait Implementations

Formats the value using the given formatter. Read more

-

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

Trait Implementations

Formats the value using the given formatter. Read more

+

Formats the value using the given formatter. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_redis/enum.RespValue.html b/actix_redis/enum.RespValue.html index fa490f5f9..1e582a03b 100644 --- a/actix_redis/enum.RespValue.html +++ b/actix_redis/enum.RespValue.html @@ -22,40 +22,41 @@ arguments, e.g. RPUSH

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Converts to this type from the input type.

-

Converts to this type from the input type.

-

Converts to this type from the input type.

-

Converts to this type from the input type.

-

Converts to this type from the input type.

-

Converts to this type from the input type.

-

Converts to this type from the input type.

+

Converts to this type from the input type.

+

Converts to this type from the input type.

+

Converts to this type from the input type.

+

Converts to this type from the input type.

+

Converts to this type from the input type.

+

Converts to this type from the input type.

+

Converts to this type from the input type.

Return a Result containing either Self or Error. Errors can occur due to either: a) the particular RespValue being incompatible with the required type, or b) a remote Redis error occuring. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_redis/index.html b/actix_redis/index.html index 3a218facf..4b73c023e 100644 --- a/actix_redis/index.html +++ b/actix_redis/index.html @@ -5,4 +5,4 @@ of types, that satisfy Into<RespValue>.

Redis communication actor.

Enums

General purpose actix-redis error.

A single RESP value, this owns the data that is read/to-be written to Redis.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_redis/macro.resp_array.html b/actix_redis/macro.resp_array.html index 4934afacc..9367bc6c9 100644 --- a/actix_redis/macro.resp_array.html +++ b/actix_redis/macro.resp_array.html @@ -1,25 +1,25 @@ -resp_array in actix_redis - Rust
macro_rules! resp_array {
-    ($($e:expr),* $(,)?) => { ... };
+resp_array in actix_redis - Rust
macro_rules! resp_array {
+    ($($e:expr),* $(,)?) => { ... };
 }
Expand description

Macro to create a RESP array, useful for preparing commands to send. Elements can be any type, or a mixture of types, that satisfy Into<RespValue>.

As a general rule, if a value is moved, the data can be deconstructed (if appropriate, e.g. String) and the raw data moved into the corresponding RespValue. If a reference is provided, the data will be copied instead.

Examples

-
#[macro_use]
-extern crate redis_async;
+
#[macro_use]
+extern crate redis_async;
 
-fn main() {
-    let value = format!("something_{}", 123);
-    resp_array!["SET", "key_name", value];
+fn main() {
+    let value = format!("something_{}", 123);
+    resp_array!["SET", "key_name", value];
 }

For variable length Redis commands:

-
#[macro_use]
-extern crate redis_async;
+
#[macro_use]
+extern crate redis_async;
 
-fn main() {
-    let data = vec!["data", "from", "somewhere", "else"];
-    let command = resp_array!["RPUSH", "mykey"].append(data);
+fn main() {
+    let data = vec!["data", "from", "somewhere", "else"];
+    let command = resp_array!["RPUSH", "mykey"].append(data);
 }
-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_redis/struct.Command.html b/actix_redis/struct.Command.html index 9f804425c..526a83071 100644 --- a/actix_redis/struct.Command.html +++ b/actix_redis/struct.Command.html @@ -4,24 +4,24 @@

This method is called for every message received by this actor.

The type of value that this message will resolved with if it is successful. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_redis/struct.RedisActor.html b/actix_redis/struct.RedisActor.html index 834f024c3..85b115a4a 100644 --- a/actix_redis/struct.RedisActor.html +++ b/actix_redis/struct.RedisActor.html @@ -16,24 +16,24 @@

Called when the supervisor restarts a failed actor.

Called when the writer emits error. Read more

Called when the writer finishes. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/all.html b/actix_session/all.html index 3b942cd85..d39beadab 100644 --- a/actix_session/all.html +++ b/actix_session/all.html @@ -1,3 +1,3 @@ List of all items in this crate
\ No newline at end of file + logo

List of all items

Structs

Enums

Traits

\ No newline at end of file diff --git a/actix_session/config/enum.CookieContentSecurity.html b/actix_session/config/enum.CookieContentSecurity.html index 95822f528..8dc595ea0 100644 --- a/actix_session/config/enum.CookieContentSecurity.html +++ b/actix_session/config/enum.CookieContentSecurity.html @@ -14,27 +14,27 @@ tamper with the cookie content, but they can read it.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/config/enum.SessionLifecycle.html b/actix_session/config/enum.SessionLifecycle.html index b3e27c9e0..bdb1cf295 100644 --- a/actix_session/config/enum.SessionLifecycle.html +++ b/actix_session/config/enum.SessionLifecycle.html @@ -19,27 +19,27 @@ attribute. They do not disappear when the current browser session ends.

Formats the value using the given formatter. Read more

Converts to this type from the input type.

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/config/enum.TtlExtensionPolicy.html b/actix_session/config/enum.TtlExtensionPolicy.html index 3073098f0..8157314be 100644 --- a/actix_session/config/enum.TtlExtensionPolicy.html +++ b/actix_session/config/enum.TtlExtensionPolicy.html @@ -21,27 +21,27 @@ your server.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/config/index.html b/actix_session/config/index.html index ffd2cfd08..d0eb96b55 100644 --- a/actix_session/config/index.html +++ b/actix_session/config/index.html @@ -8,4 +8,4 @@ browser’s current session ends.

Enums

Determines how to secure the content of the session cookie.

Determines what type of session cookie should be used and how its lifecycle should be managed.

Configuration for which events should trigger an extension of the time-to-live for your session.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/config/struct.BrowserSession.html b/actix_session/config/struct.BrowserSession.html index 7d331efae..9753c5280 100644 --- a/actix_session/config/struct.BrowserSession.html +++ b/actix_session/config/struct.BrowserSession.html @@ -32,27 +32,27 @@ specifying a more aggressive state TTL extension policy - check out

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/config/struct.PersistentSession.html b/actix_session/config/struct.PersistentSession.html index 1ab717370..5e647f77b 100644 --- a/actix_session/config/struct.PersistentSession.html +++ b/actix_session/config/struct.PersistentSession.html @@ -6,19 +6,19 @@ attribute. They do not disappear when the current browser session ends.

Due to its Into<SessionLifecycle> implementation, a PersistentSession can be passed directly to SessionMiddlewareBuilder::session_lifecycle().

Examples

-
use actix_web::cookie::time::Duration;
-use actix_session::SessionMiddleware;
-use actix_session::config::{PersistentSession, TtlExtensionPolicy};
+
use actix_web::cookie::time::Duration;
+use actix_session::SessionMiddleware;
+use actix_session::config::{PersistentSession, TtlExtensionPolicy};
 
-const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
+const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
 
-// a session lifecycle with a time-to-live (expiry) of 1 week and default extension policy
-PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK));
+// a session lifecycle with a time-to-live (expiry) of 1 week and default extension policy
+PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK));
 
-// a session lifecycle with the default time-to-live (expiry) and a custom extension policy
-PersistentSession::default()
-    // this policy causes the session state's TTL to be refreshed on every request
-    .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest);
+// a session lifecycle with the default time-to-live (expiry) and a custom extension policy +PersistentSession::default() + // this policy causes the session state's TTL to be refreshed on every request + .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest);

Implementations

Specifies how long the session cookie should live.

The session TTL is also used as the TTL for the session state in the storage backend.

Defaults to 1 day.

@@ -32,27 +32,27 @@ See TtlE

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/config/struct.SessionMiddlewareBuilder.html b/actix_session/config/struct.SessionMiddlewareBuilder.html index 77359bec0..07370759d 100644 --- a/actix_session/config/struct.SessionMiddlewareBuilder.html +++ b/actix_session/config/struct.SessionMiddlewareBuilder.html @@ -11,18 +11,18 @@ Check out SessionLifecycle’s documentation for more details on the available options.

Default is SessionLifecycle::BrowserSession.

Examples
-
use actix_web::cookie::{Key, time::Duration};
-use actix_session::{SessionMiddleware, config::PersistentSession};
-use actix_session::storage::CookieSessionStore;
+
use actix_web::cookie::{Key, time::Duration};
+use actix_session::{SessionMiddleware, config::PersistentSession};
+use actix_session::storage::CookieSessionStore;
 
-const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
+const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
 
-// creates a session middleware with a time-to-live (expiry) of 1 week
-SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
-    .session_lifecycle(
-        PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK))
+// creates a session middleware with a time-to-live (expiry) of 1 week
+SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
+    .session_lifecycle(
+        PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK))
     )
-    .build();
+ .build();

Set the SameSite attribute for the cookie used to store the session ID.

By default, the attribute is set to Lax.

Set the Path attribute for the cookie used to store the session ID.

@@ -49,24 +49,24 @@ tamper-proof session key.

running in the browser.

Default is true.

Finalise the builder and return a SessionMiddleware instance.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/enum.SessionStatus.html b/actix_session/enum.SessionStatus.html index a4650b55c..968efe9e5 100644 --- a/actix_session/enum.SessionStatus.html +++ b/actix_session/enum.SessionStatus.html @@ -20,29 +20,30 @@ extended.

Returns the “default value” for a type. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/index.html b/actix_session/index.html index 61e51aecb..9fc26553a 100644 --- a/actix_session/index.html +++ b/actix_session/index.html @@ -34,43 +34,43 @@ by implementing the SessionStore

To start using sessions in your Actix Web application you must register SessionMiddleware as a middleware on your App:

-
use actix_web::{web, App, HttpServer, HttpResponse, Error};
-use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
-use actix_web::cookie::Key;
+
use actix_web::{web, App, HttpServer, HttpResponse, Error};
+use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
+use actix_web::cookie::Key;
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    // The secret key would usually be read from a configuration file/environment variables.
-    let secret_key = Key::generate();
-    let redis_connection_string = "127.0.0.1:6379";
-    HttpServer::new(move ||
-            App::new()
-            // Add session management to your application using Redis for session state storage
-            .wrap(
-                SessionMiddleware::new(
-                    RedisActorSessionStore::new(redis_connection_string),
-                    secret_key.clone()
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    // The secret key would usually be read from a configuration file/environment variables.
+    let secret_key = Key::generate();
+    let redis_connection_string = "127.0.0.1:6379";
+    HttpServer::new(move ||
+            App::new()
+            // Add session management to your application using Redis for session state storage
+            .wrap(
+                SessionMiddleware::new(
+                    RedisActorSessionStore::new(redis_connection_string),
+                    secret_key.clone()
                 )
             )
-            .default_service(web::to(|| HttpResponse::Ok())))
-        .bind(("127.0.0.1", 8080))?
-        .run()
-        .await
-}
+ .default_service(web::to(|| HttpResponse::Ok()))) + .bind(("127.0.0.1", 8080))? + .run() + .await +}

The session state can be accessed and modified by your request handlers using the Session extractor.

-
use actix_web::Error;
-use actix_session::Session;
+
use actix_web::Error;
+use actix_session::Session;
 
-fn index(session: Session) -> Result<&'static str, Error> {
-    // access the session state
-    if let Some(count) = session.get::<i32>("counter")? {
-        println!("SESSION value: {}", count);
-        // modify the session state
-        session.insert("counter", count + 1)?;
-    } else {
-        session.insert("counter", 1)?;
+fn index(session: Session) -> Result<&'static str, Error> {
+    // access the session state
+    if let Some(count) = session.get::<i32>("counter")? {
+        println!("SESSION value: {}", count);
+        // modify the session state
+        session.insert("counter", count + 1)?;
+    } else {
+        session.insert("counter", 1)?;
     }
 
     Ok("Welcome!")
@@ -109,4 +109,4 @@ actix-session = { version = "...", features = ["redis-rs-session&
 

Enums

Status of a Session.

Traits

Extract a Session object from various actix-web types (e.g. HttpRequest, ServiceRequest, ServiceResponse).

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/enum.LoadError.html b/actix_session/storage/enum.LoadError.html index 0f6ebda82..97fb5a1e6 100644 --- a/actix_session/storage/enum.LoadError.html +++ b/actix_session/storage/enum.LoadError.html @@ -1,36 +1,38 @@ LoadError in actix_session::storage - Rust

LoadError

logo
pub enum LoadError {
-    Deserialization(Error),
-    Other(Error),
+    Deserialization(Error),
+    Other(Error),
 }
Expand description

Possible failures modes for SessionStore::load.

-

Variants

Deserialization(Error)

Failed to deserialize session state.

-

Other(Error)

Something went wrong when retrieving the session state.

+

Variants

Deserialization(Error)

Failed to deserialize session state.

+

Other(Error)

Something went wrong when retrieving the session state.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 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

Gets the TypeId of self. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

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

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/enum.SaveError.html b/actix_session/storage/enum.SaveError.html index ceae8770b..75879424c 100644 --- a/actix_session/storage/enum.SaveError.html +++ b/actix_session/storage/enum.SaveError.html @@ -1,36 +1,38 @@ SaveError in actix_session::storage - Rust

SaveError

logo
pub enum SaveError {
-    Serialization(Error),
-    Other(Error),
+    Serialization(Error),
+    Other(Error),
 }
Expand description

Possible failures modes for SessionStore::save.

-

Variants

Serialization(Error)

Failed to serialize session state.

-

Other(Error)

Something went wrong when persisting the session state.

+

Variants

Serialization(Error)

Failed to serialize session state.

+

Other(Error)

Something went wrong when persisting the session state.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 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

Gets the TypeId of self. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

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

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/enum.UpdateError.html b/actix_session/storage/enum.UpdateError.html index 07ec43828..9174c0c1f 100644 --- a/actix_session/storage/enum.UpdateError.html +++ b/actix_session/storage/enum.UpdateError.html @@ -1,36 +1,38 @@ UpdateError in actix_session::storage - Rust

UpdateError

logo
pub enum UpdateError {
-    Serialization(Error),
-    Other(Error),
+    Serialization(Error),
+    Other(Error),
 }
Expand description

Possible failures modes for SessionStore::update.

-

Variants

Serialization(Error)

Failed to serialize session state.

-

Other(Error)

Something went wrong when updating the session state.

+

Variants

Serialization(Error)

Failed to serialize session state.

+

Other(Error)

Something went wrong when updating the session state.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 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

Gets the TypeId of self. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

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

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/index.html b/actix_session/storage/index.html index c8ed23eee..b2b8c842d 100644 --- a/actix_session/storage/index.html +++ b/actix_session/storage/index.html @@ -14,4 +14,4 @@ state on the backend.

Possible failures modes for SessionStore::save.

Possible failures modes for SessionStore::update.

Traits

The interface to retrieve and save the current session data from/to the chosen storage backend.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/struct.CookieSessionStore.html b/actix_session/storage/struct.CookieSessionStore.html index 41862911f..260b17f99 100644 --- a/actix_session/storage/struct.CookieSessionStore.html +++ b/actix_session/storage/struct.CookieSessionStore.html @@ -2,25 +2,25 @@ logo

CookieSessionStore

logo
#[non_exhaustive]
pub struct CookieSessionStore;
Expand description

Use the session key, stored in the session cookie, as storage backend for the session state.

-
use actix_web::{cookie::Key, web, App, HttpServer, HttpResponse, Error};
-use actix_session::{SessionMiddleware, storage::CookieSessionStore};
+
use actix_web::{cookie::Key, web, App, HttpServer, HttpResponse, Error};
+use actix_session::{SessionMiddleware, storage::CookieSessionStore};
 
-// The secret key would usually be read from a configuration file/environment variables.
-fn get_secret_key() -> Key {
-    // [...]
-}
+// The secret key would usually be read from a configuration file/environment variables.
+fn get_secret_key() -> Key {
+    // [...]
+}
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let secret_key = get_secret_key();
-    HttpServer::new(move ||
-            App::new()
-            .wrap(SessionMiddleware::new(CookieSessionStore::default(), secret_key.clone()))
-            .default_service(web::to(|| HttpResponse::Ok())))
-        .bind(("127.0.0.1", 8080))?
-        .run()
-        .await
-}
+#[actix_web::main] +async fn main() -> std::io::Result<()> { + let secret_key = get_secret_key(); + HttpServer::new(move || + App::new() + .wrap(SessionMiddleware::new(CookieSessionStore::default(), secret_key.clone())) + .default_service(web::to(|| HttpResponse::Ok()))) + .bind(("127.0.0.1", 8080))? + .run() + .await +}

Limitations

Cookies are subject to size limits so we require session keys to be shorter than 4096 bytes. This translates into a limit on the maximum size of the session state when using cookies as @@ -34,26 +34,26 @@ storage backend.

Loads the session state associated to a session key.

Persist the session state for a newly created session. Read more

Updates the session state associated to a pre-existing session key.

-

Updates the TTL of the session state associated to a pre-existing session key.

-

Deletes a session from the store.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Updates the TTL of the session state associated to a pre-existing session key.

+

Deletes a session from the store.

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/struct.RedisActorSessionStore.html b/actix_session/storage/struct.RedisActorSessionStore.html index eae226e12..3280f4295 100644 --- a/actix_session/storage/struct.RedisActorSessionStore.html +++ b/actix_session/storage/struct.RedisActorSessionStore.html @@ -2,32 +2,32 @@ logo

RedisActorSessionStore

logo
pub struct RedisActorSessionStore { /* private fields */ }
Expand description

Use Redis as session storage backend.

-
use actix_web::{web, App, HttpServer, HttpResponse, Error};
-use actix_session::{SessionMiddleware, storage::RedisActorSessionStore};
-use actix_web::cookie::Key;
+
use actix_web::{web, App, HttpServer, HttpResponse, Error};
+use actix_session::{SessionMiddleware, storage::RedisActorSessionStore};
+use actix_web::cookie::Key;
 
-// The secret key would usually be read from a configuration file/environment variables.
-fn get_secret_key() -> Key {
-    // [...]
-}
+// The secret key would usually be read from a configuration file/environment variables.
+fn get_secret_key() -> Key {
+    // [...]
+}
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let secret_key = get_secret_key();
-    let redis_connection_string = "127.0.0.1:6379";
-    HttpServer::new(move ||
-            App::new()
-            .wrap(
-                SessionMiddleware::new(
-                    RedisActorSessionStore::new(redis_connection_string),
-                    secret_key.clone()
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    let secret_key = get_secret_key();
+    let redis_connection_string = "127.0.0.1:6379";
+    HttpServer::new(move ||
+            App::new()
+            .wrap(
+                SessionMiddleware::new(
+                    RedisActorSessionStore::new(redis_connection_string),
+                    secret_key.clone()
                 )
             )
-            .default_service(web::to(|| HttpResponse::Ok())))
-        .bind(("127.0.0.1", 8080))?
-        .run()
-        .await
-}
+ .default_service(web::to(|| HttpResponse::Ok()))) + .bind(("127.0.0.1", 8080))? + .run() + .await +}

Implementation notes

RedisActorSessionStore leverages actix-redis’s RedisActor implementation - each thread worker gets its own connection to Redis.

@@ -43,26 +43,26 @@ connection string for Redis.

Trait Implementations

Loads the session state associated to a session key.

Persist the session state for a newly created session. Read more

Updates the session state associated to a pre-existing session key.

-

Updates the TTL of the session state associated to a pre-existing session key.

-

Deletes a session from the store.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Updates the TTL of the session state associated to a pre-existing session key.

+

Deletes a session from the store.

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/struct.RedisActorSessionStoreBuilder.html b/actix_session/storage/struct.RedisActorSessionStoreBuilder.html index 5a3bcb56b..bb77e425a 100644 --- a/actix_session/storage/struct.RedisActorSessionStoreBuilder.html +++ b/actix_session/storage/struct.RedisActorSessionStoreBuilder.html @@ -4,24 +4,24 @@ parameters.

Implementations

Set a custom cache key generation strategy, expecting a session key as input.

Finalise the builder and return a RedisActorSessionStore instance.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/struct.RedisSessionStore.html b/actix_session/storage/struct.RedisSessionStore.html index 1f1aefdc3..db22c839e 100644 --- a/actix_session/storage/struct.RedisSessionStore.html +++ b/actix_session/storage/struct.RedisSessionStore.html @@ -2,46 +2,46 @@ logo

RedisSessionStore

logo
pub struct RedisSessionStore { /* private fields */ }
Expand description

Use Redis as session storage backend.

-
use actix_web::{web, App, HttpServer, HttpResponse, Error};
-use actix_session::{SessionMiddleware, storage::RedisSessionStore};
-use actix_web::cookie::Key;
+
use actix_web::{web, App, HttpServer, HttpResponse, Error};
+use actix_session::{SessionMiddleware, storage::RedisSessionStore};
+use actix_web::cookie::Key;
 
-// The secret key would usually be read from a configuration file/environment variables.
-fn get_secret_key() -> Key {
-    // [...]
-}
+// The secret key would usually be read from a configuration file/environment variables.
+fn get_secret_key() -> Key {
+    // [...]
+}
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let secret_key = get_secret_key();
-    let redis_connection_string = "redis://127.0.0.1:6379";
-    let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    let secret_key = get_secret_key();
+    let redis_connection_string = "redis://127.0.0.1:6379";
+    let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
 
-    HttpServer::new(move ||
-            App::new()
-            .wrap(SessionMiddleware::new(
-                store.clone(),
-                secret_key.clone()
+    HttpServer::new(move ||
+            App::new()
+            .wrap(SessionMiddleware::new(
+                store.clone(),
+                secret_key.clone()
             ))
-            .default_service(web::to(|| HttpResponse::Ok())))
-        .bind(("127.0.0.1", 8080))?
-        .run()
-        .await
-}
+ .default_service(web::to(|| HttpResponse::Ok()))) + .bind(("127.0.0.1", 8080))? + .run() + .await +}

TLS support

Add the redis-rs-tls-session feature flag to enable TLS support. You can then establish a TLS connection to Redis using the rediss:// URL scheme:

-
use actix_session::{storage::RedisSessionStore};
+
use actix_session::{storage::RedisSessionStore};
 
-let redis_connection_string = "rediss://127.0.0.1:6379";
-let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
+let redis_connection_string = "rediss://127.0.0.1:6379"; +let store = RedisSessionStore::new(redis_connection_string).await.unwrap();

Implementation notes

RedisSessionStore leverages redis-rs as Redis client.

Implementations

A fluent API to configure RedisSessionStore. It takes as input the only required input to create a new instance of RedisSessionStore - a connection string for Redis.

-

Create a new instance of RedisSessionStore using the default configuration. +

Create a new instance of RedisSessionStore using the default configuration. It takes as input the only required input to create a new instance of RedisSessionStore - a connection string for Redis.

Trait Implementations

Returns a copy of the value. Read more

@@ -49,29 +49,29 @@ connection string for Redis.

Loads the session state associated to a session key.

Persist the session state for a newly created session. Read more

Updates the session state associated to a pre-existing session key.

-

Updates the TTL of the session state associated to a pre-existing session key.

-

Deletes a session from the store.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Updates the TTL of the session state associated to a pre-existing session key.

+

Deletes a session from the store.

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/struct.RedisSessionStoreBuilder.html b/actix_session/storage/struct.RedisSessionStoreBuilder.html index 0585f9b1e..09189d7eb 100644 --- a/actix_session/storage/struct.RedisSessionStoreBuilder.html +++ b/actix_session/storage/struct.RedisSessionStoreBuilder.html @@ -3,25 +3,25 @@ logo
pub struct RedisSessionStoreBuilder { /* private fields */ }
Expand description

A fluent builder to construct a RedisSessionStore instance with custom configuration parameters.

Implementations

Set a custom cache key generation strategy, expecting a session key as input.

-

Finalise the builder and return a RedisActorSessionStore instance.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Finalise the builder and return a RedisActorSessionStore instance.

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/struct.SessionKey.html b/actix_session/storage/struct.SessionKey.html index b74b3bc94..18f0e4ecd 100644 --- a/actix_session/storage/struct.SessionKey.html +++ b/actix_session/storage/struct.SessionKey.html @@ -6,38 +6,39 @@ state on the backend.

Session keys are stored as cookies, therefore they cannot be arbitrary long. Session keys are required to be smaller than 4064 bytes.

-
use actix_session::storage::SessionKey;
+
use actix_session::storage::SessionKey;
 
-let key: String = std::iter::repeat('a').take(4065).collect();
-let session_key: Result<SessionKey, _> = key.try_into();
-assert!(session_key.is_err());
+let key: String = std::iter::repeat('a').take(4065).collect(); +let session_key: Result<SessionKey, _> = key.try_into(); +assert!(session_key.is_err());

Trait Implementations

Converts this type into a shared reference of the (usually inferred) input type.

Formats the value using the given formatter. Read more

Converts to this type from the input type.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

The type returned in the event of a conversion error.

Performs the conversion.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/storage/trait.SessionStore.html b/actix_session/storage/trait.SessionStore.html index 6fb1b713f..979069138 100644 --- a/actix_session/storage/trait.SessionStore.html +++ b/actix_session/storage/trait.SessionStore.html @@ -4,8 +4,8 @@ fn load<'life0, 'life1, 'async_trait>(
        &'life0 self,
        session_key: &'life1 SessionKey
    ) -> Pin<Box<dyn Future<Output = Result<Option<HashMap<String, String>>, LoadError>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: 'async_trait
; fn save<'life0, 'life1, 'async_trait>(
        &'life0 self,
        session_state: HashMap<String, String>,
        ttl: &'life1 Duration
    ) -> Pin<Box<dyn Future<Output = Result<SessionKey, SaveError>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: 'async_trait
; fn update<'life0, 'life1, 'async_trait>(
        &'life0 self,
        session_key: SessionKey,
        session_state: HashMap<String, String>,
        ttl: &'life1 Duration
    ) -> Pin<Box<dyn Future<Output = Result<SessionKey, UpdateError>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: 'async_trait
; - fn update_ttl<'life0, 'life1, 'life2, 'async_trait>(
        &'life0 self,
        session_key: &'life1 SessionKey,
        ttl: &'life2 Duration
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        'life2: 'async_trait,
        Self: 'async_trait
; - fn delete<'life0, 'life1, 'async_trait>(
        &'life0 self,
        session_key: &'life1 SessionKey
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: 'async_trait
; + fn update_ttl<'life0, 'life1, 'life2, 'async_trait>(
        &'life0 self,
        session_key: &'life1 SessionKey,
        ttl: &'life2 Duration
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        'life2: 'async_trait,
        Self: 'async_trait
; + fn delete<'life0, 'life1, 'async_trait>(
        &'life0 self,
        session_key: &'life1 SessionKey
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: 'async_trait
; }
Expand description

The interface to retrieve and save the current session data from/to the chosen storage backend.

You can provide your own custom session store backend by implementing this trait.

async-trait is used for this trait’s definition. Therefore, it @@ -15,6 +15,6 @@ is required for implementations, too. In particular, we use the send-optional va

Persist the session state for a newly created session.

Returns the corresponding session key.

Updates the session state associated to a pre-existing session key.

-

Updates the TTL of the session state associated to a pre-existing session key.

-

Deletes a session from the store.

-

Implementors

\ No newline at end of file +

Updates the TTL of the session state associated to a pre-existing session key.

+

Deletes a session from the store.

+

Implementors

\ No newline at end of file diff --git a/actix_session/struct.Session.html b/actix_session/struct.Session.html index d31ed77d2..85951f562 100644 --- a/actix_session/struct.Session.html +++ b/actix_session/struct.Session.html @@ -4,32 +4,32 @@

Session is an extractor—you can specify it as an input type for your request handlers and it will be automatically extracted from the incoming request.

-
use actix_session::Session;
+
use actix_session::Session;
 
-async fn index(session: Session) -> actix_web::Result<&'static str> {
-    // access session data
-    if let Some(count) = session.get::<i32>("counter")? {
-        session.insert("counter", count + 1)?;
-    } else {
-        session.insert("counter", 1)?;
+async fn index(session: Session) -> actix_web::Result<&'static str> {
+    // access session data
+    if let Some(count) = session.get::<i32>("counter")? {
+        session.insert("counter", count + 1)?;
+    } else {
+        session.insert("counter", 1)?;
     }
 
     Ok("Welcome!")
 }

You can also retrieve a Session object from an HttpRequest or a ServiceRequest using SessionExt.

-

Implementations

Get a value from the session.

+

Implementations

Get a value from the session.

It returns an error if it fails to deserialize as T the JSON value associated with key.

Get all raw key-value data from the session.

Note that values are JSON encoded.

Returns session status.

-

Inserts a key-value pair into the session.

+

Inserts a key-value pair into the session.

Any serializable value can be used and will be encoded as JSON in session data, hence why only a reference to the value is taken.

It returns an error if it fails to serialize value to JSON.

Remove value from the session.

If present, the JSON encoded value is returned.

-

Remove value from the session and deserialize.

+

Remove value from the session and deserialize.

Returns None if key was not present in session. Returns T if deserialization succeeds, otherwise returns un-deserialized JSON string.

Clear the session.

@@ -39,45 +39,45 @@ otherwise returns un-deserialized JSON string.

Performs copy-assignment from source. Read more

Extractor implementation for Sessions.

Examples

-
use actix_session::Session;
+
use actix_session::Session;
 
-#[get("/")]
-async fn index(session: Session) -> Result<impl Responder> {
-    // access session data
-    if let Some(count) = session.get::<i32>("counter")? {
-        session.insert("counter", count + 1)?;
-    } else {
-        session.insert("counter", 1)?;
+#[get("/")]
+async fn index(session: Session) -> Result<impl Responder> {
+    // access session data
+    if let Some(count) = session.get::<i32>("counter")? {
+        session.insert("counter", count + 1)?;
+    } else {
+        session.insert("counter", 1)?;
     }
 
-    let count = session.get::<i32>("counter")?.unwrap();
-    Ok(format!("Counter: {}", count))
+    let count = session.get::<i32>("counter")?.unwrap();
+    Ok(format!("Counter: {}", count))
 }

The associated error which can be returned.

Future that resolves to a Self. Read more

Create a Self from request parts asynchronously.

Create a Self from request head asynchronously. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/struct.SessionGetError.html b/actix_session/struct.SessionGetError.html index 65026a1af..e7cec3438 100644 --- a/actix_session/struct.SessionGetError.html +++ b/actix_session/struct.SessionGetError.html @@ -1,34 +1,36 @@ SessionGetError in actix_session - Rust

SessionGetError

logo
pub struct SessionGetError(_);
Expand description

Error returned by Session::get.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

-

Converts to this type from the input type.

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

Converts to this type from the input type.

Creates full response for error. Read more

Returns appropriate status code for error. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/struct.SessionInsertError.html b/actix_session/struct.SessionInsertError.html index c9694f10b..8f77b26bd 100644 --- a/actix_session/struct.SessionInsertError.html +++ b/actix_session/struct.SessionInsertError.html @@ -1,34 +1,36 @@ SessionInsertError in actix_session - Rust

SessionInsertError

logo
pub struct SessionInsertError(_);
Expand description

Error returned by Session::insert.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

-

Converts to this type from the input type.

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

Converts to this type from the input type.

Creates full response for error. Read more

Returns appropriate status code for error. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/struct.SessionMiddleware.html b/actix_session/struct.SessionMiddleware.html index d6beb6fbb..1924e375a 100644 --- a/actix_session/struct.SessionMiddleware.html +++ b/actix_session/struct.SessionMiddleware.html @@ -23,67 +23,67 @@ each configuration parameter.

we will not stop you. But being a subject-matter expert should not be a requirement to deploy reasonably secure implementation of sessions.

Examples

-
use actix_web::{web, App, HttpServer, HttpResponse, Error};
-use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
-use actix_web::cookie::Key;
+
use actix_web::{web, App, HttpServer, HttpResponse, Error};
+use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
+use actix_web::cookie::Key;
 
-// The secret key would usually be read from a configuration file/environment variables.
-fn get_secret_key() -> Key {
-    // [...]
-}
+// The secret key would usually be read from a configuration file/environment variables.
+fn get_secret_key() -> Key {
+    // [...]
+}
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let secret_key = get_secret_key();
-    let redis_connection_string = "127.0.0.1:6379";
-    HttpServer::new(move ||
-            App::new()
-            // Add session management to your application using Redis for session state storage
-            .wrap(
-                SessionMiddleware::new(
-                    RedisActorSessionStore::new(redis_connection_string),
-                    secret_key.clone()
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    let secret_key = get_secret_key();
+    let redis_connection_string = "127.0.0.1:6379";
+    HttpServer::new(move ||
+            App::new()
+            // Add session management to your application using Redis for session state storage
+            .wrap(
+                SessionMiddleware::new(
+                    RedisActorSessionStore::new(redis_connection_string),
+                    secret_key.clone()
                 )
             )
-            .default_service(web::to(|| HttpResponse::Ok())))
-        .bind(("127.0.0.1", 8080))?
-        .run()
-        .await
-}
+ .default_service(web::to(|| HttpResponse::Ok()))) + .bind(("127.0.0.1", 8080))? + .run() + .await +}

If you want to customise use builder instead of new:

-
use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web};
-use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
-use actix_session::config::PersistentSession;
+
use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web};
+use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
+use actix_session::config::PersistentSession;
 
-// The secret key would usually be read from a configuration file/environment variables.
-fn get_secret_key() -> Key {
-    // [...]
-}
+// The secret key would usually be read from a configuration file/environment variables.
+fn get_secret_key() -> Key {
+    // [...]
+}
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let secret_key = get_secret_key();
-    let redis_connection_string = "127.0.0.1:6379";
-    HttpServer::new(move ||
-            App::new()
-            // Customise session length!
-            .wrap(
-                SessionMiddleware::builder(
-                    RedisActorSessionStore::new(redis_connection_string),
-                    secret_key.clone()
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    let secret_key = get_secret_key();
+    let redis_connection_string = "127.0.0.1:6379";
+    HttpServer::new(move ||
+            App::new()
+            // Customise session length!
+            .wrap(
+                SessionMiddleware::builder(
+                    RedisActorSessionStore::new(redis_connection_string),
+                    secret_key.clone()
                 )
-                .session_lifecycle(
-                    PersistentSession::default()
-                        .session_ttl(time::Duration::days(5))
+                .session_lifecycle(
+                    PersistentSession::default()
+                        .session_ttl(time::Duration::days(5))
                 )
-                .build(),
+                .build(),
             )
-            .default_service(web::to(|| HttpResponse::Ok())))
-        .bind(("127.0.0.1", 8080))?
-        .run()
-        .await
-}
+ .default_service(web::to(|| HttpResponse::Ok()))) + .bind(("127.0.0.1", 8080))? + .run() + .await +}

Implementations

Use SessionMiddleware::new to initialize the session framework using the default parameters.

To create a new instance of SessionMiddleware you need to provide:

@@ -107,27 +107,27 @@ parameters.

Errors produced while building a transform service.

The future response value.

Creates and returns a new Transform component, asynchronously

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_session/trait.SessionExt.html b/actix_session/trait.SessionExt.html index 9a42a1f17..f65f2caef 100644 --- a/actix_session/trait.SessionExt.html +++ b/actix_session/trait.SessionExt.html @@ -5,4 +5,4 @@ }
Expand description

Extract a Session object from various actix-web types (e.g. HttpRequest, ServiceRequest, ServiceResponse).

Required Methods

Extract a Session object.

-

Implementations on Foreign Types

Implementors

\ No newline at end of file +

Implementations on Foreign Types

Implementors

\ No newline at end of file diff --git a/actix_settings/all.html b/actix_settings/all.html index 0c9709dc3..9d20fbd01 100644 --- a/actix_settings/all.html +++ b/actix_settings/all.html @@ -1,3 +1,3 @@ List of all items in this crate
\ No newline at end of file + logo

List of all items

Structs

Enums

Traits

Typedefs

\ No newline at end of file diff --git a/actix_settings/enum.Backlog.html b/actix_settings/enum.Backlog.html index 30d9862e5..acb3575b9 100644 --- a/actix_settings/enum.Backlog.html +++ b/actix_settings/enum.Backlog.html @@ -14,35 +14,36 @@ under significant load.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.Error.html b/actix_settings/enum.Error.html index 819fd9d25..c6d65bbe1 100644 --- a/actix_settings/enum.Error.html +++ b/actix_settings/enum.Error.html @@ -34,27 +34,27 @@

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.KeepAlive.html b/actix_settings/enum.KeepAlive.html index 2b20778c8..371de21b7 100644 --- a/actix_settings/enum.KeepAlive.html +++ b/actix_settings/enum.KeepAlive.html @@ -16,35 +16,36 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.MaxConnectionRate.html b/actix_settings/enum.MaxConnectionRate.html index 730e5fca7..960a03ffe 100644 --- a/actix_settings/enum.MaxConnectionRate.html +++ b/actix_settings/enum.MaxConnectionRate.html @@ -12,35 +12,36 @@ value: Either “default”, or an integer N > 0 e.g. “6”.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.MaxConnections.html b/actix_settings/enum.MaxConnections.html index c2bc040f3..69a4c92f0 100644 --- a/actix_settings/enum.MaxConnections.html +++ b/actix_settings/enum.MaxConnections.html @@ -12,35 +12,36 @@ integer N > 0 e.g. “6”.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.Mode.html b/actix_settings/enum.Mode.html index 6063fec47..256457608 100644 --- a/actix_settings/enum.Mode.html +++ b/actix_settings/enum.Mode.html @@ -9,35 +9,36 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.NumWorkers.html b/actix_settings/enum.NumWorkers.html index 6a50029f5..272aabd76 100644 --- a/actix_settings/enum.NumWorkers.html +++ b/actix_settings/enum.NumWorkers.html @@ -11,35 +11,36 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/enum.Timeout.html b/actix_settings/enum.Timeout.html index 2365e990b..90387bae5 100644 --- a/actix_settings/enum.Timeout.html +++ b/actix_settings/enum.Timeout.html @@ -11,35 +11,36 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/index.html b/actix_settings/index.html index a3d519752..a1f599bc7 100644 --- a/actix_settings/index.html +++ b/actix_settings/index.html @@ -10,46 +10,46 @@ the environment using Examples

See examples folder on GitHub for complete example.

-
use actix_settings::{ApplySettings as _, Mode, Settings};
+
use actix_settings::{ApplySettings as _, Mode, Settings};
 
-#[actix_web::main]
-async fn main() -> std::io::Result<()> {
-    let mut settings = Settings::parse_toml("./Server.toml")
-        .expect("Failed to parse `Settings` from Server.toml");
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+    let mut settings = Settings::parse_toml("./Server.toml")
+        .expect("Failed to parse `Settings` from Server.toml");
 
-    // If the environment variable `$APPLICATION__HOSTS` is set,
-    // have its value override the `settings.actix.hosts` setting:
-    Settings::override_field_with_env_var(&mut settings.actix.hosts, "APPLICATION__HOSTS")?;
+    // If the environment variable `$APPLICATION__HOSTS` is set,
+    // have its value override the `settings.actix.hosts` setting:
+    Settings::override_field_with_env_var(&mut settings.actix.hosts, "APPLICATION__HOSTS")?;
 
-    init_logger(&settings);
+    init_logger(&settings);
 
-    HttpServer::new({
-        // clone settings into each worker thread
-        let settings = settings.clone();
+    HttpServer::new({
+        // clone settings into each worker thread
+        let settings = settings.clone();
 
-        move || {
-            App::new()
-                // Include this `.wrap()` call for compression settings to take effect
-                .wrap(Condition::new(
-                    settings.actix.enable_compression,
-                    Compress::default(),
+        move || {
+            App::new()
+                // Include this `.wrap()` call for compression settings to take effect
+                .wrap(Condition::new(
+                    settings.actix.enable_compression,
+                    Compress::default(),
                 ))
 
-                // add request logger
-                .wrap(Logger::default())
+                // add request logger
+                .wrap(Logger::default())
 
-                // make `Settings` available to handlers
-                .app_data(web::Data::new(settings.clone()))
+                // make `Settings` available to handlers
+                .app_data(web::Data::new(settings.clone()))
 
-                // add request handlers as normal
-                .service(index)
+                // add request handlers as normal
+                .service(index)
         }
     })
-    // apply the `Settings` to Actix Web's `HttpServer`
-    .apply_settings(&settings)
-    .run()
-    .await
-}
+ // apply the `Settings` to Actix Web's `HttpServer` + .apply_settings(&settings) + .run() + .await +}

Structs

Settings types for Actix Web.

A host/port pair for the server to bind to.

Wrapper for server and application-specific settings.

@@ -66,4 +66,4 @@ the environment using Traits

Extension trait for applying parsed settings to the server object.

A specialized FromStr trait that returns [AtError] errors

Type Definitions

Convenience type alias for BasicSettings with no defined application-specific settings.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/struct.ActixSettings.html b/actix_settings/struct.ActixSettings.html index f5b570bd5..c4f285436 100644 --- a/actix_settings/struct.ActixSettings.html +++ b/actix_settings/struct.ActixSettings.html @@ -31,34 +31,35 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/struct.Address.html b/actix_settings/struct.Address.html index 1579f5007..64b54b92a 100644 --- a/actix_settings/struct.Address.html +++ b/actix_settings/struct.Address.html @@ -9,35 +9,36 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Parse Self from string.

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/struct.BasicSettings.html b/actix_settings/struct.BasicSettings.html index 86dd4101f..a41c3152b 100644 --- a/actix_settings/struct.BasicSettings.html +++ b/actix_settings/struct.BasicSettings.html @@ -6,7 +6,7 @@ }
Expand description

Wrapper for server and application-specific settings.

Fields

actix: ActixSettings

Actix Web server settings.

application: A

Application-specific settings.

-

Implementations

Parse an instance of Self from a TOML file located at filepath.

+

Implementations

Parse an instance of Self from a TOML file located at filepath.

If the file doesn’t exist, it is generated from the default TOML template, after which the newly generated file is read in and parsed.

Parse an instance of Self straight from the default TOML template.

@@ -17,55 +17,56 @@ newly generated file is read in and parsed.

location.

Attempts to parse value and override the referenced field.

Examples
-
use actix_settings::{Settings, Mode};
+
use actix_settings::{Settings, Mode};
 
-let mut settings = Settings::from_default_template()?;
-assert_eq!(settings.actix.mode, Mode::Development);
+let mut settings = Settings::from_default_template()?;
+assert_eq!(settings.actix.mode, Mode::Development);
 
-Settings::override_field(&mut settings.actix.mode, "production")?;
-assert_eq!(settings.actix.mode, Mode::Production);
+Settings::override_field(&mut settings.actix.mode, "production")?; +assert_eq!(settings.actix.mode, Mode::Production);

Attempts to read an environment variable, parse it, and override the referenced field.

Examples
-
use actix_settings::{Settings, Mode};
+
use actix_settings::{Settings, Mode};
 
-std::env::set_var("OVERRIDE__MODE", "production");
+std::env::set_var("OVERRIDE__MODE", "production");
 
-let mut settings = Settings::from_default_template()?;
-assert_eq!(settings.actix.mode, Mode::Development);
+let mut settings = Settings::from_default_template()?;
+assert_eq!(settings.actix.mode, Mode::Development);
 
-Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE")?;
-assert_eq!(settings.actix.mode, Mode::Production);
+Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE")?; +assert_eq!(settings.actix.mode, Mode::Production);

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/struct.NoSettings.html b/actix_settings/struct.NoSettings.html index 7205b43fd..4fb166fa6 100644 --- a/actix_settings/struct.NoSettings.html +++ b/actix_settings/struct.NoSettings.html @@ -4,34 +4,35 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/struct.Tls.html b/actix_settings/struct.Tls.html index 6f61a1bb3..e4f993343 100644 --- a/actix_settings/struct.Tls.html +++ b/actix_settings/struct.Tls.html @@ -11,34 +11,35 @@

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

-

Deserialize this value from the given Serde deserializer. Read more

+

Deserialize this value from the given Serde deserializer. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_settings/trait.ApplySettings.html b/actix_settings/trait.ApplySettings.html index 956f05b96..e16895fb6 100644 --- a/actix_settings/trait.ApplySettings.html +++ b/actix_settings/trait.ApplySettings.html @@ -1,7 +1,7 @@ ApplySettings in actix_settings - Rust
logo
pub trait ApplySettings {
-    fn apply_settings<A>(self, settings: &BasicSettings<A>) -> Self
    where
        A: DeserializeOwned
; + fn apply_settings<A>(self, settings: &BasicSettings<A>) -> Self
    where
        A: DeserializeOwned
; }
Expand description

Extension trait for applying parsed settings to the server object.

-

Required Methods

Apply a BasicSettings value to self.

-

Implementations on Foreign Types

Implementors

\ No newline at end of file +

Required Methods

Apply a BasicSettings value to self.

+

Implementations on Foreign Types

Implementors

\ No newline at end of file diff --git a/actix_settings/trait.Parse.html b/actix_settings/trait.Parse.html index 531529c30..de46c89cd 100644 --- a/actix_settings/trait.Parse.html +++ b/actix_settings/trait.Parse.html @@ -4,4 +4,4 @@ fn parse(string: &str) -> Result<Self, Error>; }
Expand description

A specialized FromStr trait that returns [AtError] errors

Required Methods

Parse Self from string.

-

Implementations on Foreign Types

Implementors

\ No newline at end of file +

Implementations on Foreign Types

Implementors

\ No newline at end of file diff --git a/actix_settings/type.Settings.html b/actix_settings/type.Settings.html index 5ca551858..49f690761 100644 --- a/actix_settings/type.Settings.html +++ b/actix_settings/type.Settings.html @@ -1,4 +1,4 @@ Settings in actix_settings - Rust
logo

Type Definition actix_settings::Settings

source · []
pub type Settings = BasicSettings<NoSettings>;
Expand description

Convenience type alias for BasicSettings with no defined application-specific settings.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/all.html b/actix_web_httpauth/all.html index d540c1fbb..18e6be785 100644 --- a/actix_web_httpauth/all.html +++ b/actix_web_httpauth/all.html @@ -1 +1 @@ -List of all items in this crate
\ No newline at end of file +List of all items in this crate
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/basic/index.html b/actix_web_httpauth/extractors/basic/index.html index 9410facaf..2d28f17c0 100644 --- a/actix_web_httpauth/extractors/basic/index.html +++ b/actix_web_httpauth/extractors/basic/index.html @@ -1,4 +1,4 @@ actix_web_httpauth::extractors::basic - Rust
Expand description

Extractor for the “Basic” HTTP Authentication Scheme.

Structs

Extractor for HTTP Basic auth.

BasicAuth extractor configuration used for WWW-Authenticate header later.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/basic/struct.BasicAuth.html b/actix_web_httpauth/extractors/basic/struct.BasicAuth.html index d7a417242..af9f36afd 100644 --- a/actix_web_httpauth/extractors/basic/struct.BasicAuth.html +++ b/actix_web_httpauth/extractors/basic/struct.BasicAuth.html @@ -1,23 +1,23 @@ BasicAuth in actix_web_httpauth::extractors::basic - Rust
pub struct BasicAuth(_);
Expand description

Extractor for HTTP Basic auth.

Examples

-
use actix_web_httpauth::extractors::basic::BasicAuth;
+
use actix_web_httpauth::extractors::basic::BasicAuth;
 
-async fn index(auth: BasicAuth) -> String {
-    format!("Hello, {}!", auth.user_id())
+async fn index(auth: BasicAuth) -> String {
+    format!("Hello, {}!", auth.user_id())
 }

If authentication fails, this extractor fetches the Config instance from the app data in order to properly form the WWW-Authenticate response header.

Examples

-
use actix_web::{web, App};
-use actix_web_httpauth::extractors::basic::{self, BasicAuth};
+
use actix_web::{web, App};
+use actix_web_httpauth::extractors::basic::{self, BasicAuth};
 
-async fn index(auth: BasicAuth) -> String {
-    format!("Hello, {}!", auth.user_id())
+async fn index(auth: BasicAuth) -> String {
+    format!("Hello, {}!", auth.user_id())
 }
 
-App::new()
-    .app_data(basic::Config::default().realm("Restricted area"))
-    .service(web::resource("/index.html").route(web::get().to(index)));
+App::new() + .app_data(basic::Config::default().realm("Restricted area")) + .service(web::resource("/index.html").route(web::get().to(index)));

Implementations

Returns client’s user-ID.

Returns client’s password.

Trait Implementations

Returns a copy of the value. Read more

@@ -27,27 +27,27 @@ order to properly form the WWW-Authenticate response header.

The associated error which can be returned.

Create a Self from request parts asynchronously.

Create a Self from request head asynchronously. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/basic/struct.Config.html b/actix_web_httpauth/extractors/basic/struct.Config.html index dd9c060ae..2ba0db528 100644 --- a/actix_web_httpauth/extractors/basic/struct.Config.html +++ b/actix_web_httpauth/extractors/basic/struct.Config.html @@ -9,27 +9,27 @@

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/bearer/enum.Error.html b/actix_web_httpauth/extractors/bearer/enum.Error.html index cdb64ef21..04b46f751 100644 --- a/actix_web_httpauth/extractors/bearer/enum.Error.html +++ b/actix_web_httpauth/extractors/bearer/enum.Error.html @@ -16,42 +16,43 @@ or is otherwise malformed.

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/bearer/index.html b/actix_web_httpauth/extractors/bearer/index.html index a3317ac0e..1c1d71e2a 100644 --- a/actix_web_httpauth/extractors/bearer/index.html +++ b/actix_web_httpauth/extractors/bearer/index.html @@ -2,4 +2,4 @@

Structs

Extractor for HTTP Bearer auth

BearerAuth extractor configuration.

Enums

Bearer authorization error types, described in RFC 6750.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/bearer/struct.BearerAuth.html b/actix_web_httpauth/extractors/bearer/struct.BearerAuth.html index ed3508f36..8d061a44a 100644 --- a/actix_web_httpauth/extractors/bearer/struct.BearerAuth.html +++ b/actix_web_httpauth/extractors/bearer/struct.BearerAuth.html @@ -1,28 +1,28 @@ BearerAuth in actix_web_httpauth::extractors::bearer - Rust
pub struct BearerAuth(_);
Expand description

Extractor for HTTP Bearer auth

Examples

-
use actix_web_httpauth::extractors::bearer::BearerAuth;
+
use actix_web_httpauth::extractors::bearer::BearerAuth;
 
-async fn index(auth: BearerAuth) -> String {
-    format!("Hello, user with token {}!", auth.token())
+async fn index(auth: BearerAuth) -> String {
+    format!("Hello, user with token {}!", auth.token())
 }

If authentication fails, this extractor fetches the Config instance from the [app data] in order to properly form the WWW-Authenticate response header.

Examples

-
use actix_web::{web, App};
-use actix_web_httpauth::extractors::bearer::{self, BearerAuth};
+
use actix_web::{web, App};
+use actix_web_httpauth::extractors::bearer::{self, BearerAuth};
 
-async fn index(auth: BearerAuth) -> String {
-    format!("Hello, {}!", auth.token())
+async fn index(auth: BearerAuth) -> String {
+    format!("Hello, {}!", auth.token())
 }
 
-App::new()
-    .app_data(
-        bearer::Config::default()
-            .realm("Restricted area")
-            .scope("email photo"),
+App::new()
+    .app_data(
+        bearer::Config::default()
+            .realm("Restricted area")
+            .scope("email photo"),
     )
-    .service(web::resource("/index.html").route(web::get().to(index)));
+ .service(web::resource("/index.html").route(web::get().to(index)));

Implementations

Returns bearer token provided by client.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

@@ -31,27 +31,27 @@ response header.

The associated error which can be returned.

Create a Self from request parts asynchronously.

Create a Self from request head asynchronously. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/bearer/struct.Config.html b/actix_web_httpauth/extractors/bearer/struct.Config.html index 1ebe42902..ad6f32f67 100644 --- a/actix_web_httpauth/extractors/bearer/struct.Config.html +++ b/actix_web_httpauth/extractors/bearer/struct.Config.html @@ -13,27 +13,27 @@ described in HTTP/1.1

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/index.html b/actix_web_httpauth/extractors/index.html index bd2a6abfb..cbb6b0172 100644 --- a/actix_web_httpauth/extractors/index.html +++ b/actix_web_httpauth/extractors/index.html @@ -4,4 +4,4 @@

Structs

Authentication error returned by authentication extractors.

Traits

Trait implemented for types that provides configuration for the authentication extractors.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/struct.AuthenticationError.html b/actix_web_httpauth/extractors/struct.AuthenticationError.html index 437e4b90c..6aea0226f 100644 --- a/actix_web_httpauth/extractors/struct.AuthenticationError.html +++ b/actix_web_httpauth/extractors/struct.AuthenticationError.html @@ -1,4 +1,4 @@ -AuthenticationError in actix_web_httpauth::extractors - Rust
pub struct AuthenticationError<C: Challenge> { /* private fields */ }
Expand description

Authentication error returned by authentication extractors.

+AuthenticationError in actix_web_httpauth::extractors - Rust
pub struct AuthenticationError<C: Challenge> { /* private fields */ }
Expand description

Authentication error returned by authentication extractors.

Different extractors may extend AuthenticationError implementation in order to provide access inner challenge fields.

Implementations

Extended error customization for HTTP Bearer auth.

@@ -16,32 +16,34 @@ Error.

RFC, so it might be unreasonable.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Converts to this type from the input type.

Returns appropriate status code for error. Read more

Creates full response for error. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/extractors/trait.AuthExtractorConfig.html b/actix_web_httpauth/extractors/trait.AuthExtractorConfig.html index efdf7725d..113f8fb63 100644 --- a/actix_web_httpauth/extractors/trait.AuthExtractorConfig.html +++ b/actix_web_httpauth/extractors/trait.AuthExtractorConfig.html @@ -6,4 +6,4 @@ extractors.

Required Associated Types

Associated challenge type.

Required Methods

Convert the config instance into a HTTP challenge.

-

Implementors

\ No newline at end of file +

Implementors

\ No newline at end of file diff --git a/actix_web_httpauth/headers/authorization/enum.ParseError.html b/actix_web_httpauth/headers/authorization/enum.ParseError.html index 10a31f767..960ace386 100644 --- a/actix_web_httpauth/headers/authorization/enum.ParseError.html +++ b/actix_web_httpauth/headers/authorization/enum.ParseError.html @@ -1,4 +1,4 @@ -ParseError in actix_web_httpauth::headers::authorization - Rust
pub enum ParseError {
+ParseError in actix_web_httpauth::headers::authorization - Rust
pub enum ParseError {
     Invalid,
     MissingScheme,
     MissingField(&'static str),
@@ -16,32 +16,34 @@
 

Utf8Error(Utf8Error)

Malformed UTF-8 string.

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

-

The lower-level source of this error, if any. Read more

-
👎 Deprecated since 1.42.0:

use the Display impl or to_string()

-
👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

-
🔬 This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

+

The lower-level source of this error, if any. Read more

+
👎Deprecated since 1.42.0:

use the Display impl or to_string()

+
👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

+
🔬This is a nightly-only experimental API. (error_generic_member_access)

Provides type based access to context intended for error reports. Read more

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

+
🔬This is a nightly-only experimental API. (provide_any)

Data providers should implement this method to provide all values they are able to +provide by using demand. Read more

Should always be Self

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/authorization/index.html b/actix_web_httpauth/headers/authorization/index.html index 624fa2721..8745aa41e 100644 --- a/actix_web_httpauth/headers/authorization/index.html +++ b/actix_web_httpauth/headers/authorization/index.html @@ -4,4 +4,4 @@

Credentials for Bearer authentication scheme, defined in RFC 6750.

Enums

Possible errors while parsing Authorization header.

Traits

Authentication scheme for Authorization header.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/authorization/struct.Authorization.html b/actix_web_httpauth/headers/authorization/struct.Authorization.html index 0d393ba6f..a4436fe24 100644 --- a/actix_web_httpauth/headers/authorization/struct.Authorization.html +++ b/actix_web_httpauth/headers/authorization/struct.Authorization.html @@ -5,10 +5,10 @@ consists of credentials containing the authentication information of the user ag realm of the resource being requested.

Authorization is generic over an authentication scheme.

Examples

-
fn handler(req: HttpRequest) -> Result<String> {
-    let auth = Authorization::<Basic>::parse(&req)?;
+
fn handler(req: HttpRequest) -> Result<String> {
+    let auth = Authorization::<Basic>::parse(&req)?;
 
-    Ok(format!("Hello, {}!", auth.as_ref().user_id()))
+    Ok(format!("Hello, {}!", auth.as_ref().user_id()))
 }

Implementations

Consumes Authorization header and returns inner Scheme implementation.

Trait Implementations

Converts this type into a mutable reference of the (usually inferred) input type.

@@ -24,45 +24,46 @@ realm of the resource being requested.

Returns the name of the header field.

Parse the header from a HTTP message.

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

The type returned in the event of a conversion error.

Try to convert value to a HeaderValue.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Converts to this type from the input type.

-

Returns the argument unchanged.

+

Converts to this type from the input type.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/authorization/struct.Basic.html b/actix_web_httpauth/headers/authorization/struct.Basic.html index 9bd7992e2..4c5f826a4 100644 --- a/actix_web_httpauth/headers/authorization/struct.Basic.html +++ b/actix_web_httpauth/headers/authorization/struct.Basic.html @@ -2,7 +2,7 @@

Implementations

Creates Basic credentials with provided user_id and optional password.

Examples
-
let credentials = Basic::new("Alladin", Some("open sesame"));
+
let credentials = Basic::new("Alladin", Some("open sesame"));

Returns client’s user-ID.

Returns client’s password if provided.

Trait Implementations

Returns a copy of the value. Read more

@@ -10,45 +10,46 @@

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Try to parse an authentication scheme from the Authorization header.

The type returned in the event of a conversion error.

Try to convert value to a HeaderValue.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/authorization/struct.Bearer.html b/actix_web_httpauth/headers/authorization/struct.Bearer.html index fef0bf36a..fa0ae7fa9 100644 --- a/actix_web_httpauth/headers/authorization/struct.Bearer.html +++ b/actix_web_httpauth/headers/authorization/struct.Bearer.html @@ -2,52 +2,53 @@

Should be used in combination with Authorization header.

Implementations

Creates new Bearer credentials with the token provided.

Example
-
let credentials = Bearer::new("mF_9.B5f-4.1JqM");
+
let credentials = Bearer::new("mF_9.B5f-4.1JqM");

Gets reference to the credentials token.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Try to parse an authentication scheme from the Authorization header.

The type returned in the event of a conversion error.

Try to convert value to a HeaderValue.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/authorization/trait.Scheme.html b/actix_web_httpauth/headers/authorization/trait.Scheme.html index b7b7847ac..10d76dc0b 100644 --- a/actix_web_httpauth/headers/authorization/trait.Scheme.html +++ b/actix_web_httpauth/headers/authorization/trait.Scheme.html @@ -2,4 +2,4 @@ fn parse(header: &HeaderValue) -> Result<Self, ParseError>; }
Expand description

Authentication scheme for Authorization header.

Required Methods

Try to parse an authentication scheme from the Authorization header.

-

Implementors

\ No newline at end of file +

Implementors

\ No newline at end of file diff --git a/actix_web_httpauth/headers/index.html b/actix_web_httpauth/headers/index.html index fd325fbe1..7d3016a1e 100644 --- a/actix_web_httpauth/headers/index.html +++ b/actix_web_httpauth/headers/index.html @@ -1,4 +1,4 @@ actix_web_httpauth::headers - Rust
Expand description

Typed HTTP headers.

Modules

Authorization header and various auth schemes.

WWW-Authenticate header and various auth challenges.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/basic/index.html b/actix_web_httpauth/headers/www_authenticate/basic/index.html index 0e22c3ba7..850215af0 100644 --- a/actix_web_httpauth/headers/www_authenticate/basic/index.html +++ b/actix_web_httpauth/headers/www_authenticate/basic/index.html @@ -1,4 +1,4 @@ actix_web_httpauth::headers::www_authenticate::basic - Rust
Expand description

Challenge for the “Basic” HTTP Authentication Scheme.

Structs

Challenge for WWW-Authenticate header with HTTP Basic auth scheme, described in RFC 7617

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/basic/struct.Basic.html b/actix_web_httpauth/headers/www_authenticate/basic/struct.Basic.html index 1f03cc214..4a53c6c38 100644 --- a/actix_web_httpauth/headers/www_authenticate/basic/struct.Basic.html +++ b/actix_web_httpauth/headers/www_authenticate/basic/struct.Basic.html @@ -1,25 +1,25 @@ Basic in actix_web_httpauth::headers::www_authenticate::basic - Rust
pub struct Basic { /* private fields */ }
Expand description

Challenge for WWW-Authenticate header with HTTP Basic auth scheme, described in RFC 7617

Examples

-
use actix_web_httpauth::headers::www_authenticate::basic::Basic;
-use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
+
use actix_web_httpauth::headers::www_authenticate::basic::Basic;
+use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
 
-fn index(_req: HttpRequest) -> HttpResponse {
-    let challenge = Basic::with_realm("Restricted area");
+fn index(_req: HttpRequest) -> HttpResponse {
+    let challenge = Basic::with_realm("Restricted area");
 
-    HttpResponse::Unauthorized()
-        .insert_header(WwwAuthenticate(challenge))
-        .finish()
+    HttpResponse::Unauthorized()
+        .insert_header(WwwAuthenticate(challenge))
+        .finish()
 }

Implementations

Creates new Basic challenge with an empty realm field.

Examples
-
let challenge = Basic::new();
+
let challenge = Basic::new();

Creates new Basic challenge from the provided realm field value.

Examples
-
let challenge = Basic::with_realm("Restricted area");
+
let challenge = Basic::with_realm("Restricted area");
-
let my_realm = "Earth realm".to_string();
-let challenge = Basic::with_realm(my_realm);
+
let my_realm = "Earth realm".to_string();
+let challenge = Basic::with_realm(my_realm);

Trait Implementations

Converts this type into a shared reference of the (usually inferred) input type.

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

@@ -29,44 +29,45 @@ described in RFC 7617

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

The type returned in the event of a conversion error.

Try to convert value to a HeaderValue.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/bearer/enum.Error.html b/actix_web_httpauth/headers/www_authenticate/bearer/enum.Error.html index fa14ae73e..be0ae24f1 100644 --- a/actix_web_httpauth/headers/www_authenticate/bearer/enum.Error.html +++ b/actix_web_httpauth/headers/www_authenticate/bearer/enum.Error.html @@ -16,42 +16,43 @@ or is otherwise malformed.

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/bearer/index.html b/actix_web_httpauth/headers/www_authenticate/bearer/index.html index 338af47dd..ecc32c51d 100644 --- a/actix_web_httpauth/headers/www_authenticate/bearer/index.html +++ b/actix_web_httpauth/headers/www_authenticate/bearer/index.html @@ -2,4 +2,4 @@

Structs

Challenge for WWW-Authenticate header with HTTP Bearer auth scheme, described in RFC 6750.

Builder for the Bearer challenge.

Enums

Bearer authorization error types, described in RFC 6750.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/bearer/struct.Bearer.html b/actix_web_httpauth/headers/www_authenticate/bearer/struct.Bearer.html index 50395225d..c4e24e219 100644 --- a/actix_web_httpauth/headers/www_authenticate/bearer/struct.Bearer.html +++ b/actix_web_httpauth/headers/www_authenticate/bearer/struct.Bearer.html @@ -1,29 +1,29 @@ Bearer in actix_web_httpauth::headers::www_authenticate::bearer - Rust
pub struct Bearer { /* private fields */ }
Expand description

Challenge for WWW-Authenticate header with HTTP Bearer auth scheme, described in RFC 6750.

Examples

-
use actix_web_httpauth::headers::www_authenticate::bearer::{
-    Bearer, Error,
+
use actix_web_httpauth::headers::www_authenticate::bearer::{
+    Bearer, Error,
 };
-use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
+use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
 
-fn index(_req: HttpRequest) -> HttpResponse {
-    let challenge = Bearer::build()
-        .realm("example")
-        .scope("openid profile email")
-        .error(Error::InvalidToken)
-        .error_description("The access token expired")
-        .error_uri("http://example.org")
-        .finish();
+fn index(_req: HttpRequest) -> HttpResponse {
+    let challenge = Bearer::build()
+        .realm("example")
+        .scope("openid profile email")
+        .error(Error::InvalidToken)
+        .error_description("The access token expired")
+        .error_uri("http://example.org")
+        .finish();
 
-    HttpResponse::Unauthorized()
-        .insert_header(WwwAuthenticate(challenge))
-        .finish()
+    HttpResponse::Unauthorized()
+        .insert_header(WwwAuthenticate(challenge))
+        .finish()
 }

Implementations

Creates the builder for Bearer challenge.

Examples
-
let challenge = Bearer::build()
-    .realm("Restricted area")
-    .scope("openid profile email")
-    .finish();
+
let challenge = Bearer::build()
+    .realm("Restricted area")
+    .scope("openid profile email")
+    .finish();

Trait Implementations

Converts this type into a shared reference of the (usually inferred) input type.

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

@@ -33,44 +33,45 @@

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

The type returned in the event of a conversion error.

Try to convert value to a HeaderValue.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

Converts the given value to a String. Read more

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

Converts the given value to a String. Read more

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/bearer/struct.BearerBuilder.html b/actix_web_httpauth/headers/www_authenticate/bearer/struct.BearerBuilder.html index d13149b7f..b3bc6bcf6 100644 --- a/actix_web_httpauth/headers/www_authenticate/bearer/struct.BearerBuilder.html +++ b/actix_web_httpauth/headers/www_authenticate/bearer/struct.BearerBuilder.html @@ -11,24 +11,24 @@ provide any validation.

Consumes the builder and returns built Bearer instance.

Trait Implementations

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/index.html b/actix_web_httpauth/headers/www_authenticate/index.html index 80d865bc9..7a29fc02c 100644 --- a/actix_web_httpauth/headers/www_authenticate/index.html +++ b/actix_web_httpauth/headers/www_authenticate/index.html @@ -3,4 +3,4 @@

Challenge for the “Bearer” HTTP Authentication Scheme.

Structs

WWW-Authenticate header, described in RFC 7235.

Traits

Authentication challenge for WWW-Authenticate header.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/struct.WwwAuthenticate.html b/actix_web_httpauth/headers/www_authenticate/struct.WwwAuthenticate.html index c9e2ee2d8..01a5b3a93 100644 --- a/actix_web_httpauth/headers/www_authenticate/struct.WwwAuthenticate.html +++ b/actix_web_httpauth/headers/www_authenticate/struct.WwwAuthenticate.html @@ -10,43 +10,44 @@

Returns the name of the header field.

Parse the header from a HTTP message.

This method returns an Ordering between self and other. Read more

-

Compares and returns the maximum of two values. Read more

-

Compares and returns the minimum of two values. Read more

-

Restrict a value to a certain interval. Read more

+

Compares and returns the maximum of two values. Read more

+

Compares and returns the minimum of two values. Read more

+

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

-

This method tests for !=.

+

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason. Read more

This method returns an ordering between self and other values if one exists. Read more

-

This method tests less than (for self and other) and is used by the < operator. Read more

-

This method tests less than or equal to (for self and other) and is used by the <= +

This method tests less than (for self and other) and is used by the < operator. Read more

+

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

-

This method tests greater than (for self and other) and is used by the > operator. Read more

-

This method tests greater than or equal to (for self and other) and is used by the >= +

This method tests greater than (for self and other) and is used by the > operator. Read more

+

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

The type returned in the event of a conversion error.

Try to convert value to a HeaderValue.

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/headers/www_authenticate/trait.Challenge.html b/actix_web_httpauth/headers/www_authenticate/trait.Challenge.html index 2d412d68d..294058d9c 100644 --- a/actix_web_httpauth/headers/www_authenticate/trait.Challenge.html +++ b/actix_web_httpauth/headers/www_authenticate/trait.Challenge.html @@ -2,4 +2,4 @@ fn to_bytes(&self) -> Bytes; }
Expand description

Authentication challenge for WWW-Authenticate header.

Required Methods

Converts the challenge into a bytes suitable for HTTP transmission.

-

Implementors

\ No newline at end of file +

Implementors

\ No newline at end of file diff --git a/actix_web_httpauth/index.html b/actix_web_httpauth/index.html index 4c8d079a1..7fa2c2fee 100644 --- a/actix_web_httpauth/index.html +++ b/actix_web_httpauth/index.html @@ -13,4 +13,4 @@

Modules

Type-safe authentication information extractors.

Typed HTTP headers.

HTTP Authentication middleware.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/middleware/index.html b/actix_web_httpauth/middleware/index.html index 89cd1b9ad..d89c2b8c2 100644 --- a/actix_web_httpauth/middleware/index.html +++ b/actix_web_httpauth/middleware/index.html @@ -1,3 +1,3 @@ actix_web_httpauth::middleware - Rust
Expand description

HTTP Authentication middleware.

Structs

Middleware for checking HTTP authentication.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/actix_web_httpauth/middleware/struct.HttpAuthentication.html b/actix_web_httpauth/middleware/struct.HttpAuthentication.html index 954612067..5825130c9 100644 --- a/actix_web_httpauth/middleware/struct.HttpAuthentication.html +++ b/actix_web_httpauth/middleware/struct.HttpAuthentication.html @@ -7,37 +7,37 @@ successful validation F callback is required to return the Se validation callback F.

Construct HttpAuthentication middleware for the HTTP “Basic” authentication scheme.

Examples
-
// In this example validator returns immediately, but since it is required to return
-// anything that implements `IntoFuture` trait, it can be extended to query database or to
-// do something else in a async manner.
-async fn validator(
-    req: ServiceRequest,
-    credentials: BasicAuth,
-) -> Result<ServiceRequest, (Error, ServiceRequest)> {
-    // All users are great and more than welcome!
-    Ok(req)
+
// In this example validator returns immediately, but since it is required to return
+// anything that implements `IntoFuture` trait, it can be extended to query database or to
+// do something else in a async manner.
+async fn validator(
+    req: ServiceRequest,
+    credentials: BasicAuth,
+) -> Result<ServiceRequest, (Error, ServiceRequest)> {
+    // All users are great and more than welcome!
+    Ok(req)
 }
 
-let middleware = HttpAuthentication::basic(validator);
+let middleware = HttpAuthentication::basic(validator);

Construct HttpAuthentication middleware for the HTTP “Bearer” authentication scheme.

Examples
-
async fn validator(
-    req: ServiceRequest,
-    credentials: BearerAuth
-) -> Result<ServiceRequest, (Error, ServiceRequest)> {
-    if credentials.token() == "mF_9.B5f-4.1JqM" {
-        Ok(req)
-    } else {
-        let config = req.app_data::<bearer::Config>()
-            .cloned()
-            .unwrap_or_default()
-            .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
+
async fn validator(
+    req: ServiceRequest,
+    credentials: BearerAuth
+) -> Result<ServiceRequest, (Error, ServiceRequest)> {
+    if credentials.token() == "mF_9.B5f-4.1JqM" {
+        Ok(req)
+    } else {
+        let config = req.app_data::<bearer::Config>()
+            .cloned()
+            .unwrap_or_default()
+            .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
 
-        Err((AuthenticationError::from(config).into(), req))
+        Err((AuthenticationError::from(config).into(), req))
     }
 }
 
-let middleware = HttpAuthentication::bearer(validator);
+let middleware = HttpAuthentication::bearer(validator);

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

@@ -47,27 +47,27 @@ validation callback F.

Errors produced while building a transform service.

The future response value.

Creates and returns a new Transform component, asynchronously

-

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

+

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

-

Returns the argument unchanged.

+

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

-

Calls U::from(self).

+

Calls U::from(self).

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

Should always be Self

The resulting type after obtaining ownership.

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

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

-

The type returned in the event of a conversion error.

-

Performs the conversion.

-

The type returned in the event of a conversion error.

-

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

+

The type returned in the event of a conversion error.

+

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

-
\ No newline at end of file +
\ No newline at end of file diff --git a/ayu.css b/ayu.css index f98b3417c..8b2af515f 100644 --- a/ayu.css +++ b/ayu.css @@ -1 +1 @@ - :root{--main-background-color:#0f1419;--main-color:#c5c5c5;--settings-input-color:#ffb454;--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;}.slider{background-color:#ccc;}.slider:before{background-color:white;}input:focus+.slider{box-shadow:0 0 0 2px #0a84ff,0 0 0 6px rgba(10,132,255,0.3);}h1,h2,h3,h4{color:white;}h1.fqn a{color:#fff;}h4{border:none;}.in-band{background-color:#0f1419;}.docblock code{color:#ffb454;}.code-header{color:#e6e1cf;}.docblock pre>code,pre>code{color:#e6e1cf;}span code{color:#e6e1cf;}.docblock a>code{color:#39AFD7 !important;}pre,.rustdoc.source .example-wrap{color:#e6e1cf;}.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);}.sidebar .current,.sidebar a:hover{background-color:transparent;color:#ffb44c;}.sidebar-elems .location{color:#ff7733;}.line-numbers span{color:#5c6773;}.line-numbers .line-highlighted{color:#708090;background-color:rgba(255,236,164,0.06);padding-right:4px;border-right:1px solid #ffb44c;}.docblock table td,.docblock table th{border-color:#5c6773;}.search-results a:hover{background-color:#777;}.search-results a:focus{color:#000 !important;background-color:#c6afb3;}.search-results a{color:#0096cf;}.search-results a div.desc{color:#c5c5c5;}.content .item-info::before{color:#ccc;}.content span.foreigntype,.content a.foreigntype{color:#ffa0a5;}.content span.union,.content a.union{color:#ffa0a5;}.content span.constant,.content a.constant,.content span.static,.content a.static{color:#39AFD7;}.content span.primitive,.content a.primitive{color:#ffa0a5;}.content span.traitalias,.content a.traitalias{color:#39AFD7;}.content span.keyword,.content a.keyword{color:#39AFD7;}.content span.externcrate,.content span.mod,.content a.mod{color:#39AFD7;}.content span.struct,.content a.struct{color:#ffa0a5;}.content span.enum,.content a.enum{color:#ffa0a5;}.content span.trait,.content a.trait{color:#39AFD7;}.content span.type,.content a.type{color:#39AFD7;}.content span.type,.content a.type,.block a.current.type{color:#39AFD7;}.content span.associatedtype,.content a.associatedtype,.block a.current.associatedtype{color:#39AFD7;}.content span.fn,.content a.fn,.content span.method,.content a.method,.content span.tymethod,.content a.tymethod,.content .fnname{color:#fdd687;}.content span.attr,.content a.attr,.content span.derive,.content a.derive,.content span.macro,.content a.macro{color:#a37acc;}.sidebar a{color:#53b1db;}.sidebar a.current.type{color:#53b1db;}.sidebar a.current.associatedtype{color:#53b1db;}pre.rust .comment{color:#788797;}pre.rust .doccomment{color:#a1ac88;}nav.main .current{border-top-color:#5c6773;border-bottom-color:#5c6773;}nav.main .separator{border:1px solid #5c6773;}a{color:#39AFD7;}.sidebar h2 a,.sidebar h3 a{color:white;}.search-results a{color:#0096cf;}body.source .example-wrap pre.rust a{background:#333;}details.rustdoc-toggle>summary.hideme>span,details.rustdoc-toggle>summary::before{color:#999;}details.rustdoc-toggle>summary::before{filter:invert(100%);}#crate-search,.search-input{background-color:#141920;border-color:#424c57;}#crate-search{border-color:#424c57 !important;}.search-input{color:#ffffff;}.module-item .stab,.import-item .stab{color:#000;}.stab.empty-impl{}.stab.must_implement{}.stab.unstable,.stab.deprecated,.stab.portability,.stab.empty-impl,.stab.must_implement{color:#c5c5c5;background:#314559 !important;border-style:none !important;border-radius:4px;padding:3px 6px 3px 6px;}.stab.portability>code{color:#e6e1cf;background:none;}.rightside,.out-of-band{color:grey;}.result-name .primitive>i,.result-name .keyword>i{color:#788797;}.line-numbers :target{background-color:transparent;}pre.rust .number,pre.rust .string{color:#b8cc52;}pre.rust .kw,pre.rust .kw-2,pre.rust .prelude-ty,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .op,pre.rust .lifetime{color:#ff7733;}pre.rust .macro,pre.rust .macro-nonterminal{color:#a37acc;}pre.rust .question-mark{color:#ff9011;}pre.rust .self{color:#36a3d9;font-style:italic;}pre.rust .attribute{color:#e6e1cf;}pre.rust .attribute .ident,pre.rust .attribute .op{color:#e6e1cf;}.example-wrap>pre.line-number{color:#5c67736e;border:none;}a.test-arrow{font-size:100%;color:#788797;border-radius:4px;background-color:rgba(57,175,215,0.09);}a.test-arrow:hover{background-color:rgba(57,175,215,0.368);color:#c5c5c5;}.toggle-label,.code-attribute{color:#999;}:target{background:rgba(255,236,164,0.06);border-right:3px solid rgba(255,180,76,0.85);}pre.compile_fail{border-left:2px solid rgba(255,0,0,.4);}pre.compile_fail:hover,.information:hover+pre.compile_fail{border-left:2px solid #f00;}pre.should_panic{border-left:2px solid rgba(255,0,0,.4);}pre.should_panic:hover,.information:hover+pre.should_panic{border-left:2px solid #f00;}pre.ignore{border-left:2px solid rgba(255,142,0,.6);}pre.ignore:hover,.information:hover+pre.ignore{border-left:2px solid #ff9200;}.tooltip.compile_fail{color:rgba(255,0,0,.5);}.information>.compile_fail:hover{color:#f00;}.tooltip.should_panic{color:rgba(255,0,0,.5);}.information>.should_panic:hover{color:#f00;}.tooltip.ignore{color:rgba(255,142,0,.6);}.information>.ignore:hover{color:#ff9200;}.search-failed a{color:#39AFD7;}.tooltip::after{background-color:#314559;color:#c5c5c5;border:1px solid #5c6773;}.tooltip::before{border-color:transparent #314559 transparent transparent;}.notable-traits-tooltiptext{background-color:#314559;border-color:#5c6773;}.notable-traits-tooltiptext .notable{border-bottom-color:#5c6773;}#titles>button.selected{background-color:#141920 !important;border-bottom:1px solid #ffb44c !important;border-top:none;}#titles>button:not(.selected){background-color:transparent !important;border:none;}#titles>button:hover{border-bottom:1px solid rgba(242,151,24,0.3);}#titles>button>div.count{color:#888;}.search-input:focus{}.content span.attr,.content a.attr,.block a.current.attr,.content span.derive,.content a.derive,.block a.current.derive,.content span.macro,.content a.macro,.block a.current.macro{}.content span.struct,.content a.struct,.block a.current.struct{}#titles>button:hover,#titles>button.selected{}.content span.typedef,.content a.typedef,.block a.current.typedef{}.content span.union,.content a.union,.block a.current.union{}pre.rust .lifetime{}.stab.unstable{}h2,h3:not(.impl):not(.method):not(.type):not(.tymethod),h4:not(.method):not(.type):not(.tymethod){}.content span.enum,.content a.enum,.block a.current.enum{}.content span.constant,.content a.constant,.block a.current.constant,.content span.static,.content a.static,.block a.current.static{}.content span.keyword,.content a.keyword,.block a.current.keyword{}pre.rust .comment{}.content span.traitalias,.content a.traitalias,.block a.current.traitalias{}.content span.fn,.content a.fn,.block a.current.fn,.content span.method,.content a.method,.block a.current.method,.content span.tymethod,.content a.tymethod,.block a.current.tymethod,.content .fnname{}pre.rust .kw{}pre.rust .self,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .attribute,pre.rust .attribute .ident{}.content span.foreigntype,.content a.foreigntype,.block a.current.foreigntype{}pre.rust .doccomment{}.stab.deprecated{}.content a.attr,.content a.derive,.content a.macro{}.stab.portability{}.content span.primitive,.content a.primitive,.block a.current.primitive{}.content span.externcrate,.content span.mod,.content a.mod,.block a.current.mod{}pre.rust .kw-2,pre.rust .prelude-ty{}.content span.trait,.content a.trait,.block a.current.trait{}.search-results a:focus span{}a.result-trait:focus{}a.result-traitalias:focus{}a.result-mod:focus,a.result-externcrate:focus{}a.result-mod:focus{}a.result-externcrate:focus{}a.result-enum:focus{}a.result-struct:focus{}a.result-union:focus{}a.result-fn:focus,a.result-method:focus,a.result-tymethod:focus{}a.result-type:focus{}a.result-associatedtype:focus{}a.result-foreigntype:focus{}a.result-attr:focus,a.result-derive:focus,a.result-macro:focus{}a.result-constant:focus,a.result-static:focus{}a.result-primitive:focus{}a.result-keyword:focus{}.sidebar a.current.enum{}.sidebar a.current.struct{}.sidebar a.current.foreigntype{}.sidebar a.current.attr,.sidebar a.current.derive,.sidebar a.current.macro{}.sidebar a.current.union{}.sidebar a.current.constant .sidebar a.current.static{}.sidebar a.current.primitive{}.sidebar a.current.externcrate .sidebar a.current.mod{}.sidebar a.current.trait{}.sidebar a.current.traitalias{}.sidebar a.current.fn,.sidebar a.current.method,.sidebar a.current.tymethod{}.sidebar a.current.keyword{}@media (max-width:700px){.sidebar-elems{border-right-color:#5c6773;}}kbd{color:#c5c5c5;background-color:#314559;border-color:#5c6773;border-bottom-color:#5c6773;box-shadow:inset 0 -1px 0 #5c6773;}#settings-menu>a,#help-button>button{border-color:#5c6773;background-color:#0f1419;color:#fff;}#settings-menu>a img{filter:invert(100);}.popover,.popover::before,#help-button span.top,#help-button span.bottom{border-color:#5c6773;}#copy-path{color:#fff;}#copy-path>img{filter:invert(70%);}#copy-path:hover>img{filter:invert(100%);}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>button:hover,#help-button>button:focus{border-color:#e0e0e0;}#theme-choices{border-color:#5c6773;background-color:#0f1419;}#theme-choices>button:not(:first-child){border-top-color:#5c6773;}#theme-choices>button:hover,#theme-choices>button:focus{background-color:rgba(110,110,110,0.33);}.search-results .result-name span.alias{color:#c5c5c5;}.search-results .result-name span.grey{color:#999;}#source-sidebar>.title{color:#fff;border-bottom-color:#5c6773;}#source-sidebar div.files>a:hover,details.dir-entry summary:hover,#source-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:#14191f;color:#ffb44c;}#source-sidebar div.files>a.selected{background-color:#14191f;color:#ffb44c;}.scraped-example-list .scrape-help{border-color:#aaa;color:#eee;}.scraped-example-list .scrape-help:hover{border-color:white;color:white;}.more-examples-toggle summary,.more-examples-toggle .hide-more{color:#999;}.scraped-example .example-wrap .rust span.highlight{background:rgb(91,59,1);}.scraped-example .example-wrap .rust span.highlight.focus{background:rgb(124,75,15);}.scraped-example:not(.expanded) .code-wrapper:before{background:linear-gradient(to bottom,rgba(15,20,25,1),rgba(15,20,25,0));}.scraped-example:not(.expanded) .code-wrapper:after{background:linear-gradient(to top,rgba(15,20,25,1),rgba(15,20,25,0));}.toggle-line-inner{background:#999;}.toggle-line:hover .toggle-line-inner{background:#c5c5c5;} \ No newline at end of file + :root{--main-background-color:#0f1419;--main-color:#c5c5c5;--settings-input-color:#ffb454;--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;}.slider{background-color:#ccc;}.slider:before{background-color:white;}input:focus+.slider{box-shadow:0 0 0 2px #0a84ff,0 0 0 6px rgba(10,132,255,0.3);}h1,h2,h3,h4{color:white;}h1.fqn a{color:#fff;}h4{border:none;}.docblock code{color:#ffb454;}.code-header{color:#e6e1cf;}.docblock pre>code,pre>code{color:#e6e1cf;}span code{color:#e6e1cf;}.docblock a>code{color:#39AFD7 !important;}pre,.rustdoc.source .example-wrap{color:#e6e1cf;}.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);}.sidebar .current,.sidebar a:hover{background-color:transparent;color:#ffb44c;}.sidebar-elems .location{color:#ff7733;}.line-numbers span{color:#5c6773;}.line-numbers .line-highlighted{color:#708090;background-color:rgba(255,236,164,0.06);padding-right:4px;border-right:1px solid #ffb44c;}.search-results a:hover{background-color:#777;}.search-results a:focus{color:#000 !important;background-color:#c6afb3;}.search-results a{color:#0096cf;}.search-results a div.desc{color:#c5c5c5;}.content .item-info::before{color:#ccc;}.content span.foreigntype,.content a.foreigntype{color:#ffa0a5;}.content span.union,.content a.union{color:#ffa0a5;}.content span.constant,.content a.constant,.content span.static,.content a.static{color:#39AFD7;}.content span.primitive,.content a.primitive{color:#ffa0a5;}.content span.traitalias,.content a.traitalias{color:#39AFD7;}.content span.keyword,.content a.keyword{color:#39AFD7;}.content span.externcrate,.content span.mod,.content a.mod{color:#39AFD7;}.content span.struct,.content a.struct{color:#ffa0a5;}.content span.enum,.content a.enum{color:#ffa0a5;}.content span.trait,.content a.trait{color:#39AFD7;}.content span.type,.content a.type{color:#39AFD7;}.content span.type,.content a.type,.block a.current.type{color:#39AFD7;}.content span.associatedtype,.content a.associatedtype,.block a.current.associatedtype{color:#39AFD7;}.content span.fn,.content a.fn,.content span.method,.content a.method,.content span.tymethod,.content a.tymethod,.content .fnname{color:#fdd687;}.content span.attr,.content a.attr,.content span.derive,.content a.derive,.content span.macro,.content a.macro{color:#a37acc;}.sidebar a{color:#53b1db;}.sidebar a.current.type{color:#53b1db;}.sidebar a.current.associatedtype{color:#53b1db;}pre.rust .comment{color:#788797;}pre.rust .doccomment{color:#a1ac88;}a{color:#39AFD7;}.sidebar h2 a,.sidebar h3 a{color:white;}.search-results a{color:#0096cf;}body.source .example-wrap pre.rust a{background:#333;}details.rustdoc-toggle>summary.hideme>span,details.rustdoc-toggle>summary::before{color:#999;}details.rustdoc-toggle>summary::before{filter:invert(100%);}#crate-search-div::after{filter:invert(41%) sepia(12%) saturate(487%) hue-rotate(171deg) brightness(94%) contrast(94%);}#crate-search:hover,#crate-search:focus{border-color:#e0e0e0 !important;}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg) brightness(113%) contrast(76%);}.search-input{color:#fff;}.module-item .stab,.import-item .stab{color:#000;}.stab{color:#c5c5c5;background:#314559 !important;}.stab.portability>code{color:#e6e1cf;background:none;}.rightside,.out-of-band{color:grey;}.result-name .primitive>i,.result-name .keyword>i{color:#788797;}.line-numbers :target{background-color:transparent;}pre.rust .number,pre.rust .string{color:#b8cc52;}pre.rust .kw,pre.rust .kw-2,pre.rust .prelude-ty,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .lifetime{color:#ff7733;}pre.rust .macro,pre.rust .macro-nonterminal{color:#a37acc;}pre.rust .question-mark{color:#ff9011;}pre.rust .self{color:#36a3d9;font-style:italic;}pre.rust .attribute{color:#e6e1cf;}.example-wrap>pre.line-number{color:#5c67736e;border:none;}a.test-arrow{font-size:100%;color:#788797;border-radius:4px;background-color:rgba(57,175,215,0.09);}a.test-arrow:hover{background-color:rgba(57,175,215,0.368);color:#c5c5c5;}.toggle-label,.code-attribute{color:#999;}:target{background:rgba(255,236,164,0.06);border-right:3px solid rgba(255,180,76,0.85);}pre.compile_fail{border-left:2px solid rgba(255,0,0,.4);}pre.compile_fail:hover,.information:hover+pre.compile_fail{border-left:2px solid #f00;}pre.should_panic{border-left:2px solid rgba(255,0,0,.4);}pre.should_panic:hover,.information:hover+pre.should_panic{border-left:2px solid #f00;}pre.ignore{border-left:2px solid rgba(255,142,0,.6);}pre.ignore:hover,.information:hover+pre.ignore{border-left:2px solid #ff9200;}.tooltip.compile_fail{color:rgba(255,0,0,.5);}.information>.compile_fail:hover{color:#f00;}.tooltip.should_panic{color:rgba(255,0,0,.5);}.information>.should_panic:hover{color:#f00;}.tooltip.ignore{color:rgba(255,142,0,.6);}.information>.ignore:hover{color:#ff9200;}.search-failed a{color:#39AFD7;}.tooltip::after{background-color:#314559;color:#c5c5c5;}.tooltip::before{border-color:transparent #314559 transparent transparent;}.notable-traits-tooltiptext{background-color:#314559;}#titles>button.selected{background-color:#141920 !important;border-bottom:1px solid #ffb44c !important;border-top:none;}#titles>button:not(.selected){background-color:transparent !important;border:none;}#titles>button:hover{border-bottom:1px solid rgba(242,151,24,0.3);}#titles>button>div.count{color:#888;}.search-input:focus{}.content span.attr,.content a.attr,.block a.current.attr,.content span.derive,.content a.derive,.block a.current.derive,.content span.macro,.content a.macro,.block a.current.macro{}.content span.struct,.content a.struct,.block a.current.struct{}#titles>button:hover,#titles>button.selected{}.content span.typedef,.content a.typedef,.block a.current.typedef{}.content span.union,.content a.union,.block a.current.union{}pre.rust .lifetime{}.stab.unstable{}h2,h3:not(.impl):not(.method):not(.type):not(.tymethod),h4:not(.method):not(.type):not(.tymethod){}.content span.enum,.content a.enum,.block a.current.enum{}.content span.constant,.content a.constant,.block a.current.constant,.content span.static,.content a.static,.block a.current.static{}.content span.keyword,.content a.keyword,.block a.current.keyword{}pre.rust .comment{}.content span.traitalias,.content a.traitalias,.block a.current.traitalias{}.content span.fn,.content a.fn,.block a.current.fn,.content span.method,.content a.method,.block a.current.method,.content span.tymethod,.content a.tymethod,.block a.current.tymethod,.content .fnname{}pre.rust .kw{}pre.rust .self,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .attribute{}.content span.foreigntype,.content a.foreigntype,.block a.current.foreigntype{}pre.rust .doccomment{}.stab.deprecated{}.content a.attr,.content a.derive,.content a.macro{}.stab.portability{}.content span.primitive,.content a.primitive,.block a.current.primitive{}.content span.externcrate,.content span.mod,.content a.mod,.block a.current.mod{}pre.rust .kw-2,pre.rust .prelude-ty{}.content span.trait,.content a.trait,.block a.current.trait{}.search-results a:focus span{}a.result-trait:focus{}a.result-traitalias:focus{}a.result-mod:focus,a.result-externcrate:focus{}a.result-mod:focus{}a.result-externcrate:focus{}a.result-enum:focus{}a.result-struct:focus{}a.result-union:focus{}a.result-fn:focus,a.result-method:focus,a.result-tymethod:focus{}a.result-type:focus{}a.result-associatedtype:focus{}a.result-foreigntype:focus{}a.result-attr:focus,a.result-derive:focus,a.result-macro:focus{}a.result-constant:focus,a.result-static:focus{}a.result-primitive:focus{}a.result-keyword:focus{}.sidebar a.current.enum{}.sidebar a.current.struct{}.sidebar a.current.foreigntype{}.sidebar a.current.attr,.sidebar a.current.derive,.sidebar a.current.macro{}.sidebar a.current.union{}.sidebar a.current.constant .sidebar a.current.static{}.sidebar a.current.primitive{}.sidebar a.current.externcrate .sidebar a.current.mod{}.sidebar a.current.trait{}.sidebar a.current.traitalias{}.sidebar a.current.fn,.sidebar a.current.method,.sidebar a.current.tymethod{}.sidebar a.current.keyword{}kbd{color:#c5c5c5;background-color:#314559;box-shadow:inset 0 -1px 0 #5c6773;}#settings-menu>a,#help-button>button{color:#fff;}#settings-menu>a img{filter:invert(100);}#copy-path{color:#fff;}#copy-path>img{filter:invert(70%);}#copy-path:hover>img{filter:invert(100%);}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>button:hover,#help-button>button:focus{border-color:#e0e0e0;}.search-results .result-name span.alias{color:#c5c5c5;}.search-results .result-name span.grey{color:#999;}#source-sidebar>.title{color:#fff;}#source-sidebar div.files>a:hover,details.dir-entry summary:hover,#source-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:#14191f;color:#ffb44c;}#source-sidebar div.files>a.selected{background-color:#14191f;color:#ffb44c;}.scraped-example-list .scrape-help{border-color:#aaa;color:#eee;}.scraped-example-list .scrape-help:hover{border-color:white;color:white;}.more-examples-toggle summary,.more-examples-toggle .hide-more{color:#999;}.scraped-example .example-wrap .rust span.highlight{background:rgb(91,59,1);}.scraped-example .example-wrap .rust span.highlight.focus{background:rgb(124,75,15);}.scraped-example:not(.expanded) .code-wrapper:before{background:linear-gradient(to bottom,rgba(15,20,25,1),rgba(15,20,25,0));}.scraped-example:not(.expanded) .code-wrapper:after{background:linear-gradient(to top,rgba(15,20,25,1),rgba(15,20,25,0));}.toggle-line-inner{background:#999;}.toggle-line:hover .toggle-line-inner{background:#c5c5c5;} \ No newline at end of file diff --git a/dark.css b/dark.css index 242423d03..1a8639805 100644 --- a/dark.css +++ b/dark.css @@ -1 +1 @@ -:root{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--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;}.slider{background-color:#ccc;}.slider:before{background-color:white;}input:focus+.slider{box-shadow:0 0 0 2px #0a84ff,0 0 0 6px rgba(10,132,255,0.3);}.in-band{background-color:#353535;}.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)}.sidebar .current,.sidebar a:hover{background:#444;}.line-numbers span{color:#3B91E2;}.line-numbers .line-highlighted{background-color:#0a042f !important;}.docblock table td,.docblock table th{border-color:#ddd;}.search-results a:hover{background-color:#777;}.search-results a:focus{color:#eee !important;background-color:#616161;}.search-results a:focus span{color:#eee !important;}a.result-trait:focus{background-color:#013191;}a.result-traitalias:focus{background-color:#013191;}a.result-mod:focus,a.result-externcrate:focus{background-color:#884719;}a.result-enum:focus{background-color:#194e9f;}a.result-struct:focus{background-color:#194e9f;}a.result-union:focus{background-color:#194e9f;}a.result-fn:focus,a.result-method:focus,a.result-tymethod:focus{background-color:#4950ed;}a.result-type:focus{background-color:#194e9f;}a.result-associatedtype:focus{background-color:#884719;}a.result-foreigntype:focus{background-color:#194e9f;}a.result-attr:focus,a.result-derive:focus,a.result-macro:focus{background-color:#217d1c;}a.result-constant:focus,a.result-static:focus{background-color:#884719;}a.result-primitive:focus{background-color:#194e9f;}a.result-keyword:focus{background-color:#884719;}.content .item-info::before{color:#ccc;}.content span.enum,.content a.enum,.block a.current.enum{color:#2dbfb8;}.content span.struct,.content a.struct,.block a.current.struct{color:#2dbfb8;}.content span.type,.content a.type,.block a.current.type{color:#2dbfb8;}.content span.associatedtype,.content a.associatedtype,.block a.current.associatedtype{color:#D2991D;}.content span.foreigntype,.content a.foreigntype,.block a.current.foreigntype{color:#2dbfb8;}.content span.attr,.content a.attr,.block a.current.attr,.content span.derive,.content a.derive,.block a.current.derive,.content span.macro,.content a.macro,.block a.current.macro{color:#09bd00;}.content span.union,.content a.union,.block a.current.union{color:#2dbfb8;}.content span.constant,.content a.constant,.block a.current.constant,.content span.static,.content a.static,.block a.current.static{color:#D2991D;}.content span.primitive,.content a.primitive,.block a.current.primitive{color:#2dbfb8;}.content span.externcrate,.content span.mod,.content a.mod,.block a.current.mod{color:#D2991D;}.content span.trait,.content a.trait,.block a.current.trait{color:#b78cf2;}.content span.traitalias,.content a.traitalias,.block a.current.traitalias{color:#b78cf2;}.content span.fn,.content a.fn,.block a.current.fn,.content span.method,.content a.method,.block a.current.method,.content span.tymethod,.content a.tymethod,.block a.current.tymethod,.content .fnname{color:#2BAB63;}.content span.keyword,.content a.keyword,.block a.current.keyword{color:#D2991D;}.sidebar a{color:#fdbf35;}.sidebar a.current.enum{color:#12ece2;}.sidebar a.current.struct{color:#12ece2;}.sidebar a.current.type{color:#12ece2;}.sidebar a.current.associatedtype{color:#fdbf35;}.sidebar a.current.foreigntype{color:#12ece2;}.sidebar a.current.attr,.sidebar a.current.derive,.sidebar a.current.macro{color:#0be900;}.sidebar a.current.union{color:#12ece2;}.sidebar a.current.constant .sidebar a.current.static{color:#fdbf35;}.sidebar a.current.primitive{color:#12ece2;}.sidebar a.current.externcrate .sidebar a.current.mod{color:#fdbf35;}.sidebar a.current.trait{color:#cca7ff;}.sidebar a.current.traitalias{color:#cca7ff;}.sidebar a.current.fn,.sidebar a.current.method,.sidebar a.current.tymethod{color:#32d479;}.sidebar a.current.keyword{color:#fdbf35;}pre.rust .comment{color:#8d8d8b;}pre.rust .doccomment{color:#8ca375;}nav.main .current{border-top-color:#eee;border-bottom-color:#eee;}nav.main .separator{border-color:#eee;}a{color:#D2991D;}body.source .example-wrap pre.rust a{background:#333;}details.rustdoc-toggle>summary.hideme>span,details.rustdoc-toggle>summary::before{color:#999;}details.rustdoc-toggle>summary::before{filter:invert(100%);}#crate-search,.search-input{color:#111;background-color:#f0f0f0;border-color:#f0f0f0;}#crate-search{border-color:#f0f0f0 !important;}.search-input{border-color:#e0e0e0;}.search-input:focus{border-color:#008dfd;}.stab.empty-impl{background:#FFF5D6;border-color:#FFC600;color:#2f2f2f;}.stab.unstable{background:#FFF5D6;border-color:#FFC600;color:#2f2f2f;}.stab.deprecated{background:#ffc4c4;border-color:#db7b7b;color:#2f2f2f;}.stab.must_implement{background:#F3DFFF;border-color:#b07bdb;color:#2f2f2f;}.stab.portability{background:#F3DFFF;border-color:#b07bdb;color:#2f2f2f;}.stab.portability>code{background:none;}.rightside,.out-of-band{color:grey;}.line-numbers :target{background-color:transparent;}pre.rust .kw{color:#ab8ac1;}pre.rust .kw-2,pre.rust .prelude-ty{color:#769acb;}pre.rust .number,pre.rust .string{color:#83a300;}pre.rust .self,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .attribute,pre.rust .attribute .ident{color:#ee6868;}pre.rust .macro,pre.rust .macro-nonterminal{color:#3E999F;}pre.rust .lifetime{color:#d97f26;}pre.rust .question-mark{color:#ff9011;}.example-wrap>pre.line-number{border-color:#4a4949;}a.test-arrow{color:#dedede;background-color:rgba(78,139,202,0.2);}a.test-arrow:hover{background-color:#4e8bca;}.toggle-label,.code-attribute{color:#999;}:target{background-color:#494a3d;border-right:3px solid #bb7410;}pre.compile_fail{border-left:2px solid rgba(255,0,0,.8);}pre.compile_fail:hover,.information:hover+pre.compile_fail{border-left:2px solid #f00;}pre.should_panic{border-left:2px solid rgba(255,0,0,.8);}pre.should_panic:hover,.information:hover+pre.should_panic{border-left:2px solid #f00;}pre.ignore{border-left:2px solid rgba(255,142,0,.6);}pre.ignore:hover,.information:hover+pre.ignore{border-left:2px solid #ff9200;}.tooltip.compile_fail{color:rgba(255,0,0,.8);}.information>.compile_fail:hover{color:#f00;}.tooltip.should_panic{color:rgba(255,0,0,.8);}.information>.should_panic:hover{color:#f00;}.tooltip.ignore{color:rgba(255,142,0,.6);}.information>.ignore:hover{color:#ff9200;}.search-failed a{color:#0089ff;}.tooltip::after{background-color:#000;color:#fff;border-color:#000;}.tooltip::before{border-color:transparent black transparent transparent;}.notable-traits-tooltiptext{background-color:#111;border-color:#777;}.notable-traits-tooltiptext .notable{border-bottom-color:#d2d2d2;}#titles>button:not(.selected){background-color:#252525;border-top-color:#252525;}#titles>button:hover,#titles>button.selected{border-top-color:#0089ff;background-color:#353535;}#titles>button>div.count{color:#888;}@media (max-width:700px){.sidebar-elems{border-right-color:#000;}}kbd{color:#000;background-color:#fafbfc;border-color:#d1d5da;border-bottom-color:#c6cbd1;box-shadow:inset 0 -1px 0 #c6cbd1;}#settings-menu>a,#help-button>button{border-color:#e0e0e0;background:#f0f0f0;color:#000;}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>button:hover,#help-button>button:focus{border-color:#ffb900;}.popover,.popover::before,#help-button span.top,#help-button span.bottom{border-color:#d2d2d2;}#copy-path{color:#999;}#copy-path>img{filter:invert(50%);}#copy-path:hover>img{filter:invert(65%);}#theme-choices{border-color:#e0e0e0;background-color:#353535;}#theme-choices>button:not(:first-child){border-top-color:#e0e0e0;}#theme-choices>button:hover,#theme-choices>button:focus{background-color:#4e4e4e;}.search-results .result-name span.alias{color:#fff;}.search-results .result-name span.grey{color:#ccc;}#source-sidebar>.title{border-bottom-color:#ccc;}#source-sidebar div.files>a:hover,details.dir-entry summary:hover,#source-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:#444;}#source-sidebar div.files>a.selected{background-color:#333;}.scraped-example-list .scrape-help{border-color:#aaa;color:#eee;}.scraped-example-list .scrape-help:hover{border-color:white;color:white;}.more-examples-toggle summary,.more-examples-toggle .hide-more{color:#999;}.scraped-example .example-wrap .rust span.highlight{background:rgb(91,59,1);}.scraped-example .example-wrap .rust span.highlight.focus{background:rgb(124,75,15);}.scraped-example:not(.expanded) .code-wrapper:before{background:linear-gradient(to bottom,rgba(53,53,53,1),rgba(53,53,53,0));}.scraped-example:not(.expanded) .code-wrapper:after{background:linear-gradient(to top,rgba(53,53,53,1),rgba(53,53,53,0));}.toggle-line-inner{background:#999;}.toggle-line:hover .toggle-line-inner{background:#c5c5c5;} \ No newline at end of file +:root{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--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;}.slider{background-color:#ccc;}.slider:before{background-color:white;}input:focus+.slider{box-shadow:0 0 0 2px #0a84ff,0 0 0 6px rgba(10,132,255,0.3);}.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)}.sidebar .current,.sidebar a:hover{background:#444;}.line-numbers span{color:#3B91E2;}.line-numbers .line-highlighted{background-color:#0a042f !important;}.search-results a:hover{background-color:#777;}.search-results a:focus{color:#eee !important;background-color:#616161;}.search-results a:focus span{color:#eee !important;}a.result-trait:focus{background-color:#013191;}a.result-traitalias:focus{background-color:#013191;}a.result-mod:focus,a.result-externcrate:focus{background-color:#884719;}a.result-enum:focus{background-color:#194e9f;}a.result-struct:focus{background-color:#194e9f;}a.result-union:focus{background-color:#194e9f;}a.result-fn:focus,a.result-method:focus,a.result-tymethod:focus{background-color:#4950ed;}a.result-type:focus{background-color:#194e9f;}a.result-associatedtype:focus{background-color:#884719;}a.result-foreigntype:focus{background-color:#194e9f;}a.result-attr:focus,a.result-derive:focus,a.result-macro:focus{background-color:#217d1c;}a.result-constant:focus,a.result-static:focus{background-color:#884719;}a.result-primitive:focus{background-color:#194e9f;}a.result-keyword:focus{background-color:#884719;}.content .item-info::before{color:#ccc;}.content span.enum,.content a.enum,.block a.current.enum{color:#2dbfb8;}.content span.struct,.content a.struct,.block a.current.struct{color:#2dbfb8;}.content span.type,.content a.type,.block a.current.type{color:#2dbfb8;}.content span.associatedtype,.content a.associatedtype,.block a.current.associatedtype{color:#D2991D;}.content span.foreigntype,.content a.foreigntype,.block a.current.foreigntype{color:#2dbfb8;}.content span.attr,.content a.attr,.block a.current.attr,.content span.derive,.content a.derive,.block a.current.derive,.content span.macro,.content a.macro,.block a.current.macro{color:#09bd00;}.content span.union,.content a.union,.block a.current.union{color:#2dbfb8;}.content span.constant,.content a.constant,.block a.current.constant,.content span.static,.content a.static,.block a.current.static{color:#D2991D;}.content span.primitive,.content a.primitive,.block a.current.primitive{color:#2dbfb8;}.content span.externcrate,.content span.mod,.content a.mod,.block a.current.mod{color:#D2991D;}.content span.trait,.content a.trait,.block a.current.trait{color:#b78cf2;}.content span.traitalias,.content a.traitalias,.block a.current.traitalias{color:#b78cf2;}.content span.fn,.content a.fn,.block a.current.fn,.content span.method,.content a.method,.block a.current.method,.content span.tymethod,.content a.tymethod,.block a.current.tymethod,.content .fnname{color:#2BAB63;}.content span.keyword,.content a.keyword,.block a.current.keyword{color:#D2991D;}.sidebar a{color:#fdbf35;}.sidebar a.current.enum{color:#12ece2;}.sidebar a.current.struct{color:#12ece2;}.sidebar a.current.type{color:#12ece2;}.sidebar a.current.associatedtype{color:#fdbf35;}.sidebar a.current.foreigntype{color:#12ece2;}.sidebar a.current.attr,.sidebar a.current.derive,.sidebar a.current.macro{color:#0be900;}.sidebar a.current.union{color:#12ece2;}.sidebar a.current.constant .sidebar a.current.static{color:#fdbf35;}.sidebar a.current.primitive{color:#12ece2;}.sidebar a.current.externcrate .sidebar a.current.mod{color:#fdbf35;}.sidebar a.current.trait{color:#cca7ff;}.sidebar a.current.traitalias{color:#cca7ff;}.sidebar a.current.fn,.sidebar a.current.method,.sidebar a.current.tymethod{color:#32d479;}.sidebar a.current.keyword{color:#fdbf35;}pre.rust .comment{color:#8d8d8b;}pre.rust .doccomment{color:#8ca375;}a{color:#D2991D;}body.source .example-wrap pre.rust a{background:#333;}details.rustdoc-toggle>summary.hideme>span,details.rustdoc-toggle>summary::before{color:#999;}details.rustdoc-toggle>summary::before{filter:invert(100%);}.search-input{color:#111;border-color:#f0f0f0;}#crate-search-div::after{filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);}#crate-search:hover,#crate-search:focus{border-color:#2196f3 !important;}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);}.search-input:focus{border-color:#008dfd;}.stab{background:#314559;}.stab.portability>code{color:#e6e1cf;background:none;}.rightside,.out-of-band{color:grey;}.line-numbers :target{background-color:transparent;}pre.rust .kw{color:#ab8ac1;}pre.rust .kw-2,pre.rust .prelude-ty{color:#769acb;}pre.rust .number,pre.rust .string{color:#83a300;}pre.rust .self,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .attribute{color:#ee6868;}pre.rust .macro,pre.rust .macro-nonterminal{color:#3E999F;}pre.rust .lifetime{color:#d97f26;}pre.rust .question-mark{color:#ff9011;}.example-wrap>pre.line-number{border-color:#4a4949;}a.test-arrow{color:#dedede;background-color:rgba(78,139,202,0.2);}a.test-arrow:hover{background-color:#4e8bca;}.toggle-label,.code-attribute{color:#999;}:target{background-color:#494a3d;border-right:3px solid #bb7410;}pre.compile_fail{border-left:2px solid rgba(255,0,0,.8);}pre.compile_fail:hover,.information:hover+pre.compile_fail{border-left:2px solid #f00;}pre.should_panic{border-left:2px solid rgba(255,0,0,.8);}pre.should_panic:hover,.information:hover+pre.should_panic{border-left:2px solid #f00;}pre.ignore{border-left:2px solid rgba(255,142,0,.6);}pre.ignore:hover,.information:hover+pre.ignore{border-left:2px solid #ff9200;}.tooltip.compile_fail{color:rgba(255,0,0,.8);}.information>.compile_fail:hover{color:#f00;}.tooltip.should_panic{color:rgba(255,0,0,.8);}.information>.should_panic:hover{color:#f00;}.tooltip.ignore{color:rgba(255,142,0,.6);}.information>.ignore:hover{color:#ff9200;}.search-failed a{color:#0089ff;}.tooltip::after{background-color:#000;color:#fff;border-color:#000;}.tooltip::before{border-color:transparent black transparent transparent;}.notable-traits-tooltiptext{background-color:#111;}#titles>button:not(.selected){background-color:#252525;border-top-color:#252525;}#titles>button:hover,#titles>button.selected{border-top-color:#0089ff;background-color:#353535;}#titles>button>div.count{color:#888;}kbd{color:#000;background-color:#fafbfc;box-shadow:inset 0 -1px 0 #c6cbd1;}#settings-menu>a,#help-button>button{color:#000;}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>button:hover,#help-button>button:focus{border-color:#ffb900;}#copy-path{color:#999;}#copy-path>img{filter:invert(50%);}#copy-path:hover>img{filter:invert(65%);}.search-results .result-name span.alias{color:#fff;}.search-results .result-name span.grey{color:#ccc;}#source-sidebar div.files>a:hover,details.dir-entry summary:hover,#source-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:#444;}#source-sidebar div.files>a.selected{background-color:#333;}.scraped-example-list .scrape-help{border-color:#aaa;color:#eee;}.scraped-example-list .scrape-help:hover{border-color:white;color:white;}.more-examples-toggle summary,.more-examples-toggle .hide-more{color:#999;}.scraped-example .example-wrap .rust span.highlight{background:rgb(91,59,1);}.scraped-example .example-wrap .rust span.highlight.focus{background:rgb(124,75,15);}.scraped-example:not(.expanded) .code-wrapper:before{background:linear-gradient(to bottom,rgba(53,53,53,1),rgba(53,53,53,0));}.scraped-example:not(.expanded) .code-wrapper:after{background:linear-gradient(to top,rgba(53,53,53,1),rgba(53,53,53,0));}.toggle-line-inner{background:#999;}.toggle-line:hover .toggle-line-inner{background:#c5c5c5;} \ No newline at end of file diff --git a/down-arrow.svg b/down-arrow.svg index 35437e77a..5d76a64e9 100644 --- a/down-arrow.svg +++ b/down-arrow.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/implementors/actix_web/extract/trait.FromRequest.js b/implementors/actix_web/extract/trait.FromRequest.js index 5bd0672b1..513052dae 100644 --- a/implementors/actix_web/extract/trait.FromRequest.js +++ b/implementors/actix_web/extract/trait.FromRequest.js @@ -1,6 +1,6 @@ (function() {var implementors = { "actix_identity":[["impl FromRequest for Identity"]], -"actix_protobuf":[["impl<T> FromRequest for ProtoBuf<T> where
    T: Message + Default + 'static, 
"]], +"actix_protobuf":[["impl<T> FromRequest for ProtoBuf<T> where
    T: Message + Default + 'static, 
"]], "actix_session":[["impl FromRequest for Session"]], "actix_web_httpauth":[["impl FromRequest for BasicAuth"],["impl FromRequest for BearerAuth"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/actix_web/response/responder/trait.Responder.js b/implementors/actix_web/response/responder/trait.Responder.js index 0e837e07c..330a02733 100644 --- a/implementors/actix_web/response/responder/trait.Responder.js +++ b/implementors/actix_web/response/responder/trait.Responder.js @@ -1,3 +1,3 @@ (function() {var implementors = { -"actix_protobuf":[["impl<T: Message + Default> Responder for ProtoBuf<T>"]] +"actix_protobuf":[["impl<T: Message + Default> Responder for ProtoBuf<T>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/core/convert/trait.From.js b/implementors/core/convert/trait.From.js index 72c9f8dfd..1efb212af 100644 --- a/implementors/core/convert/trait.From.js +++ b/implementors/core/convert/trait.From.js @@ -1,8 +1,8 @@ (function() {var implementors = { "actix_limitation":[["impl From<ComponentRange> for Error"],["impl From<RedisError> for Error"]], -"actix_protobuf":[["impl From<PayloadError> for ProtoBufPayloadError"],["impl From<DecodeError> for ProtoBufPayloadError"]], +"actix_protobuf":[["impl From<PayloadError> for ProtoBufPayloadError"],["impl From<DecodeError> for ProtoBufPayloadError"]], "actix_redis":[["impl From<Error> for Error"]], -"actix_session":[["impl From<PersistentSession> for SessionLifecycle"],["impl From<BrowserSession> for SessionLifecycle"],["impl From<Error> for SessionGetError"],["impl From<Error> for SessionInsertError"],["impl From<SessionKey> for String"]], +"actix_session":[["impl From<PersistentSession> for SessionLifecycle"],["impl From<BrowserSession> for SessionLifecycle"],["impl From<Error> for SessionGetError"],["impl From<Error> for SessionInsertError"],["impl From<SessionKey> for String"]], "actix_settings":[["impl From<Error> for Error"],["impl From<IoError> for Error"],["impl From<ParseBoolError> for Error"],["impl From<ParseIntError> for Error"],["impl From<Error> for Error"],["impl From<VarError> for Error"],["impl From<Error> for Error"]], "actix_web_httpauth":[["impl<T> From<T> for AuthenticationError<<T as AuthExtractorConfig>::Inner> where
    T: AuthExtractorConfig
"],["impl From<ToStrError> for ParseError"],["impl From<DecodeError> for ParseError"],["impl From<Utf8Error> for ParseError"],["impl<S: Scheme> From<S> for Authorization<S>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/core/error/trait.Error.js b/implementors/core/error/trait.Error.js new file mode 100644 index 000000000..2b7e31c82 --- /dev/null +++ b/implementors/core/error/trait.Error.js @@ -0,0 +1,7 @@ +(function() {var implementors = { +"actix_cors":[["impl Error for CorsError"]], +"actix_limitation":[["impl Error for Error"]], +"actix_redis":[["impl Error for Error"]], +"actix_session":[["impl Error for SessionGetError"],["impl Error for SessionInsertError"],["impl Error for LoadError"],["impl Error for SaveError"],["impl Error for UpdateError"]], +"actix_web_httpauth":[["impl<C: Challenge + 'static> Error for AuthenticationError<C>"],["impl Error for ParseError"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/core/fmt/trait.Debug.js b/implementors/core/fmt/trait.Debug.js index 000fc8d50..55ddc3bc5 100644 --- a/implementors/core/fmt/trait.Debug.js +++ b/implementors/core/fmt/trait.Debug.js @@ -2,7 +2,7 @@ "actix_cors":[["impl Debug for Cors"],["impl Debug for CorsError"]], "actix_identity":[["impl Debug for LogoutBehaviour"],["impl Debug for IdentityMiddlewareBuilder"]], "actix_limitation":[["impl Debug for Builder"],["impl Debug for Error"],["impl Debug for RateLimiter"],["impl Debug for Status"],["impl Debug for Limiter"]], -"actix_protobuf":[["impl Debug for ProtoBufPayloadError"],["impl<T: Message> Debug for ProtoBuf<T> where
    T: Debug
"]], +"actix_protobuf":[["impl Debug for ProtoBufPayloadError"],["impl<T: Message> Debug for ProtoBuf<T> where
    T: Debug
"]], "actix_redis":[["impl Debug for Command"],["impl Debug for Error"]], "actix_session":[["impl Debug for SessionLifecycle"],["impl Debug for BrowserSession"],["impl Debug for PersistentSession"],["impl Debug for TtlExtensionPolicy"],["impl Debug for CookieContentSecurity"],["impl Debug for SessionStatus"],["impl Debug for SessionGetError"],["impl Debug for SessionInsertError"],["impl Debug for LoadError"],["impl Debug for SaveError"],["impl Debug for UpdateError"],["impl Debug for SessionKey"]], "actix_settings":[["impl Debug for Error"],["impl Debug for Address"],["impl Debug for Backlog"],["impl Debug for KeepAlive"],["impl Debug for MaxConnectionRate"],["impl Debug for MaxConnections"],["impl Debug for Mode"],["impl Debug for NumWorkers"],["impl Debug for Timeout"],["impl Debug for Tls"],["impl Debug for ActixSettings"],["impl<A: Debug> Debug for BasicSettings<A>"],["impl Debug for NoSettings"]], diff --git a/implementors/core/fmt/trait.Display.js b/implementors/core/fmt/trait.Display.js index f780f1666..4e17a9919 100644 --- a/implementors/core/fmt/trait.Display.js +++ b/implementors/core/fmt/trait.Display.js @@ -1,7 +1,7 @@ (function() {var implementors = { "actix_cors":[["impl Display for CorsError"]], "actix_limitation":[["impl Display for Error"]], -"actix_protobuf":[["impl Display for ProtoBufPayloadError"],["impl<T: Message> Display for ProtoBuf<T> where
    T: Display
"]], +"actix_protobuf":[["impl Display for ProtoBufPayloadError"],["impl<T: Message> Display for ProtoBuf<T> where
    T: Display
"]], "actix_redis":[["impl Display for Error"]], "actix_session":[["impl Display for SessionGetError"],["impl Display for SessionInsertError"],["impl Display for LoadError"],["impl Display for SaveError"],["impl Display for UpdateError"]], "actix_web_httpauth":[["impl<C: Challenge> Display for AuthenticationError<C>"],["impl Display for ParseError"],["impl<S: Scheme> Display for Authorization<S>"],["impl Display for Basic"],["impl Display for Bearer"],["impl Display for Basic"],["impl Display for Bearer"],["impl Display for Error"]] diff --git a/implementors/core/future/future/trait.Future.js b/implementors/core/future/future/trait.Future.js index 6bf3d490e..e8231046c 100644 --- a/implementors/core/future/future/trait.Future.js +++ b/implementors/core/future/future/trait.Future.js @@ -1,3 +1,3 @@ (function() {var implementors = { -"actix_protobuf":[["impl<T: Message + Default + 'static> Future for ProtoBufMessage<T>"]] +"actix_protobuf":[["impl<T: Message + Default + 'static> Future for ProtoBufMessage<T>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/core/ops/deref/trait.Deref.js b/implementors/core/ops/deref/trait.Deref.js index e731ee9d8..ba7439742 100644 --- a/implementors/core/ops/deref/trait.Deref.js +++ b/implementors/core/ops/deref/trait.Deref.js @@ -1,3 +1,3 @@ (function() {var implementors = { -"actix_protobuf":[["impl<T: Message> Deref for ProtoBuf<T>"]] +"actix_protobuf":[["impl<T: Message> Deref for ProtoBuf<T>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/core/ops/deref/trait.DerefMut.js b/implementors/core/ops/deref/trait.DerefMut.js index fa43e549a..f9e72dd26 100644 --- a/implementors/core/ops/deref/trait.DerefMut.js +++ b/implementors/core/ops/deref/trait.DerefMut.js @@ -1,3 +1,3 @@ (function() {var implementors = { -"actix_protobuf":[["impl<T: Message> DerefMut for ProtoBuf<T>"]] +"actix_protobuf":[["impl<T: Message> DerefMut for ProtoBuf<T>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/serde/de/trait.Deserialize.js b/implementors/serde/de/trait.Deserialize.js index c69d874a5..f1c1c347f 100644 --- a/implementors/serde/de/trait.Deserialize.js +++ b/implementors/serde/de/trait.Deserialize.js @@ -1,3 +1,3 @@ (function() {var implementors = { -"actix_settings":[["impl<'de> Deserialize<'de> for Address"],["impl<'de> Deserialize<'de> for Backlog"],["impl<'de> Deserialize<'de> for KeepAlive"],["impl<'de> Deserialize<'de> for MaxConnectionRate"],["impl<'de> Deserialize<'de> for MaxConnections"],["impl<'de> Deserialize<'de> for Mode"],["impl<'de> Deserialize<'de> for NumWorkers"],["impl<'de> Deserialize<'de> for Timeout"],["impl<'de> Deserialize<'de> for Tls"],["impl<'de> Deserialize<'de> for ActixSettings"],["impl<'de, A> Deserialize<'de> for BasicSettings<A> where
    A: Deserialize<'de>, 
"],["impl<'de> Deserialize<'de> for NoSettings"]] +"actix_settings":[["impl<'de> Deserialize<'de> for Address"],["impl<'de> Deserialize<'de> for Backlog"],["impl<'de> Deserialize<'de> for KeepAlive"],["impl<'de> Deserialize<'de> for MaxConnectionRate"],["impl<'de> Deserialize<'de> for MaxConnections"],["impl<'de> Deserialize<'de> for Mode"],["impl<'de> Deserialize<'de> for NumWorkers"],["impl<'de> Deserialize<'de> for Timeout"],["impl<'de> Deserialize<'de> for Tls"],["impl<'de> Deserialize<'de> for ActixSettings"],["impl<'de, A> Deserialize<'de> for BasicSettings<A> where
    A: Deserialize<'de>, 
"],["impl<'de> Deserialize<'de> for NoSettings"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/implementors/std/error/trait.Error.js b/implementors/std/error/trait.Error.js deleted file mode 100644 index 65d5497c1..000000000 --- a/implementors/std/error/trait.Error.js +++ /dev/null @@ -1,7 +0,0 @@ -(function() {var implementors = { -"actix_cors":[["impl Error for CorsError"]], -"actix_limitation":[["impl Error for Error"]], -"actix_redis":[["impl Error for Error"]], -"actix_session":[["impl Error for SessionGetError"],["impl Error for SessionInsertError"],["impl Error for LoadError"],["impl Error for SaveError"],["impl Error for UpdateError"]], -"actix_web_httpauth":[["impl<C: Challenge + 'static> Error for AuthenticationError<C>"],["impl Error for ParseError"]] -};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/light.css b/light.css index a71085b0e..92630ba14 100644 --- a/light.css +++ b/light.css @@ -1 +1 @@ -:root{--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--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;}.slider{background-color:#ccc;}.slider:before{background-color:white;}input:focus+.slider{box-shadow:0 0 0 2px #0a84ff,0 0 0 6px rgba(10,132,255,0.3);}.in-band{background-color:white;}.rust-logo{}.sidebar .current,.sidebar a:hover{background-color:#fff;}.line-numbers span{color:#c67e2d;}.line-numbers .line-highlighted{background-color:#FDFFD3 !important;}.docblock table td,.docblock table th{border-color:#ddd;}.search-results a:hover{background-color:#ddd;}.search-results a:focus{color:#000 !important;background-color:#ccc;}.search-results a:focus span{color:#000 !important;}a.result-trait:focus{background-color:#c7b6ff;}a.result-traitalias:focus{background-color:#c7b6ff;}a.result-mod:focus,a.result-externcrate:focus{background-color:#afc6e4;}a.result-enum:focus{background-color:#e7b1a0;}a.result-struct:focus{background-color:#e7b1a0;}a.result-union:focus{background-color:#e7b1a0;}a.result-fn:focus,a.result-method:focus,a.result-tymethod:focus{background-color:#c6afb3;}a.result-type:focus{background-color:#e7b1a0;}a.result-associatedtype:focus{background-color:#afc6e4;}a.result-foreigntype:focus{background-color:#e7b1a0;}a.result-attr:focus,a.result-derive:focus,a.result-macro:focus{background-color:#8ce488;}a.result-constant:focus,a.result-static:focus{background-color:#afc6e4;}a.result-primitive:focus{background-color:#e7b1a0;}a.result-keyword:focus{background-color:#afc6e4;}.content .item-info::before{color:#ccc;}.content span.enum,.content a.enum,.block a.current.enum{color:#AD378A;}.content span.struct,.content a.struct,.block a.current.struct{color:#AD378A;}.content span.type,.content a.type,.block a.current.type{color:#AD378A;}.content span.foreigntype,.content a.foreigntype,.block a.current.foreigntype{color:#3873AD;}.content span.associatedtype,.content a.associatedtype,.block a.current.associatedtype{color:#3873AD;}.content span.attr,.content a.attr,.block a.current.attr,.content span.derive,.content a.derive,.block a.current.derive,.content span.macro,.content a.macro,.block a.current.macro{color:#068000;}.content span.union,.content a.union,.block a.current.union{color:#AD378A;}.content span.constant,.content a.constant,.block a.current.constant,.content span.static,.content a.static,.block a.current.static{color:#3873AD;}.content span.primitive,.content a.primitive,.block a.current.primitive{color:#AD378A;}.content span.externcrate,.content span.mod,.content a.mod,.block a.current.mod{color:#3873AD;}.content span.trait,.content a.trait,.block a.current.trait{color:#6E4FC9;}.content span.traitalias,.content a.traitalias,.block a.current.traitalias{color:#5137AD;}.content span.fn,.content a.fn,.block a.current.fn,.content span.method,.content a.method,.block a.current.method,.content span.tymethod,.content a.tymethod,.block a.current.tymethod,.content .fnname{color:#AD7C37;}.content span.keyword,.content a.keyword,.block a.current.keyword{color:#3873AD;}.sidebar a{color:#356da4;}.sidebar a.current.enum{color:#a63283;}.sidebar a.current.struct{color:#a63283;}.sidebar a.current.type{color:#a63283;}.sidebar a.current.associatedtype{color:#356da4;}.sidebar a.current.foreigntype{color:#356da4;}.sidebar a.current.attr,.sidebar a.current.derive,.sidebar a.current.macro{color:#067901;}.sidebar a.current.union{color:#a63283;}.sidebar a.current.constant .sidebar a.current.static{color:#356da4;}.sidebar a.current.primitive{color:#a63283;}.sidebar a.current.externcrate .sidebar a.current.mod{color:#356da4;}.sidebar a.current.trait{color:#6849c3;}.sidebar a.current.traitalias{color:#4b349e;}.sidebar a.current.fn,.sidebar a.current.method,.sidebar a.current.tymethod{color:#a67736;}.sidebar a.current.keyword{color:#356da4;}nav.main .current{border-top-color:#000;border-bottom-color:#000;}nav.main .separator{border:1px solid #000;}a{color:#3873AD;}body.source .example-wrap pre.rust a{background:#eee;}details.rustdoc-toggle>summary.hideme>span,details.rustdoc-toggle>summary::before{color:#999;}#crate-search,.search-input{background-color:white;border-color:#e0e0e0;}#crate-search{border-color:#e0e0e0 !important;}.search-input:focus{border-color:#66afe9;}.stab.empty-impl{background:#FFF5D6;border-color:#FFC600;}.stab.unstable{background:#FFF5D6;border-color:#FFC600;}.stab.deprecated{background:#ffc4c4;border-color:#db7b7b;}.stab.must_implement{background:#F3DFFF;border-color:#b07bdb;}.stab.portability{background:#F3DFFF;border-color:#b07bdb;}.stab.portability>code{background:none;}.rightside,.out-of-band{color:grey;}.line-numbers :target{background-color:transparent;}pre.rust .kw{color:#8959A8;}pre.rust .kw-2,pre.rust .prelude-ty{color:#4271AE;}pre.rust .number,pre.rust .string{color:#718C00;}pre.rust .self,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .attribute,pre.rust .attribute .ident{color:#C82829;}pre.rust .comment{color:#8E908C;}pre.rust .doccomment{color:#4D4D4C;}pre.rust .macro,pre.rust .macro-nonterminal{color:#3E999F;}pre.rust .lifetime{color:#B76514;}pre.rust .question-mark{color:#ff9011;}.example-wrap>pre.line-number{border-color:#c7c7c7;}a.test-arrow{color:#f5f5f5;background-color:rgba(78,139,202,0.2);}a.test-arrow:hover{background-color:#4e8bca;}.toggle-label,.code-attribute{color:#999;}:target{background:#FDFFD3;border-right:3px solid #AD7C37;}pre.compile_fail{border-left:2px solid rgba(255,0,0,.5);}pre.compile_fail:hover,.information:hover+pre.compile_fail{border-left:2px solid #f00;}pre.should_panic{border-left:2px solid rgba(255,0,0,.5);}pre.should_panic:hover,.information:hover+pre.should_panic{border-left:2px solid #f00;}pre.ignore{border-left:2px solid rgba(255,142,0,.6);}pre.ignore:hover,.information:hover+pre.ignore{border-left:2px solid #ff9200;}.tooltip.compile_fail{color:rgba(255,0,0,.5);}.information>.compile_fail:hover{color:#f00;}.tooltip.should_panic{color:rgba(255,0,0,.5);}.information>.should_panic:hover{color:#f00;}.tooltip.ignore{color:rgba(255,142,0,.6);}.information>.ignore:hover{color:#ff9200;}.search-failed a{color:#3873AD;}.tooltip::after{background-color:#000;color:#fff;}.tooltip::before{border-color:transparent black transparent transparent;}.notable-traits-tooltiptext{background-color:#eee;border-color:#999;}.notable-traits-tooltiptext .notable{border-bottom-color:#DDDDDD;}#titles>button:not(.selected){background-color:#e6e6e6;border-top-color:#e6e6e6;}#titles>button:hover,#titles>button.selected{background-color:#ffffff;border-top-color:#0089ff;}#titles>button>div.count{color:#888;}@media (max-width:700px){.sidebar-elems{border-right-color:#000;}}kbd{color:#000;background-color:#fafbfc;border-color:#d1d5da;border-bottom-color:#c6cbd1;box-shadow:inset 0 -1px 0 #c6cbd1;}#settings-menu>a,#help-button>button{border-color:#e0e0e0;background-color:#fff;}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>button:hover,#help-button>button:focus{border-color:#717171;}.popover,.popover::before,#help-button span.top,#help-button span.bottom{border-color:#DDDDDD;}#copy-path{color:#999;}#copy-path>img{filter:invert(50%);}#copy-path:hover>img{filter:invert(35%);}#theme-choices{border-color:#ccc;background-color:#fff;}#theme-choices>button:not(:first-child){border-top-color:#e0e0e0;}#theme-choices>button:hover,#theme-choices>button:focus{background-color:#eee;}.search-results .result-name span.alias{color:#000;}.search-results .result-name span.grey{color:#999;}#source-sidebar>.title{border-bottom-color:#ccc;}#source-sidebar div.files>a:hover,details.dir-entry summary:hover,#source-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:#E0E0E0;}#source-sidebar div.files>a.selected{background-color:#fff;}.scraped-example-list .scrape-help{border-color:#555;color:#333;}.scraped-example-list .scrape-help:hover{border-color:black;color:black;}.more-examples-toggle summary,.more-examples-toggle .hide-more{color:#999;}.scraped-example .example-wrap .rust span.highlight{background:#fcffd6;}.scraped-example .example-wrap .rust span.highlight.focus{background:#f6fdb0;}.scraped-example:not(.expanded) .code-wrapper:before{background:linear-gradient(to bottom,rgba(255,255,255,1),rgba(255,255,255,0));}.scraped-example:not(.expanded) .code-wrapper:after{background:linear-gradient(to top,rgba(255,255,255,1),rgba(255,255,255,0));}.toggle-line-inner{background:#ccc;}.toggle-line:hover .toggle-line-inner{background:#999;} \ No newline at end of file +:root{--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--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;}.slider{background-color:#ccc;}.slider:before{background-color:white;}input:focus+.slider{box-shadow:0 0 0 2px #0a84ff,0 0 0 6px rgba(10,132,255,0.3);}.rust-logo{}.sidebar .current,.sidebar a:hover{background-color:#fff;}.line-numbers span{color:#c67e2d;}.line-numbers .line-highlighted{background-color:#FDFFD3 !important;}.search-results a:hover{background-color:#ddd;}.search-results a:focus{color:#000 !important;background-color:#ccc;}.search-results a:focus span{color:#000 !important;}a.result-trait:focus{background-color:#c7b6ff;}a.result-traitalias:focus{background-color:#c7b6ff;}a.result-mod:focus,a.result-externcrate:focus{background-color:#afc6e4;}a.result-enum:focus{background-color:#e7b1a0;}a.result-struct:focus{background-color:#e7b1a0;}a.result-union:focus{background-color:#e7b1a0;}a.result-fn:focus,a.result-method:focus,a.result-tymethod:focus{background-color:#c6afb3;}a.result-type:focus{background-color:#e7b1a0;}a.result-associatedtype:focus{background-color:#afc6e4;}a.result-foreigntype:focus{background-color:#e7b1a0;}a.result-attr:focus,a.result-derive:focus,a.result-macro:focus{background-color:#8ce488;}a.result-constant:focus,a.result-static:focus{background-color:#afc6e4;}a.result-primitive:focus{background-color:#e7b1a0;}a.result-keyword:focus{background-color:#afc6e4;}.content .item-info::before{color:#ccc;}.content span.enum,.content a.enum,.block a.current.enum{color:#AD378A;}.content span.struct,.content a.struct,.block a.current.struct{color:#AD378A;}.content span.type,.content a.type,.block a.current.type{color:#AD378A;}.content span.foreigntype,.content a.foreigntype,.block a.current.foreigntype{color:#3873AD;}.content span.associatedtype,.content a.associatedtype,.block a.current.associatedtype{color:#3873AD;}.content span.attr,.content a.attr,.block a.current.attr,.content span.derive,.content a.derive,.block a.current.derive,.content span.macro,.content a.macro,.block a.current.macro{color:#068000;}.content span.union,.content a.union,.block a.current.union{color:#AD378A;}.content span.constant,.content a.constant,.block a.current.constant,.content span.static,.content a.static,.block a.current.static{color:#3873AD;}.content span.primitive,.content a.primitive,.block a.current.primitive{color:#AD378A;}.content span.externcrate,.content span.mod,.content a.mod,.block a.current.mod{color:#3873AD;}.content span.trait,.content a.trait,.block a.current.trait{color:#6E4FC9;}.content span.traitalias,.content a.traitalias,.block a.current.traitalias{color:#5137AD;}.content span.fn,.content a.fn,.block a.current.fn,.content span.method,.content a.method,.block a.current.method,.content span.tymethod,.content a.tymethod,.block a.current.tymethod,.content .fnname{color:#AD7C37;}.content span.keyword,.content a.keyword,.block a.current.keyword{color:#3873AD;}.sidebar a{color:#356da4;}.sidebar a.current.enum{color:#a63283;}.sidebar a.current.struct{color:#a63283;}.sidebar a.current.type{color:#a63283;}.sidebar a.current.associatedtype{color:#356da4;}.sidebar a.current.foreigntype{color:#356da4;}.sidebar a.current.attr,.sidebar a.current.derive,.sidebar a.current.macro{color:#067901;}.sidebar a.current.union{color:#a63283;}.sidebar a.current.constant .sidebar a.current.static{color:#356da4;}.sidebar a.current.primitive{color:#a63283;}.sidebar a.current.externcrate .sidebar a.current.mod{color:#356da4;}.sidebar a.current.trait{color:#6849c3;}.sidebar a.current.traitalias{color:#4b349e;}.sidebar a.current.fn,.sidebar a.current.method,.sidebar a.current.tymethod{color:#a67736;}.sidebar a.current.keyword{color:#356da4;}a{color:#3873AD;}body.source .example-wrap pre.rust a{background:#eee;}details.rustdoc-toggle>summary.hideme>span,details.rustdoc-toggle>summary::before{color:#999;}#crate-search-div::after{filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);}#crate-search:hover,#crate-search:focus{border-color:#717171 !important;}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);}.search-input:focus{border-color:#66afe9;}.stab{background:#FFF5D6;border-color:#FFC600;}.stab.portability>code{background:none;}.rightside,.out-of-band{color:grey;}.line-numbers :target{background-color:transparent;}pre.rust .kw{color:#8959A8;}pre.rust .kw-2,pre.rust .prelude-ty{color:#4271AE;}pre.rust .number,pre.rust .string{color:#718C00;}pre.rust .self,pre.rust .bool-val,pre.rust .prelude-val,pre.rust .attribute{color:#C82829;}pre.rust .comment{color:#8E908C;}pre.rust .doccomment{color:#4D4D4C;}pre.rust .macro,pre.rust .macro-nonterminal{color:#3E999F;}pre.rust .lifetime{color:#B76514;}pre.rust .question-mark{color:#ff9011;}.example-wrap>pre.line-number{border-color:#c7c7c7;}a.test-arrow{color:#f5f5f5;background-color:rgba(78,139,202,0.2);}a.test-arrow:hover{background-color:#4e8bca;}.toggle-label,.code-attribute{color:#999;}:target{background:#FDFFD3;border-right:3px solid #AD7C37;}pre.compile_fail{border-left:2px solid rgba(255,0,0,.5);}pre.compile_fail:hover,.information:hover+pre.compile_fail{border-left:2px solid #f00;}pre.should_panic{border-left:2px solid rgba(255,0,0,.5);}pre.should_panic:hover,.information:hover+pre.should_panic{border-left:2px solid #f00;}pre.ignore{border-left:2px solid rgba(255,142,0,.6);}pre.ignore:hover,.information:hover+pre.ignore{border-left:2px solid #ff9200;}.tooltip.compile_fail{color:rgba(255,0,0,.5);}.information>.compile_fail:hover{color:#f00;}.tooltip.should_panic{color:rgba(255,0,0,.5);}.information>.should_panic:hover{color:#f00;}.tooltip.ignore{color:rgba(255,142,0,.6);}.information>.ignore:hover{color:#ff9200;}.search-failed a{color:#3873AD;}.tooltip::after{background-color:#000;color:#fff;}.tooltip::before{border-color:transparent black transparent transparent;}.notable-traits-tooltiptext{background-color:#eee;}#titles>button:not(.selected){background-color:#e6e6e6;border-top-color:#e6e6e6;}#titles>button:hover,#titles>button.selected{background-color:#ffffff;border-top-color:#0089ff;}#titles>button>div.count{color:#888;}kbd{color:#000;background-color:#fafbfc;box-shadow:inset 0 -1px 0 #c6cbd1;}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>button:hover,#help-button>button:focus{border-color:#717171;}#copy-path{color:#999;}#copy-path>img{filter:invert(50%);}#copy-path:hover>img{filter:invert(35%);}.search-results .result-name span.alias{color:#000;}.search-results .result-name span.grey{color:#999;}#source-sidebar div.files>a:hover,details.dir-entry summary:hover,#source-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:#E0E0E0;}#source-sidebar div.files>a.selected{background-color:#fff;}.scraped-example-list .scrape-help{border-color:#555;color:#333;}.scraped-example-list .scrape-help:hover{border-color:black;color:black;}.more-examples-toggle summary,.more-examples-toggle .hide-more{color:#999;}.scraped-example .example-wrap .rust span.highlight{background:#fcffd6;}.scraped-example .example-wrap .rust span.highlight.focus{background:#f6fdb0;}.scraped-example:not(.expanded) .code-wrapper:before{background:linear-gradient(to bottom,rgba(255,255,255,1),rgba(255,255,255,0));}.scraped-example:not(.expanded) .code-wrapper:after{background:linear-gradient(to top,rgba(255,255,255,1),rgba(255,255,255,0));}.toggle-line-inner{background:#ccc;}.toggle-line:hover .toggle-line-inner{background:#999;} \ No newline at end of file diff --git a/main.js b/main.js index 206467caf..f62acc48c 100644 --- a/main.js +++ b/main.js @@ -1,4 +1,4 @@ -"use strict";function getVar(name){const el=document.getElementById("rustdoc-vars");if(el){return el.attributes["data-"+name].value}else{return null}}function resourcePath(basename,extension){return getVar("root-path")+basename+getVar("resource-suffix")+extension}function hideMain(){addClass(document.getElementById(MAIN_ID),"hidden")}function showMain(){removeClass(document.getElementById(MAIN_ID),"hidden")}function elemIsInParent(elem,parent){while(elem&&elem!==document.body){if(elem===parent){return true}elem=elem.parentElement}return false}function blurHandler(event,parentElem,hideCallback){if(!elemIsInParent(document.activeElement,parentElem)&&!elemIsInParent(event.relatedTarget,parentElem)){hideCallback()}}(function(){window.rootPath=getVar("root-path");window.currentCrate=getVar("current-crate")}());function setMobileTopbar(){const mobileLocationTitle=document.querySelector(".mobile-topbar h2.location");const locationTitle=document.querySelector(".sidebar h2.location");if(mobileLocationTitle&&locationTitle){mobileLocationTitle.innerHTML=locationTitle.innerHTML}}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")}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}function loadCss(cssFileName){const link=document.createElement("link");link.href=resourcePath(cssFileName,".css");link.type="text/css";link.rel="stylesheet";document.getElementsByTagName("head")[0].appendChild(link)}(function(){function loadScript(url){const script=document.createElement("script");script.src=url;document.head.append(script)}getSettingsButton().onclick=event=>{addClass(getSettingsButton(),"rotate");event.preventDefault();loadCss("settings");loadScript(resourcePath("settings",".js"))};window.searchState={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},hideResults:()=>{switchDisplayedElement(null);document.title=searchState.titleBeforeSearch;if(browserSupportsHistoryApi()){history.replaceState(null,window.currentCrate+" - Rust",getNakedUrl()+window.location.hash)}},getQueryStringParams:()=>{const params={};window.location.search.substring(1).split("&").map(s=>{const pair=s.split("=");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 loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(resourcePath("search",".js"));loadScript(resourcePath("search-index",".js"))}}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){const search=searchState.outputElement();search.innerHTML="

"+searchState.loadingText+"

";searchState.showResults(search);loadSearch()}},};function getPageId(){if(window.location.hash){const tmp=window.location.hash.replace(/^#/,"");if(tmp.length>0){return tmp}}return null}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()}}if(savedHash!==window.location.hash){savedHash=window.location.hash;if(savedHash.length===0){return}expandSection(savedHash.slice(1))}}function onHashChange(ev){const sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"shown");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();switchDisplayedElement(null);if(browserSupportsHistoryApi()){history.replaceState(null,window.currentCrate+" - Rust",getNakedUrl()+window.location.hash)}ev.preventDefault();searchState.defocus();window.hidePopoverMenus()}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"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break;case"s":case"S":ev.preventDefault();searchState.focus();break;case"+":case"-":ev.preventDefault();toggleAllDocs();break;case"?":showHelp();break;default:break}}}document.addEventListener("keypress",handleShortcut);document.addEventListener("keydown",handleShortcut);function addSidebarItems(){if(!window.SIDEBAR_ITEMS){return}const sidebar=document.getElementsByClassName("sidebar-elems")[0];function block(shortty,id,longty){const filtered=window.SIDEBAR_ITEMS[shortty];if(!filtered){return}const div=document.createElement("div");div.className="block "+shortty;const h3=document.createElement("h3");h3.innerHTML=`${longty}`;div.appendChild(h3);const ul=document.createElement("ul");for(const item of filtered){const name=item[0];const desc=item[1];let klass=shortty;let path;if(shortty==="mod"){path=name+"/index.html"}else{path=shortty+"."+name+".html"}const current_page=document.location.href.split("/").pop();if(path===current_page){klass+=" current"}const link=document.createElement("a");link.href=path;link.title=desc;link.className=klass;link.textContent=name;const li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}div.appendChild(ul);sidebar.appendChild(div)}if(sidebar){block("primitive","primitives","Primitive Types");block("mod","modules","Modules");block("macro","macros","Macros");block("struct","structs","Structs");block("enum","enums","Enums");block("union","unions","Unions");block("constant","constants","Constants");block("static","static","Statics");block("trait","traits","Traits");block("fn","functions","Functions");block("type","types","Type Definitions");block("foreigntype","foreign-types","Foreign Types");block("keyword","keywords","Keywords");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("h1.fqn > .in-band > .trait").textContent;const baseIdName="impl-"+traitName+"-";const libs=Object.getOwnPropertyNames(imp);const ignoreExternCrates=document.querySelector("script[data-ignore-extern-crates]").getAttribute("data-ignore-extern-crates");for(const lib of libs){if(lib===window.currentCrate||ignoreExternCrates.indexOf(lib)!==-1){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");addClass(code,"in-band");onEachLazy(code.getElementsByTagName("a"),elem=>{const href=elem.getAttribute("href");if(href&&href.indexOf("http")!==0){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)}function addSidebarCrates(){if(!window.ALL_CRATES){return}const sidebarElems=document.getElementsByClassName("sidebar-elems")[0];if(!sidebarElems){return}const div=document.createElement("div");div.className="block crate";div.innerHTML="

Crates

";const ul=document.createElement("ul");div.appendChild(ul);for(const crate of window.ALL_CRATES){let klass="crate";if(window.rootPath!=="./"&&crate===window.currentCrate){klass+=" current"}const link=document.createElement("a");link.href=window.rootPath+crate+"/index.html";link.className=klass;link.textContent=crate;const li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}sidebarElems.appendChild(div)}function labelForToggleButton(sectionIsCollapsed){if(sectionIsCollapsed){return"+"}return"\u2212"}function toggleAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}let sectionIsCollapsed=false;if(hasClass(innerToggle,"will-expand")){removeClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("rustdoc-toggle"),e=>{if(!hasClass(e,"type-contents-toggle")){e.open=true}});innerToggle.title="collapse all docs"}else{addClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("rustdoc-toggle"),e=>{if(e.parentNode.id!=="implementations-list"||(!hasClass(e,"implementors-toggle")&&!hasClass(e,"type-contents-toggle"))){e.open=false}});sectionIsCollapsed=true;innerToggle.title="expand all docs"}innerToggle.children[0].innerText=labelForToggleButton(sectionIsCollapsed)}(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("rustdoc-toggle"),e=>{if(!hideLargeItemContents&&hasClass(e,"type-contents-toggle")){e.open=true}if(hideMethodDocs&&hasClass(e,"method-toggle")){e.open=false}});const pageId=getPageId();if(pageId!==null){expandSection(pageId)}}());(function(){let lineNumbersFunc=()=>{};if(getSettingValue("line-numbers")==="true"){lineNumbersFunc=x=>{const count=x.textContent.split("\n").length;const elems=[];for(let i=0;i{if(hasClass(e,"compile_fail")){e.addEventListener("mouseover",function(){this.parentElement.previousElementSibling.childNodes[0].style.color="#f00"});e.addEventListener("mouseout",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=""})}else if(hasClass(e,"ignore")){e.addEventListener("mouseover",function(){this.parentElement.previousElementSibling.childNodes[0].style.color="#ff9200"});e.addEventListener("mouseout",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=""})}lineNumbersFunc(e)})}());function hideSidebar(){const sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"shown")}function handleClick(id,f){const elem=document.getElementById(id);if(elem){elem.addEventListener("click",f)}}handleClick(MAIN_ID,()=>{hideSidebar()});onEachLazy(document.getElementsByTagName("a"),el=>{if(el.hash){el.addEventListener("click",()=>{expandSection(el.hash.slice(1));hideSidebar()})}});onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"),el=>{el.addEventListener("click",e=>{if(e.target.tagName!=="SUMMARY"&&e.target.tagName!=="A"){e.preventDefault()}})});onEachLazy(document.getElementsByClassName("notable-traits"),e=>{e.onclick=function(){this.getElementsByClassName("notable-traits-tooltiptext")[0].classList.toggle("force-tooltip")}});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")){addClass(sidebar,"shown")}else{removeClass(sidebar,"shown")}})}function helpBlurHandler(event){blurHandler(event,getHelpButton(),window.hidePopoverMenus)}function buildHelpMenu(){const book_info=document.createElement("span");book_info.className="top";book_info.innerHTML="You can find more information in \ +"use strict";function getVar(name){const el=document.getElementById("rustdoc-vars");if(el){return el.attributes["data-"+name].value}else{return null}}function resourcePath(basename,extension){return getVar("root-path")+basename+getVar("resource-suffix")+extension}function hideMain(){addClass(document.getElementById(MAIN_ID),"hidden")}function showMain(){removeClass(document.getElementById(MAIN_ID),"hidden")}function elemIsInParent(elem,parent){while(elem&&elem!==document.body){if(elem===parent){return true}elem=elem.parentElement}return false}function blurHandler(event,parentElem,hideCallback){if(!elemIsInParent(document.activeElement,parentElem)&&!elemIsInParent(event.relatedTarget,parentElem)){hideCallback()}}(function(){window.rootPath=getVar("root-path");window.currentCrate=getVar("current-crate")}());function setMobileTopbar(){const mobileLocationTitle=document.querySelector(".mobile-topbar h2.location");const locationTitle=document.querySelector(".sidebar h2.location");if(mobileLocationTitle&&locationTitle){mobileLocationTitle.innerHTML=locationTitle.innerHTML}}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")}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}function loadCss(cssFileName){const link=document.createElement("link");link.href=resourcePath(cssFileName,".css");link.type="text/css";link.rel="stylesheet";document.getElementsByTagName("head")[0].appendChild(link)}(function(){function loadScript(url){const script=document.createElement("script");script.src=url;document.head.append(script)}getSettingsButton().onclick=event=>{addClass(getSettingsButton(),"rotate");event.preventDefault();loadCss("settings");loadScript(resourcePath("settings",".js"))};window.searchState={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},hideResults:()=>{switchDisplayedElement(null);document.title=searchState.titleBeforeSearch;if(browserSupportsHistoryApi()){history.replaceState(null,window.currentCrate+" - Rust",getNakedUrl()+window.location.hash)}},getQueryStringParams:()=>{const params={};window.location.search.substring(1).split("&").map(s=>{const pair=s.split("=");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 loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(resourcePath("search",".js"));loadScript(resourcePath("search-index",".js"))}}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){const search=searchState.outputElement();search.innerHTML="

"+searchState.loadingText+"

";searchState.showResults(search);loadSearch()}},};function getPageId(){if(window.location.hash){const tmp=window.location.hash.replace(/^#/,"");if(tmp.length>0){return tmp}}return null}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()}}if(savedHash!==window.location.hash){savedHash=window.location.hash;if(savedHash.length===0){return}expandSection(savedHash.slice(1))}}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();switchDisplayedElement(null);if(browserSupportsHistoryApi()){history.replaceState(null,window.currentCrate+" - Rust",getNakedUrl()+window.location.hash)}ev.preventDefault();searchState.defocus();window.hidePopoverMenus()}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"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break;case"s":case"S":ev.preventDefault();searchState.focus();break;case"+":case"-":ev.preventDefault();toggleAllDocs();break;case"?":showHelp();break;default:break}}}document.addEventListener("keypress",handleShortcut);document.addEventListener("keydown",handleShortcut);function addSidebarItems(){if(!window.SIDEBAR_ITEMS){return}const sidebar=document.getElementsByClassName("sidebar-elems")[0];function block(shortty,id,longty){const filtered=window.SIDEBAR_ITEMS[shortty];if(!filtered){return}const div=document.createElement("div");div.className="block "+shortty;const h3=document.createElement("h3");h3.innerHTML=`${longty}`;div.appendChild(h3);const ul=document.createElement("ul");for(const item of filtered){const name=item[0];const desc=item[1];let klass=shortty;let path;if(shortty==="mod"){path=name+"/index.html"}else{path=shortty+"."+name+".html"}const current_page=document.location.href.split("/").pop();if(path===current_page){klass+=" current"}const link=document.createElement("a");link.href=path;link.title=desc;link.className=klass;link.textContent=name;const li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}div.appendChild(ul);sidebar.appendChild(div)}if(sidebar){block("primitive","primitives","Primitive Types");block("mod","modules","Modules");block("macro","macros","Macros");block("struct","structs","Structs");block("enum","enums","Enums");block("union","unions","Unions");block("constant","constants","Constants");block("static","static","Statics");block("trait","traits","Traits");block("fn","functions","Functions");block("type","types","Type Definitions");block("foreigntype","foreign-types","Foreign Types");block("keyword","keywords","Keywords");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("h1.fqn > .in-band > .trait").textContent;const baseIdName="impl-"+traitName+"-";const libs=Object.getOwnPropertyNames(imp);const ignoreExternCrates=document.querySelector("script[data-ignore-extern-crates]").getAttribute("data-ignore-extern-crates");for(const lib of libs){if(lib===window.currentCrate||ignoreExternCrates.indexOf(lib)!==-1){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");addClass(code,"in-band");onEachLazy(code.getElementsByTagName("a"),elem=>{const href=elem.getAttribute("href");if(href&&href.indexOf("http")!==0){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)}function addSidebarCrates(){if(!window.ALL_CRATES){return}const sidebarElems=document.getElementsByClassName("sidebar-elems")[0];if(!sidebarElems){return}const div=document.createElement("div");div.className="block crate";div.innerHTML="

Crates

";const ul=document.createElement("ul");div.appendChild(ul);for(const crate of window.ALL_CRATES){let klass="crate";if(window.rootPath!=="./"&&crate===window.currentCrate){klass+=" current"}const link=document.createElement("a");link.href=window.rootPath+crate+"/index.html";link.className=klass;link.textContent=crate;const li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}sidebarElems.appendChild(div)}function labelForToggleButton(sectionIsCollapsed){if(sectionIsCollapsed){return"+"}return"\u2212"}function toggleAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}let sectionIsCollapsed=false;if(hasClass(innerToggle,"will-expand")){removeClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("rustdoc-toggle"),e=>{if(!hasClass(e,"type-contents-toggle")){e.open=true}});innerToggle.title="collapse all docs"}else{addClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("rustdoc-toggle"),e=>{if(e.parentNode.id!=="implementations-list"||(!hasClass(e,"implementors-toggle")&&!hasClass(e,"type-contents-toggle"))){e.open=false}});sectionIsCollapsed=true;innerToggle.title="expand all docs"}innerToggle.children[0].innerText=labelForToggleButton(sectionIsCollapsed)}(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("rustdoc-toggle"),e=>{if(!hideLargeItemContents&&hasClass(e,"type-contents-toggle")){e.open=true}if(hideMethodDocs&&hasClass(e,"method-toggle")){e.open=false}});const pageId=getPageId();if(pageId!==null){expandSection(pageId)}}());(function(){let lineNumbersFunc=()=>{};if(getSettingValue("line-numbers")==="true"){lineNumbersFunc=x=>{const count=x.textContent.split("\n").length;const elems=[];for(let i=0;i{if(hasClass(e,"compile_fail")){e.addEventListener("mouseover",function(){this.parentElement.previousElementSibling.childNodes[0].style.color="#f00"});e.addEventListener("mouseout",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=""})}else if(hasClass(e,"ignore")){e.addEventListener("mouseover",function(){this.parentElement.previousElementSibling.childNodes[0].style.color="#ff9200"});e.addEventListener("mouseout",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=""})}lineNumbersFunc(e)})}());let oldSidebarScrollPosition=null;function showSidebar(){if(window.innerWidth{if(window.innerWidth>=window.RUSTDOC_MOBILE_BREAKPOINT&&oldSidebarScrollPosition!==null){hideSidebar()}});function handleClick(id,f){const elem=document.getElementById(id);if(elem){elem.addEventListener("click",f)}}handleClick(MAIN_ID,()=>{hideSidebar()});onEachLazy(document.getElementsByTagName("a"),el=>{if(el.hash){el.addEventListener("click",()=>{expandSection(el.hash.slice(1));hideSidebar()})}});onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"),el=>{el.addEventListener("click",e=>{if(e.target.tagName!=="SUMMARY"&&e.target.tagName!=="A"){e.preventDefault()}})});onEachLazy(document.getElementsByClassName("notable-traits"),e=>{e.onclick=function(){this.getElementsByClassName("notable-traits-tooltiptext")[0].classList.toggle("force-tooltip")}});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){blurHandler(event,getHelpButton(),window.hidePopoverMenus)}function buildHelpMenu(){const book_info=document.createElement("span");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=["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, \ diff --git a/rustdoc.css b/rustdoc.css index 2e22b4cf1..307bd6a27 100644 --- a/rustdoc.css +++ b/rustdoc.css @@ -1 +1 @@ - @font-face {font-family:'Fira Sans';font-style:normal;font-weight:400;src:local('Fira Sans'),url("FiraSans-Regular.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.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.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.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.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:400;src:url("SourceCodePro-Regular.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:italic;font-weight:400;src:url("SourceCodePro-It.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:600;src:url("SourceCodePro-Semibold.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'NanumBarunGothic';src:url("NanumBarunGothic.ttf.woff2") format("woff2");font-display:swap;unicode-range:U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF;}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}html{content:"";}@media (prefers-color-scheme:light){html{content:"light";}}@media (prefers-color-scheme:dark){html{content:"dark";}}body{font:1rem/1.5 "Source Serif 4",NanumBarunGothic,serif;margin:0;position:relative;overflow-wrap:break-word;overflow-wrap:anywhere;-webkit-font-feature-settings:"kern","liga";-moz-font-feature-settings:"kern","liga";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:20px 0 15px 0;padding-bottom:6px;}.docblock h3,.docblock h4,h5,h6{margin:15px 0 5px 0;}h1.fqn{margin:0;padding:0;border-bottom-color:var(--headings-border-bottom-color);}h2,h3,h4{border-bottom-color:var(--headings-border-bottom-color);}.main-heading{display:flex;flex-wrap:wrap;justify-content:space-between;padding-bottom:6px;margin-bottom:15px;}.main-heading a:hover{text-decoration:underline;}#toggle-all-docs{text-decoration:none;}h2,.top-doc .docblock>h3,.top-doc .docblock>h4{border-bottom:1px solid var(--headings-border-bottom-color);}h3.code-header{font-size:1.125rem;}h4.code-header{font-size:1rem;}.code-header{font-weight:600;border-bottom-style:none;margin:0;padding:0;margin-top:0.6em;margin-bottom:0.4em;}.impl,.impl-items .method,.methods .method,.impl-items .type,.methods .type,.impl-items .associatedconstant,.methods .associatedconstant,.impl-items .associatedtype,.methods .associatedtype{flex-basis:100%;font-weight:600;position:relative;}div.impl-items>div{padding-left:0;}h1,h2,h3,h4,h5,h6,.sidebar,.mobile-topbar,a.source,.search-input,.search-results .result-name,.content table td:first-child>a,.item-left>a,.out-of-band,span.since,#source-sidebar,#sidebar-toggle,details.rustdoc-toggle>summary::before,div.impl-items>div:not(.docblock):not(.item-info),.content ul.crate a.crate,a.srclink,#main-content>.since,#help-button>button,details.rustdoc-toggle.top-doc>summary,details.rustdoc-toggle.top-doc>summary::before,details.rustdoc-toggle.non-exhaustive>summary,details.rustdoc-toggle.non-exhaustive>summary::before,.scraped-example-title,.more-examples-toggle summary,.more-examples-toggle .hide-more,.example-links a,#main-content>ul.docblock>li>a{font-family:"Fira Sans",Arial,NanumBarunGothic,sans-serif;}h1,h2,h3,h4,a#toggle-all-docs,a.anchor,.small-section-header a,#source-sidebar a,pre.rust a,.sidebar h2 a,.sidebar h3 a,.mobile-topbar h2 a,.in-band a,.search-results a,.module-item .stab,.import-item .stab,.result-name .primitive>i,.result-name .keyword>i,.content .method .where,.content .fn .where,.content .where.fmt-newline{color:var(--main-color);}ol,ul{padding-left:24px;}ul ul,ol ul,ul ol,ol ol{margin-bottom:.625em;}p{margin:0 0 .75em 0;}summary{outline:none;}td,th{padding:0;}table{border-collapse:collapse;}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0;}button{padding:1px 6px;}.rustdoc{display:flex;flex-direction:row;flex-wrap:nowrap;}main{position:relative;flex-grow:1;padding:10px 15px 40px 45px;min-width:0;}.source main{padding:15px;}.width-limiter{max-width:960px;margin-right:auto;}.source .width-limiter{max-width:unset;}details:not(.rustdoc-toggle) summary{margin-bottom:.6em;}code,pre,a.test-arrow,.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;}.docblock.item-decl{margin-left:0;}.item-decl pre{overflow-x:auto;}.source .content pre{padding:20px;}img{max-width:100%;}li{position:relative;}.source .content{max-width:none;overflow:visible;margin-left:0px;}nav.sub{position:relative;font-size:1rem;}.sub-container{display:flex;flex-direction:row;flex-wrap:nowrap;}.sub-logo-container{display:none;margin-right:20px;}.source .sub-logo-container{display:block;}.source .sub-logo-container>img{height:60px;width:60px;object-fit:contain;}.sidebar,.mobile-topbar,.sidebar-menu-toggle{background-color:var(--sidebar-background-color);}.sidebar{font-size:0.875rem;width:250px;min-width:200px;overflow-y:scroll;position:sticky;height:100vh;top:0;left:0;}.sidebar-elems,.sidebar>.location{padding-left:24px;}.sidebar .location{overflow-wrap:anywhere;}.rustdoc.source .sidebar{width:50px;min-width:0px;max-width:300px;flex-grow:0;flex-shrink:0;flex-basis:auto;border-right:1px solid;overflow-x:hidden;overflow-y:hidden;}.rustdoc.source .sidebar .sidebar-logo{display:none;}.source .sidebar,#sidebar-toggle,#source-sidebar{background-color:var(--sidebar-background-color);}#sidebar-toggle>button:hover,#sidebar-toggle>button:focus{background-color:var(--sidebar-background-color-hover);}.source .sidebar>*:not(#sidebar-toggle){opacity:0;visibility:hidden;}.source-sidebar-expanded .source .sidebar{overflow-y:auto;}.source-sidebar-expanded .source .sidebar>*:not(#sidebar-toggle){opacity:1;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;}.sidebar .logo-container{display:flex;margin-top:10px;margin-bottom:10px;justify-content:center;}.version{overflow-wrap:break-word;}.logo-container>img{height:100px;width:100px;}.location:empty{border:none;}.location a:first-of-type{font-weight:500;}.block{padding:0;}.block ul,.block li{padding:0;margin:0;list-style:none;}.block a,h2.location a{display:block;padding:0.25rem;margin-left:-0.25rem;text-overflow:ellipsis;overflow:hidden;}.sidebar h2{border-bottom:none;font-weight:500;padding:0;margin:0;margin-top:0.7rem;margin-bottom:0.7rem;}.sidebar h3{font-size:1.125rem;font-weight:500;padding:0;margin:0;}.sidebar-elems .block{margin-bottom:2em;}.sidebar-elems .block li a{white-space:nowrap;}.mobile-topbar{display:none;}.source .content pre.rust{white-space:pre;overflow:auto;padding-left:0;}.rustdoc .example-wrap{display:inline-flex;margin-bottom:10px;}.example-wrap{position:relative;width:100%;}.example-wrap>pre.line-number{overflow:initial;border:1px solid;padding:13px 8px;text-align:right;border-top-left-radius:5px;border-bottom-left-radius:5px;}.example-wrap>pre.rust a:hover{text-decoration:underline;}.line-numbers{text-align:right;}.rustdoc:not(.source) .example-wrap>pre:not(.line-number){width:100%;overflow-x:auto;}.rustdoc:not(.source) .example-wrap>pre.line-numbers{width:auto;overflow-x:visible;}.rustdoc .example-wrap>pre{margin:0;}#search{position:relative;}.search-loading{text-align:center;}#results>table{width:100%;table-layout:fixed;}.content>.example-wrap pre.line-numbers{position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}.line-numbers span{cursor:pointer;}.docblock-short{overflow-wrap:break-word;overflow-wrap:anywhere;}.docblock-short p{display:inline;}.docblock-short p{overflow:hidden;text-overflow:ellipsis;margin:0;}.docblock>:not(pre)>code,.docblock-short>:not(pre)>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 h1,.docblock h2,.docblock h3,.docblock h4,.docblock h5,.docblock h6{border-bottom-color:var(--headings-border-bottom-color);}.docblock{margin-left:24px;position:relative;}.docblock>:not(.information):not(.more-examples-toggle){max-width:100%;overflow-x:auto;}.content .out-of-band{flex-grow:0;font-size:1.125rem;font-weight:normal;float:right;}.method>.code-header,.trait-impl>.code-header{max-width:calc(100% - 41px);display:block;}.content .in-band{flex-grow:1;margin:0px;padding:0px;overflow-wrap:break-word;overflow-wrap:anywhere;}.in-band>code,.in-band>.code-header{display:inline-block;}.docblock code,.docblock-short code,pre,.rustdoc.source .example-wrap{background-color:var(--code-block-background-color);}#main-content{position:relative;}#main-content>.since{top:inherit;}.content table:not(.table-display){border-spacing:0 5px;}.content td{vertical-align:top;}.content td:first-child{padding-right:20px;}.content td p:first-child{margin-top:0;}.content td h1,.content td h2{margin-left:0;font-size:1.125rem;}.content tr:first-child td{border-top:0;}.docblock table{margin:.5em 0;width:calc(100% - 2px);overflow-x:auto;display:block;}.docblock table td{padding:.5em;border:1px dashed;}.docblock table th{padding:.5em;text-align:left;border:1px solid;}.fields+table{margin-bottom:1em;}.content .item-list{list-style-type:none;padding:0;}.content .multi-column{-moz-column-count:5;-moz-column-gap:2.5em;-webkit-column-count:5;-webkit-column-gap:2.5em;column-count:5;column-gap:2.5em;}.content .multi-column li{width:100%;display:inline-block;}.content>.methods>.method{font-size:1rem;position:relative;}.content .method .where,.content .fn .where,.content .where.fmt-newline{display:block;font-size:0.875rem;}.content .methods>div:not(.notable-traits):not(.method){margin-left:40px;margin-bottom:15px;}.content .docblock>.impl-items{margin-left:20px;margin-top:-34px;}.content .docblock>.impl-items .table-display{margin:0;}.content .docblock>.impl-items table td{padding:0;}.content .docblock>.impl-items .table-display,.impl-items table td{border:none;}.item-info{display:block;}.content .item-info code{font-size:0.875rem;}.content .item-info{position:relative;margin-left:24px;}.sub-variant>div>.item-info{margin-top:initial;}.content .impl-items .docblock,.content .impl-items .item-info{margin-bottom:.6em;}.content .impl-items>.item-info{margin-left:40px;}.methods>.item-info,.content .impl-items>.item-info{margin-top:-8px;}.impl-items{flex-basis:100%;}#main-content>.item-info{margin-top:0;margin-left:0;}nav.sub{flex-grow:1;margin-bottom:25px;}.source nav.sub{margin-left:32px;}nav.main{padding:20px 0;text-align:center;}nav.main .current{border-top:1px solid;border-bottom:1px solid;}nav.main .separator{border:1px solid;display:inline-block;height:23px;margin:0 20px;}nav.sum{text-align:right;}nav.sub form{display:inline;}a{text-decoration:none;background:transparent;}.small-section-header{display:flex;justify-content:space-between;position:relative;}.small-section-header:hover>.anchor{display:initial;}.in-band:hover>.anchor,.impl:hover>.anchor,.method.trait-impl:hover>.anchor,.type.trait-impl:hover>.anchor,.associatedconstant.trait-impl:hover>.anchor,.associatedtype.trait-impl:hover>.anchor{display:inline-block;position:absolute;}.anchor{display:none;position:absolute;left:-0.5em;background:none !important;}.anchor.field{left:-5px;}.small-section-header>.anchor{left:-15px;padding-right:8px;}h2.small-section-header>.anchor{padding-right:6px;}.anchor::before{content:'§';}.docblock a:not(.srclink):not(.test-arrow):not(.scrape-help):hover,.docblock-short a:not(.srclink):not(.test-arrow):not(.scrape-help):hover,.item-info a{text-decoration:underline;}.block a.current.crate{font-weight:500;}table,.item-table{overflow-wrap:break-word;}.item-table{display:table;}.item-row{display:table-row;}.item-left,.item-right{display:table-cell;}.item-left{padding-right:1.25rem;}.search-container{position:relative;display:flex;height:34px;}.search-container>*{height:100%;}.search-results-title{display:inline;}#search-settings{font-size:1.5rem;font-weight:500;margin-bottom:20px;}#crate-search{min-width:115px;margin-top:5px;padding-left:0.15em;padding-right:23px;border:1px solid;border-radius:4px;outline:none;cursor:pointer;-moz-appearance:none;-webkit-appearance:none;background-repeat:no-repeat;background-color:transparent;background-size:20px;background-position:calc(100% - 1px) 56%;background-image:url("down-arrow.svg");max-width:100%;text-overflow:ellipsis;}.search-container{margin-top:4px;}.search-input{-webkit-appearance:none;-moz-box-sizing:border-box !important;box-sizing:border-box !important;outline:none;border:1px solid;border-radius:2px;padding:8px;font-size:1rem;width:100%;}.search-results{display:none;padding-bottom:2em;}.search-results.active{display:block;clear:both;}.search-results .desc>span{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;display:block;}.search-results>a{display:block;width:100%;margin-left:2px;margin-right:2px;border-bottom:1px solid #aaa3;}.search-results>a>div{display:flex;flex-flow:row wrap;}.search-results .result-name,.search-results div.desc,.search-results .result-description{width:50%;}.search-results .result-name{padding-right:1em;}.search-results .result-name>span{display:inline-block;margin:0;font-weight:normal;}.popover{font-size:1rem;position:absolute;right:0;z-index:2;display:block;margin-top:7px;border-radius:3px;border:1px solid;font-size:1rem;}.popover::before{content:'';position:absolute;right:11px;border:solid;border-width:1px 1px 0 0;display:inline-block;padding:4px;transform:rotate(-45deg);top:-5px;}.popover,.popover::before{background-color:var(--main-background-color);color:var(--main-color);}#help-button .popover{max-width:600px;}#help-button .popover::before{right:48px;}#help-button dt{float:left;clear:left;display:block;margin-right:0.5rem;}#help-button span.top,#help-button span.bottom{text-align:center;display:block;font-size:1.125rem;}#help-button span.top{text-align:center;display:block;margin:10px 0;border-bottom:1px solid;padding-bottom:4px;margin-bottom:6px;}#help-button span.bottom{clear:both;border-top:1px solid;}.side-by-side{text-align:initial;}.side-by-side>div{width:50%;float:left;padding:0 20px 20px 17px;}.item-info .stab{width:fit-content;min-height:36px;display:flex;align-items:center;white-space:pre-wrap;}.stab{padding:3px;margin-bottom:5px;font-size:0.875rem;font-weight:normal;}.stab p{display:inline;margin:0;}.stab .emoji{font-size:1.25rem;}.emoji{text-shadow:1px 0 0 black,-1px 0 0 black,0 1px 0 black,0 -1px 0 black;}.module-item .stab,.import-item .stab{border-radius:3px;display:inline-block;font-size:0.875rem;line-height:1.2;margin-bottom:0;margin-left:0.3125em;padding:2px;vertical-align:text-bottom;}.module-item.unstable,.import-item.unstable{opacity:0.65;}.since{font-weight:normal;font-size:initial;}.rightside{padding-left:12px;padding-right:2px;position:initial;}.impl-items .srclink,.impl .srclink,.methods .srclink{font-weight:normal;font-size:1rem;}.rightside{float:right;}.variants_table{width:100%;}.variants_table tbody tr td:first-child{width:1%;}td.summary-column{width:100%;}.summary{padding-right:0px;}pre.rust .question-mark{font-weight:bold;}a.test-arrow{display:inline-block;visibility:hidden;position:absolute;padding:5px 10px 5px 10px;border-radius:5px;font-size:1.375rem;top:5px;right:5px;z-index:1;}.example-wrap:hover .test-arrow{visibility:visible;}a.test-arrow:hover{text-decoration:none;}.code-attribute{font-weight:300;}.item-spacer{width:100%;height:12px;}.out-of-band>span.since{position:initial;font-size:1.25rem;}h3.variant{font-weight:600;font-size:1.125rem;margin-bottom:10px;border-bottom:none;}.sub-variant h4{font-size:1rem;font-weight:400;border-bottom:none;margin-top:0;margin-bottom:0;}.sub-variant{margin-left:24px;margin-bottom:40px;}.sub-variant>.sub-variant-field{margin-left:24px;}.toggle-label{display:inline-block;margin-left:4px;margin-top:3px;}:target>code,:target>.code-header{opacity:1;}:target{padding-right:3px;}.information{position:absolute;left:-25px;margin-top:7px;z-index:1;}.tooltip{position:relative;display:inline-block;cursor:pointer;}.tooltip::after{display:none;text-align:center;padding:5px 3px 3px 3px;border-radius:6px;margin-left:5px;font-size:1rem;}.tooltip.ignore::after{content:"This example is not tested";}.tooltip.compile_fail::after{content:"This example deliberately fails to compile";}.tooltip.should_panic::after{content:"This example panics";}.tooltip.edition::after{content:"This code runs with edition " attr(data-edition);}.tooltip::before{content:" ";position:absolute;top:50%;left:16px;margin-top:-5px;border-width:5px;border-style:solid;display:none;}.tooltip:hover::before,.tooltip:hover::after{display:inline;}.tooltip.compile_fail,.tooltip.should_panic,.tooltip.ignore{font-weight:bold;font-size:1.25rem;}.notable-traits-tooltip{display:inline-block;cursor:pointer;}.notable-traits:hover .notable-traits-tooltiptext,.notable-traits .notable-traits-tooltiptext.force-tooltip{display:inline-block;}.notable-traits .notable-traits-tooltiptext{display:none;padding:5px 3px 3px 3px;border-radius:6px;margin-left:5px;z-index:10;font-size:1rem;cursor:default;position:absolute;border:1px solid;}.notable-traits-tooltip::after{content:"\00a0\00a0\00a0";}.notable-traits .notable,.notable-traits .docblock{margin:0;}.notable-traits .notable{margin:0;margin-bottom:13px;font-size:1.1875rem;font-weight:600;display:block;}.notable-traits .docblock code.content{margin:0;padding:0;font-size:1.25rem;}pre.rust.rust-example-rendered{position:relative;}pre.rust{tab-size:4;-moz-tab-size:4;}.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;}#titles{height:35px;}#titles>button{float:left;width:33.3%;text-align:center;font-size:1.125rem;cursor:pointer;border:0;border-top:2px solid;}#titles>button:first-child:last-child{margin-right:1px;width:calc(100% - 1px);}#titles>button:not(:last-child){margin-right:1px;width:calc(33.3% - 1px);}#titles>button>div.count{display:inline-block;font-size:1rem;}.notable-traits{cursor:pointer;z-index:2;margin-left:5px;}#sidebar-toggle{position:sticky;top:0;left:0;font-weight:bold;font-size:1.25rem;border-bottom:1px solid;display:flex;height:40px;justify-content:center;align-items:center;z-index:10;}#source-sidebar{width:100%;z-index:1;overflow:auto;}#source-sidebar>.title{font-size:1.5rem;text-align:center;border-bottom:1px solid;margin-bottom:6px;}#sidebar-toggle>button{background:none;color:inherit;cursor:pointer;text-align:center;border:none;outline:none;position:absolute;top:0;bottom:0;left:0;right:0;width:100%;-webkit-appearance:none;opacity:1;}#settings-menu,#help-button{margin-left:4px;outline:none;}#copy-path{height:34px;}#settings-menu>a,#help-button>button,#copy-path{padding:5px;width:33px;border:1px solid;border-radius:2px;cursor:pointer;}#settings-menu{padding:0;}#settings-menu>a,#help-button>button{padding:5px;height:100%;display:block;}@keyframes rotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}#settings-menu.rotate>a img{animation:rotating 2s linear infinite;}.setting-line .radio-line input:checked{box-shadow:inset 0 0 0 3px var(--main-background-color);background-color:var(--settings-input-color);}.setting-line .radio-line input:focus{box-shadow:0 0 1px 1px var(--settings-input-color);}.setting-line .radio-line input:checked:focus{box-shadow:inset 0 0 0 3px var(--main-background-color),0 0 2px 2px var(--settings-input-color);}.setting-line .radio-line input:hover{border-color:var(--settings-input-color) !important;}input:checked+.slider{background-color:var(--settings-input-color);}#help-button>button{text-align:center;font-size:20px;padding-top:2px;}#copy-path{background:initial;margin-left:10px;padding:0;padding-left:2px;border:0;}#theme-choices{display:none;position:absolute;left:0;top:28px;border:1px solid;border-radius:3px;z-index:1;cursor:pointer;}#theme-choices>button{border:none;width:100%;padding:4px 8px;text-align:center;background:rgba(0,0,0,0);overflow-wrap:normal;}#theme-choices>button:not(:first-child){border-top:1px solid;}kbd{display:inline-block;padding:3px 5px;font:15px monospace;line-height:10px;vertical-align:middle;border:solid 1px;border-radius:3px;cursor:default;}.hidden-by-impl-hider,.hidden-by-usual-hider{display:none !important;}#implementations-list>h3>span.in-band{width:100%;}.table-display{width:100%;border:0;border-collapse:collapse;border-spacing:0;font-size:1rem;}.table-display tr td:first-child{padding-right:0;}.table-display tr td:last-child{float:right;}.table-display .out-of-band{position:relative;font-size:1.125rem;display:block;}.table-display td:hover .anchor{display:block;top:2px;left:-5px;}#main-content>ul{padding-left:10px;}#main-content>ul>li{list-style:none;}.non-exhaustive{margin-bottom:1em;}details.dir-entry{padding-left:4px;}details.dir-entry>summary{margin:0 0 0 13px;list-style-position:outside;cursor:pointer;}details.dir-entry div.folders,details.dir-entry div.files{padding-left:23px;}details.dir-entry a{display:block;}details.rustdoc-toggle>summary.hideme{cursor:pointer;}details.rustdoc-toggle>summary{list-style:none;}details.rustdoc-toggle>summary::-webkit-details-marker,details.rustdoc-toggle>summary::marker{display:none;}details.rustdoc-toggle>summary.hideme>span{margin-left:9px;}details.rustdoc-toggle>summary::before{content:"";cursor:pointer;width:16px;height:16px;background-repeat:no-repeat;background-position:top left;display:inline-block;vertical-align:middle;opacity:.5;}details.rustdoc-toggle>summary::after{content:"Expand";overflow:hidden;width:0;height:0;position:absolute;}details.rustdoc-toggle>summary.hideme::after{content:"";}details.rustdoc-toggle>summary:focus::before,details.rustdoc-toggle>summary:hover::before{opacity:1;}details.rustdoc-toggle.top-doc>summary,details.rustdoc-toggle.top-doc>summary::before,details.rustdoc-toggle.non-exhaustive>summary,details.rustdoc-toggle.non-exhaustive>summary::before{font-size:1rem;}details.non-exhaustive{margin-bottom:8px;}details.rustdoc-toggle>summary.hideme::before{position:relative;}details.rustdoc-toggle>summary:not(.hideme)::before{position:absolute;left:-24px;top:4px;}.impl-items>details.rustdoc-toggle>summary:not(.hideme)::before{position:absolute;left:-24px;}details.rustdoc-toggle[open] >summary.hideme{position:absolute;}details.rustdoc-toggle{position:relative;}details.rustdoc-toggle[open] >summary.hideme>span{display:none;}details.rustdoc-toggle[open] >summary::before,details.rustdoc-toggle[open] >summary.hideme::before{background-image:url("toggle-minus.svg");}details.rustdoc-toggle>summary::before{background-image:url("toggle-plus.svg");}details.rustdoc-toggle[open] >summary::before,details.rustdoc-toggle[open] >summary.hideme::before{width:16px;height:16px;background-repeat:no-repeat;background-position:top left;display:inline-block;content:"";}details.rustdoc-toggle[open] >summary::after,details.rustdoc-toggle[open] >summary.hideme::after{content:"Collapse";}.docblock summary>*{display:inline-block;}@media (min-width:701px){.docblock>.information:first-child>.tooltip{margin-top:16px;}.source-sidebar-expanded .source .sidebar+main .width-limiter .sub-logo-container.rust-logo{display:none;}.source-sidebar-expanded .source .sidebar{width:300px;}}@media (max-width:700px){*[id]{scroll-margin-top:45px;}.rustdoc{padding-top:0px;display:block;}main{padding-left:15px;padding-top:0px;}.rustdoc,.main-heading{flex-direction:column;}.content .out-of-band{text-align:left;margin-left:initial;padding:initial;}.content .out-of-band .since::before{content:"Since ";}#copy-path{display:none;}.sidebar .sidebar-logo,.sidebar .location{display:none;}.sidebar-elems{margin-top:1em;}.sidebar{position:fixed;top:45px;left:-1000px;margin-left:0;margin:0;padding:0;z-index:11;height:calc(100vh - 45px);}.source main,.rustdoc.source .sidebar{top:0;padding:0;height:100vh;border:0;}.sidebar.shown,.source-sidebar-expanded .source .sidebar,.sidebar:focus-within{left:0;}.rustdoc.source>.sidebar{position:fixed;margin:0;z-index:11;width:0;}.mobile-topbar .location a{padding:0;margin:0;}.mobile-topbar .location{border:none;padding:0;margin:auto 0.5em auto auto;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;font-size:24px;}.mobile-topbar .logo-container{max-height:45px;}.mobile-topbar .logo-container>img{max-width:35px;max-height:35px;margin-left:20px;margin-top:5px;margin-bottom:5px;}.mobile-topbar{display:flex;flex-direction:row;position:sticky;z-index:10;font-size:2rem;height:45px;width:100%;left:0;top:0;}.source .mobile-topbar{display:none;}.sidebar-menu-toggle{width:45px;font-size:32px;border:none;}.sidebar-elems{background-color:var(--sidebar-background-color);}.source nav:not(.sidebar).sub{margin-left:32px;}.content{margin-left:0px;}.source .content{margin-top:10px;}#search{margin-left:0;padding:0;}.anchor{display:none !important;}.notable-traits{position:absolute;left:-22px;top:24px;}#titles>button>div.count{float:left;width:100%;}#titles{height:50px;}#sidebar-filler{position:fixed;left:45px;width:calc(100% - 45px);top:0;height:45px;z-index:-1;border-bottom:1px solid;}#main-content>details.rustdoc-toggle>summary::before,#main-content>div>details.rustdoc-toggle>summary::before{left:-11px;}#sidebar-toggle{position:fixed;left:1px;top:100px;width:30px;font-size:1.5rem;text-align:center;padding:0;z-index:10;border-top-right-radius:3px;border-bottom-right-radius:3px;cursor:pointer;font-weight:bold;border:1px solid;border-left:0;}.source-sidebar-expanded #sidebar-toggle{left:unset;top:unset;width:unset;border-top-right-radius:unset;border-bottom-right-radius:unset;position:sticky;border:0;border-bottom:1px solid;}#source-sidebar{z-index:11;}#main-content>.line-numbers{margin-top:0;}.notable-traits .notable-traits-tooltiptext{left:0;top:100%;}#help-button{display:none;}.item-table{display:block;}.item-row{display:flex;flex-flow:column wrap;}.item-left,.item-right{width:100%;}.search-results>a{border-bottom:1px solid #aaa9;padding:5px 0px;}.search-results .result-name,.search-results div.desc,.search-results .result-description{width:100%;}.search-results div.desc,.search-results .result-description,.item-right{padding-left:2em;}.source-sidebar-expanded .source .sidebar{max-width:100vw;width:100vw;}details.rustdoc-toggle:not(.top-doc)>summary{margin-left:10px;}.impl-items>details.rustdoc-toggle>summary:not(.hideme)::before,#main-content>details.rustdoc-toggle:not(.top-doc)>summary::before,#main-content>div>details.rustdoc-toggle>summary::before{left:-11px;}}@media print{nav.sidebar,nav.sub,.content .out-of-band,a.srclink,#copy-path,details.rustdoc-toggle[open] >summary::before,details.rustdoc-toggle>summary::before,details.rustdoc-toggle.top-doc>summary{display:none;}.docblock{margin-left:0;}main{padding:10px;}}@media (max-width:464px){#titles,#titles>button{height:73px;}#main-content>table:not(.table-display) td{word-break:break-word;width:50%;}#crate-search{border-radius:4px;}.docblock{margin-left:12px;}.docblock code{overflow-wrap:break-word;overflow-wrap:anywhere;}.sub-container{flex-direction:column;}.sub-logo-container{align-self:center;}.source .sub-logo-container>img{height:35px;width:35px;}#sidebar-toggle{top:10px;}.source-sidebar-expanded #sidebar-toggle{top:unset;}}.method-toggle summary,.implementors-toggle summary,.impl{margin-bottom:0.75em;}.method-toggle[open]{margin-bottom:2em;}.implementors-toggle[open]{margin-bottom:2em;}#trait-implementations-list .method-toggle,#synthetic-implementations-list .method-toggle,#blanket-implementations-list .method-toggle{margin-bottom:1em;}.scraped-example-list .scrape-help{margin-left:10px;padding:0 4px;font-weight:normal;font-size:12px;position:relative;bottom:1px;background:transparent;border-width:1px;border-style:solid;border-radius:50px;}.scraped-example .code-wrapper{position:relative;display:flex;flex-direction:row;flex-wrap:wrap;width:100%;}.scraped-example:not(.expanded) .code-wrapper{max-height:240px;}.scraped-example:not(.expanded) .code-wrapper pre{overflow-y:hidden;max-height:240px;padding-bottom:0;}.scraped-example:not(.expanded) .code-wrapper pre.line-numbers{overflow-x:hidden;}.scraped-example .code-wrapper .prev{position:absolute;top:0.25em;right:2.25em;z-index:100;cursor:pointer;}.scraped-example .code-wrapper .next{position:absolute;top:0.25em;right:1.25em;z-index:100;cursor:pointer;}.scraped-example .code-wrapper .expand{position:absolute;top:0.25em;right:0.25em;z-index:100;cursor:pointer;}.scraped-example:not(.expanded) .code-wrapper:before{content:" ";width:100%;height:5px;position:absolute;z-index:100;top:0;}.scraped-example:not(.expanded) .code-wrapper:after{content:" ";width:100%;height:5px;position:absolute;z-index:100;bottom:0;}.scraped-example .code-wrapper .line-numbers{margin:0;padding:14px 0;}.scraped-example .code-wrapper .line-numbers span{padding:0 14px;}.scraped-example .code-wrapper .example-wrap{flex:1;overflow-x:auto;overflow-y:hidden;margin-bottom:0;}.scraped-example:not(.expanded) .code-wrapper .example-wrap{overflow-x:hidden;}.scraped-example .code-wrapper .example-wrap pre.rust{overflow-x:inherit;width:inherit;overflow-y:hidden;}.more-examples-toggle{max-width:calc(100% + 25px);margin-top:10px;margin-left:-25px;}.more-examples-toggle .hide-more{margin-left:25px;margin-bottom:5px;cursor:pointer;}.more-scraped-examples{margin-left:5px;display:flex;flex-direction:row;}.more-scraped-examples-inner{width:calc(100% - 20px);}.toggle-line{align-self:stretch;margin-right:10px;margin-top:5px;padding:0 4px;cursor:pointer;}.toggle-line-inner{min-width:2px;height:100%;}.more-scraped-examples .scraped-example{margin-bottom:20px;}.more-scraped-examples .scraped-example:last-child{margin-bottom:0;}.example-links a{margin-top:20px;}.example-links ul{margin-bottom:0;} \ No newline at end of file + @font-face {font-family:'Fira Sans';font-style:normal;font-weight:400;src:local('Fira Sans'),url("FiraSans-Regular.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.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.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.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.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:400;src:url("SourceCodePro-Regular.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:italic;font-weight:400;src:url("SourceCodePro-It.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:600;src:url("SourceCodePro-Semibold.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'NanumBarunGothic';src:url("NanumBarunGothic.ttf.woff2") format("woff2");font-display:swap;unicode-range:U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF;}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}html{content:"";}@media (prefers-color-scheme:light){html{content:"light";}}@media (prefers-color-scheme:dark){html{content:"dark";}}body{font:1rem/1.5 "Source Serif 4",NanumBarunGothic,serif;margin:0;position:relative;overflow-wrap:break-word;overflow-wrap:anywhere;-webkit-font-feature-settings:"kern","liga";-moz-font-feature-settings:"kern","liga";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:20px 0 15px 0;padding-bottom:6px;}.docblock h3,.docblock h4,h5,h6{margin:15px 0 5px 0;}h1.fqn{margin:0;padding:0;border-bottom-color:var(--headings-border-bottom-color);}h2,h3,h4{border-bottom-color:var(--headings-border-bottom-color);}.main-heading{display:flex;flex-wrap:wrap;justify-content:space-between;padding-bottom:6px;margin-bottom:15px;}.main-heading a:hover{text-decoration:underline;}#toggle-all-docs{text-decoration:none;}h2,.top-doc .docblock>h3,.top-doc .docblock>h4{border-bottom:1px solid var(--headings-border-bottom-color);}h3.code-header{font-size:1.125rem;}h4.code-header{font-size:1rem;}.code-header{font-weight:600;border-bottom-style:none;margin:0;padding:0;margin-top:0.6em;margin-bottom:0.4em;}.impl,.impl-items .method,.methods .method,.impl-items .type,.methods .type,.impl-items .associatedconstant,.methods .associatedconstant,.impl-items .associatedtype,.methods .associatedtype{flex-basis:100%;font-weight:600;position:relative;}div.impl-items>div{padding-left:0;}h1,h2,h3,h4,h5,h6,.sidebar,.mobile-topbar,a.source,.search-input,.search-results .result-name,.content table td:first-child>a,.item-left>a,.out-of-band,span.since,#source-sidebar,#sidebar-toggle,details.rustdoc-toggle>summary::before,div.impl-items>div:not(.docblock):not(.item-info),.content ul.crate a.crate,a.srclink,#main-content>.since,#help-button>button,details.rustdoc-toggle.top-doc>summary,details.rustdoc-toggle.top-doc>summary::before,details.rustdoc-toggle.non-exhaustive>summary,details.rustdoc-toggle.non-exhaustive>summary::before,.scraped-example-title,.more-examples-toggle summary,.more-examples-toggle .hide-more,.example-links a,#main-content>ul.docblock>li>a{font-family:"Fira Sans",Arial,NanumBarunGothic,sans-serif;}h1,h2,h3,h4,a#toggle-all-docs,a.anchor,.small-section-header a,#source-sidebar a,pre.rust a,.sidebar h2 a,.sidebar h3 a,.mobile-topbar h2 a,.in-band a,.search-results a,.module-item .stab,.import-item .stab,.result-name .primitive>i,.result-name .keyword>i,.content .method .where,.content .fn .where,.content .where.fmt-newline{color:var(--main-color);}ol,ul{padding-left:24px;}ul ul,ol ul,ul ol,ol ol{margin-bottom:.625em;}p{margin:0 0 .75em 0;}summary{outline:none;}td,th{padding:0;}table{border-collapse:collapse;}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0;}button{padding:1px 6px;}.rustdoc{display:flex;flex-direction:row;flex-wrap:nowrap;}main{position:relative;flex-grow:1;padding:10px 15px 40px 45px;min-width:0;}.source main{padding:15px;}.width-limiter{max-width:960px;margin-right:auto;}.source .width-limiter{max-width:unset;}details:not(.rustdoc-toggle) summary{margin-bottom:.6em;}code,pre,a.test-arrow,.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;}.docblock.item-decl{margin-left:0;}.item-decl pre{overflow-x:auto;}.source .content pre{padding:20px;}img{max-width:100%;}li{position:relative;}.source .content{max-width:none;overflow:visible;margin-left:0px;}nav.sub{position:relative;font-size:1rem;}.sub-container{display:flex;flex-direction:row;flex-wrap:nowrap;}.sub-logo-container{display:none;margin-right:20px;}.source .sub-logo-container{display:block;}.source .sub-logo-container>img{height:60px;width:60px;object-fit:contain;}.sidebar,.mobile-topbar,.sidebar-menu-toggle{background-color:var(--sidebar-background-color);}.sidebar{font-size:0.875rem;width:250px;min-width:200px;overflow-y:scroll;position:sticky;height:100vh;top:0;left:0;}.sidebar-elems,.sidebar>.location{padding-left:24px;}.sidebar .location{overflow-wrap:anywhere;}.rustdoc.source .sidebar{width:50px;min-width:0px;max-width:300px;flex-grow:0;flex-shrink:0;flex-basis:auto;border-right:1px solid;overflow-x:hidden;overflow-y:hidden;}.rustdoc.source .sidebar .sidebar-logo{display:none;}.source .sidebar,#sidebar-toggle,#source-sidebar{background-color:var(--sidebar-background-color);}#sidebar-toggle>button:hover,#sidebar-toggle>button:focus{background-color:var(--sidebar-background-color-hover);}.source .sidebar>*:not(#sidebar-toggle){opacity:0;visibility:hidden;}.source-sidebar-expanded .source .sidebar{overflow-y:auto;}.source-sidebar-expanded .source .sidebar>*:not(#sidebar-toggle){opacity:1;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;}.sidebar .logo-container{display:flex;margin-top:10px;margin-bottom:10px;justify-content:center;}.version{overflow-wrap:break-word;}.logo-container>img{height:100px;width:100px;}.location:empty{border:none;}.location a:first-of-type{font-weight:500;}.block{padding:0;}.block ul,.block li{padding:0;margin:0;list-style:none;}.block a,h2.location a{display:block;padding:0.25rem;margin-left:-0.25rem;text-overflow:ellipsis;overflow:hidden;}.sidebar h2{border-bottom:none;font-weight:500;padding:0;margin:0;margin-top:0.7rem;margin-bottom:0.7rem;}.sidebar h3{font-size:1.125rem;font-weight:500;padding:0;margin:0;}.sidebar-elems .block{margin-bottom:2em;}.sidebar-elems .block li a{white-space:nowrap;}.mobile-topbar{display:none;}.source .content pre.rust{white-space:pre;overflow:auto;padding-left:0;}.rustdoc .example-wrap{display:inline-flex;margin-bottom:10px;}.example-wrap{position:relative;width:100%;}.example-wrap>pre.line-number{overflow:initial;border:1px solid;padding:13px 8px;text-align:right;border-top-left-radius:5px;border-bottom-left-radius:5px;}.example-wrap>pre.rust a:hover{text-decoration:underline;}.line-numbers{text-align:right;}.rustdoc:not(.source) .example-wrap>pre:not(.line-number){width:100%;overflow-x:auto;}.rustdoc:not(.source) .example-wrap>pre.line-numbers{width:auto;overflow-x:visible;}.rustdoc .example-wrap>pre{margin:0;}#search{position:relative;}.search-loading{text-align:center;}#results>table{width:100%;table-layout:fixed;}.content>.example-wrap pre.line-numbers{position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}.line-numbers span{cursor:pointer;}.docblock-short{overflow-wrap:break-word;overflow-wrap:anywhere;}.docblock-short p{display:inline;}.docblock-short p{overflow:hidden;text-overflow:ellipsis;margin:0;}.docblock>:not(pre)>code,.docblock-short>:not(pre)>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 h1,.docblock h2,.docblock h3,.docblock h4,.docblock h5,.docblock h6{border-bottom-color:var(--headings-border-bottom-color);}.docblock{margin-left:24px;position:relative;}.docblock>:not(.information):not(.more-examples-toggle){max-width:100%;overflow-x:auto;}.content .out-of-band{flex-grow:0;font-size:1.125rem;font-weight:normal;float:right;}.method>.code-header,.trait-impl>.code-header{max-width:calc(100% - 41px);display:block;}.content .in-band{flex-grow:1;margin:0px;padding:0px;overflow-wrap:break-word;overflow-wrap:anywhere;background-color:var(--main-background-color);}.in-band>code,.in-band>.code-header{display:inline-block;}.docblock code,.docblock-short code,pre,.rustdoc.source .example-wrap{background-color:var(--code-block-background-color);}#main-content{position:relative;}#main-content>.since{top:inherit;}.content table:not(.table-display){border-spacing:0 5px;}.content td{vertical-align:top;}.content td:first-child{padding-right:20px;}.content td p:first-child{margin-top:0;}.content td h1,.content td h2{margin-left:0;font-size:1.125rem;}.content tr:first-child td{border-top:0;}.docblock table{margin:.5em 0;width:calc(100% - 2px);overflow-x:auto;display:block;}.docblock table td{padding:.5em;border:1px dashed var(--border-color);}.docblock table th{padding:.5em;text-align:left;border:1px solid var(--border-color);}.fields+table{margin-bottom:1em;}.content .item-list{list-style-type:none;padding:0;}.content .multi-column{-moz-column-count:5;-moz-column-gap:2.5em;-webkit-column-count:5;-webkit-column-gap:2.5em;column-count:5;column-gap:2.5em;}.content .multi-column li{width:100%;display:inline-block;}.content>.methods>.method{font-size:1rem;position:relative;}.content .method .where,.content .fn .where,.content .where.fmt-newline{display:block;font-size:0.875rem;}.content .methods>div:not(.notable-traits):not(.method){margin-left:40px;margin-bottom:15px;}.content .docblock>.impl-items{margin-left:20px;margin-top:-34px;}.content .docblock>.impl-items .table-display{margin:0;}.content .docblock>.impl-items table td{padding:0;}.content .docblock>.impl-items .table-display,.impl-items table td{border:none;}.item-info{display:block;}.content .item-info code{font-size:0.875rem;}.content .item-info{position:relative;margin-left:24px;}.sub-variant>div>.item-info{margin-top:initial;}.content .impl-items .docblock,.content .impl-items .item-info{margin-bottom:.6em;}.content .impl-items>.item-info{margin-left:40px;}.methods>.item-info,.content .impl-items>.item-info{margin-top:-8px;}.impl-items{flex-basis:100%;}#main-content>.item-info{margin-top:0;margin-left:0;}nav.sub{flex-grow:1;margin-bottom:25px;}.source nav.sub{margin-left:32px;}nav.sum{text-align:right;}nav.sub form{display:inline;}a{text-decoration:none;background:transparent;}.small-section-header{display:flex;justify-content:space-between;position:relative;}.small-section-header:hover>.anchor{display:initial;}.in-band:hover>.anchor,.impl:hover>.anchor,.method.trait-impl:hover>.anchor,.type.trait-impl:hover>.anchor,.associatedconstant.trait-impl:hover>.anchor,.associatedtype.trait-impl:hover>.anchor{display:inline-block;position:absolute;}.anchor{display:none;position:absolute;left:-0.5em;background:none !important;}.anchor.field{left:-5px;}.small-section-header>.anchor{left:-15px;padding-right:8px;}h2.small-section-header>.anchor{padding-right:6px;}.anchor::before{content:'§';}.docblock a:not(.srclink):not(.test-arrow):not(.scrape-help):hover,.docblock-short a:not(.srclink):not(.test-arrow):not(.scrape-help):hover,.item-info a{text-decoration:underline;}.block a.current.crate{font-weight:500;}table,.item-table{overflow-wrap:break-word;}.item-table{display:table;}.item-row{display:table-row;}.item-left,.item-right{display:table-cell;}.item-left{padding-right:1.25rem;}.search-container{position:relative;display:flex;height:34px;}.search-container>*{height:100%;}.search-results-title{margin-top:0;white-space:nowrap;display:inline-flex;max-width:100%;align-items:baseline;}#crate-search-div{display:inline-block;position:relative;min-width:5em;}#crate-search{min-width:115px;padding:0;padding-left:4px;padding-right:23px;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);}@-moz-document url-prefix(){#crate-search{padding-left:0px;padding-right:19px;}}#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("down-arrow.svg");}#crate-search>option{font-size:1rem;}.search-container{margin-top:4px;}.search-input{-webkit-appearance:none;-moz-box-sizing:border-box !important;box-sizing:border-box !important;outline:none;border:1px solid var(--border-color);border-radius:2px;padding:8px;font-size:1rem;width:100%;background-color:var(--button-background-color);}.search-results{display:none;padding-bottom:2em;}.search-results.active{display:block;clear:both;}.search-results .desc>span{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;display:block;}.search-results>a{display:block;width:100%;margin-left:2px;margin-right:2px;border-bottom:1px solid #aaa3;}.search-results>a>div{display:flex;flex-flow:row wrap;}.search-results .result-name,.search-results div.desc,.search-results .result-description{width:50%;}.search-results .result-name{padding-right:1em;}.search-results .result-name>span{display:inline-block;margin:0;font-weight:normal;}.popover{font-size:1rem;position:absolute;right:0;z-index:2;display:block;margin-top:7px;border-radius:3px;border:1px solid var(--border-color);font-size:1rem;}.popover::before{content:'';position:absolute;right:11px;border:solid var(--border-color);border-width:1px 1px 0 0;display:inline-block;padding:4px;transform:rotate(-45deg);top:-5px;}.popover,.popover::before{background-color:var(--main-background-color);color:var(--main-color);}#help-button .popover{max-width:600px;}#help-button .popover::before{right:48px;}#help-button dt{float:left;clear:left;display:block;margin-right:0.5rem;}#help-button span.top,#help-button span.bottom{text-align:center;display:block;font-size:1.125rem;}#help-button span.top{text-align:center;display:block;margin:10px 0;border-bottom:1px solid var(--border-color);padding-bottom:4px;margin-bottom:6px;}#help-button span.bottom{clear:both;border-top:1px solid var(--border-color);}.side-by-side{text-align:initial;}.side-by-side>div{width:50%;float:left;padding:0 20px 20px 17px;}.item-info .stab{width:fit-content;min-height:36px;display:flex;align-items:center;white-space:pre-wrap;}.stab{padding:3px;margin-bottom:5px;font-size:0.875rem;font-weight:normal;}.stab p{display:inline;margin:0;}.stab .emoji{font-size:1.25rem;margin-right:0.3rem;}.emoji{text-shadow:1px 0 0 black,-1px 0 0 black,0 1px 0 black,0 -1px 0 black;}.module-item .stab,.import-item .stab{border-radius:3px;display:inline-block;font-size:0.875rem;line-height:1.2;margin-bottom:0;margin-left:0.3125em;padding:2px;vertical-align:text-bottom;}.module-item.unstable,.import-item.unstable{opacity:0.65;}.since{font-weight:normal;font-size:initial;}.rightside{padding-left:12px;padding-right:2px;position:initial;}.impl-items .srclink,.impl .srclink,.methods .srclink{font-weight:normal;font-size:1rem;}.rightside{float:right;}.variants_table{width:100%;}.variants_table tbody tr td:first-child{width:1%;}td.summary-column{width:100%;}.summary{padding-right:0px;}pre.rust .question-mark{font-weight:bold;}a.test-arrow{display:inline-block;visibility:hidden;position:absolute;padding:5px 10px 5px 10px;border-radius:5px;font-size:1.375rem;top:5px;right:5px;z-index:1;}.example-wrap:hover .test-arrow{visibility:visible;}a.test-arrow:hover{text-decoration:none;}.code-attribute{font-weight:300;}.item-spacer{width:100%;height:12px;}.out-of-band>span.since{position:initial;font-size:1.25rem;}h3.variant{font-weight:600;font-size:1.125rem;margin-bottom:10px;border-bottom:none;}.sub-variant h4{font-size:1rem;font-weight:400;border-bottom:none;margin-top:0;margin-bottom:0;}.sub-variant{margin-left:24px;margin-bottom:40px;}.sub-variant>.sub-variant-field{margin-left:24px;}.toggle-label{display:inline-block;margin-left:4px;margin-top:3px;}:target>code,:target>.code-header{opacity:1;}:target{padding-right:3px;}.information{position:absolute;left:-25px;margin-top:7px;z-index:1;}.tooltip{position:relative;display:inline-block;cursor:pointer;}.tooltip::after{display:none;text-align:center;padding:5px 3px 3px 3px;border-radius:6px;margin-left:5px;font-size:1rem;border:1px solid var(--border-color);}.tooltip.ignore::after{content:"This example is not tested";}.tooltip.compile_fail::after{content:"This example deliberately fails to compile";}.tooltip.should_panic::after{content:"This example panics";}.tooltip.edition::after{content:"This code runs with edition " attr(data-edition);}.tooltip::before{content:" ";position:absolute;top:50%;left:16px;margin-top:-5px;border-width:5px;border-style:solid;display:none;}.tooltip:hover::before,.tooltip:hover::after{display:inline;}.tooltip.compile_fail,.tooltip.should_panic,.tooltip.ignore{font-weight:bold;font-size:1.25rem;}.notable-traits-tooltip{display:inline-block;cursor:pointer;}.notable-traits:hover .notable-traits-tooltiptext,.notable-traits .notable-traits-tooltiptext.force-tooltip{display:inline-block;}.notable-traits .notable-traits-tooltiptext{display:none;padding:5px 3px 3px 3px;border-radius:6px;margin-left:5px;z-index:10;font-size:1rem;cursor:default;position:absolute;border:1px solid;}.notable-traits-tooltip::after{content:"\00a0\00a0\00a0";}.notable-traits .notable,.notable-traits .docblock{margin:0;}.notable-traits .notable{margin:0;margin-bottom:13px;font-size:1.1875rem;font-weight:600;display:block;}.notable-traits .docblock code.content{margin:0;padding:0;font-size:1.25rem;}pre.rust.rust-example-rendered{position:relative;}pre.rust{tab-size:4;-moz-tab-size:4;}.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;}#titles{height:35px;}#titles>button{float:left;width:33.3%;text-align:center;font-size:1.125rem;cursor:pointer;border:0;border-top:2px solid;}#titles>button:first-child:last-child{margin-right:1px;width:calc(100% - 1px);}#titles>button:not(:last-child){margin-right:1px;width:calc(33.3% - 1px);}#titles>button>div.count{display:inline-block;font-size:1rem;}.notable-traits{cursor:pointer;z-index:2;margin-left:5px;}#sidebar-toggle{position:sticky;top:0;left:0;font-weight:bold;font-size:1.25rem;border-bottom:1px solid;display:flex;height:40px;justify-content:center;align-items:center;z-index:10;}#source-sidebar{width:100%;z-index:1;overflow:auto;}#source-sidebar>.title{font-size:1.5rem;text-align:center;border-bottom:1px solid var(--border-color);margin-bottom:6px;}#sidebar-toggle>button{background:none;color:inherit;cursor:pointer;text-align:center;border:none;outline:none;position:absolute;top:0;bottom:0;left:0;right:0;width:100%;-webkit-appearance:none;opacity:1;}#settings-menu,#help-button{margin-left:4px;outline:none;}#copy-path{height:34px;background-color:var(--main-background-color);}#settings-menu>a,#help-button>button,#copy-path{padding:5px;width:33px;border:1px solid var(--border-color);border-radius:2px;cursor:pointer;}#settings-menu{padding:0;}#settings-menu>a,#help-button>button{padding:5px;height:100%;display:block;background-color:var(--button-background-color);}@keyframes rotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}#settings-menu.rotate>a img{animation:rotating 2s linear infinite;}.setting-line .radio-line input:checked{box-shadow:inset 0 0 0 3px var(--main-background-color);background-color:var(--settings-input-color);}.setting-line .radio-line input:focus{box-shadow:0 0 1px 1px var(--settings-input-color);}.setting-line .radio-line input:checked:focus{box-shadow:inset 0 0 0 3px var(--main-background-color),0 0 2px 2px var(--settings-input-color);}.setting-line .radio-line input:hover{border-color:var(--settings-input-color) !important;}input:checked+.slider{background-color:var(--settings-input-color);}#help-button>button{text-align:center;font-size:20px;padding-top:2px;}#copy-path{background:initial;margin-left:10px;padding:0;padding-left:2px;border:0;}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;cursor:default;}.hidden-by-impl-hider,.hidden-by-usual-hider{display:none !important;}#implementations-list>h3>span.in-band{width:100%;}.table-display{width:100%;border:0;border-collapse:collapse;border-spacing:0;font-size:1rem;}.table-display tr td:first-child{padding-right:0;}.table-display tr td:last-child{float:right;}.table-display .out-of-band{position:relative;font-size:1.125rem;display:block;}.table-display td:hover .anchor{display:block;top:2px;left:-5px;}#main-content>ul{padding-left:10px;}#main-content>ul>li{list-style:none;}.non-exhaustive{margin-bottom:1em;}details.dir-entry{padding-left:4px;}details.dir-entry>summary{margin:0 0 0 13px;list-style-position:outside;cursor:pointer;}details.dir-entry div.folders,details.dir-entry div.files{padding-left:23px;}details.dir-entry a{display:block;}details.rustdoc-toggle>summary.hideme{cursor:pointer;}details.rustdoc-toggle>summary{list-style:none;}details.rustdoc-toggle>summary::-webkit-details-marker,details.rustdoc-toggle>summary::marker{display:none;}details.rustdoc-toggle>summary.hideme>span{margin-left:9px;}details.rustdoc-toggle>summary::before{content:"";cursor:pointer;width:16px;height:16px;background-repeat:no-repeat;background-position:top left;display:inline-block;vertical-align:middle;opacity:.5;}details.rustdoc-toggle>summary::after{content:"Expand";overflow:hidden;width:0;height:0;position:absolute;}details.rustdoc-toggle>summary.hideme::after{content:"";}details.rustdoc-toggle>summary:focus::before,details.rustdoc-toggle>summary:hover::before{opacity:1;}details.rustdoc-toggle.top-doc>summary,details.rustdoc-toggle.top-doc>summary::before,details.rustdoc-toggle.non-exhaustive>summary,details.rustdoc-toggle.non-exhaustive>summary::before{font-size:1rem;}details.non-exhaustive{margin-bottom:8px;}details.rustdoc-toggle>summary.hideme::before{position:relative;}details.rustdoc-toggle>summary:not(.hideme)::before{position:absolute;left:-24px;top:4px;}.impl-items>details.rustdoc-toggle>summary:not(.hideme)::before{position:absolute;left:-24px;}details.rustdoc-toggle[open] >summary.hideme{position:absolute;}details.rustdoc-toggle{position:relative;}details.rustdoc-toggle[open] >summary.hideme>span{display:none;}details.rustdoc-toggle[open] >summary::before,details.rustdoc-toggle[open] >summary.hideme::before{background-image:url("toggle-minus.svg");}details.rustdoc-toggle>summary::before{background-image:url("toggle-plus.svg");}details.rustdoc-toggle[open] >summary::before,details.rustdoc-toggle[open] >summary.hideme::before{width:16px;height:16px;background-repeat:no-repeat;background-position:top left;display:inline-block;content:"";}details.rustdoc-toggle[open] >summary::after,details.rustdoc-toggle[open] >summary.hideme::after{content:"Collapse";}.docblock summary>*{display:inline-block;}@media (min-width:701px){.docblock>.information:first-child>.tooltip{margin-top:16px;}.source-sidebar-expanded .source .sidebar+main .width-limiter .sub-logo-container.rust-logo{display:none;}.source-sidebar-expanded .source .sidebar{width:300px;}}@media (max-width:700px){*[id]{scroll-margin-top:45px;}.rustdoc{padding-top:0px;display:block;}main{padding-left:15px;padding-top:0px;}.rustdoc,.main-heading{flex-direction:column;}.content .out-of-band{text-align:left;margin-left:initial;padding:initial;}.content .out-of-band .since::before{content:"Since ";}#copy-path{display:none;}.sidebar .sidebar-logo,.sidebar .location{display:none;}.sidebar-elems{margin-top:1em;}.sidebar{position:fixed;top:45px;left:-1000px;margin-left:0;margin:0;padding:0;z-index:11;height:calc(100vh - 45px);}.source main,.rustdoc.source .sidebar{top:0;padding:0;height:100vh;border:0;}.sidebar.shown,.source-sidebar-expanded .source .sidebar,.sidebar:focus-within{left:0;}.rustdoc.source>.sidebar{position:fixed;margin:0;z-index:11;width:0;}.mobile-topbar .location a{padding:0;margin:0;}.mobile-topbar .location{border:none;padding:0;margin:auto 0.5em auto auto;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;font-size:24px;}.mobile-topbar .logo-container{max-height:45px;}.mobile-topbar .logo-container>img{max-width:35px;max-height:35px;margin-left:20px;margin-top:5px;margin-bottom:5px;}.mobile-topbar{display:flex;flex-direction:row;position:sticky;z-index:10;font-size:2rem;height:45px;width:100%;left:0;top:0;}.source .mobile-topbar{display:none;}.sidebar-menu-toggle{width:45px;font-size:32px;border:none;}.sidebar-elems{background-color:var(--sidebar-background-color);}.source nav:not(.sidebar).sub{margin-left:32px;}.content{margin-left:0px;}.source .content{margin-top:10px;}#search{margin-left:0;padding:0;}.anchor{display:none !important;}.notable-traits{position:absolute;left:-22px;top:24px;}#titles>button>div.count{float:left;width:100%;}#titles{height:50px;}#sidebar-filler{position:fixed;left:45px;width:calc(100% - 45px);top:0;height:45px;z-index:-1;border-bottom:1px solid;}#main-content>details.rustdoc-toggle>summary::before,#main-content>div>details.rustdoc-toggle>summary::before{left:-11px;}#sidebar-toggle{position:fixed;left:1px;top:100px;width:30px;font-size:1.5rem;text-align:center;padding:0;z-index:10;border-top-right-radius:3px;border-bottom-right-radius:3px;cursor:pointer;font-weight:bold;border:1px solid;border-left:0;}.source-sidebar-expanded #sidebar-toggle{left:unset;top:unset;width:unset;border-top-right-radius:unset;border-bottom-right-radius:unset;position:sticky;border:0;border-bottom:1px solid;}#source-sidebar{z-index:11;}#main-content>.line-numbers{margin-top:0;}.notable-traits .notable-traits-tooltiptext{left:0;top:100%;}#help-button{display:none;}.item-table{display:block;}.item-row{display:flex;flex-flow:column wrap;}.item-left,.item-right{width:100%;}.search-results>a{border-bottom:1px solid #aaa9;padding:5px 0px;}.search-results .result-name,.search-results div.desc,.search-results .result-description{width:100%;}.search-results div.desc,.search-results .result-description,.item-right{padding-left:2em;}.source-sidebar-expanded .source .sidebar{max-width:100vw;width:100vw;}details.rustdoc-toggle:not(.top-doc)>summary{margin-left:10px;}.impl-items>details.rustdoc-toggle>summary:not(.hideme)::before,#main-content>details.rustdoc-toggle:not(.top-doc)>summary::before,#main-content>div>details.rustdoc-toggle>summary::before{left:-11px;}}@media print{nav.sidebar,nav.sub,.content .out-of-band,a.srclink,#copy-path,details.rustdoc-toggle[open] >summary::before,details.rustdoc-toggle>summary::before,details.rustdoc-toggle.top-doc>summary{display:none;}.docblock{margin-left:0;}main{padding:10px;}}@media (max-width:464px){#titles,#titles>button{height:73px;}#main-content>table:not(.table-display) td{word-break:break-word;width:50%;}#crate-search{border-radius:4px;}.docblock{margin-left:12px;}.docblock code{overflow-wrap:break-word;overflow-wrap:anywhere;}.sub-container{flex-direction:column;}.sub-logo-container{align-self:center;}.source .sub-logo-container>img{height:35px;width:35px;}#sidebar-toggle{top:10px;}.source-sidebar-expanded #sidebar-toggle{top:unset;}}.method-toggle summary,.implementors-toggle summary,.impl{margin-bottom:0.75em;}.method-toggle[open]{margin-bottom:2em;}.implementors-toggle[open]{margin-bottom:2em;}#trait-implementations-list .method-toggle,#synthetic-implementations-list .method-toggle,#blanket-implementations-list .method-toggle{margin-bottom:1em;}.scraped-example-list .scrape-help{margin-left:10px;padding:0 4px;font-weight:normal;font-size:12px;position:relative;bottom:1px;background:transparent;border-width:1px;border-style:solid;border-radius:50px;}.scraped-example .code-wrapper{position:relative;display:flex;flex-direction:row;flex-wrap:wrap;width:100%;}.scraped-example:not(.expanded) .code-wrapper{max-height:240px;}.scraped-example:not(.expanded) .code-wrapper pre{overflow-y:hidden;max-height:240px;padding-bottom:0;}.scraped-example:not(.expanded) .code-wrapper pre.line-numbers{overflow-x:hidden;}.scraped-example .code-wrapper .prev{position:absolute;top:0.25em;right:2.25em;z-index:100;cursor:pointer;}.scraped-example .code-wrapper .next{position:absolute;top:0.25em;right:1.25em;z-index:100;cursor:pointer;}.scraped-example .code-wrapper .expand{position:absolute;top:0.25em;right:0.25em;z-index:100;cursor:pointer;}.scraped-example:not(.expanded) .code-wrapper:before{content:" ";width:100%;height:5px;position:absolute;z-index:100;top:0;}.scraped-example:not(.expanded) .code-wrapper:after{content:" ";width:100%;height:5px;position:absolute;z-index:100;bottom:0;}.scraped-example .code-wrapper .line-numbers{margin:0;padding:14px 0;}.scraped-example .code-wrapper .line-numbers span{padding:0 14px;}.scraped-example .code-wrapper .example-wrap{flex:1;overflow-x:auto;overflow-y:hidden;margin-bottom:0;}.scraped-example:not(.expanded) .code-wrapper .example-wrap{overflow-x:hidden;}.scraped-example .code-wrapper .example-wrap pre.rust{overflow-x:inherit;width:inherit;overflow-y:hidden;}.more-examples-toggle{max-width:calc(100% + 25px);margin-top:10px;margin-left:-25px;}.more-examples-toggle .hide-more{margin-left:25px;margin-bottom:5px;cursor:pointer;}.more-scraped-examples{margin-left:5px;display:flex;flex-direction:row;}.more-scraped-examples-inner{width:calc(100% - 20px);}.toggle-line{align-self:stretch;margin-right:10px;margin-top:5px;padding:0 4px;cursor:pointer;}.toggle-line-inner{min-width:2px;height:100%;}.more-scraped-examples .scraped-example{margin-bottom:20px;}.more-scraped-examples .scraped-example:last-child{margin-bottom:0;}.example-links a{margin-top:20px;}.example-links ul{margin-bottom:0;} \ No newline at end of file diff --git a/search-index.js b/search-index.js index f3347b451..4fb6362ea 100644 --- a/search-index.js +++ b/search-index.js @@ -1,12 +1,12 @@ var searchIndex = JSON.parse('{\ -"actix_cors":{"doc":"Cross-Origin Resource Sharing (CORS) controls for Actix …","t":[13,13,3,4,13,13,13,13,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["BadRequestHeaders","BadRequestMethod","Cors","CorsError","HeadersNotAllowed","MethodNotAllowed","MissingOrigin","MissingRequestMethod","OriginNotAllowed","WildcardOrigin","allow_any_header","allow_any_method","allow_any_origin","allowed_header","allowed_headers","allowed_methods","allowed_origin","allowed_origin_fn","borrow","borrow","borrow_mut","borrow_mut","clone","clone_into","default","disable_preflight","disable_vary_header","error_response","expose_any_header","expose_headers","fmt","fmt","fmt","from","from","into","into","max_age","new_transform","permissive","send_wildcard","status_code","supports_credentials","to_owned","to_string","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip"],"q":["actix_cors","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"d":["Request header Access-Control-Request-Headers has an …","Request header Access-Control-Request-Method has an …","Builder for CORS middleware.","Errors that can occur when processing CORS guarded …","One or more request headers are not allowed.","Request method is not allowed.","Request header Origin is required but was not provided.","Request header Access-Control-Request-Method is required …","Origin is not allowed to make this request.","Allowed origin argument must not be wildcard (*).","Resets allowed request header list to a state where any …","Resets allowed methods list to all methods.","Resets allowed origin list to a state where any origin is …","Add an allowed request header.","Set a list of request header field names which can be used …","Set a list of methods which allowed origins can perform.","Add an origin that is allowed to make requests.","Determinate allowed origins by processing requests which …","","","","","","","A restrictive (security paranoid) set of defaults.","Disable support for preflight requests.","Disable Vary header support.","","Resets exposed response header list to a state where all …","Set a list of headers which are safe to expose to the API …","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Set a maximum time (in seconds) for which this CORS …","","A very permissive set of default for quick development. …","Set to use wildcard origins.","","Allows users to make authenticated requests","","","","","","","","","",""],"i":[3,3,0,0,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,3,1,3,3,3,1,1,1,3,1,1,1,3,3,1,3,1,3,1,1,1,1,3,1,3,3,1,3,1,3,1,3,1,3],"f":[0,0,0,0,0,0,0,0,0,0,[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[[1,2],1],[1,1],[[]],[[]],[[]],[[]],[3,3],[[]],[[],1],[1,1],[1,1],[3,4],[1,1],[1,1],[[1,5],6],[[3,5],6],[[3,5],6],[[]],[[]],[[]],[[]],[[1,[9,[[8,[7]]]]],1],[1],[[],1],[1,1],[3,10],[1,1],[[]],[[],11],[[],12],[[],12],[[],12],[[],12],[[],13],[[],13],[[]],[[]]],"p":[[3,"Cors"],[15,"str"],[4,"CorsError"],[3,"HttpResponse"],[3,"Formatter"],[6,"Result"],[15,"usize"],[4,"Option"],[8,"Into"],[3,"StatusCode"],[3,"String"],[4,"Result"],[3,"TypeId"]]},\ +"actix_cors":{"doc":"Cross-Origin Resource Sharing (CORS) controls for Actix …","t":[13,13,3,4,13,13,13,13,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["BadRequestHeaders","BadRequestMethod","Cors","CorsError","HeadersNotAllowed","MethodNotAllowed","MissingOrigin","MissingRequestMethod","OriginNotAllowed","WildcardOrigin","allow_any_header","allow_any_method","allow_any_origin","allowed_header","allowed_headers","allowed_methods","allowed_origin","allowed_origin_fn","borrow","borrow","borrow_mut","borrow_mut","clone","clone_into","default","disable_preflight","disable_vary_header","error_response","expose_any_header","expose_headers","fmt","fmt","fmt","from","from","into","into","max_age","new_transform","permissive","provide","send_wildcard","status_code","supports_credentials","to_owned","to_string","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip"],"q":["actix_cors","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"d":["Request header Access-Control-Request-Headers has an …","Request header Access-Control-Request-Method has an …","Builder for CORS middleware.","Errors that can occur when processing CORS guarded …","One or more request headers are not allowed.","Request method is not allowed.","Request header Origin is required but was not provided.","Request header Access-Control-Request-Method is required …","Origin is not allowed to make this request.","Allowed origin argument must not be wildcard (*).","Resets allowed request header list to a state where any …","Resets allowed methods list to all methods.","Resets allowed origin list to a state where any origin is …","Add an allowed request header.","Set a list of request header field names which can be used …","Set a list of methods which allowed origins can perform.","Add an origin that is allowed to make requests.","Determinate allowed origins by processing requests which …","","","","","","","A restrictive (security paranoid) set of defaults.","Disable support for preflight requests.","Disable Vary header support.","","Resets exposed response header list to a state where all …","Set a list of headers which are safe to expose to the API …","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Set a maximum time (in seconds) for which this CORS …","","A very permissive set of default for quick development. …","","Set to use wildcard origins.","","Allows users to make authenticated requests","","","","","","","","","",""],"i":[3,3,0,0,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,3,1,3,3,3,1,1,1,3,1,1,1,3,3,1,3,1,3,1,1,1,3,1,3,1,3,3,1,3,1,3,1,3,1,3],"f":[0,0,0,0,0,0,0,0,0,0,[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[[1,2],1],[1,1],[[]],[[]],[[]],[[]],[3,3],[[]],[[],1],[1,1],[1,1],[3,4],[1,1],[1,1],[[1,5],6],[[3,5],6],[[3,5],6],[[]],[[]],[[]],[[]],[[1,[9,[[8,[7]]]]],1],[1],[[],1],[10],[1,1],[3,11],[1,1],[[]],[[],12],[[],13],[[],13],[[],13],[[],13],[[],14],[[],14],[[]],[[]]],"p":[[3,"Cors"],[15,"str"],[4,"CorsError"],[3,"HttpResponse"],[3,"Formatter"],[6,"Result"],[15,"usize"],[4,"Option"],[8,"Into"],[3,"Demand"],[3,"StatusCode"],[3,"String"],[4,"Result"],[3,"TypeId"]]},\ "actix_identity":{"doc":"Identity management for Actix Web.","t":[3,8,3,11,11,11,11,11,11,11,0,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,13,3,4,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["Identity","IdentityExt","IdentityMiddleware","borrow","borrow","borrow_mut","borrow_mut","builder","clone","clone_into","config","default","from","from","from_request","get_identity","id","into","into","login","logout","new_transform","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip","DeleteIdentityKeys","IdentityMiddlewareBuilder","LogoutBehaviour","PurgeSession","borrow","borrow","borrow_mut","borrow_mut","build","clone","clone","clone_into","clone_into","fmt","fmt","from","from","into","into","login_deadline","logout_behaviour","to_owned","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","visit_deadline","vzip","vzip"],"q":["actix_identity","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_identity::config","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"d":["A verified user identity. It can be used as a request …","Helper trait to retrieve an Identity instance from various …","Identity management middleware.","","","","","A fluent API to configure IdentityMiddleware.","","","Configuration options to tune the behaviour of …","","Returns the argument unchanged.","Returns the argument unchanged.","","Retrieve the identity attached to the current session, if …","Return the user id associated to the current session.","Calls U::from(self).","Calls U::from(self).","Attach a valid user identity to the current session.","Remove the user identity from the current session.","","","","","","","","","","","When Identity::logout is called, remove the identity …","A fluent builder to construct an IdentityMiddleware …","LogoutBehaviour controls what actions are going to be …","When Identity::logout is called, purge the current session.","","","","","Finalises the builder and returns an IdentityMiddleware …","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Automatically logs out users after a certain amount of …","Determines how Identity::logout affects the current …","","","","","","","","","Automatically logs out users after a certain amount of …","",""],"i":[0,0,0,5,2,5,2,2,2,2,0,2,5,2,5,16,5,5,2,5,5,2,2,5,2,5,2,5,2,5,2,11,0,0,11,11,1,11,1,1,11,1,11,1,11,1,11,1,11,1,1,1,11,1,11,1,11,1,11,1,1,11,1],"f":[0,0,0,[[]],[[]],[[]],[[]],[[],1],[2,2],[[]],0,[[],2],[[]],[[]],[[3,4]],[[],[[7,[5,6]]]],[5,[[7,[8,6]]]],[[]],[[]],[[9,8],[[7,[5,6]]]],[5],[2],[[]],[[],7],[[],7],[[],7],[[],7],[[],10],[[],10],[[]],[[]],0,0,0,0,[[]],[[]],[[]],[[]],[1,2],[11,11],[1,1],[[]],[[]],[[11,12],13],[[1,12],13],[[]],[[]],[[]],[[]],[[1,[15,[14]]],1],[[1,11],1],[[]],[[]],[[],7],[[],7],[[],7],[[],7],[[],10],[[],10],[[1,[15,[14]]],1],[[]],[[]]],"p":[[3,"IdentityMiddlewareBuilder"],[3,"IdentityMiddleware"],[3,"HttpRequest"],[4,"Payload"],[3,"Identity"],[3,"Error"],[4,"Result"],[3,"String"],[3,"Extensions"],[3,"TypeId"],[4,"LogoutBehaviour"],[3,"Formatter"],[6,"Result"],[3,"Duration"],[4,"Option"],[8,"IdentityExt"]]},\ -"actix_limitation":{"doc":"Rate limiter using a fixed window counter for arbitrary …","t":[3,13,17,17,17,17,4,13,3,13,3,3,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12],"n":["Builder","Client","DEFAULT_COOKIE_NAME","DEFAULT_PERIOD_SECS","DEFAULT_REQUEST_LIMIT","DEFAULT_SESSION_KEY","Error","LimitExceeded","Limiter","Other","RateLimiter","Status","Time","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","build","builder","clone","clone","clone_into","clone_into","cookie_name","count","default","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","into","into","into","into","into","limit","limit","new_transform","period","remaining","reset_epoch_utc","session_key","source","to_owned","to_owned","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","0","0","0","0"],"q":["actix_limitation","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_limitation::Error","","",""],"d":["Rate limiter builder.","Redis client failed to connect or run a query.","Default cookie name.","Default period (in seconds).","Default request limit.","Default session key.","Failure modes of the rate limiter.","Limit is exceeded for a key.","Rate limiter.","Generic error.","Rate limit middleware.","A report for a given key containing the limit status.","Time conversion failed.","","","","","","","","","","","Finalizes and returns a Limiter.","Construct rate limiter builder with defaults.","","","","","Set name of cookie to be sent.","Consumes one rate limit unit, returning the status.","","","","","","","","Returns the argument unchanged.","","Returns the argument unchanged.","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Set upper limit.","Returns the maximum number of requests allowed in the …","","Set limit window/period.","Returns how many requests are left in the current period.","Returns a UNIX timestamp in UTC approximately when the …","Set session key to be used in backend.","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"i":[0,3,0,0,0,0,0,3,0,3,0,0,3,1,3,11,7,2,1,3,11,7,2,1,2,7,2,7,2,1,2,11,1,3,3,11,7,2,1,3,3,3,11,7,2,1,3,11,7,2,1,7,11,1,7,7,1,3,7,2,3,1,3,11,7,2,1,3,11,7,2,1,3,11,7,2,1,3,11,7,2,21,22,23,24],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[1,[[4,[2,3]]]],[[[6,[5]]],1],[7,7],[2,2],[[]],[[]],[[1,[6,[[9,[8]]]]],1],[[2,[6,[5]]],10],[[],11],[[1,12],13],[[3,12],13],[[3,12],13],[[11,12],13],[[7,12],13],[[2,12],13],[[]],[14,3],[[]],[15,3],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[1,16],1],[7,16],[11],[[1,17],1],[7,16],[7,16],[[1,[6,[[9,[8]]]]],1],[3,[[19,[18]]]],[[]],[[]],[[],5],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],20],[[],20],[[],20],[[],20],[[],20],[[]],[[]],[[]],[[]],[[]],0,0,0,0],"p":[[3,"Builder"],[3,"Limiter"],[4,"Error"],[4,"Result"],[3,"String"],[8,"Into"],[3,"Status"],[15,"str"],[4,"Cow"],[8,"Future"],[3,"RateLimiter"],[3,"Formatter"],[6,"Result"],[3,"ComponentRange"],[3,"RedisError"],[15,"usize"],[3,"Duration"],[8,"Error"],[4,"Option"],[3,"TypeId"],[13,"Client"],[13,"LimitExceeded"],[13,"Time"],[13,"Other"]]},\ +"actix_limitation":{"doc":"Rate limiter using a fixed window counter for arbitrary …","t":[3,13,17,17,17,17,4,13,3,13,3,3,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12],"n":["Builder","Client","DEFAULT_COOKIE_NAME","DEFAULT_PERIOD_SECS","DEFAULT_REQUEST_LIMIT","DEFAULT_SESSION_KEY","Error","LimitExceeded","Limiter","Other","RateLimiter","Status","Time","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","build","builder","clone","clone","clone_into","clone_into","cookie_name","count","default","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","into","into","into","into","into","limit","limit","new_transform","period","provide","remaining","reset_epoch_utc","session_key","source","to_owned","to_owned","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","0","0","0","0"],"q":["actix_limitation","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_limitation::Error","","",""],"d":["Rate limiter builder.","Redis client failed to connect or run a query.","Default cookie name.","Default period (in seconds).","Default request limit.","Default session key.","Failure modes of the rate limiter.","Limit is exceeded for a key.","Rate limiter.","Generic error.","Rate limit middleware.","A report for a given key containing the limit status.","Time conversion failed.","","","","","","","","","","","Finalizes and returns a Limiter.","Construct rate limiter builder with defaults.","","","","","Set name of cookie to be sent.","Consumes one rate limit unit, returning the status.","","","","","","","","Returns the argument unchanged.","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Set upper limit.","Returns the maximum number of requests allowed in the …","","Set limit window/period.","","Returns how many requests are left in the current period.","Returns a UNIX timestamp in UTC approximately when the …","Set session key to be used in backend.","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"i":[0,3,0,0,0,0,0,3,0,3,0,0,3,1,3,11,7,2,1,3,11,7,2,1,2,7,2,7,2,1,2,11,1,3,3,11,7,2,1,3,3,3,11,7,2,1,3,11,7,2,1,7,11,1,3,7,7,1,3,7,2,3,1,3,11,7,2,1,3,11,7,2,1,3,11,7,2,1,3,11,7,2,22,23,24,25],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[1,[[4,[2,3]]]],[[[6,[5]]],1],[7,7],[2,2],[[]],[[]],[[1,[6,[[9,[8]]]]],1],[[2,[6,[5]]],10],[[],11],[[1,12],13],[[3,12],13],[[3,12],13],[[11,12],13],[[7,12],13],[[2,12],13],[[]],[14,3],[15,3],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[1,16],1],[7,16],[11],[[1,17],1],[18],[7,16],[7,16],[[1,[6,[[9,[8]]]]],1],[3,[[20,[19]]]],[[]],[[]],[[],5],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],4],[[],21],[[],21],[[],21],[[],21],[[],21],[[]],[[]],[[]],[[]],[[]],0,0,0,0],"p":[[3,"Builder"],[3,"Limiter"],[4,"Error"],[4,"Result"],[3,"String"],[8,"Into"],[3,"Status"],[15,"str"],[4,"Cow"],[8,"Future"],[3,"RateLimiter"],[3,"Formatter"],[6,"Result"],[3,"RedisError"],[3,"ComponentRange"],[15,"usize"],[3,"Duration"],[3,"Demand"],[8,"Error"],[4,"Option"],[3,"TypeId"],[13,"Client"],[13,"LimitExceeded"],[13,"Time"],[13,"Other"]]},\ "actix_protobuf":{"doc":"Protobuf payload extractor for Actix Web.","t":[12,13,13,13,13,3,3,3,4,8,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12],"n":["0","ContentType","Deserialize","Overflow","Payload","ProtoBuf","ProtoBufConfig","ProtoBufMessage","ProtoBufPayloadError","ProtoBufResponseBuilder","Serialize","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","default","deref","deref_mut","error_response","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from_request","into","into","into","into","into_future","limit","limit","new","poll","protobuf","resource_path","respond_to","to_string","to_string","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_poll","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","0","0","0"],"q":["actix_protobuf","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_protobuf::ProtoBufPayloadError","",""],"d":["","Content type error","Deserialize error","Payload size is bigger than 256k","Payload error","","","","","","Serialize error","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Change max size of payload. By default max size is 256Kb","Change max size of payload. By default max size is 256Kb","Create ProtoBufMessage for request.","","","","","","","","","","","","","","","","","","","","","","","","","",""],"i":[3,4,4,4,4,0,0,0,0,0,4,3,1,14,4,3,1,14,4,1,3,3,4,3,3,4,4,3,1,14,4,4,4,3,3,1,14,4,14,1,14,14,14,23,3,3,3,4,3,1,14,4,3,1,14,4,14,3,1,14,4,3,1,14,4,24,25,26],"f":[0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],1],[[[3,[2]]]],[[[3,[2]]]],[4,5],[[[3,[2]],6],7],[[[3,[2]],6],7],[[4,6],7],[[4,6],7],[[]],[[]],[[]],[[]],[8,4],[9,4],[[10,11]],[[]],[[]],[[]],[[]],[[]],[[1,12],1],[[[14,[[0,[2,13]]]],12],[[14,[[0,[2,13]]]]]],[[10,11],[[14,[[0,[2,13]]]]]],[[[15,[[14,[[0,[2,13]]]]]],16],17],[2,[[19,[5,18]]]],[[],20],[[[3,[[0,[2,13]]]],10],5],[[],21],[[],21],[[],19],[[],19],[[],19],[[],19],[[],19],[[],19],[[],19],[[],19],[[15,16],17],[[],22],[[],22],[[],22],[[],22],[[]],[[]],[[]],[[]],0,0,0],"p":[[3,"ProtoBufConfig"],[8,"Message"],[3,"ProtoBuf"],[4,"ProtoBufPayloadError"],[3,"HttpResponse"],[3,"Formatter"],[6,"Result"],[3,"DecodeError"],[4,"PayloadError"],[3,"HttpRequest"],[4,"Payload"],[15,"usize"],[8,"Default"],[3,"ProtoBufMessage"],[3,"Pin"],[3,"Context"],[4,"Poll"],[3,"Error"],[4,"Result"],[3,"Path"],[3,"String"],[3,"TypeId"],[8,"ProtoBufResponseBuilder"],[13,"Serialize"],[13,"Deserialize"],[13,"Payload"]]},\ -"actix_redis":{"doc":"Redis integration for actix.","t":[12,13,13,3,13,13,4,13,13,13,13,13,13,13,3,13,13,4,4,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,14,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12],"n":["0","Array","BulkString","Command","Connection","Disconnected","Error","Error","IO","Integer","Internal","Nil","NotConnected","Redis","RedisActor","Remote","Resp","RespError","RespValue","SimpleString","Unexpected","append","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone_into","eq","equivalent","error","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from_resp_int","handle","handle","into","into","into","into","into","ne","push","resp_array","restarting","source","source","start","started","to_owned","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","0","0","0","0","0","0","0","1","0","0","0","0","0"],"q":["actix_redis","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_redis::Error","actix_redis::RespError","","","","","","","actix_redis::RespValue","","","",""],"d":["","Zero, one or more other RespValues.","A bulk string. In Redis terminology a string is a …","Command for sending data to Redis.","Error creating a connection, or an error with a connection …","Cancel all waiters when connection is dropped.","General purpose actix-redis error.","An error from the Redis server","An IO error occurred","Redis documentation defines an integer as being a signed …","A non-specific internal error that prevented an operation …","","Receiving message during reconnecting.","","Redis communication actor.","A remote error","A RESP parsing/serialising error occurred","","A single RESP value, this owns the data that is read/to-be …","","An unexpected error. In this context “unexpected” …","Convenience function for building dynamic Redis commands …","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Returns the argument unchanged.","","","Returns the argument unchanged.","","","","","","","","Returns the argument unchanged.","","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Push item to Resp array","Macro to create a RESP array, useful for preparing …","","","","Start new Supervisor with RedisActor.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"i":[7,1,1,0,13,10,0,1,13,1,13,1,10,10,0,13,13,0,0,1,13,1,4,7,10,1,13,4,7,10,1,13,1,1,1,1,4,7,10,10,1,13,13,4,7,10,10,1,1,1,1,1,1,1,1,13,13,13,1,4,4,4,7,10,1,13,1,1,0,4,10,13,4,4,1,10,13,4,7,10,1,13,4,7,10,1,13,4,7,10,1,13,4,7,10,1,13,28,29,30,31,32,33,34,31,35,36,37,38,39],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[1,2],1],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[1,1],[[]],[[1,1],3],[[],3],[[4,5],6],[[7,8],9],[[10,8],9],[[10,8],9],[[1,8],[[12,[11]]]],[[13,8],[[12,[11]]]],[[13,8],[[12,[11]]]],[[]],[[]],[13,10],[[]],[[],1],[14,1],[[]],[15,1],[[[18,[16,17]]],1],[[[20,[19]]],1],[14,1],[19,1],[5,13],[21,13],[[]],[1,[[12,[1,13]]]],[[4,7]],[[4,[12,[1,13]]]],[[]],[[]],[[]],[[]],[[]],[[1,1],3],[1],0,[4],[10,[[23,[22]]]],[13,[[23,[22]]]],[[[24,[14]]],[[25,[4]]]],[[4,26]],[[]],[[],14],[[],14],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],27],[[],27],[[],27],[[],27],[[],27],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,0],"p":[[4,"RespValue"],[8,"IntoIterator"],[15,"bool"],[3,"RedisActor"],[3,"Error"],[4,"Running"],[3,"Command"],[3,"Formatter"],[6,"Result"],[4,"Error"],[3,"Error"],[4,"Result"],[4,"RespError"],[3,"String"],[15,"usize"],[15,"u8"],[3,"Global"],[3,"Vec"],[15,"str"],[3,"Arc"],[3,"TrySendError"],[8,"Error"],[4,"Option"],[8,"Into"],[3,"Addr"],[3,"Context"],[3,"TypeId"],[13,"Redis"],[13,"Internal"],[13,"IO"],[13,"Resp"],[13,"Remote"],[13,"Connection"],[13,"Unexpected"],[13,"Array"],[13,"BulkString"],[13,"Error"],[13,"Integer"],[13,"SimpleString"]]},\ -"actix_session":{"doc":"Session management for Actix Web.","t":[13,13,13,3,8,3,3,3,4,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,13,4,13,13,3,13,13,4,3,13,4,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,3,13,4,13,13,13,3,3,3,3,4,13,13,3,8,4,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12],"n":["Changed","Purged","Renewed","Session","SessionExt","SessionGetError","SessionInsertError","SessionMiddleware","SessionStatus","Unchanged","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","builder","clear","clone","clone","clone","clone_into","clone_into","clone_into","config","default","entries","eq","equivalent","error_response","error_response","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from_request","get","get_session","insert","into","into","into","into","into","new","new_transform","purge","remove","remove_as","renew","source","source","status","storage","to_owned","to_owned","to_owned","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","BrowserSession","BrowserSession","CookieContentSecurity","OnEveryRequest","OnStateChanges","PersistentSession","PersistentSession","Private","SessionLifecycle","SessionMiddlewareBuilder","Signed","TtlExtensionPolicy","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","build","clone","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","clone_into","cookie_content_security","cookie_domain","cookie_http_only","cookie_name","cookie_path","cookie_same_site","cookie_secure","default","default","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","into","into","into","into","into","into","session_lifecycle","session_ttl","session_ttl_extension_policy","state_ttl","state_ttl_extension_policy","to_owned","to_owned","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","vzip","0","0","CookieSessionStore","Deserialization","LoadError","Other","Other","Other","RedisActorSessionStore","RedisActorSessionStoreBuilder","RedisSessionStore","RedisSessionStoreBuilder","SaveError","Serialization","Serialization","SessionKey","SessionStore","UpdateError","as_ref","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","build","build","builder","builder","cache_keygen","cache_keygen","clone","clone_into","default","delete","delete","delete","delete","eq","equivalent","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","into","into","into","into","into","into","into","into","into","load","load","load","load","ne","new","new","save","save","save","save","source","source","source","to_owned","to_string","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","update","update","update","update","update_ttl","update_ttl","update_ttl","update_ttl","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","0","0","0","0","0","0"],"q":["actix_session","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_session::config","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_session::config::SessionLifecycle","","actix_session::storage","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_session::storage::LoadError","","actix_session::storage::SaveError","","actix_session::storage::UpdateError",""],"d":["Session state has been updated - the changes will have to …","The session has been flagged for deletion - the session …","The session has been flagged for renewal.","The primary interface to access and modify session state.","Extract a Session object from various actix-web types …","Error returned by Session::get.","Error returned by Session::insert.","A middleware for session management in Actix Web …","Status of a Session.","The session state has not been modified since its …","","","","","","","","","","","A fluent API to configure SessionMiddleware.","Clear the session.","","","","","","","Configuration options to tune the behaviour of …","","Get all raw key-value data from the session.","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","Returns the argument unchanged.","","","Get a value from the session.","Extract a Session object.","Inserts a key-value pair into the session.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Use SessionMiddleware::new to initialize the session …","","Removes session both client and server side.","Remove value from the session.","Remove value from the session and deserialize.","Renews the session key, assigning existing session state …","","","Returns session status.","Pluggable storage backends for session state.","","","","","","","","","","","","","","","","","","","","","","","","","","A session lifecycle strategy where the session cookie …","The session cookie will expire when the current browser …","Determines how to secure the content of the session cookie.","The TTL is refreshed every time the server receives a …","The TTL is refreshed every time the session state changes …","A session lifecycle strategy where the session cookie will …","The session cookie will be a persistent cookie.","The cookie content is encrypted when using …","Determines what type of session cookie should be used and …","A fluent, customized SessionMiddleware builder.","The cookie content is signed when using …","Configuration for which events should trigger an extension …","","","","","","","","","","","","","Finalise the builder and return a SessionMiddleware …","","","","","","","","","","","Choose how the session cookie content should be secured.","Set the Domain attribute for the cookie used to store the …","Set the HttpOnly attribute for the cookie used to store …","Set the name of the cookie used to store the session ID.","Set the Path attribute for the cookie used to store the …","Set the SameSite attribute for the cookie used to store …","Set the Secure attribute for the cookie used to store the …","","","","","","","","Returns the argument unchanged.","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Determines what type of session cookie should be used and …","Specifies how long the session cookie should live.","Determines under what circumstances the TTL of your …","Sets a time-to-live (TTL) when storing the session state …","Determine under what circumstances the TTL of your session …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Use the session key, stored in the session cookie, as …","Failed to deserialize session state.","Possible failures modes for SessionStore::load.","Something went wrong when retrieving the session state.","Something went wrong when persisting the session state.","Something went wrong when updating the session state.","Use Redis as session storage backend.","A fluent builder to construct a RedisActorSessionStore …","Use Redis as session storage backend.","A fluent builder to construct a RedisSessionStore instance …","Possible failures modes for SessionStore::save.","Failed to serialize session state.","Failed to serialize session state.","A session key, the string stored in a client-side cookie …","The interface to retrieve and save the current session …","Possible failures modes for SessionStore::update.","","","","","","","","","","","","","","","","","","","","Finalise the builder and return a RedisActorSessionStore …","Finalise the builder and return a RedisActorSessionStore …","A fluent API to configure RedisActorSessionStore.","A fluent API to configure RedisSessionStore. It takes as …","Set a custom cache key generation strategy, expecting a …","Set a custom cache key generation strategy, expecting a …","","","","Deletes a session from the store.","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Loads the session state associated to a session key.","","","","","Create a new instance of RedisActorSessionStore using the …","Create a new instance of RedisSessionStore using the …","Persist the session state for a newly created session.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Updates the session state associated to a pre-existing …","","","","Updates the TTL of the session state associated to a …","","","","","","","","","","","","","","","","","",""],"i":[7,7,7,0,0,0,0,0,0,7,6,4,7,12,15,6,4,7,12,15,6,4,6,4,7,6,4,7,0,7,4,7,7,12,15,7,12,12,15,15,6,4,7,12,12,15,15,4,4,48,4,6,4,7,12,15,6,6,4,4,4,4,12,15,4,0,6,4,7,12,15,6,4,7,12,15,6,4,7,12,15,6,4,7,12,15,6,4,7,12,15,0,29,0,32,32,0,29,33,0,0,33,0,3,29,30,31,32,33,3,29,30,31,32,33,3,29,30,31,32,33,29,30,31,32,33,3,3,3,3,3,3,3,30,31,29,30,31,32,33,3,29,29,29,30,31,32,33,3,29,30,31,32,33,3,31,31,30,30,29,30,31,32,33,3,29,30,31,32,33,3,29,30,31,32,33,3,29,30,31,32,33,3,29,30,31,32,33,49,50,0,45,0,45,46,47,0,0,0,0,0,46,47,0,0,0,36,38,37,39,45,46,47,36,42,41,38,37,39,45,46,47,36,42,41,37,39,38,41,37,39,41,41,42,1,38,42,41,36,36,45,45,46,46,47,47,36,38,37,39,45,46,47,36,42,41,38,37,39,45,46,47,36,42,41,1,38,42,41,36,38,41,1,38,42,41,45,46,47,41,45,46,47,38,37,39,45,46,47,36,36,42,41,38,37,39,45,46,47,36,42,41,38,37,39,45,46,47,36,42,41,1,38,42,41,1,38,42,41,38,37,39,45,46,47,36,42,41,51,52,53,54,55,56],"f":[0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[1,2],[[3,[1]]]],[4],[[[6,[[0,[5,1]]]]],[[6,[[0,[5,1]]]]]],[4,4],[7,7],[[]],[[]],[[]],0,[[],7],[4,[[10,[[9,[8,8]]]]]],[[7,7],11],[[],11],[12,[[14,[13]]]],[15,[[14,[13]]]],[[7,16],17],[[12,16],17],[[12,16],17],[[15,16],17],[[15,16],17],[[]],[[]],[[]],[[]],[18,12],[[]],[18,15],[[19,20]],[[4,21],[[24,[[23,[22]],12]]]],[[],4],[[4,[25,[8]],26],[[24,[15]]]],[[]],[[]],[[]],[[]],[[]],[[1,2],[[6,[1]]]],[6],[4],[[4,21],[[23,[8]]]],[[4,21],[[23,[[24,[22,8]]]]]],[4],[12,[[23,[27]]]],[15,[[23,[27]]]],[4,7],0,[[]],[[]],[[]],[[],8],[[],8],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],28],[[],28],[[],28],[[],28],[[],28],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[3,[1]]],[[6,[1]]]],[29,29],[30,30],[31,31],[32,32],[33,33],[[]],[[]],[[]],[[]],[[]],[[[3,[1]],33],[[3,[1]]]],[[[3,[1]],[23,[8]]],[[3,[1]]]],[[[3,[1]],11],[[3,[1]]]],[[[3,[1]],8],[[3,[1]]]],[[[3,[1]],8],[[3,[1]]]],[[[3,[1]],34],[[3,[1]]]],[[[3,[1]],11],[[3,[1]]]],[[],30],[[],31],[[29,16],17],[[30,16],17],[[31,16],17],[[32,16],17],[[33,16],17],[[]],[31,29],[30,29],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[3,[1]],[25,[29]]],[[3,[1]]]],[[31,35],31],[[31,32],31],[[30,35],30],[[30,32],30],[[]],[[]],[[]],[[]],[[]],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[36,21],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[37,38],[39,40],[[[25,[8]]],37],[[[25,[8]]],39],[37,37],[39,39],[41,41],[[]],[[],42],[36,[[44,[[43,[40]]]]]],[[38,36],[[44,[[43,[40]]]]]],[[42,36],[[44,[[43,[40]]]]]],[[41,36],[[44,[[43,[40]]]]]],[[36,36],11],[[],11],[[45,16],17],[[45,16],17],[[46,16],17],[[46,16],17],[[47,16],17],[[47,16],17],[[36,16],17],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[36,[[44,[[43,[40]]]]]],[[38,36],[[44,[[43,[40]]]]]],[[42,36],[[44,[[43,[40]]]]]],[[41,36],[[44,[[43,[40]]]]]],[[36,36],11],[[[25,[8]]],38],[[[25,[8]]],40],[[[9,[8,8]],35],[[44,[[43,[40]]]]]],[[38,[9,[8,8]],35],[[44,[[43,[40]]]]]],[[42,[9,[8,8]],35],[[44,[[43,[40]]]]]],[[41,[9,[8,8]],35],[[44,[[43,[40]]]]]],[45,[[23,[27]]]],[46,[[23,[27]]]],[47,[[23,[27]]]],[[]],[[],8],[[],8],[[],8],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[8,[[24,[36]]]],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[36,[9,[8,8]],35],[[44,[[43,[40]]]]]],[[38,36,[9,[8,8]],35],[[44,[[43,[40]]]]]],[[42,36,[9,[8,8]],35],[[44,[[43,[40]]]]]],[[41,36,[9,[8,8]],35],[[44,[[43,[40]]]]]],[[36,35],[[44,[[43,[40]]]]]],[[38,36,35],[[44,[[43,[40]]]]]],[[42,36,35],[[44,[[43,[40]]]]]],[[41,36,35],[[44,[[43,[40]]]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0],"p":[[8,"SessionStore"],[3,"Key"],[3,"SessionMiddlewareBuilder"],[3,"Session"],[8,"Clone"],[3,"SessionMiddleware"],[4,"SessionStatus"],[3,"String"],[3,"HashMap"],[3,"Ref"],[15,"bool"],[3,"SessionGetError"],[3,"BoxBody"],[3,"HttpResponse"],[3,"SessionInsertError"],[3,"Formatter"],[6,"Result"],[3,"Error"],[3,"HttpRequest"],[4,"Payload"],[15,"str"],[8,"DeserializeOwned"],[4,"Option"],[4,"Result"],[8,"Into"],[8,"Serialize"],[8,"Error"],[3,"TypeId"],[4,"SessionLifecycle"],[3,"BrowserSession"],[3,"PersistentSession"],[4,"TtlExtensionPolicy"],[4,"CookieContentSecurity"],[4,"SameSite"],[3,"Duration"],[3,"SessionKey"],[3,"RedisActorSessionStoreBuilder"],[3,"RedisActorSessionStore"],[3,"RedisSessionStoreBuilder"],[8,"Future"],[3,"RedisSessionStore"],[3,"CookieSessionStore"],[3,"Box"],[3,"Pin"],[4,"LoadError"],[4,"SaveError"],[4,"UpdateError"],[8,"SessionExt"],[13,"BrowserSession"],[13,"PersistentSession"],[13,"Deserialization"],[13,"Other"],[13,"Serialization"],[13,"Other"],[13,"Serialization"],[13,"Other"]]},\ -"actix_settings":{"doc":"Easily manage Actix Web’s settings from a TOML file and …","t":[3,3,8,4,3,13,13,13,13,13,13,13,13,13,4,13,13,13,4,13,13,13,13,4,4,13,4,3,4,13,8,13,13,13,13,13,13,6,4,3,13,12,12,10,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,11,11,11,11,11,11,11,11,11,11,12,11,11,10,11,11,11,11,11,11,11,11,11,12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12],"n":["ActixSettings","Address","ApplySettings","Backlog","BasicSettings","Default","Default","Default","Default","Default","Default","Development","Disabled","EnvVarError","Error","FileExists","InvalidValue","IoError","KeepAlive","Manual","Manual","Manual","Manual","MaxConnectionRate","MaxConnections","Milliseconds","Mode","NoSettings","NumWorkers","Os","Parse","ParseAddressError","ParseBoolError","ParseIntError","Production","Seconds","Seconds","Settings","Timeout","Tls","TomlError","actix","application","apply_settings","backlog","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","certificate","client_shutdown","client_timeout","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","enable_compression","enable_log","enabled","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from_default_template","from_template","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","host","hosts","into","into","into","into","into","into","into","into","into","into","into","into","into","keep_alive","max_connection_rate","max_connections","mode","ne","ne","ne","ne","ne","ne","ne","ne","ne","ne","num_workers","override_field","override_field_with_env_var","parse","parse","parse","parse","parse","parse","parse","parse","parse","parse_toml","port","private_key","shutdown_timeout","tls","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","write_toml_file","0","0","0","0","0","0","0","0","column","expected","file","got","line","0","0","0","0","0","0"],"q":["actix_settings","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_settings::Backlog","actix_settings::Error","","","","","","","","","","","","actix_settings::KeepAlive","actix_settings::MaxConnectionRate","actix_settings::MaxConnections","actix_settings::NumWorkers","actix_settings::Timeout",""],"d":["Settings types for Actix Web.","A host/port pair for the server to bind to.","Extension trait for applying parsed settings to the server …","The maximum number of pending connections.","Wrapper for server and application-specific settings.","The default number of connections. See struct docs.","The default keep-alive as defined by Actix Web.","The default connection limit. See struct docs.","The default number of connections. See struct docs.","The default number of workers. See struct docs.","The default timeout. Depends on context.","Marks development environment.","Disable keep-alive.","Environment variable does not exists or is invalid.","Errors that can be returned from methods in this crate.","File already exists on disk.","Invalid value.","I/O error.","The server keep-alive preference.","A specific number of connections.","A specific connection limit.","A specific number of connections.","A specific number of workers.","The maximum per-worker concurrent TLS connection limit.","The maximum per-worker number of concurrent connections.","Timeout in milliseconds.","Marker of intended deployment environment.","Marker type representing no defined application-specific …","The number of workers that the server should start.","Let the OS determine keep-alive duration.","A specialized FromStr trait that returns [AtError] errors","Value is not an address.","Value is not a boolean.","Value is not an integer.","Marks production environment.","A specific keep-alive duration (in seconds).","Timeout in seconds.","Convenience type alias for BasicSettings with no defined …","A timeout duration in milliseconds or seconds.","TLS (HTTPS) configuration.","Error deserializing as TOML.","Actix Web server settings.","Application-specific settings.","Apply a BasicSettings value to self.","The maximum number of pending connections.","","","","","","","","","","","","","","","","","","","","","","","","","","","Path to certificate .pem file.","Timeout duration for connection shutdown.","Timeout duration for reading client request header.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","True if the Compress middleware should be enabled.","True if the Logger middleware should be enabled.","Tru if accepting TLS connections should be enabled.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Parse an instance of Self straight from the default TOML …","Parse an instance of Self straight from the default TOML …","","","","","","","","","","","","","","","","","","","","","","","","","Host part of address.","List of addresses for the server to bind to.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Server keep-alive preference.","The per-worker maximum concurrent TLS connection limit.","The per-worker maximum number of concurrent connections.","Marker of intended deployment environment.","","","","","","","","","","","The number of workers that the server should start.","Attempts to parse value and override the referenced field.","Attempts to read an environment variable, parse it, and …","Parse Self from string.","","","","","","","","","Parse an instance of Self from a TOML file located at …","Port part of address.","Path to private key .pem file.","Timeout duration for graceful worker shutdown.","TLS (HTTPS) configuration.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Writes the default TOML template to a new file, located at …","","","","","","","","","","","","","","","","","","",""],"i":[0,0,0,0,0,4,5,6,7,9,10,8,5,2,0,2,2,2,0,4,6,7,9,0,0,10,0,0,0,5,0,2,2,2,8,5,10,0,0,0,2,1,1,31,12,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,11,12,12,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,3,4,5,6,7,8,9,10,11,12,1,14,12,12,11,3,4,5,6,7,8,9,10,11,12,1,14,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,2,2,2,2,2,2,3,4,5,6,7,8,9,10,11,12,1,14,1,1,3,4,5,6,7,8,9,10,11,12,1,14,3,4,5,6,7,8,9,10,11,12,1,14,3,12,2,3,4,5,6,7,8,9,10,11,12,1,14,12,12,12,12,3,4,5,6,7,9,10,11,12,1,12,1,1,32,3,4,5,6,7,8,9,10,1,3,11,12,12,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,1,33,34,35,36,37,38,39,40,41,41,41,41,41,42,43,44,45,46,47],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1],0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[11,11],[12,12],[[[1,[13]]],[[1,[13]]]],[14,14],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],[[15,[3]]]],[[],[[15,[4]]]],[[],[[15,[5]]]],[[],[[15,[6]]]],[[],[[15,[7]]]],[[],[[15,[8]]]],[[],[[15,[9]]]],[[],[[15,[10]]]],[[],[[15,[11]]]],[[],[[15,[12]]]],[[],[[15,[1]]]],[[],[[15,[14]]]],0,0,0,[[3,3],16],[[4,4],16],[[5,5],16],[[6,6],16],[[7,7],16],[[8,8],16],[[9,9],16],[[10,10],16],[[11,11],16],[[12,12],16],[[[1,[17]],1],16],[[14,14],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[2,18],19],[[3,18],19],[[4,18],19],[[5,18],19],[[6,18],19],[[7,18],19],[[8,18],19],[[9,18],19],[[10,18],19],[[11,18],19],[[12,18],19],[[[1,[20]],18],19],[[14,18],19],[21,2],[22,2],[23,2],[[]],[24,2],[25,2],[26,2],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],[[15,[1,2]]]],[27,[[15,[1,2]]]],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[[[1,[29]]]],[14],0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,[[3,3],16],[[4,4],16],[[5,5],16],[[6,6],16],[[7,7],16],[[9,9],16],[[10,10],16],[[11,11],16],[[12,12],16],[[[1,[17]],1],16],0,[[],[[15,[2]]]],[[],[[15,[2]]]],[27,[[15,[2]]]],[27,[[15,[3,2]]]],[27,[[15,[4,2]]]],[27,[[15,[5,2]]]],[27,[[15,[6,2]]]],[27,[[15,[7,2]]]],[27,[[15,[8,2]]]],[27,[[15,[9,2]]]],[27,[[15,[10,2]]]],[[],[[15,[1,2]]]],0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],[[15,[2]]]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"p":[[3,"BasicSettings"],[4,"Error"],[3,"Address"],[4,"Backlog"],[4,"KeepAlive"],[4,"MaxConnectionRate"],[4,"MaxConnections"],[4,"Mode"],[4,"NumWorkers"],[4,"Timeout"],[3,"Tls"],[3,"ActixSettings"],[8,"Clone"],[3,"NoSettings"],[4,"Result"],[15,"bool"],[8,"PartialEq"],[3,"Formatter"],[6,"Result"],[8,"Debug"],[4,"VarError"],[3,"Error"],[3,"ParseIntError"],[3,"ParseBoolError"],[3,"IoError"],[3,"Error"],[15,"str"],[15,"u64"],[8,"Hash"],[3,"TypeId"],[8,"ApplySettings"],[8,"Parse"],[13,"Manual"],[13,"EnvVarError"],[13,"FileExists"],[13,"IoError"],[13,"ParseBoolError"],[13,"ParseIntError"],[13,"ParseAddressError"],[13,"TomlError"],[13,"InvalidValue"],[13,"Seconds"],[13,"Manual"],[13,"Manual"],[13,"Manual"],[13,"Milliseconds"],[13,"Seconds"]],"a":{"https":[39],"ssl":[39]}},\ -"actix_web_httpauth":{"doc":"HTTP authentication schemes for Actix Web.","t":[0,0,0,8,3,16,0,0,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,3,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,3,4,13,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,0,3,13,3,3,13,13,13,4,8,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,8,3,0,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,3,4,13,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["extractors","headers","middleware","AuthExtractorConfig","AuthenticationError","Inner","basic","bearer","borrow","borrow_mut","challenge_mut","error_response","fmt","fmt","from","from","into","into_inner","new","status_code","status_code_mut","to_string","try_from","try_into","type_id","vzip","with_error","with_error_description","with_error_uri","BasicAuth","Config","as_ref","borrow","borrow","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","default","fmt","fmt","from","from","from_request","into","into","into_inner","password","realm","to_owned","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","user_id","vzip","vzip","BearerAuth","Config","Error","InsufficientScope","InvalidRequest","InvalidToken","as_ref","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone_into","clone_into","clone_into","cmp","default","eq","equivalent","fmt","fmt","fmt","fmt","from","from","from","from_request","get_hash","hash","into","into","into","into_inner","partial_cmp","realm","scope","status_code","to_owned","to_owned","to_owned","to_string","token","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","vzip","vzip","vzip","authorization","www_authenticate","Authorization","Base64DecodeError","Basic","Bearer","Invalid","MissingField","MissingScheme","ParseError","Scheme","ToStrError","Utf8Error","as_mut","as_ref","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone_into","clone_into","clone_into","cmp","cmp","cmp","default","eq","eq","eq","equivalent","equivalent","equivalent","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","get_hash","hash","into","into","into","into","into_scheme","name","ne","ne","ne","new","new","parse","parse","parse","parse","partial_cmp","partial_cmp","partial_cmp","password","source","to_owned","to_owned","to_owned","to_string","to_string","to_string","to_string","token","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into_pair","try_into_value","try_into_value","try_into_value","type_id","type_id","type_id","type_id","user_id","vzip","vzip","vzip","vzip","0","0","0","0","0","Challenge","WwwAuthenticate","basic","bearer","borrow","borrow_mut","clone","clone_into","cmp","default","eq","equivalent","fmt","from","get_hash","hash","into","name","ne","parse","partial_cmp","to_bytes","to_owned","try_from","try_into","try_into_pair","try_into_value","type_id","vzip","Basic","borrow","borrow_mut","clone","clone_into","cmp","default","eq","equivalent","fmt","fmt","from","get_hash","hash","into","ne","new","partial_cmp","to_owned","to_string","try_from","try_into","try_into_value","type_id","vzip","with_realm","Bearer","BearerBuilder","Error","InsufficientScope","InvalidRequest","InvalidToken","borrow","borrow","borrow_mut","borrow_mut","build","clone","clone_into","cmp","default","default","eq","equivalent","error","error_description","error_uri","finish","fmt","fmt","fmt","from","from","get_hash","hash","into","into","ne","partial_cmp","realm","scope","to_owned","to_string","try_from","try_from","try_into","try_into","try_into_value","type_id","type_id","vzip","vzip","HttpAuthentication","basic","bearer","borrow","borrow_mut","clone","clone_into","fmt","from","into","new_transform","to_owned","try_from","try_into","type_id","vzip","with_fn"],"q":["actix_web_httpauth","","","actix_web_httpauth::extractors","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::extractors::basic","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::extractors::bearer","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers","","actix_web_httpauth::headers::authorization","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers::authorization::ParseError","","","","actix_web_httpauth::headers::www_authenticate","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers::www_authenticate::basic","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers::www_authenticate::bearer","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::middleware","","","","","","","","","","","","","","","",""],"d":["Type-safe authentication information extractors.","Typed HTTP headers.","HTTP Authentication middleware.","Trait implemented for types that provides configuration …","Authentication error returned by authentication extractors.","Associated challenge type.","Extractor for the “Basic” HTTP Authentication Scheme.","Extractor for the “Bearer” HTTP Authentication Scheme.","","","Returns mutable reference to the inner challenge instance.","","","","","Returns the argument unchanged.","Calls U::from(self).","Convert the config instance into a HTTP challenge.","Creates new authentication error from the provided …","","Returns mutable reference to the inner status code.","","","","","","Attach Error to the current Authentication error.","Attach error description to the current Authentication …","Attach error URI to the current Authentication error.","Extractor for HTTP Basic auth.","BasicAuth extractor configuration used for WWW-Authenticate…","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","","Returns client’s password.","Set challenge realm attribute.","","","","","","","","","Returns client’s user-ID.","","","Extractor for HTTP Bearer auth","BearerAuth extractor configuration.","Bearer authorization error types, described in RFC 6750.","The request requires higher privileges than provided by …","The request is missing a required parameter, includes an …","The access token provided is expired, revoked, malformed, …","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","Set challenge realm attribute.","Set challenge scope attribute.","Returns HTTP status code suitable for current error type.","","","","","Returns bearer token provided by client.","","","","","","","","","","","","","Authorization header and various auth schemes.","WWW-Authenticate header and various auth challenges.","Authorization header, defined in RFC 7235","Malformed base64 string.","Credentials for Basic authentication scheme, defined in …","Credentials for Bearer authentication scheme, defined in …","Header value is malformed.","Required authentication field is missing.","Authentication scheme is missing.","Possible errors while parsing Authorization header.","Authentication scheme for Authorization header.","Unable to convert header into the str.","Malformed UTF-8 string.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","","","","Returns the argument unchanged.","","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Consumes Authorization header and returns inner Scheme …","","","","","Creates Basic credentials with provided user_id and …","Creates new Bearer credentials with the token provided.","Try to parse an authentication scheme from the …","","","","","","","Returns client’s password if provided.","","","","","","","","","Gets reference to the credentials token.","","","","","","","","","","","","","","","","","Returns client’s user-ID.","","","","","","","","","","Authentication challenge for WWW-Authenticate header.","WWW-Authenticate header, described in RFC 7235.","Challenge for the “Basic” HTTP Authentication Scheme.","Challenge for the “Bearer” HTTP Authentication Scheme.","","","","","","","","","","Returns the argument unchanged.","","","Calls U::from(self).","","","","","Converts the challenge into a bytes suitable for HTTP …","","","","","","","","Challenge for WWW-Authenticate header with HTTP Basic auth …","","","","","","","","","","","Returns the argument unchanged.","","","Calls U::from(self).","","Creates new Basic challenge with an empty realm field.","","","","","","","","","Creates new Basic challenge from the provided realm field …","Challenge for WWW-Authenticate header with HTTP Bearer …","Builder for the Bearer challenge.","Bearer authorization error types, described in RFC 6750.","The request requires higher privileges than provided by …","The request is missing a required parameter, includes an …","The access token provided is expired, revoked, malformed, …","","","","","Creates the builder for Bearer challenge.","","","","","","","","Provides the error attribute, as defined in [RFC 6750, …","Provides the error_description attribute, as defined in […","Provides the error_uri attribute, as defined in [RFC 6750 …","Consumes the builder and returns built Bearer instance.","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","","","Provides the realm attribute, as defined in RFC 2617.","Provides the scope attribute, as defined in RFC 6749 §3.3.","","","","","","","","","","","","Middleware for checking HTTP authentication.","Construct HttpAuthentication middleware for the HTTP “…","Construct HttpAuthentication middleware for the HTTP “…","","","","","","Returns the argument unchanged.","Calls U::from(self).","","","","","","","Construct HttpAuthentication middleware with the provided …"],"i":[0,0,0,0,0,51,0,0,2,2,2,2,2,2,2,2,2,51,2,2,2,2,2,2,2,2,2,2,2,0,0,13,13,15,13,15,13,15,13,15,13,13,15,13,15,15,13,15,13,15,13,13,15,13,15,13,15,13,15,15,13,15,0,0,0,12,12,12,20,20,21,12,20,21,12,20,21,12,20,21,12,12,20,12,12,20,21,12,12,20,21,12,21,12,12,20,21,12,20,12,20,20,12,20,21,12,12,21,20,21,12,20,21,12,20,21,12,20,21,12,0,0,0,35,0,0,35,35,35,0,0,35,35,28,28,35,28,30,31,35,28,30,31,28,30,31,28,30,31,28,30,31,28,28,30,31,28,30,31,35,35,28,28,30,30,31,31,35,35,35,35,28,28,28,30,31,28,28,35,28,30,31,28,28,28,30,31,30,31,27,28,30,31,28,30,31,30,35,28,30,31,35,28,30,31,31,35,28,30,31,35,28,30,31,28,28,30,31,35,28,30,31,30,35,28,30,31,52,53,54,55,46,0,0,0,0,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,1,46,46,46,46,46,46,46,0,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,0,0,0,12,12,12,49,11,49,11,11,11,11,11,49,11,11,11,49,49,49,49,49,11,11,49,11,11,11,49,11,11,11,49,49,11,11,49,11,49,11,11,49,11,49,11,0,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50],"f":[0,0,0,0,0,0,0,0,[[]],[[]],[[[2,[1]]]],[[[2,[1]]],3],[[[2,[[0,[4,1]]]],5],6],[[[2,[1]],5],6],[[],2],[[]],[[]],[[]],[1,[[2,[1]]]],[[[2,[1]]],7],[[[2,[1]]],7],[[],8],[[],9],[[],9],[[],10],[[]],[[[2,[11]],12],[[2,[11]]]],[[[2,[11]]],[[2,[11]]]],[[[2,[11]]],[[2,[11]]]],0,0,[13,14],[[]],[[]],[[]],[[]],[13,13],[15,15],[[]],[[]],[[],13],[[13,5],6],[[15,5],6],[[]],[[]],[[16,17]],[[]],[[]],[13],[15,[[19,[18]]]],[13,13],[[]],[[]],[[],9],[[],9],[[],9],[[],9],[[],10],[[],10],[15,18],[[]],[[]],0,0,0,0,0,0,[20,11],[[]],[[]],[[]],[[]],[[]],[[]],[20,20],[21,21],[12,12],[[]],[[]],[[]],[[12,12],22],[[],20],[[12,12],23],[[],23],[[20,5],6],[[21,5],6],[[12,5],6],[[12,5],6],[[]],[[]],[[]],[[16,17]],[[],24],[12],[[]],[[]],[[]],[20],[[12,12],[[19,[22]]]],[[20,[26,[[25,[18]]]]],20],[[20,[26,[[25,[18]]]]],20],[12,7],[[]],[[]],[[]],[[],8],[21,18],[[],9],[[],9],[[],9],[[],9],[[],9],[[],9],[[],10],[[],10],[[],10],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,0,[[[28,[27]]]],[[[28,[27]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[28,[[0,[29,27]]]]],[[28,[[0,[29,27]]]]]],[30,30],[31,31],[[]],[[]],[[]],[[[28,[[0,[32,27]]]],28],22],[[30,30],22],[[31,31],22],[[],[[28,[[0,[33,27]]]]]],[[[28,[[0,[34,27]]]],28],23],[[30,30],23],[[31,31],23],[[],23],[[],23],[[],23],[[35,5],6],[[35,5],6],[[[28,[[0,[4,27]]]],5],6],[[[28,[27]],5],6],[[30,5],6],[[30,5],6],[[31,5],6],[[31,5],6],[[]],[36,35],[37,35],[38,35],[27,[[28,[27]]]],[[]],[39],[[]],[[]],[[],24],[[[28,[[0,[40,27]]]]]],[[]],[[]],[[]],[[]],[[[28,[27]]],27],[[],41],[[[28,[[0,[34,27]]]],28],23],[[30,30],23],[[31,31],23],[19,30],[[],31],[42,[[9,[35]]]],[[],[[9,[[28,[27]],43]]]],[42,[[9,[30,35]]]],[42,[[9,[31,35]]]],[[[28,[[0,[44,27]]]],28],[[19,[22]]]],[[30,30],[[19,[22]]]],[[31,31],[[19,[22]]]],[30,[[19,[18]]]],[35,[[19,[45]]]],[[]],[[]],[[]],[[],8],[[],8],[[],8],[[],8],[31,18],[[],9],[[],9],[[],9],[[],9],[[],9],[[],9],[[],9],[[],9],[[],9],[[[28,[27]]],[[9,[42]]]],[30,[[9,[42]]]],[31,[[9,[42]]]],[[],10],[[],10],[[],10],[[],10],[30,18],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,[[]],[[]],[[[46,[[0,[29,1]]]]],[[46,[[0,[29,1]]]]]],[[]],[[[46,[[0,[32,1]]]],46],22],[[],[[46,[[0,[33,1]]]]]],[[[46,[[0,[34,1]]]],46],23],[[],23],[[[46,[[0,[4,1]]]],5],6],[[]],[[],24],[[[46,[[0,[40,1]]]]]],[[]],[[],41],[[[46,[[0,[34,1]]]],46],23],[[],[[9,[[46,[1]],43]]]],[[[46,[[0,[44,1]]]],46],[[19,[22]]]],[[],47],[[]],[[],9],[[],9],[[],9],[[[46,[1]]],[[9,[42]]]],[[],10],[[]],0,[[]],[[]],[14,14],[[]],[[14,14],22],[[],14],[[14,14],23],[[],23],[[14,5],6],[[14,5],[[9,[48]]]],[[]],[[],24],[14],[[]],[[14,14],23],[[],14],[[14,14],[[19,[22]]]],[[]],[[],8],[[],9],[[],9],[14,[[9,[42]]]],[[],10],[[]],[[],14],0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[],49],[11,11],[[]],[[11,11],22],[[],49],[[],11],[[11,11],23],[[],23],[[49,12],49],[49,49],[49,49],[49,11],[[49,5],6],[[11,5],[[9,[48]]]],[[11,5],6],[[]],[[]],[[],24],[11],[[]],[[]],[[11,11],23],[[11,11],[[19,[22]]]],[49,49],[49,49],[[]],[[],8],[[],9],[[],9],[[],9],[[],9],[11,[[9,[42]]]],[[],10],[[],10],[[]],[[]],0,[[],[[50,[15]]]],[[],[[50,[21]]]],[[]],[[]],[[[50,[29,29]]],[[50,[29,29]]]],[[]],[[[50,[4,4]],5],6],[[]],[[]],[50],[[]],[[],9],[[],9],[[],10],[[]],[[],50]],"p":[[8,"Challenge"],[3,"AuthenticationError"],[3,"HttpResponse"],[8,"Debug"],[3,"Formatter"],[6,"Result"],[3,"StatusCode"],[3,"String"],[4,"Result"],[3,"TypeId"],[3,"Bearer"],[4,"Error"],[3,"Config"],[3,"Basic"],[3,"BasicAuth"],[3,"HttpRequest"],[4,"Payload"],[15,"str"],[4,"Option"],[3,"Config"],[3,"BearerAuth"],[4,"Ordering"],[15,"bool"],[15,"u64"],[4,"Cow"],[8,"Into"],[8,"Scheme"],[3,"Authorization"],[8,"Clone"],[3,"Basic"],[3,"Bearer"],[8,"Ord"],[8,"Default"],[8,"PartialEq"],[4,"ParseError"],[3,"ToStrError"],[3,"Utf8Error"],[4,"DecodeError"],[15,"never"],[8,"Hash"],[3,"HeaderName"],[3,"HeaderValue"],[4,"ParseError"],[8,"PartialOrd"],[8,"Error"],[3,"WwwAuthenticate"],[3,"Bytes"],[3,"Error"],[3,"BearerBuilder"],[3,"HttpAuthentication"],[8,"AuthExtractorConfig"],[13,"MissingField"],[13,"ToStrError"],[13,"Base64DecodeError"],[13,"Utf8Error"]]}\ +"actix_redis":{"doc":"Redis integration for actix.","t":[12,13,13,3,13,13,4,13,13,13,13,13,13,13,3,13,13,4,4,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,14,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12],"n":["0","Array","BulkString","Command","Connection","Disconnected","Error","Error","IO","Integer","Internal","Nil","NotConnected","Redis","RedisActor","Remote","Resp","RespError","RespValue","SimpleString","Unexpected","append","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone_into","eq","equivalent","error","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from_resp_int","handle","handle","into","into","into","into","into","provide","provide","push","resp_array","restarting","source","source","start","started","to_owned","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","0","0","0","0","0","0","0","1","0","0","0","0","0"],"q":["actix_redis","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_redis::Error","actix_redis::RespError","","","","","","","actix_redis::RespValue","","","",""],"d":["","Zero, one or more other RespValues.","A bulk string. In Redis terminology a string is a …","Command for sending data to Redis.","Error creating a connection, or an error with a connection …","Cancel all waiters when connection is dropped.","General purpose actix-redis error.","An error from the Redis server","An IO error occurred","Redis documentation defines an integer as being a signed …","A non-specific internal error that prevented an operation …","","Receiving message during reconnecting.","","Redis communication actor.","A remote error","A RESP parsing/serialising error occurred","","A single RESP value, this owns the data that is read/to-be …","","An unexpected error. In this context “unexpected” …","Convenience function for building dynamic Redis commands …","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","","","","Returns the argument unchanged.","","","Returns the argument unchanged.","","","","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","Push item to Resp array","Macro to create a RESP array, useful for preparing …","","","","Start new Supervisor with RedisActor.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"i":[7,1,1,0,13,10,0,1,13,1,13,1,10,10,0,13,13,0,0,1,13,1,4,7,10,1,13,4,7,10,1,13,1,1,1,1,4,7,10,10,1,13,13,4,7,10,10,1,1,1,1,1,1,1,1,13,13,13,1,4,4,4,7,10,1,13,10,13,1,0,4,10,13,4,4,1,10,13,4,7,10,1,13,4,7,10,1,13,4,7,10,1,13,4,7,10,1,13,29,30,31,32,33,34,35,32,36,37,38,39,40],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[1,2],1],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[1,1],[[]],[[1,1],3],[[],3],[[4,5],6],[[7,8],9],[[10,8],9],[[10,8],9],[[1,8],[[12,[11]]]],[[13,8],[[12,[11]]]],[[13,8],[[12,[11]]]],[[]],[[]],[[]],[13,10],[14,1],[[[17,[15,16]]],1],[18,1],[14,1],[[],1],[[]],[19,1],[[[20,[19]]],1],[[]],[21,13],[5,13],[1,[[12,[1,13]]]],[[4,[12,[1,13]]]],[[4,7]],[[]],[[]],[[]],[[]],[[]],[22],[22],[1],0,[4],[10,[[24,[23]]]],[13,[[24,[23]]]],[[[25,[14]]],[[26,[4]]]],[[4,27]],[[]],[[],14],[[],14],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],28],[[],28],[[],28],[[],28],[[],28],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,0],"p":[[4,"RespValue"],[8,"IntoIterator"],[15,"bool"],[3,"RedisActor"],[3,"Error"],[4,"Running"],[3,"Command"],[3,"Formatter"],[6,"Result"],[4,"Error"],[3,"Error"],[4,"Result"],[4,"RespError"],[3,"String"],[15,"u8"],[3,"Global"],[3,"Vec"],[15,"usize"],[15,"str"],[3,"Arc"],[3,"TrySendError"],[3,"Demand"],[8,"Error"],[4,"Option"],[8,"Into"],[3,"Addr"],[3,"Context"],[3,"TypeId"],[13,"Redis"],[13,"Internal"],[13,"IO"],[13,"Resp"],[13,"Remote"],[13,"Connection"],[13,"Unexpected"],[13,"Array"],[13,"BulkString"],[13,"Error"],[13,"Integer"],[13,"SimpleString"]]},\ +"actix_session":{"doc":"Session management for Actix Web.","t":[13,13,13,3,8,3,3,3,4,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,13,4,13,13,3,13,13,4,3,13,4,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,3,13,4,13,13,13,3,3,3,3,4,13,13,3,8,4,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12],"n":["Changed","Purged","Renewed","Session","SessionExt","SessionGetError","SessionInsertError","SessionMiddleware","SessionStatus","Unchanged","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","builder","clear","clone","clone","clone","clone_into","clone_into","clone_into","config","default","entries","eq","equivalent","error_response","error_response","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from_request","get","get_session","insert","into","into","into","into","into","new","new_transform","provide","provide","purge","remove","remove_as","renew","source","source","status","storage","to_owned","to_owned","to_owned","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","BrowserSession","BrowserSession","CookieContentSecurity","OnEveryRequest","OnStateChanges","PersistentSession","PersistentSession","Private","SessionLifecycle","SessionMiddlewareBuilder","Signed","TtlExtensionPolicy","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","build","clone","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","clone_into","cookie_content_security","cookie_domain","cookie_http_only","cookie_name","cookie_path","cookie_same_site","cookie_secure","default","default","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","into","into","into","into","into","into","session_lifecycle","session_ttl","session_ttl_extension_policy","state_ttl","state_ttl_extension_policy","to_owned","to_owned","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","vzip","0","0","CookieSessionStore","Deserialization","LoadError","Other","Other","Other","RedisActorSessionStore","RedisActorSessionStoreBuilder","RedisSessionStore","RedisSessionStoreBuilder","SaveError","Serialization","Serialization","SessionKey","SessionStore","UpdateError","as_ref","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","build","build","builder","builder","cache_keygen","cache_keygen","clone","clone_into","default","delete","delete","delete","delete","eq","equivalent","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","into","into","into","into","into","into","into","into","into","load","load","load","load","new","new","provide","provide","provide","save","save","save","save","source","source","source","to_owned","to_string","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","update","update","update","update","update_ttl","update_ttl","update_ttl","update_ttl","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","0","0","0","0","0","0"],"q":["actix_session","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_session::config","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_session::config::SessionLifecycle","","actix_session::storage","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_session::storage::LoadError","","actix_session::storage::SaveError","","actix_session::storage::UpdateError",""],"d":["Session state has been updated - the changes will have to …","The session has been flagged for deletion - the session …","The session has been flagged for renewal.","The primary interface to access and modify session state.","Extract a Session object from various actix-web types …","Error returned by Session::get.","Error returned by Session::insert.","A middleware for session management in Actix Web …","Status of a Session.","The session state has not been modified since its …","","","","","","","","","","","A fluent API to configure SessionMiddleware.","Clear the session.","","","","","","","Configuration options to tune the behaviour of …","","Get all raw key-value data from the session.","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","Returns the argument unchanged.","","Returns the argument unchanged.","","Get a value from the session.","Extract a Session object.","Inserts a key-value pair into the session.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Use SessionMiddleware::new to initialize the session …","","","","Removes session both client and server side.","Remove value from the session.","Remove value from the session and deserialize.","Renews the session key, assigning existing session state …","","","Returns session status.","Pluggable storage backends for session state.","","","","","","","","","","","","","","","","","","","","","","","","","","A session lifecycle strategy where the session cookie …","The session cookie will expire when the current browser …","Determines how to secure the content of the session cookie.","The TTL is refreshed every time the server receives a …","The TTL is refreshed every time the session state changes …","A session lifecycle strategy where the session cookie will …","The session cookie will be a persistent cookie.","The cookie content is encrypted when using …","Determines what type of session cookie should be used and …","A fluent, customized SessionMiddleware builder.","The cookie content is signed when using …","Configuration for which events should trigger an extension …","","","","","","","","","","","","","Finalise the builder and return a SessionMiddleware …","","","","","","","","","","","Choose how the session cookie content should be secured.","Set the Domain attribute for the cookie used to store the …","Set the HttpOnly attribute for the cookie used to store …","Set the name of the cookie used to store the session ID.","Set the Path attribute for the cookie used to store the …","Set the SameSite attribute for the cookie used to store …","Set the Secure attribute for the cookie used to store the …","","","","","","","","Returns the argument unchanged.","","Returns the argument unchanged.","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Determines what type of session cookie should be used and …","Specifies how long the session cookie should live.","Determines under what circumstances the TTL of your …","Sets a time-to-live (TTL) when storing the session state …","Determine under what circumstances the TTL of your session …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Use the session key, stored in the session cookie, as …","Failed to deserialize session state.","Possible failures modes for SessionStore::load.","Something went wrong when retrieving the session state.","Something went wrong when persisting the session state.","Something went wrong when updating the session state.","Use Redis as session storage backend.","A fluent builder to construct a RedisActorSessionStore …","Use Redis as session storage backend.","A fluent builder to construct a RedisSessionStore instance …","Possible failures modes for SessionStore::save.","Failed to serialize session state.","Failed to serialize session state.","A session key, the string stored in a client-side cookie …","The interface to retrieve and save the current session …","Possible failures modes for SessionStore::update.","","","","","","","","","","","","","","","","","","","","Finalise the builder and return a RedisActorSessionStore …","Finalise the builder and return a RedisActorSessionStore …","A fluent API to configure RedisActorSessionStore.","A fluent API to configure RedisSessionStore. It takes as …","Set a custom cache key generation strategy, expecting a …","Set a custom cache key generation strategy, expecting a …","","","","Deletes a session from the store.","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Loads the session state associated to a session key.","","","","Create a new instance of RedisActorSessionStore using the …","Create a new instance of RedisSessionStore using the …","","","","Persist the session state for a newly created session.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Updates the session state associated to a pre-existing …","","","","Updates the TTL of the session state associated to a …","","","","","","","","","","","","","","","","","",""],"i":[7,7,7,0,0,0,0,0,0,7,6,4,7,12,15,6,4,7,12,15,6,4,6,4,7,6,4,7,0,7,4,7,7,12,15,7,12,12,15,15,6,4,7,12,12,15,15,4,4,49,4,6,4,7,12,15,6,6,12,15,4,4,4,4,12,15,4,0,6,4,7,12,15,6,4,7,12,15,6,4,7,12,15,6,4,7,12,15,6,4,7,12,15,0,30,0,33,33,0,30,34,0,0,34,0,3,30,31,32,33,34,3,30,31,32,33,34,3,30,31,32,33,34,30,31,32,33,34,3,3,3,3,3,3,3,31,32,30,31,32,33,34,3,30,30,30,31,32,33,34,3,30,31,32,33,34,3,32,32,31,31,30,31,32,33,34,3,30,31,32,33,34,3,30,31,32,33,34,3,30,31,32,33,34,3,30,31,32,33,34,50,51,0,46,0,46,47,48,0,0,0,0,0,47,48,0,0,0,37,39,38,40,46,47,48,37,43,42,39,38,40,46,47,48,37,43,42,38,40,39,42,38,40,42,42,43,1,39,43,42,37,37,46,46,47,47,48,48,37,39,38,40,46,47,48,37,43,42,39,38,40,46,47,48,37,43,42,1,39,43,42,39,42,46,47,48,1,39,43,42,46,47,48,42,46,47,48,39,38,40,46,47,48,37,37,43,42,39,38,40,46,47,48,37,43,42,39,38,40,46,47,48,37,43,42,1,39,43,42,1,39,43,42,39,38,40,46,47,48,37,43,42,52,53,54,55,56,57],"f":[0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[1,2],[[3,[1]]]],[4],[[[6,[[0,[5,1]]]]],[[6,[[0,[5,1]]]]]],[4,4],[7,7],[[]],[[]],[[]],0,[[],7],[4,[[10,[[9,[8,8]]]]]],[[7,7],11],[[],11],[12,[[14,[13]]]],[15,[[14,[13]]]],[[7,16],17],[[12,16],17],[[12,16],17],[[15,16],17],[[15,16],17],[[]],[[]],[[]],[18,12],[[]],[18,15],[[]],[[19,20]],[[4,21],[[24,[[23,[22]],12]]]],[[],4],[[4,[25,[8]],26],[[24,[15]]]],[[]],[[]],[[]],[[]],[[]],[[1,2],[[6,[1]]]],[6],[27],[27],[4],[[4,21],[[23,[8]]]],[[4,21],[[23,[[24,[22,8]]]]]],[4],[12,[[23,[28]]]],[15,[[23,[28]]]],[4,7],0,[[]],[[]],[[]],[[],8],[[],8],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],29],[[],29],[[],29],[[],29],[[],29],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[3,[1]]],[[6,[1]]]],[30,30],[31,31],[32,32],[33,33],[34,34],[[]],[[]],[[]],[[]],[[]],[[[3,[1]],34],[[3,[1]]]],[[[3,[1]],[23,[8]]],[[3,[1]]]],[[[3,[1]],11],[[3,[1]]]],[[[3,[1]],8],[[3,[1]]]],[[[3,[1]],8],[[3,[1]]]],[[[3,[1]],35],[[3,[1]]]],[[[3,[1]],11],[[3,[1]]]],[[],31],[[],32],[[30,16],17],[[31,16],17],[[32,16],17],[[33,16],17],[[34,16],17],[[]],[32,30],[[]],[31,30],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[3,[1]],[25,[30]]],[[3,[1]]]],[[32,36],32],[[32,33],32],[[31,36],31],[[31,33],31],[[]],[[]],[[]],[[]],[[]],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[37,21],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[38,39],[40,41],[[[25,[8]]],38],[[[25,[8]]],40],[38,38],[40,40],[42,42],[[]],[[],43],[37,[[45,[[44,[41]]]]]],[[39,37],[[45,[[44,[41]]]]]],[[43,37],[[45,[[44,[41]]]]]],[[42,37],[[45,[[44,[41]]]]]],[[37,37],11],[[],11],[[46,16],17],[[46,16],17],[[47,16],17],[[47,16],17],[[48,16],17],[[48,16],17],[[37,16],17],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[37,[[45,[[44,[41]]]]]],[[39,37],[[45,[[44,[41]]]]]],[[43,37],[[45,[[44,[41]]]]]],[[42,37],[[45,[[44,[41]]]]]],[[[25,[8]]],39],[[[25,[8]]],41],[27],[27],[27],[[[9,[8,8]],36],[[45,[[44,[41]]]]]],[[39,[9,[8,8]],36],[[45,[[44,[41]]]]]],[[43,[9,[8,8]],36],[[45,[[44,[41]]]]]],[[42,[9,[8,8]],36],[[45,[[44,[41]]]]]],[46,[[23,[28]]]],[47,[[23,[28]]]],[48,[[23,[28]]]],[[]],[[],8],[[],8],[[],8],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[8,[[24,[37]]]],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],24],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[37,[9,[8,8]],36],[[45,[[44,[41]]]]]],[[39,37,[9,[8,8]],36],[[45,[[44,[41]]]]]],[[43,37,[9,[8,8]],36],[[45,[[44,[41]]]]]],[[42,37,[9,[8,8]],36],[[45,[[44,[41]]]]]],[[37,36],[[45,[[44,[41]]]]]],[[39,37,36],[[45,[[44,[41]]]]]],[[43,37,36],[[45,[[44,[41]]]]]],[[42,37,36],[[45,[[44,[41]]]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0],"p":[[8,"SessionStore"],[3,"Key"],[3,"SessionMiddlewareBuilder"],[3,"Session"],[8,"Clone"],[3,"SessionMiddleware"],[4,"SessionStatus"],[3,"String"],[3,"HashMap"],[3,"Ref"],[15,"bool"],[3,"SessionGetError"],[3,"BoxBody"],[3,"HttpResponse"],[3,"SessionInsertError"],[3,"Formatter"],[6,"Result"],[3,"Error"],[3,"HttpRequest"],[4,"Payload"],[15,"str"],[8,"DeserializeOwned"],[4,"Option"],[4,"Result"],[8,"Into"],[8,"Serialize"],[3,"Demand"],[8,"Error"],[3,"TypeId"],[4,"SessionLifecycle"],[3,"BrowserSession"],[3,"PersistentSession"],[4,"TtlExtensionPolicy"],[4,"CookieContentSecurity"],[4,"SameSite"],[3,"Duration"],[3,"SessionKey"],[3,"RedisActorSessionStoreBuilder"],[3,"RedisActorSessionStore"],[3,"RedisSessionStoreBuilder"],[8,"Future"],[3,"RedisSessionStore"],[3,"CookieSessionStore"],[3,"Box"],[3,"Pin"],[4,"LoadError"],[4,"SaveError"],[4,"UpdateError"],[8,"SessionExt"],[13,"BrowserSession"],[13,"PersistentSession"],[13,"Deserialization"],[13,"Other"],[13,"Serialization"],[13,"Other"],[13,"Serialization"],[13,"Other"]]},\ +"actix_settings":{"doc":"Easily manage Actix Web’s settings from a TOML file and …","t":[3,3,8,4,3,13,13,13,13,13,13,13,13,13,4,13,13,13,4,13,13,13,13,4,4,13,4,3,4,13,8,13,13,13,13,13,13,6,4,3,13,12,12,10,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,11,11,10,11,11,11,11,11,11,11,11,11,12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12],"n":["ActixSettings","Address","ApplySettings","Backlog","BasicSettings","Default","Default","Default","Default","Default","Default","Development","Disabled","EnvVarError","Error","FileExists","InvalidValue","IoError","KeepAlive","Manual","Manual","Manual","Manual","MaxConnectionRate","MaxConnections","Milliseconds","Mode","NoSettings","NumWorkers","Os","Parse","ParseAddressError","ParseBoolError","ParseIntError","Production","Seconds","Seconds","Settings","Timeout","Tls","TomlError","actix","application","apply_settings","backlog","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","certificate","client_shutdown","client_timeout","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","deserialize","enable_compression","enable_log","enabled","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","equivalent","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from_default_template","from_template","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","get_hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","hash","host","hosts","into","into","into","into","into","into","into","into","into","into","into","into","into","keep_alive","max_connection_rate","max_connections","mode","num_workers","override_field","override_field_with_env_var","parse","parse","parse","parse","parse","parse","parse","parse","parse","parse_toml","port","private_key","shutdown_timeout","tls","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","write_toml_file","0","0","0","0","0","0","0","0","column","expected","file","got","line","0","0","0","0","0","0"],"q":["actix_settings","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_settings::Backlog","actix_settings::Error","","","","","","","","","","","","actix_settings::KeepAlive","actix_settings::MaxConnectionRate","actix_settings::MaxConnections","actix_settings::NumWorkers","actix_settings::Timeout",""],"d":["Settings types for Actix Web.","A host/port pair for the server to bind to.","Extension trait for applying parsed settings to the server …","The maximum number of pending connections.","Wrapper for server and application-specific settings.","The default number of connections. See struct docs.","The default keep-alive as defined by Actix Web.","The default connection limit. See struct docs.","The default number of connections. See struct docs.","The default number of workers. See struct docs.","The default timeout. Depends on context.","Marks development environment.","Disable keep-alive.","Environment variable does not exists or is invalid.","Errors that can be returned from methods in this crate.","File already exists on disk.","Invalid value.","I/O error.","The server keep-alive preference.","A specific number of connections.","A specific connection limit.","A specific number of connections.","A specific number of workers.","The maximum per-worker concurrent TLS connection limit.","The maximum per-worker number of concurrent connections.","Timeout in milliseconds.","Marker of intended deployment environment.","Marker type representing no defined application-specific …","The number of workers that the server should start.","Let the OS determine keep-alive duration.","A specialized FromStr trait that returns [AtError] errors","Value is not an address.","Value is not a boolean.","Value is not an integer.","Marks production environment.","A specific keep-alive duration (in seconds).","Timeout in seconds.","Convenience type alias for BasicSettings with no defined …","A timeout duration in milliseconds or seconds.","TLS (HTTPS) configuration.","Error deserializing as TOML.","Actix Web server settings.","Application-specific settings.","Apply a BasicSettings value to self.","The maximum number of pending connections.","","","","","","","","","","","","","","","","","","","","","","","","","","","Path to certificate .pem file.","Timeout duration for connection shutdown.","Timeout duration for reading client request header.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","True if the Compress middleware should be enabled.","True if the Logger middleware should be enabled.","Tru if accepting TLS connections should be enabled.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Parse an instance of Self straight from the default TOML …","Parse an instance of Self straight from the default TOML …","","","","","","","","","","","","","","","","","","","","","","","","","Host part of address.","List of addresses for the server to bind to.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Server keep-alive preference.","The per-worker maximum concurrent TLS connection limit.","The per-worker maximum number of concurrent connections.","Marker of intended deployment environment.","The number of workers that the server should start.","Attempts to parse value and override the referenced field.","Attempts to read an environment variable, parse it, and …","Parse Self from string.","","","","","","","","","Parse an instance of Self from a TOML file located at …","Port part of address.","Path to private key .pem file.","Timeout duration for graceful worker shutdown.","TLS (HTTPS) configuration.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Writes the default TOML template to a new file, located at …","","","","","","","","","","","","","","","","","","",""],"i":[0,0,0,0,0,4,5,6,7,9,10,8,5,2,0,2,2,2,0,4,6,7,9,0,0,10,0,0,0,5,0,2,2,2,8,5,10,0,0,0,2,1,1,31,12,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,11,12,12,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,3,4,5,6,7,8,9,10,11,12,1,14,12,12,11,3,4,5,6,7,8,9,10,11,12,1,14,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,2,2,2,2,2,2,3,4,5,6,7,8,9,10,11,12,1,14,1,1,3,4,5,6,7,8,9,10,11,12,1,14,3,4,5,6,7,8,9,10,11,12,1,14,3,12,2,3,4,5,6,7,8,9,10,11,12,1,14,12,12,12,12,12,1,1,32,3,4,5,6,7,8,9,10,1,3,11,12,12,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,2,3,4,5,6,7,8,9,10,11,12,1,14,1,33,34,35,36,37,38,39,40,41,41,41,41,41,42,43,44,45,46,47],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1],0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[11,11],[12,12],[[[1,[13]]],[[1,[13]]]],[14,14],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],[[15,[3]]]],[[],[[15,[4]]]],[[],[[15,[5]]]],[[],[[15,[6]]]],[[],[[15,[7]]]],[[],[[15,[8]]]],[[],[[15,[9]]]],[[],[[15,[10]]]],[[],[[15,[11]]]],[[],[[15,[12]]]],[[],[[15,[1]]]],[[],[[15,[14]]]],0,0,0,[[3,3],16],[[4,4],16],[[5,5],16],[[6,6],16],[[7,7],16],[[8,8],16],[[9,9],16],[[10,10],16],[[11,11],16],[[12,12],16],[[[1,[17]],1],16],[[14,14],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[],16],[[2,18],19],[[3,18],19],[[4,18],19],[[5,18],19],[[6,18],19],[[7,18],19],[[8,18],19],[[9,18],19],[[10,18],19],[[11,18],19],[[12,18],19],[[[1,[20]],18],19],[[14,18],19],[21,2],[22,2],[23,2],[24,2],[25,2],[[]],[26,2],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],[[15,[1,2]]]],[27,[[15,[1,2]]]],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[[],28],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[[[1,[29]]]],[14],0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,[[],[[15,[2]]]],[[],[[15,[2]]]],[27,[[15,[2]]]],[27,[[15,[3,2]]]],[27,[[15,[4,2]]]],[27,[[15,[5,2]]]],[27,[[15,[6,2]]]],[27,[[15,[7,2]]]],[27,[[15,[8,2]]]],[27,[[15,[9,2]]]],[27,[[15,[10,2]]]],[[],[[15,[1,2]]]],0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],15],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[],30],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[],[[15,[2]]]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"p":[[3,"BasicSettings"],[4,"Error"],[3,"Address"],[4,"Backlog"],[4,"KeepAlive"],[4,"MaxConnectionRate"],[4,"MaxConnections"],[4,"Mode"],[4,"NumWorkers"],[4,"Timeout"],[3,"Tls"],[3,"ActixSettings"],[8,"Clone"],[3,"NoSettings"],[4,"Result"],[15,"bool"],[8,"PartialEq"],[3,"Formatter"],[6,"Result"],[8,"Debug"],[4,"VarError"],[3,"Error"],[3,"ParseIntError"],[3,"ParseBoolError"],[3,"IoError"],[3,"Error"],[15,"str"],[15,"u64"],[8,"Hash"],[3,"TypeId"],[8,"ApplySettings"],[8,"Parse"],[13,"Manual"],[13,"EnvVarError"],[13,"FileExists"],[13,"IoError"],[13,"ParseBoolError"],[13,"ParseIntError"],[13,"ParseAddressError"],[13,"TomlError"],[13,"InvalidValue"],[13,"Seconds"],[13,"Manual"],[13,"Manual"],[13,"Manual"],[13,"Milliseconds"],[13,"Seconds"]],"a":{"https":[39],"ssl":[39]}},\ +"actix_web_httpauth":{"doc":"HTTP authentication schemes for Actix Web.","t":[0,0,0,8,3,16,0,0,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,3,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,3,4,13,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,0,3,13,3,3,13,13,13,4,8,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,8,3,0,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,11,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,3,4,13,13,13,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["extractors","headers","middleware","AuthExtractorConfig","AuthenticationError","Inner","basic","bearer","borrow","borrow_mut","challenge_mut","error_response","fmt","fmt","from","from","into","into_inner","new","provide","status_code","status_code_mut","to_string","try_from","try_into","type_id","vzip","with_error","with_error_description","with_error_uri","BasicAuth","Config","as_ref","borrow","borrow","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","default","fmt","fmt","from","from","from_request","into","into","into_inner","password","realm","to_owned","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","user_id","vzip","vzip","BearerAuth","Config","Error","InsufficientScope","InvalidRequest","InvalidToken","as_ref","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone_into","clone_into","clone_into","cmp","default","eq","equivalent","fmt","fmt","fmt","fmt","from","from","from","from_request","get_hash","hash","into","into","into","into_inner","partial_cmp","realm","scope","status_code","to_owned","to_owned","to_owned","to_string","token","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","vzip","vzip","vzip","authorization","www_authenticate","Authorization","Base64DecodeError","Basic","Bearer","Invalid","MissingField","MissingScheme","ParseError","Scheme","ToStrError","Utf8Error","as_mut","as_ref","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone_into","clone_into","clone_into","cmp","cmp","cmp","default","eq","eq","eq","equivalent","equivalent","equivalent","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","get_hash","hash","into","into","into","into","into_scheme","name","new","new","parse","parse","parse","parse","partial_cmp","partial_cmp","partial_cmp","password","provide","source","to_owned","to_owned","to_owned","to_string","to_string","to_string","to_string","token","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into_pair","try_into_value","try_into_value","try_into_value","type_id","type_id","type_id","type_id","user_id","vzip","vzip","vzip","vzip","0","0","0","0","0","Challenge","WwwAuthenticate","basic","bearer","borrow","borrow_mut","clone","clone_into","cmp","default","eq","equivalent","fmt","from","get_hash","hash","into","name","parse","partial_cmp","to_bytes","to_owned","try_from","try_into","try_into_pair","try_into_value","type_id","vzip","Basic","borrow","borrow_mut","clone","clone_into","cmp","default","eq","equivalent","fmt","fmt","from","get_hash","hash","into","new","partial_cmp","to_owned","to_string","try_from","try_into","try_into_value","type_id","vzip","with_realm","Bearer","BearerBuilder","Error","InsufficientScope","InvalidRequest","InvalidToken","borrow","borrow","borrow_mut","borrow_mut","build","clone","clone_into","cmp","default","default","eq","equivalent","error","error_description","error_uri","finish","fmt","fmt","fmt","from","from","get_hash","hash","into","into","partial_cmp","realm","scope","to_owned","to_string","try_from","try_from","try_into","try_into","try_into_value","type_id","type_id","vzip","vzip","HttpAuthentication","basic","bearer","borrow","borrow_mut","clone","clone_into","fmt","from","into","new_transform","to_owned","try_from","try_into","type_id","vzip","with_fn"],"q":["actix_web_httpauth","","","actix_web_httpauth::extractors","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::extractors::basic","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::extractors::bearer","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers","","actix_web_httpauth::headers::authorization","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers::authorization::ParseError","","","","actix_web_httpauth::headers::www_authenticate","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers::www_authenticate::basic","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::headers::www_authenticate::bearer","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","actix_web_httpauth::middleware","","","","","","","","","","","","","","","",""],"d":["Type-safe authentication information extractors.","Typed HTTP headers.","HTTP Authentication middleware.","Trait implemented for types that provides configuration …","Authentication error returned by authentication extractors.","Associated challenge type.","Extractor for the “Basic” HTTP Authentication Scheme.","Extractor for the “Bearer” HTTP Authentication Scheme.","","","Returns mutable reference to the inner challenge instance.","","","","Returns the argument unchanged.","","Calls U::from(self).","Convert the config instance into a HTTP challenge.","Creates new authentication error from the provided …","","","Returns mutable reference to the inner status code.","","","","","","Attach Error to the current Authentication error.","Attach error description to the current Authentication …","Attach error URI to the current Authentication error.","Extractor for HTTP Basic auth.","BasicAuth extractor configuration used for WWW-Authenticate…","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","","Returns client’s password.","Set challenge realm attribute.","","","","","","","","","Returns client’s user-ID.","","","Extractor for HTTP Bearer auth","BearerAuth extractor configuration.","Bearer authorization error types, described in RFC 6750.","The request requires higher privileges than provided by …","The request is missing a required parameter, includes an …","The access token provided is expired, revoked, malformed, …","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","Set challenge realm attribute.","Set challenge scope attribute.","Returns HTTP status code suitable for current error type.","","","","","Returns bearer token provided by client.","","","","","","","","","","","","","Authorization header and various auth schemes.","WWW-Authenticate header and various auth challenges.","Authorization header, defined in RFC 7235","Malformed base64 string.","Credentials for Basic authentication scheme, defined in …","Credentials for Bearer authentication scheme, defined in …","Header value is malformed.","Required authentication field is missing.","Authentication scheme is missing.","Possible errors while parsing Authorization header.","Authentication scheme for Authorization header.","Unable to convert header into the str.","Malformed UTF-8 string.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Consumes Authorization header and returns inner Scheme …","","Creates Basic credentials with provided user_id and …","Creates new Bearer credentials with the token provided.","Try to parse an authentication scheme from the …","","","","","","","Returns client’s password if provided.","","","","","","","","","","Gets reference to the credentials token.","","","","","","","","","","","","","","","","","Returns client’s user-ID.","","","","","","","","","","Authentication challenge for WWW-Authenticate header.","WWW-Authenticate header, described in RFC 7235.","Challenge for the “Basic” HTTP Authentication Scheme.","Challenge for the “Bearer” HTTP Authentication Scheme.","","","","","","","","","","Returns the argument unchanged.","","","Calls U::from(self).","","","","Converts the challenge into a bytes suitable for HTTP …","","","","","","","","Challenge for WWW-Authenticate header with HTTP Basic auth …","","","","","","","","","","","Returns the argument unchanged.","","","Calls U::from(self).","Creates new Basic challenge with an empty realm field.","","","","","","","","","Creates new Basic challenge from the provided realm field …","Challenge for WWW-Authenticate header with HTTP Bearer …","Builder for the Bearer challenge.","Bearer authorization error types, described in RFC 6750.","The request requires higher privileges than provided by …","The request is missing a required parameter, includes an …","The access token provided is expired, revoked, malformed, …","","","","","Creates the builder for Bearer challenge.","","","","","","","","Provides the error attribute, as defined in [RFC 6750, …","Provides the error_description attribute, as defined in […","Provides the error_uri attribute, as defined in [RFC 6750 …","Consumes the builder and returns built Bearer instance.","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","","Provides the realm attribute, as defined in RFC 2617.","Provides the scope attribute, as defined in RFC 6749 §3.3.","","","","","","","","","","","","Middleware for checking HTTP authentication.","Construct HttpAuthentication middleware for the HTTP “…","Construct HttpAuthentication middleware for the HTTP “…","","","","","","Returns the argument unchanged.","Calls U::from(self).","","","","","","","Construct HttpAuthentication middleware with the provided …"],"i":[0,0,0,0,0,52,0,0,2,2,2,2,2,2,2,2,2,52,2,2,2,2,2,2,2,2,2,2,2,2,0,0,14,14,16,14,16,14,16,14,16,14,14,16,14,16,16,14,16,14,16,14,14,16,14,16,14,16,14,16,16,14,16,0,0,0,13,13,13,21,21,22,13,21,22,13,21,22,13,21,22,13,13,21,13,13,21,22,13,13,21,22,13,22,13,13,21,22,13,21,13,21,21,13,21,22,13,13,22,21,22,13,21,22,13,21,22,13,21,22,13,0,0,0,36,0,0,36,36,36,0,0,36,36,29,29,36,29,31,32,36,29,31,32,29,31,32,29,31,32,29,31,32,29,29,31,32,29,31,32,36,36,29,29,31,31,32,32,36,36,36,36,29,29,29,31,32,29,29,36,29,31,32,29,29,31,32,28,29,31,32,29,31,32,31,36,36,29,31,32,36,29,31,32,32,36,29,31,32,36,29,31,32,29,29,31,32,36,29,31,32,31,36,29,31,32,53,54,55,56,47,0,0,0,0,47,47,47,47,47,47,47,47,47,47,47,47,47,47,47,47,1,47,47,47,47,47,47,47,0,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,0,0,0,13,13,13,50,12,50,12,12,12,12,12,50,12,12,12,50,50,50,50,50,12,12,50,12,12,12,50,12,12,50,50,12,12,50,12,50,12,12,50,12,50,12,0,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51,51],"f":[0,0,0,0,0,0,0,0,[[]],[[]],[[[2,[1]]]],[[[2,[1]]],3],[[[2,[[0,[4,1]]]],5],6],[[[2,[1]],5],6],[[]],[[],2],[[]],[[]],[1,[[2,[1]]]],[7],[[[2,[1]]],8],[[[2,[1]]],8],[[],9],[[],10],[[],10],[[],11],[[]],[[[2,[12]],13],[[2,[12]]]],[[[2,[12]]],[[2,[12]]]],[[[2,[12]]],[[2,[12]]]],0,0,[14,15],[[]],[[]],[[]],[[]],[14,14],[16,16],[[]],[[]],[[],14],[[14,5],6],[[16,5],6],[[]],[[]],[[17,18]],[[]],[[]],[14],[16,[[20,[19]]]],[14,14],[[]],[[]],[[],10],[[],10],[[],10],[[],10],[[],11],[[],11],[16,19],[[]],[[]],0,0,0,0,0,0,[21,12],[[]],[[]],[[]],[[]],[[]],[[]],[21,21],[22,22],[13,13],[[]],[[]],[[]],[[13,13],23],[[],21],[[13,13],24],[[],24],[[21,5],6],[[22,5],6],[[13,5],6],[[13,5],6],[[]],[[]],[[]],[[17,18]],[[],25],[13],[[]],[[]],[[]],[21],[[13,13],[[20,[23]]]],[[21,[27,[[26,[19]]]]],21],[[21,[27,[[26,[19]]]]],21],[13,8],[[]],[[]],[[]],[[],9],[22,19],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],11],[[],11],[[],11],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,0,[[[29,[28]]]],[[[29,[28]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[29,[[0,[30,28]]]]],[[29,[[0,[30,28]]]]]],[31,31],[32,32],[[]],[[]],[[]],[[[29,[[0,[33,28]]]],29],23],[[31,31],23],[[32,32],23],[[],[[29,[[0,[34,28]]]]]],[[[29,[[0,[35,28]]]],29],24],[[31,31],24],[[32,32],24],[[],24],[[],24],[[],24],[[36,5],6],[[36,5],6],[[[29,[[0,[4,28]]]],5],6],[[[29,[28]],5],6],[[31,5],6],[[31,5],6],[[32,5],6],[[32,5],6],[37,36],[[]],[38,36],[39,36],[40],[28,[[29,[28]]]],[[]],[[]],[[]],[[],25],[[[29,[[0,[41,28]]]]]],[[]],[[]],[[]],[[]],[[[29,[28]]],28],[[],42],[20,31],[[],32],[43,[[10,[36]]]],[[],[[10,[[29,[28]],44]]]],[43,[[10,[31,36]]]],[43,[[10,[32,36]]]],[[[29,[[0,[45,28]]]],29],[[20,[23]]]],[[31,31],[[20,[23]]]],[[32,32],[[20,[23]]]],[31,[[20,[19]]]],[7],[36,[[20,[46]]]],[[]],[[]],[[]],[[],9],[[],9],[[],9],[[],9],[32,19],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[[29,[28]]],[[10,[43]]]],[31,[[10,[43]]]],[32,[[10,[43]]]],[[],11],[[],11],[[],11],[[],11],[31,19],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,[[]],[[]],[[[47,[[0,[30,1]]]]],[[47,[[0,[30,1]]]]]],[[]],[[[47,[[0,[33,1]]]],47],23],[[],[[47,[[0,[34,1]]]]]],[[[47,[[0,[35,1]]]],47],24],[[],24],[[[47,[[0,[4,1]]]],5],6],[[]],[[],25],[[[47,[[0,[41,1]]]]]],[[]],[[],42],[[],[[10,[[47,[1]],44]]]],[[[47,[[0,[45,1]]]],47],[[20,[23]]]],[[],48],[[]],[[],10],[[],10],[[],10],[[[47,[1]]],[[10,[43]]]],[[],11],[[]],0,[[]],[[]],[15,15],[[]],[[15,15],23],[[],15],[[15,15],24],[[],24],[[15,5],[[10,[49]]]],[[15,5],6],[[]],[[],25],[15],[[]],[[],15],[[15,15],[[20,[23]]]],[[]],[[],9],[[],10],[[],10],[15,[[10,[43]]]],[[],11],[[]],[[],15],0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[],50],[12,12],[[]],[[12,12],23],[[],50],[[],12],[[12,12],24],[[],24],[[50,13],50],[50,50],[50,50],[50,12],[[50,5],6],[[12,5],6],[[12,5],[[10,[49]]]],[[]],[[]],[[],25],[12],[[]],[[]],[[12,12],[[20,[23]]]],[50,50],[50,50],[[]],[[],9],[[],10],[[],10],[[],10],[[],10],[12,[[10,[43]]]],[[],11],[[],11],[[]],[[]],0,[[],[[51,[16]]]],[[],[[51,[22]]]],[[]],[[]],[[[51,[30,30]]],[[51,[30,30]]]],[[]],[[[51,[4,4]],5],6],[[]],[[]],[51],[[]],[[],10],[[],10],[[],11],[[]],[[],51]],"p":[[8,"Challenge"],[3,"AuthenticationError"],[3,"HttpResponse"],[8,"Debug"],[3,"Formatter"],[6,"Result"],[3,"Demand"],[3,"StatusCode"],[3,"String"],[4,"Result"],[3,"TypeId"],[3,"Bearer"],[4,"Error"],[3,"Config"],[3,"Basic"],[3,"BasicAuth"],[3,"HttpRequest"],[4,"Payload"],[15,"str"],[4,"Option"],[3,"Config"],[3,"BearerAuth"],[4,"Ordering"],[15,"bool"],[15,"u64"],[4,"Cow"],[8,"Into"],[8,"Scheme"],[3,"Authorization"],[8,"Clone"],[3,"Basic"],[3,"Bearer"],[8,"Ord"],[8,"Default"],[8,"PartialEq"],[4,"ParseError"],[3,"Utf8Error"],[4,"DecodeError"],[3,"ToStrError"],[15,"never"],[8,"Hash"],[3,"HeaderName"],[3,"HeaderValue"],[4,"ParseError"],[8,"PartialOrd"],[8,"Error"],[3,"WwwAuthenticate"],[3,"Bytes"],[3,"Error"],[3,"BearerBuilder"],[3,"HttpAuthentication"],[8,"AuthExtractorConfig"],[13,"MissingField"],[13,"ToStrError"],[13,"Base64DecodeError"],[13,"Utf8Error"]]}\ }'); if (typeof window !== 'undefined' && window.initSearch) {window.initSearch(searchIndex)}; if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; diff --git a/search.js b/search.js index d35a7db81..f0ccdfb1b 100644 --- a/search.js +++ b/search.js @@ -1 +1 @@ -"use strict";(function(){const itemTypes=["mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","primitive","associatedtype","constant","associatedconstant","union","foreigntype","keyword","existential","attr","derive","traitalias",];const TY_PRIMITIVE=itemTypes.indexOf("primitive");const TY_KEYWORD=itemTypes.indexOf("keyword");const ROOT_PATH=typeof window!=="undefined"?window.rootPath:"../";function hasOwnPropertyRustdoc(obj,property){return Object.prototype.hasOwnProperty.call(obj,property)}function printTab(nb){let iter=0;let foundCurrentTab=false;let foundCurrentResultSet=false;onEachLazy(document.getElementById("titles").childNodes,elem=>{if(nb===iter){addClass(elem,"selected");foundCurrentTab=true}else{removeClass(elem,"selected")}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}else if(nb!==0){printTab(0)}}const levenshtein_row2=[];function levenshtein(s1,s2){if(s1===s2){return 0}const s1_len=s1.length,s2_len=s2.length;if(s1_len&&s2_len){let i1=0,i2=0,a,b,c,c2;const row=levenshtein_row2;while(i1-".indexOf(c)!==-1}function isStopCharacter(c){return isWhitespace(c)||isEndCharacter(c)}function isErrorCharacter(c){return"()".indexOf(c)!==-1}function itemTypeFromName(typename){for(let i=0,len=itemTypes.length;i0){throw new Error("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 new Error("Unclosed `\"`")}else if(parserState.userQuery[end]!=="\""){throw new Error(`Unexpected \`${parserState.userQuery[end]}\` in a string element`)}else if(start===end){throw new Error("Cannot have empty string element")}parserState.pos+=1;query.literalSearch=true}function isPathStart(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="::"}function isReturnArrow(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="->"}function isIdentCharacter(c){return(c==="_"||(c>="0"&&c<="9")||(c>="a"&&c<="z")||(c>="A"&&c<="Z"))}function isSeparatorCharacter(c){return c===","||isWhitespaceCharacter(c)}function isWhitespaceCharacter(c){return c===" "||c==="\t"}function createQueryElement(query,parserState,name,generics,isInGenerics){if(name==="*"||(name.length===0&&generics.length===0)){return}if(query.literalSearch&&parserState.totalElems-parserState.genericsElems>0){throw new Error("You cannot have more than one element if you use quotes")}const pathSegments=name.split("::");if(pathSegments.length>1){for(let i=0,len=pathSegments.length;i=end){throw new Error("Found generics without a path")}parserState.pos+=1;getItemsBefore(query,parserState,generics,">")}if(start>=end&&generics.length===0){return}elems.push(createQueryElement(query,parserState,parserState.userQuery.slice(start,end),generics,isInGenerics))}function getItemsBefore(query,parserState,elems,endChar){let foundStopChar=true;while(parserState.pos"){extra="`<`"}else if(endChar===""){extra="`->`"}throw new Error("Unexpected `"+c+"` after "+extra)}if(!foundStopChar){if(endChar!==""){throw new Error(`Expected \`,\`, \` \` or \`${endChar}\`, found \`${c}\``)}throw new Error(`Expected \`,\` or \` \`, found \`${c}\``)}const posBefore=parserState.pos;getNextElem(query,parserState,elems,endChar===">");if(posBefore===parserState.pos){parserState.pos+=1}foundStopChar=false}parserState.pos+=1}function checkExtraTypeFilterCharacters(parserState){const query=parserState.userQuery;for(let pos=0;pos"){if(isReturnArrow(parserState)){break}throw new Error(`Unexpected \`${c}\` (did you mean \`->\`?)`)}throw new Error(`Unexpected \`${c}\``)}else if(c===":"&&!isPathStart(parserState)){if(parserState.typeFilter!==null){throw new Error("Unexpected `:`")}if(query.elems.length===0){throw new Error("Expected type filter before `:`")}else if(query.elems.length!==1||parserState.totalElems!==1){throw new Error("Unexpected `:`")}else if(query.literalSearch){throw new Error("You cannot use quotes on type filter")}checkExtraTypeFilterCharacters(parserState);parserState.typeFilter=query.elems.pop().name;parserState.pos+=1;parserState.totalElems=0;query.literalSearch=false;foundStopChar=true;continue}if(!foundStopChar){if(parserState.typeFilter!==null){throw new Error(`Expected \`,\`, \` \` or \`->\`, found \`${c}\``)}throw new Error(`Expected \`,\`, \` \`, \`:\` or \`->\`, found \`${c}\``)}before=query.elems.length;getNextElem(query,parserState,query.elems,false);if(query.elems.length===before){parserState.pos+=1}foundStopChar=false}while(parserState.pos`")}break}else{parserState.pos+=1}}}function newParsedQuery(userQuery){return{original:userQuery,userQuery:userQuery.toLowerCase(),typeFilter:NO_TYPE_FILTER,elems:[],returned:[],foundElems:0,literalSearch:false,error:null,}}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"&&hasOwnPropertyRustdoc(rawSearchIndex,elem.value)){return elem.value}return null}function parseQuery(userQuery){userQuery=userQuery.trim();const parserState={length:userQuery.length,pos:0,totalElems:0,genericsElems:0,typeFilter:null,userQuery:userQuery.toLowerCase(),};let query=newParsedQuery(userQuery);try{parseInput(query,parserState);if(parserState.typeFilter!==null){let typeFilter=parserState.typeFilter;if(typeFilter==="const"){typeFilter="constant"}query.typeFilter=itemTypeFromName(typeFilter)}}catch(err){query=newParsedQuery(userQuery);query.error=err.message;query.typeFilter=-1;return query}if(!query.literalSearch){query.literalSearch=parserState.totalElems>1}query.foundElems=query.elems.length+query.returned.length;return query}function createQueryResults(results_in_args,results_returned,results_others,parsedQuery){return{"in_args":results_in_args,"returned":results_returned,"others":results_others,"query":parsedQuery,}}function execQuery(parsedQuery,searchWords,filterCrates,currentCrate){const results_others={},results_in_args={},results_returned={};function transformResults(results){const duplicates={};const out=[];for(const result of results){if(result.id>-1){const obj=searchIndex[result.id];obj.lev=result.lev;const res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=obj.displayPath+obj.name;obj.fullPath+="|"+obj.ty;if(duplicates[obj.fullPath]){continue}duplicates[obj.fullPath]=true;obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}return out}function sortResults(results,isType,preferredCrate){const userQuery=parsedQuery.userQuery;const ar=[];for(const entry in results){if(hasOwnPropertyRustdoc(results,entry)){const result=results[entry];result.word=searchWords[result.id];result.item=searchIndex[result.id]||{};ar.push(result)}}results=ar;if(results.length===0){return[]}results.sort((aaa,bbb)=>{let a,b;a=(aaa.word!==userQuery);b=(bbb.word!==userQuery);if(a!==b){return a-b}a=(aaa.lev);b=(bbb.lev);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=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}if((aaa.item.ty===TY_PRIMITIVE&&bbb.item.ty!==TY_KEYWORD)||(aaa.item.ty===TY_KEYWORD&&bbb.item.ty!==TY_PRIMITIVE)){return-1}if((bbb.item.ty===TY_PRIMITIVE&&aaa.item.ty!==TY_PRIMITIVE)||(bbb.item.ty===TY_KEYWORD&&aaa.item.ty!==TY_KEYWORD)){return 1}a=(aaa.item.desc==="");b=(bbb.item.desc==="");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});let nameSplit=null;if(parsedQuery.elems.length===1){const hasPath=typeof parsedQuery.elems[0].path==="undefined";nameSplit=hasPath?null:parsedQuery.elems[0].path}for(const result of results){if(result.dontValidate){continue}const name=result.item.name.toLowerCase(),path=result.item.path.toLowerCase(),parent=result.item.parent;if(!isType&&!validateResult(name,path,nameSplit,parent)){result.id=-1}}return transformResults(results)}function checkGenerics(row,elem,defaultLev){if(row.generics.length===0){return elem.generics.length===0?defaultLev:MAX_LEV_DISTANCE+1}else if(row.generics.length>0&&row.generics[0].name===null){return checkGenerics(row.generics[0],elem,defaultLev)}let elem_name;if(elem.generics.length>0&&row.generics.length>=elem.generics.length){const elems=Object.create(null);for(const entry of row.generics){elem_name=entry.name;if(elem_name===""){if(checkGenerics(entry,elem,MAX_LEV_DISTANCE+1)!==0){return MAX_LEV_DISTANCE+1}continue}if(elems[elem_name]===undefined){elems[elem_name]=0}elems[elem_name]+=1}for(const generic of elem.generics){let match=null;if(elems[generic.name]){match=generic.name}else{for(elem_name in elems){if(!hasOwnPropertyRustdoc(elems,elem_name)){continue}if(elem_name===generic){match=elem_name;break}}}if(match===null){return MAX_LEV_DISTANCE+1}elems[match]-=1;if(elems[match]===0){delete elems[match]}}return 0}return MAX_LEV_DISTANCE+1}function checkIfInGenerics(row,elem){let lev=MAX_LEV_DISTANCE+1;for(const entry of row.generics){lev=Math.min(checkType(entry,elem,true),lev);if(lev===0){break}}return lev}function checkType(row,elem,literalSearch){if(row.name===null){if(row.generics.length>0){return checkIfInGenerics(row,elem)}return MAX_LEV_DISTANCE+1}let lev=levenshtein(row.name,elem.name);if(literalSearch){if(lev!==0){if(elem.generics.length===0){const checkGeneric=row.generics.length>0;if(checkGeneric&&row.generics.findIndex(tmp_elem=>tmp_elem.name===elem.name)!==-1){return 0}}return MAX_LEV_DISTANCE+1}else if(elem.generics.length>0){return checkGenerics(row,elem,MAX_LEV_DISTANCE+1)}return 0}else if(row.generics.length>0){if(elem.generics.length===0){if(lev===0){return 0}lev=checkIfInGenerics(row,elem);return lev+0.5}else if(lev>MAX_LEV_DISTANCE){return checkIfInGenerics(row,elem)}else{const tmp_lev=checkGenerics(row,elem,lev);if(tmp_lev>MAX_LEV_DISTANCE){return MAX_LEV_DISTANCE+1}return(tmp_lev+lev)/2}}else if(elem.generics.length>0){return MAX_LEV_DISTANCE+1}return lev}function findArg(row,elem,typeFilter){let lev=MAX_LEV_DISTANCE+1;if(row&&row.type&&row.type.inputs&&row.type.inputs.length>0){for(const input of row.type.inputs){if(!typePassesFilter(typeFilter,input.ty)){continue}lev=Math.min(lev,checkType(input,elem,parsedQuery.literalSearch));if(lev===0){return 0}}}return parsedQuery.literalSearch?MAX_LEV_DISTANCE+1:lev}function checkReturned(row,elem,typeFilter){let lev=MAX_LEV_DISTANCE+1;if(row&&row.type&&row.type.output.length>0){const ret=row.type.output;for(const ret_ty of ret){if(!typePassesFilter(typeFilter,ret_ty.ty)){continue}lev=Math.min(lev,checkType(ret_ty,elem,parsedQuery.literalSearch));if(lev===0){return 0}}}return parsedQuery.literalSearch?MAX_LEV_DISTANCE+1:lev}function checkPath(contains,ty){if(contains.length===0){return 0}let ret_lev=MAX_LEV_DISTANCE+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;if(clength>length){return MAX_LEV_DISTANCE+1}for(let i=0;ilength){break}let lev_total=0;let aborted=false;for(let x=0;xMAX_LEV_DISTANCE){aborted=true;break}lev_total+=lev}if(!aborted){ret_lev=Math.min(ret_lev,Math.round(lev_total/clength))}}return ret_lev}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,desc:item.desc,ty:item.ty,parent:item.parent,type:item.type,is_alias:true,}}function handleAliases(ret,query,filterCrates,currentCrate){const lowerQuery=query.toLowerCase();const aliases=[];const crateAliases=[];if(filterCrates!==null){if(ALIASES[filterCrates]&&ALIASES[filterCrates][lowerQuery]){const query_aliases=ALIASES[filterCrates][lowerQuery];for(const alias of query_aliases){aliases.push(createAliasFromItem(searchIndex[alias]))}}}else{Object.keys(ALIASES).forEach(crate=>{if(ALIASES[crate][lowerQuery]){const pushTo=crate===currentCrate?crateAliases:aliases;const query_aliases=ALIASES[crate][lowerQuery];for(const alias of query_aliases){pushTo.push(createAliasFromItem(searchIndex[alias]))}}})}const sortFunc=(aaa,bbb)=>{if(aaa.path{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(pushFunc);crateAliases.forEach(pushFunc)}function addIntoResults(results,fullId,id,index,lev){if(lev===0||(!parsedQuery.literalSearch&&lev<=MAX_LEV_DISTANCE)){if(results[fullId]!==undefined){const result=results[fullId];if(result.dontValidate||result.lev<=lev){return}}results[fullId]={id:id,index:index,dontValidate:parsedQuery.literalSearch,lev:lev,}}}function handleSingleArg(row,pos,elem,results_others,results_in_args,results_returned){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let lev,lev_add=0,index=-1;const fullId=row.id;const in_args=findArg(row,elem,parsedQuery.typeFilter);const returned=checkReturned(row,elem,parsedQuery.typeFilter);addIntoResults(results_in_args,fullId,pos,index,in_args);addIntoResults(results_returned,fullId,pos,index,returned);if(!typePassesFilter(parsedQuery.typeFilter,row.ty)){return}const searchWord=searchWords[pos];if(parsedQuery.literalSearch){if(searchWord===elem.name){addIntoResults(results_others,fullId,pos,-1,0)}return}if(elem.name.length===0){if(row.type!==null){lev=checkGenerics(row.type,elem,MAX_LEV_DISTANCE+1);addIntoResults(results_others,fullId,pos,index,lev)}return}if(elem.fullPath.length>1){lev=checkPath(elem.pathWithoutLast,row);if(lev>MAX_LEV_DISTANCE||(parsedQuery.literalSearch&&lev!==0)){return}else if(lev>0){lev_add=lev/10}}if(searchWord.indexOf(elem.pathLast)>-1||row.normalizedName.indexOf(elem.pathLast)>-1){index=row.normalizedName.indexOf(elem.pathLast)}lev=levenshtein(searchWord,elem.pathLast);if(lev>0&&elem.pathLast.length>2&&searchWord.indexOf(elem.pathLast)>-1){if(elem.pathLast.length<6){lev=1}else{lev=0}}lev+=lev_add;if(lev>MAX_LEV_DISTANCE){return}else if(index!==-1&&elem.fullPath.length<2){lev-=1}if(lev<0){lev=0}addIntoResults(results_others,fullId,pos,index,lev)}function handleArgs(row,pos,results){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let totalLev=0;let nbLev=0;function checkArgs(elems,callback){for(const elem of elems){const lev=callback(row,elem,NO_TYPE_FILTER);if(lev<=1){nbLev+=1;totalLev+=lev}else{return false}}return true}if(!checkArgs(parsedQuery.elems,findArg)){return}if(!checkArgs(parsedQuery.returned,checkReturned)){return}if(nbLev===0){return}const lev=Math.round(totalLev/nbLev);addIntoResults(results,row.id,pos,0,lev)}function innerRunQuery(){let elem,i,nSearchWords,in_returned,row;if(parsedQuery.foundElems===1){if(parsedQuery.elems.length===1){elem=parsedQuery.elems[0];for(i=0,nSearchWords=searchWords.length;i0){for(i=0,nSearchWords=searchWords.length;i-1||path.indexOf(key)>-1||(parent!==undefined&&parent.name!==undefined&&parent.name.toLowerCase().indexOf(key)>-1)||levenshtein(name,key)<=MAX_LEV_DISTANCE)){return false}}return true}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("#titles > button").item(searchState.currentTab);if(target){target.focus()}}function buildHrefAndPath(item){let displayPath;let href;const type=itemTypes[item.ty];const name=item.name;let path=item.path;if(type==="mod"){displayPath=path+"::";href=ROOT_PATH+path.replace(/::/g,"/")+"/"+name+"/index.html"}else if(type==="import"){displayPath=item.path+"::";href=ROOT_PATH+item.path.replace(/::/g,"/")+"/index.html#reexport."+name}else if(type==="primitive"||type==="keyword"){displayPath="";href=ROOT_PATH+path.replace(/::/g,"/")+"/"+type+"."+name+".html"}else if(type==="externcrate"){displayPath="";href=ROOT_PATH+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;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+"::"}href=ROOT_PATH+path.replace(/::/g,"/")+"/"+pageType+"."+pageName+".html"+anchor}else{displayPath=item.path+"::";href=ROOT_PATH+item.path.replace(/::/g,"/")+"/"+type+"."+name+".html"}return[displayPath,href]}function escape(content){const h1=document.createElement("h1");h1.textContent=content;return h1.innerHTML}function pathSplitter(path){const tmp=""+path.replace(/::/g,"::");if(tmp.endsWith("")){return tmp.slice(0,tmp.length-6)}return tmp}function addTab(array,query,display){let extraClass="";if(display===true){extraClass=" active"}const output=document.createElement("div");let length=0;if(array.length>0){output.className="search-results "+extraClass;array.forEach(item=>{const name=item.name;const type=itemTypes[item.ty];length+=1;let extra="";if(type==="primitive"){extra=" (primitive type)"}else if(type==="keyword"){extra=" (keyword)"}const link=document.createElement("a");link.className="result-"+type;link.href=item.href;const wrapper=document.createElement("div");const resultName=document.createElement("div");resultName.className="result-name";if(item.is_alias){const alias=document.createElement("span");alias.className="alias";const bold=document.createElement("b");bold.innerText=item.alias;alias.appendChild(bold);alias.insertAdjacentHTML("beforeend"," - see ");resultName.appendChild(alias)}resultName.insertAdjacentHTML("beforeend",item.displayPath+""+name+extra+"");wrapper.appendChild(resultName);const description=document.createElement("div");description.className="desc";const spanDesc=document.createElement("span");spanDesc.insertAdjacentHTML("beforeend",item.desc);description.appendChild(spanDesc);wrapper.appendChild(description);link.appendChild(wrapper);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,length]}function makeTabHeader(tabNb,text,nbElems){if(searchState.currentTab===tabNb){return""}return""}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"&&(!search.firstChild||search.firstChild.innerText!==searchState.loadingText))){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=parseQuery(searchState.input.value)}currentResults=results.query.userQuery;const ret_others=addTab(results.others,results.query,true);const ret_in_args=addTab(results.in_args,results.query,false);const ret_returned=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="";const crates_list=Object.keys(rawSearchIndex);if(crates_list.length>1){crates=" in "}let typeFilter="";if(results.query.typeFilter!==NO_TYPE_FILTER){typeFilter=" (type: "+escape(itemTypes[results.query.typeFilter])+")"}let output="
"+`

Results for ${escape(results.query.userQuery)}`+`${typeFilter}

${crates}
`;if(results.query.error!==null){output+=`

Query parser error: "${results.query.error}".

`;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}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;const crateSearch=document.getElementById("crate-search");if(crateSearch){crateSearch.addEventListener("input",updateCrate)}search.appendChild(resultsElem);searchState.showResults(search);const elems=document.getElementById("titles").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 search(e,forced){const params=searchState.getQueryStringParams();const query=parseQuery(searchState.input.value.trim());if(e){e.preventDefault()}if(!forced&&query.userQuery===currentResults){if(query.userQuery.length>0){putBackSearch()}return}let filterCrates=getFilterCrates();if(filterCrates===null&¶ms["filter-crate"]!==undefined){filterCrates=params["filter-crate"]}searchState.title="Results for "+query.original+" - Rust";if(browserSupportsHistoryApi()){const newURL=buildUrl(query.original,filterCrates);if(!history.state&&!params.search){history.pushState(null,"",newURL)}else{history.replaceState(null,"",newURL)}}showResults(execQuery(query,searchWords,filterCrates,window.currentCrate),params.go_to_first,filterCrates)}function buildItemSearchTypeAll(types,lowercasePaths){const PATH_INDEX_DATA=0;const GENERICS_DATA=1;return types.map(type=>{let pathIndex,generics;if(typeof type==="number"){pathIndex=type;generics=[]}else{pathIndex=type[PATH_INDEX_DATA];generics=buildItemSearchTypeAll(type[GENERICS_DATA],lowercasePaths)}return{name:pathIndex===0?null:lowercasePaths[pathIndex-1].name,ty:pathIndex===0?null:lowercasePaths[pathIndex-1].ty,generics:generics,}})}function buildFunctionSearchType(functionSearchType,lowercasePaths){const INPUTS_DATA=0;const OUTPUT_DATA=1;if(functionSearchType===0){return null}let inputs,output;if(typeof functionSearchType[INPUTS_DATA]==="number"){const pathIndex=functionSearchType[INPUTS_DATA];inputs=[{name:pathIndex===0?null:lowercasePaths[pathIndex-1].name,ty:pathIndex===0?null:lowercasePaths[pathIndex-1].ty,generics:[],}]}else{inputs=buildItemSearchTypeAll(functionSearchType[INPUTS_DATA],lowercasePaths)}if(functionSearchType.length>1){if(typeof functionSearchType[OUTPUT_DATA]==="number"){const pathIndex=functionSearchType[OUTPUT_DATA];output=[{name:pathIndex===0?null:lowercasePaths[pathIndex-1].name,ty:pathIndex===0?null:lowercasePaths[pathIndex-1].ty,generics:[],}]}else{output=buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA],lowercasePaths)}}else{output=[]}return{inputs,output,}}function buildIndex(rawSearchIndex){searchIndex=[];const searchWords=[];let i,word;let currentIndex=0;let id=0;for(const crate in rawSearchIndex){if(!hasOwnPropertyRustdoc(rawSearchIndex,crate)){continue}let crateSize=0;const crateCorpus=rawSearchIndex[crate];searchWords.push(crate);const crateRow={crate:crate,ty:1,name:crate,path:"",desc:crateCorpus.doc,parent:undefined,type:null,id:id,normalizedName:crate.indexOf("_")===-1?crate:crate.replace(/_/g,""),};id+=1;searchIndex.push(crateRow);currentIndex+=1;const itemTypes=crateCorpus.t;const itemNames=crateCorpus.n;const itemPaths=crateCorpus.q;const itemDescs=crateCorpus.d;const itemParentIdxs=crateCorpus.i;const itemFunctionSearchTypes=crateCorpus.f;const paths=crateCorpus.p;const aliases=crateCorpus.a;const lowercasePaths=[];let len=paths.length;for(i=0;i0?paths[itemParentIdxs[i]-1]:undefined,type:buildFunctionSearchType(itemFunctionSearchTypes[i],lowercasePaths),id:id,normalizedName:word.indexOf("_")===-1?word:word.replace(/_/g,""),};id+=1;searchIndex.push(row);lastPath=row.path;crateSize+=1}if(aliases){ALIASES[crate]=Object.create(null);for(const alias_name in aliases){if(!hasOwnPropertyRustdoc(aliases,alias_name)){continue}if(!hasOwnPropertyRustdoc(ALIASES[crate],alias_name)){ALIASES[crate][alias_name]=[]}for(const local_alias of aliases[alias_name]){ALIASES[crate][alias_name].push(local_alias+currentIndex)}}}currentIndex+=crateSize}return searchWords}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){if(browserSupportsHistoryApi()){history.replaceState(null,window.currentCrate+" - Rust",getNakedUrl()+window.location.hash)}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;search(e)}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 params=searchState.getQueryStringParams();const query=searchState.input.value.trim();if(!history.state&&!params.search){history.pushState(null,"",buildUrl(query,null))}else{history.replaceState(null,"",buildUrl(query,null))}}currentResults=null;search(undefined,true)}const searchWords=buildIndex(rawSearchIndex);if(typeof window!=="undefined"){registerSearchEvents();if(window.searchState.getQueryStringParams().search){search()}}if(typeof exports!=="undefined"){exports.initSearch=initSearch;exports.execQuery=execQuery;exports.parseQuery=parseQuery}return searchWords}if(typeof window!=="undefined"){window.initSearch=initSearch;if(window.searchIndex!==undefined){initSearch(window.searchIndex)}}else{initSearch({})}})() \ No newline at end of file +"use strict";(function(){const itemTypes=["mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","primitive","associatedtype","constant","associatedconstant","union","foreigntype","keyword","existential","attr","derive","traitalias",];const TY_PRIMITIVE=itemTypes.indexOf("primitive");const TY_KEYWORD=itemTypes.indexOf("keyword");const ROOT_PATH=typeof window!=="undefined"?window.rootPath:"../";function hasOwnPropertyRustdoc(obj,property){return Object.prototype.hasOwnProperty.call(obj,property)}function printTab(nb){let iter=0;let foundCurrentTab=false;let foundCurrentResultSet=false;onEachLazy(document.getElementById("titles").childNodes,elem=>{if(nb===iter){addClass(elem,"selected");foundCurrentTab=true}else{removeClass(elem,"selected")}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}else if(nb!==0){printTab(0)}}const levenshtein_row2=[];function levenshtein(s1,s2){if(s1===s2){return 0}const s1_len=s1.length,s2_len=s2.length;if(s1_len&&s2_len){let i1=0,i2=0,a,b,c,c2;const row=levenshtein_row2;while(i1-".indexOf(c)!==-1}function isStopCharacter(c){return isWhitespace(c)||isEndCharacter(c)}function isErrorCharacter(c){return"()".indexOf(c)!==-1}function itemTypeFromName(typename){for(let i=0,len=itemTypes.length;i0){throw new Error("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 new Error("Unclosed `\"`")}else if(parserState.userQuery[end]!=="\""){throw new Error(`Unexpected \`${parserState.userQuery[end]}\` in a string element`)}else if(start===end){throw new Error("Cannot have empty string element")}parserState.pos+=1;query.literalSearch=true}function isPathStart(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="::"}function isReturnArrow(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="->"}function isIdentCharacter(c){return(c==="_"||(c>="0"&&c<="9")||(c>="a"&&c<="z")||(c>="A"&&c<="Z"))}function isSeparatorCharacter(c){return c===","||isWhitespaceCharacter(c)}function isWhitespaceCharacter(c){return c===" "||c==="\t"}function createQueryElement(query,parserState,name,generics,isInGenerics){if(name==="*"||(name.length===0&&generics.length===0)){return}if(query.literalSearch&&parserState.totalElems-parserState.genericsElems>0){throw new Error("You cannot have more than one element if you use quotes")}const pathSegments=name.split("::");if(pathSegments.length>1){for(let i=0,len=pathSegments.length;i=end){throw new Error("Found generics without a path")}parserState.pos+=1;getItemsBefore(query,parserState,generics,">")}if(start>=end&&generics.length===0){return}elems.push(createQueryElement(query,parserState,parserState.userQuery.slice(start,end),generics,isInGenerics))}function getItemsBefore(query,parserState,elems,endChar){let foundStopChar=true;while(parserState.pos"){extra="`<`"}else if(endChar===""){extra="`->`"}throw new Error("Unexpected `"+c+"` after "+extra)}if(!foundStopChar){if(endChar!==""){throw new Error(`Expected \`,\`, \` \` or \`${endChar}\`, found \`${c}\``)}throw new Error(`Expected \`,\` or \` \`, found \`${c}\``)}const posBefore=parserState.pos;getNextElem(query,parserState,elems,endChar===">");if(posBefore===parserState.pos){parserState.pos+=1}foundStopChar=false}parserState.pos+=1}function checkExtraTypeFilterCharacters(parserState){const query=parserState.userQuery;for(let pos=0;pos"){if(isReturnArrow(parserState)){break}throw new Error(`Unexpected \`${c}\` (did you mean \`->\`?)`)}throw new Error(`Unexpected \`${c}\``)}else if(c===":"&&!isPathStart(parserState)){if(parserState.typeFilter!==null){throw new Error("Unexpected `:`")}if(query.elems.length===0){throw new Error("Expected type filter before `:`")}else if(query.elems.length!==1||parserState.totalElems!==1){throw new Error("Unexpected `:`")}else if(query.literalSearch){throw new Error("You cannot use quotes on type filter")}checkExtraTypeFilterCharacters(parserState);parserState.typeFilter=query.elems.pop().name;parserState.pos+=1;parserState.totalElems=0;query.literalSearch=false;foundStopChar=true;continue}if(!foundStopChar){if(parserState.typeFilter!==null){throw new Error(`Expected \`,\`, \` \` or \`->\`, found \`${c}\``)}throw new Error(`Expected \`,\`, \` \`, \`:\` or \`->\`, found \`${c}\``)}before=query.elems.length;getNextElem(query,parserState,query.elems,false);if(query.elems.length===before){parserState.pos+=1}foundStopChar=false}while(parserState.pos`")}break}else{parserState.pos+=1}}}function newParsedQuery(userQuery){return{original:userQuery,userQuery:userQuery.toLowerCase(),typeFilter:NO_TYPE_FILTER,elems:[],returned:[],foundElems:0,literalSearch:false,error:null,}}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"&&hasOwnPropertyRustdoc(rawSearchIndex,elem.value)){return elem.value}return null}function parseQuery(userQuery){userQuery=userQuery.trim();const parserState={length:userQuery.length,pos:0,totalElems:0,genericsElems:0,typeFilter:null,userQuery:userQuery.toLowerCase(),};let query=newParsedQuery(userQuery);try{parseInput(query,parserState);if(parserState.typeFilter!==null){let typeFilter=parserState.typeFilter;if(typeFilter==="const"){typeFilter="constant"}query.typeFilter=itemTypeFromName(typeFilter)}}catch(err){query=newParsedQuery(userQuery);query.error=err.message;query.typeFilter=-1;return query}if(!query.literalSearch){query.literalSearch=parserState.totalElems>1}query.foundElems=query.elems.length+query.returned.length;return query}function createQueryResults(results_in_args,results_returned,results_others,parsedQuery){return{"in_args":results_in_args,"returned":results_returned,"others":results_others,"query":parsedQuery,}}function execQuery(parsedQuery,searchWords,filterCrates,currentCrate){const results_others={},results_in_args={},results_returned={};function transformResults(results){const duplicates={};const out=[];for(const result of results){if(result.id>-1){const obj=searchIndex[result.id];obj.lev=result.lev;const res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=obj.displayPath+obj.name;obj.fullPath+="|"+obj.ty;if(duplicates[obj.fullPath]){continue}duplicates[obj.fullPath]=true;obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}return out}function sortResults(results,isType,preferredCrate){const userQuery=parsedQuery.userQuery;const ar=[];for(const entry in results){if(hasOwnPropertyRustdoc(results,entry)){const result=results[entry];result.word=searchWords[result.id];result.item=searchIndex[result.id]||{};ar.push(result)}}results=ar;if(results.length===0){return[]}results.sort((aaa,bbb)=>{let a,b;a=(aaa.word!==userQuery);b=(bbb.word!==userQuery);if(a!==b){return a-b}a=(aaa.lev);b=(bbb.lev);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=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}if((aaa.item.ty===TY_PRIMITIVE&&bbb.item.ty!==TY_KEYWORD)||(aaa.item.ty===TY_KEYWORD&&bbb.item.ty!==TY_PRIMITIVE)){return-1}if((bbb.item.ty===TY_PRIMITIVE&&aaa.item.ty!==TY_PRIMITIVE)||(bbb.item.ty===TY_KEYWORD&&aaa.item.ty!==TY_KEYWORD)){return 1}a=(aaa.item.desc==="");b=(bbb.item.desc==="");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});let nameSplit=null;if(parsedQuery.elems.length===1){const hasPath=typeof parsedQuery.elems[0].path==="undefined";nameSplit=hasPath?null:parsedQuery.elems[0].path}for(const result of results){if(result.dontValidate){continue}const name=result.item.name.toLowerCase(),path=result.item.path.toLowerCase(),parent=result.item.parent;if(!isType&&!validateResult(name,path,nameSplit,parent)){result.id=-1}}return transformResults(results)}function checkGenerics(row,elem,defaultLev){if(row.generics.length===0){return elem.generics.length===0?defaultLev:MAX_LEV_DISTANCE+1}else if(row.generics.length>0&&row.generics[0].name===null){return checkGenerics(row.generics[0],elem,defaultLev)}let elem_name;if(elem.generics.length>0&&row.generics.length>=elem.generics.length){const elems=Object.create(null);for(const entry of row.generics){elem_name=entry.name;if(elem_name===""){if(checkGenerics(entry,elem,MAX_LEV_DISTANCE+1)!==0){return MAX_LEV_DISTANCE+1}continue}if(elems[elem_name]===undefined){elems[elem_name]=0}elems[elem_name]+=1}for(const generic of elem.generics){let match=null;if(elems[generic.name]){match=generic.name}else{for(elem_name in elems){if(!hasOwnPropertyRustdoc(elems,elem_name)){continue}if(elem_name===generic){match=elem_name;break}}}if(match===null){return MAX_LEV_DISTANCE+1}elems[match]-=1;if(elems[match]===0){delete elems[match]}}return 0}return MAX_LEV_DISTANCE+1}function checkIfInGenerics(row,elem){let lev=MAX_LEV_DISTANCE+1;for(const entry of row.generics){lev=Math.min(checkType(entry,elem,true),lev);if(lev===0){break}}return lev}function checkType(row,elem,literalSearch){if(row.name===null){if(row.generics.length>0){return checkIfInGenerics(row,elem)}return MAX_LEV_DISTANCE+1}let lev=levenshtein(row.name,elem.name);if(literalSearch){if(lev!==0){if(elem.generics.length===0){const checkGeneric=row.generics.length>0;if(checkGeneric&&row.generics.findIndex(tmp_elem=>tmp_elem.name===elem.name)!==-1){return 0}}return MAX_LEV_DISTANCE+1}else if(elem.generics.length>0){return checkGenerics(row,elem,MAX_LEV_DISTANCE+1)}return 0}else if(row.generics.length>0){if(elem.generics.length===0){if(lev===0){return 0}lev=checkIfInGenerics(row,elem);return lev+0.5}else if(lev>MAX_LEV_DISTANCE){return checkIfInGenerics(row,elem)}else{const tmp_lev=checkGenerics(row,elem,lev);if(tmp_lev>MAX_LEV_DISTANCE){return MAX_LEV_DISTANCE+1}return(tmp_lev+lev)/2}}else if(elem.generics.length>0){return MAX_LEV_DISTANCE+1}return lev}function findArg(row,elem,typeFilter){let lev=MAX_LEV_DISTANCE+1;if(row&&row.type&&row.type.inputs&&row.type.inputs.length>0){for(const input of row.type.inputs){if(!typePassesFilter(typeFilter,input.ty)){continue}lev=Math.min(lev,checkType(input,elem,parsedQuery.literalSearch));if(lev===0){return 0}}}return parsedQuery.literalSearch?MAX_LEV_DISTANCE+1:lev}function checkReturned(row,elem,typeFilter){let lev=MAX_LEV_DISTANCE+1;if(row&&row.type&&row.type.output.length>0){const ret=row.type.output;for(const ret_ty of ret){if(!typePassesFilter(typeFilter,ret_ty.ty)){continue}lev=Math.min(lev,checkType(ret_ty,elem,parsedQuery.literalSearch));if(lev===0){return 0}}}return parsedQuery.literalSearch?MAX_LEV_DISTANCE+1:lev}function checkPath(contains,ty){if(contains.length===0){return 0}let ret_lev=MAX_LEV_DISTANCE+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;if(clength>length){return MAX_LEV_DISTANCE+1}for(let i=0;ilength){break}let lev_total=0;let aborted=false;for(let x=0;xMAX_LEV_DISTANCE){aborted=true;break}lev_total+=lev}if(!aborted){ret_lev=Math.min(ret_lev,Math.round(lev_total/clength))}}return ret_lev}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,desc:item.desc,ty:item.ty,parent:item.parent,type:item.type,is_alias:true,}}function handleAliases(ret,query,filterCrates,currentCrate){const lowerQuery=query.toLowerCase();const aliases=[];const crateAliases=[];if(filterCrates!==null){if(ALIASES[filterCrates]&&ALIASES[filterCrates][lowerQuery]){const query_aliases=ALIASES[filterCrates][lowerQuery];for(const alias of query_aliases){aliases.push(createAliasFromItem(searchIndex[alias]))}}}else{Object.keys(ALIASES).forEach(crate=>{if(ALIASES[crate][lowerQuery]){const pushTo=crate===currentCrate?crateAliases:aliases;const query_aliases=ALIASES[crate][lowerQuery];for(const alias of query_aliases){pushTo.push(createAliasFromItem(searchIndex[alias]))}}})}const sortFunc=(aaa,bbb)=>{if(aaa.path{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(pushFunc);crateAliases.forEach(pushFunc)}function addIntoResults(results,fullId,id,index,lev){if(lev===0||(!parsedQuery.literalSearch&&lev<=MAX_LEV_DISTANCE)){if(results[fullId]!==undefined){const result=results[fullId];if(result.dontValidate||result.lev<=lev){return}}results[fullId]={id:id,index:index,dontValidate:parsedQuery.literalSearch,lev:lev,}}}function handleSingleArg(row,pos,elem,results_others,results_in_args,results_returned){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let lev,lev_add=0,index=-1;const fullId=row.id;const in_args=findArg(row,elem,parsedQuery.typeFilter);const returned=checkReturned(row,elem,parsedQuery.typeFilter);addIntoResults(results_in_args,fullId,pos,index,in_args);addIntoResults(results_returned,fullId,pos,index,returned);if(!typePassesFilter(parsedQuery.typeFilter,row.ty)){return}const searchWord=searchWords[pos];if(parsedQuery.literalSearch){if(searchWord===elem.name){addIntoResults(results_others,fullId,pos,-1,0)}return}if(elem.name.length===0){if(row.type!==null){lev=checkGenerics(row.type,elem,MAX_LEV_DISTANCE+1);addIntoResults(results_others,fullId,pos,index,lev)}return}if(elem.fullPath.length>1){lev=checkPath(elem.pathWithoutLast,row);if(lev>MAX_LEV_DISTANCE||(parsedQuery.literalSearch&&lev!==0)){return}else if(lev>0){lev_add=lev/10}}if(searchWord.indexOf(elem.pathLast)>-1||row.normalizedName.indexOf(elem.pathLast)>-1){index=row.normalizedName.indexOf(elem.pathLast)}lev=levenshtein(searchWord,elem.pathLast);if(lev>0&&elem.pathLast.length>2&&searchWord.indexOf(elem.pathLast)>-1){if(elem.pathLast.length<6){lev=1}else{lev=0}}lev+=lev_add;if(lev>MAX_LEV_DISTANCE){return}else if(index!==-1&&elem.fullPath.length<2){lev-=1}if(lev<0){lev=0}addIntoResults(results_others,fullId,pos,index,lev)}function handleArgs(row,pos,results){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let totalLev=0;let nbLev=0;function checkArgs(elems,callback){for(const elem of elems){const lev=callback(row,elem,NO_TYPE_FILTER);if(lev<=1){nbLev+=1;totalLev+=lev}else{return false}}return true}if(!checkArgs(parsedQuery.elems,findArg)){return}if(!checkArgs(parsedQuery.returned,checkReturned)){return}if(nbLev===0){return}const lev=Math.round(totalLev/nbLev);addIntoResults(results,row.id,pos,0,lev)}function innerRunQuery(){let elem,i,nSearchWords,in_returned,row;if(parsedQuery.foundElems===1){if(parsedQuery.elems.length===1){elem=parsedQuery.elems[0];for(i=0,nSearchWords=searchWords.length;i0){for(i=0,nSearchWords=searchWords.length;i-1||path.indexOf(key)>-1||(parent!==undefined&&parent.name!==undefined&&parent.name.toLowerCase().indexOf(key)>-1)||levenshtein(name,key)<=MAX_LEV_DISTANCE)){return false}}return true}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("#titles > button").item(searchState.currentTab);if(target){target.focus()}}function buildHrefAndPath(item){let displayPath;let href;const type=itemTypes[item.ty];const name=item.name;let path=item.path;if(type==="mod"){displayPath=path+"::";href=ROOT_PATH+path.replace(/::/g,"/")+"/"+name+"/index.html"}else if(type==="import"){displayPath=item.path+"::";href=ROOT_PATH+item.path.replace(/::/g,"/")+"/index.html#reexport."+name}else if(type==="primitive"||type==="keyword"){displayPath="";href=ROOT_PATH+path.replace(/::/g,"/")+"/"+type+"."+name+".html"}else if(type==="externcrate"){displayPath="";href=ROOT_PATH+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;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+"::"}href=ROOT_PATH+path.replace(/::/g,"/")+"/"+pageType+"."+pageName+".html"+anchor}else{displayPath=item.path+"::";href=ROOT_PATH+item.path.replace(/::/g,"/")+"/"+type+"."+name+".html"}return[displayPath,href]}function pathSplitter(path){const tmp=""+path.replace(/::/g,"::");if(tmp.endsWith("")){return tmp.slice(0,tmp.length-6)}return tmp}function addTab(array,query,display){let extraClass="";if(display===true){extraClass=" active"}const output=document.createElement("div");let length=0;if(array.length>0){output.className="search-results "+extraClass;array.forEach(item=>{const name=item.name;const type=itemTypes[item.ty];length+=1;let extra="";if(type==="primitive"){extra=" (primitive type)"}else if(type==="keyword"){extra=" (keyword)"}const link=document.createElement("a");link.className="result-"+type;link.href=item.href;const wrapper=document.createElement("div");const resultName=document.createElement("div");resultName.className="result-name";if(item.is_alias){const alias=document.createElement("span");alias.className="alias";const bold=document.createElement("b");bold.innerText=item.alias;alias.appendChild(bold);alias.insertAdjacentHTML("beforeend"," - see ");resultName.appendChild(alias)}resultName.insertAdjacentHTML("beforeend",item.displayPath+""+name+extra+"");wrapper.appendChild(resultName);const description=document.createElement("div");description.className="desc";const spanDesc=document.createElement("span");spanDesc.insertAdjacentHTML("beforeend",item.desc);description.appendChild(spanDesc);wrapper.appendChild(description);link.appendChild(wrapper);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,length]}function makeTabHeader(tabNb,text,nbElems){if(searchState.currentTab===tabNb){return""}return""}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"&&(!search.firstChild||search.firstChild.innerText!==searchState.loadingText))){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=parseQuery(searchState.input.value)}currentResults=results.query.userQuery;const ret_others=addTab(results.others,results.query,true);const ret_in_args=addTab(results.in_args,results.query,false);const ret_returned=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="";const crates_list=Object.keys(rawSearchIndex);if(crates_list.length>1){crates=" in 
"}let output=`

Results${crates}

`;if(results.query.error!==null){output+=`

Query parser error: "${results.query.error}".

`;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}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;const crateSearch=document.getElementById("crate-search");if(crateSearch){crateSearch.addEventListener("input",updateCrate)}search.appendChild(resultsElem);searchState.showResults(search);const elems=document.getElementById("titles").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 search(e,forced){const params=searchState.getQueryStringParams();const query=parseQuery(searchState.input.value.trim());if(e){e.preventDefault()}if(!forced&&query.userQuery===currentResults){if(query.userQuery.length>0){putBackSearch()}return}let filterCrates=getFilterCrates();if(filterCrates===null&¶ms["filter-crate"]!==undefined){filterCrates=params["filter-crate"]}searchState.title="Results for "+query.original+" - Rust";if(browserSupportsHistoryApi()){const newURL=buildUrl(query.original,filterCrates);if(!history.state&&!params.search){history.pushState(null,"",newURL)}else{history.replaceState(null,"",newURL)}}showResults(execQuery(query,searchWords,filterCrates,window.currentCrate),params.go_to_first,filterCrates)}function buildItemSearchTypeAll(types,lowercasePaths){const PATH_INDEX_DATA=0;const GENERICS_DATA=1;return types.map(type=>{let pathIndex,generics;if(typeof type==="number"){pathIndex=type;generics=[]}else{pathIndex=type[PATH_INDEX_DATA];generics=buildItemSearchTypeAll(type[GENERICS_DATA],lowercasePaths)}return{name:pathIndex===0?null:lowercasePaths[pathIndex-1].name,ty:pathIndex===0?null:lowercasePaths[pathIndex-1].ty,generics:generics,}})}function buildFunctionSearchType(functionSearchType,lowercasePaths){const INPUTS_DATA=0;const OUTPUT_DATA=1;if(functionSearchType===0){return null}let inputs,output;if(typeof functionSearchType[INPUTS_DATA]==="number"){const pathIndex=functionSearchType[INPUTS_DATA];inputs=[{name:pathIndex===0?null:lowercasePaths[pathIndex-1].name,ty:pathIndex===0?null:lowercasePaths[pathIndex-1].ty,generics:[],}]}else{inputs=buildItemSearchTypeAll(functionSearchType[INPUTS_DATA],lowercasePaths)}if(functionSearchType.length>1){if(typeof functionSearchType[OUTPUT_DATA]==="number"){const pathIndex=functionSearchType[OUTPUT_DATA];output=[{name:pathIndex===0?null:lowercasePaths[pathIndex-1].name,ty:pathIndex===0?null:lowercasePaths[pathIndex-1].ty,generics:[],}]}else{output=buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA],lowercasePaths)}}else{output=[]}return{inputs,output,}}function buildIndex(rawSearchIndex){searchIndex=[];const searchWords=[];let i,word;let currentIndex=0;let id=0;for(const crate in rawSearchIndex){if(!hasOwnPropertyRustdoc(rawSearchIndex,crate)){continue}let crateSize=0;const crateCorpus=rawSearchIndex[crate];searchWords.push(crate);const crateRow={crate:crate,ty:1,name:crate,path:"",desc:crateCorpus.doc,parent:undefined,type:null,id:id,normalizedName:crate.indexOf("_")===-1?crate:crate.replace(/_/g,""),};id+=1;searchIndex.push(crateRow);currentIndex+=1;const itemTypes=crateCorpus.t;const itemNames=crateCorpus.n;const itemPaths=crateCorpus.q;const itemDescs=crateCorpus.d;const itemParentIdxs=crateCorpus.i;const itemFunctionSearchTypes=crateCorpus.f;const paths=crateCorpus.p;const aliases=crateCorpus.a;const lowercasePaths=[];let len=paths.length;for(i=0;i0?paths[itemParentIdxs[i]-1]:undefined,type:buildFunctionSearchType(itemFunctionSearchTypes[i],lowercasePaths),id:id,normalizedName:word.indexOf("_")===-1?word:word.replace(/_/g,""),};id+=1;searchIndex.push(row);lastPath=row.path;crateSize+=1}if(aliases){ALIASES[crate]=Object.create(null);for(const alias_name in aliases){if(!hasOwnPropertyRustdoc(aliases,alias_name)){continue}if(!hasOwnPropertyRustdoc(ALIASES[crate],alias_name)){ALIASES[crate][alias_name]=[]}for(const local_alias of aliases[alias_name]){ALIASES[crate][alias_name].push(local_alias+currentIndex)}}}currentIndex+=crateSize}return searchWords}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){if(browserSupportsHistoryApi()){history.replaceState(null,window.currentCrate+" - Rust",getNakedUrl()+window.location.hash)}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;search(e)}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 params=searchState.getQueryStringParams();const query=searchState.input.value.trim();if(!history.state&&!params.search){history.pushState(null,"",buildUrl(query,null))}else{history.replaceState(null,"",buildUrl(query,null))}}currentResults=null;search(undefined,true)}const searchWords=buildIndex(rawSearchIndex);if(typeof window!=="undefined"){registerSearchEvents();if(window.searchState.getQueryStringParams().search){search()}}if(typeof exports!=="undefined"){exports.initSearch=initSearch;exports.execQuery=execQuery;exports.parseQuery=parseQuery}return searchWords}if(typeof window!=="undefined"){window.initSearch=initSearch;if(window.searchIndex!==undefined){initSearch(window.searchIndex)}}else{initSearch({})}})() \ No newline at end of file diff --git a/settings.html b/settings.html index 4b0922ab3..e2aceb585 100644 --- a/settings.html +++ b/settings.html @@ -1 +1,3 @@ -Rustdoc settings

Rustdoc settings

Back
\ No newline at end of file +Rustdoc settings

Rustdoc settings

Back
\ No newline at end of file diff --git a/source-script.js b/source-script.js index e0fac0739..3866dfd27 100644 --- a/source-script.js +++ b/source-script.js @@ -1 +1 @@ -"use strict";(function(){const rootPath=document.getElementById("rustdoc-vars").attributes["data-root-path"].value;let oldScrollPosition=0;const NAME_OFFSET=0;const DIRS_OFFSET=1;const FILES_OFFSET=2;function closeSidebarIfMobile(){if(window.innerWidth"){if(window.innerWidth";updateLocalStorage("source-sidebar-show","false")}}function createSidebarToggle(){const sidebarToggle=document.createElement("div");sidebarToggle.id="sidebar-toggle";const inner=document.createElement("button");if(getCurrentValue("source-sidebar-show")==="true"){inner.innerText="<"}else{inner.innerText=">"}inner.onclick=toggleSidebar;sidebarToggle.appendChild(inner);return sidebarToggle}function createSourceSidebar(){const container=document.querySelector("nav.sidebar");const sidebarToggle=createSidebarToggle();container.insertBefore(sidebarToggle,container.firstChild);const sidebar=document.createElement("div");sidebar.id="source-sidebar";let hasFoundFile=false;const title=document.createElement("div");title.className="title";title.innerText="Files";sidebar.appendChild(title);Object.keys(sourcesIndex).forEach(key=>{sourcesIndex[key][NAME_OFFSET]=key;hasFoundFile=createDirEntry(sourcesIndex[key],sidebar,"",hasFoundFile)});container.appendChild(sidebar);const selected_elem=sidebar.getElementsByClassName("selected")[0];if(typeof selected_elem!=="undefined"){selected_elem.focus()}}const lineNumbersRegex=/^#?(\d+)(?:-(\d+))?$/;function highlightSourceLines(match){if(typeof match==="undefined"){match=window.location.hash.match(lineNumbersRegex)}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("span"),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 handleSourceHighlight=(function(){let prev_line_id=0;const set_fragment=name=>{const x=window.scrollX,y=window.scrollY;if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);highlightSourceLines()}else{location.replace("#"+name)}window.scrollTo(x,y)};return ev=>{let cur_line_id=parseInt(ev.target.id,10);if(isNaN(cur_line_id)){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",()=>{const match=window.location.hash.match(lineNumbersRegex);if(match){return highlightSourceLines(match)}});onEachLazy(document.getElementsByClassName("line-numbers"),el=>{el.addEventListener("click",handleSourceHighlight)});highlightSourceLines();window.createSourceSidebar=createSourceSidebar})() \ No newline at end of file +"use strict";(function(){const rootPath=document.getElementById("rustdoc-vars").attributes["data-root-path"].value;let oldScrollPosition=null;const NAME_OFFSET=0;const DIRS_OFFSET=1;const FILES_OFFSET=2;function closeSidebarIfMobile(){if(window.innerWidth"){if(window.innerWidth";updateLocalStorage("source-sidebar-show","false")}}window.addEventListener("resize",()=>{if(window.innerWidth>=window.RUSTDOC_MOBILE_BREAKPOINT&&oldScrollPosition!==null){document.body.style.position="";document.body.style.top="";window.scrollTo(0,oldScrollPosition);oldScrollPosition=null}});function createSidebarToggle(){const sidebarToggle=document.createElement("div");sidebarToggle.id="sidebar-toggle";const inner=document.createElement("button");if(getCurrentValue("source-sidebar-show")==="true"){inner.innerText="<"}else{inner.innerText=">"}inner.onclick=toggleSidebar;sidebarToggle.appendChild(inner);return sidebarToggle}function createSourceSidebar(){const container=document.querySelector("nav.sidebar");const sidebarToggle=createSidebarToggle();container.insertBefore(sidebarToggle,container.firstChild);const sidebar=document.createElement("div");sidebar.id="source-sidebar";let hasFoundFile=false;const title=document.createElement("div");title.className="title";title.innerText="Files";sidebar.appendChild(title);Object.keys(sourcesIndex).forEach(key=>{sourcesIndex[key][NAME_OFFSET]=key;hasFoundFile=createDirEntry(sourcesIndex[key],sidebar,"",hasFoundFile)});container.appendChild(sidebar);const selected_elem=sidebar.getElementsByClassName("selected")[0];if(typeof selected_elem!=="undefined"){selected_elem.focus()}}const lineNumbersRegex=/^#?(\d+)(?:-(\d+))?$/;function highlightSourceLines(match){if(typeof match==="undefined"){match=window.location.hash.match(lineNumbersRegex)}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("span"),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 handleSourceHighlight=(function(){let prev_line_id=0;const set_fragment=name=>{const x=window.scrollX,y=window.scrollY;if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);highlightSourceLines()}else{location.replace("#"+name)}window.scrollTo(x,y)};return ev=>{let cur_line_id=parseInt(ev.target.id,10);if(isNaN(cur_line_id)){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",()=>{const match=window.location.hash.match(lineNumbersRegex);if(match){return highlightSourceLines(match)}});onEachLazy(document.getElementsByClassName("line-numbers"),el=>{el.addEventListener("click",handleSourceHighlight)});highlightSourceLines();window.createSourceSidebar=createSourceSidebar})() \ No newline at end of file diff --git a/src/actix_cors/all_or_some.rs.html b/src/actix_cors/all_or_some.rs.html index 75b7738a5..6b1c09373 100644 --- a/src/actix_cors/all_or_some.rs.html +++ b/src/actix_cors/all_or_some.rs.html @@ -55,60 +55,60 @@ 53 54 55 -
/// An enum signifying that some of type `T` is allowed, or `All` (anything is allowed).
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum AllOrSome<T> {
-    /// Everything is allowed. Usually equivalent to the `*` value.
-    All,
+
/// An enum signifying that some of type `T` is allowed, or `All` (anything is allowed).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AllOrSome<T> {
+    /// Everything is allowed. Usually equivalent to the `*` value.
+    All,
 
-    /// Only some of `T` is allowed
-    Some(T),
+    /// Only some of `T` is allowed
+    Some(T),
 }
 
-/// Default as `AllOrSome::All`.
-impl<T> Default for AllOrSome<T> {
-    fn default() -> Self {
-        AllOrSome::All
+/// Default as `AllOrSome::All`.
+impl<T> Default for AllOrSome<T> {
+    fn default() -> Self {
+        AllOrSome::All
     }
 }
 
-impl<T> AllOrSome<T> {
-    /// Returns whether this is an `All` variant.
-    pub fn is_all(&self) -> bool {
-        matches!(self, AllOrSome::All)
+impl<T> AllOrSome<T> {
+    /// Returns whether this is an `All` variant.
+    pub fn is_all(&self) -> bool {
+        matches!(self, AllOrSome::All)
     }
 
-    /// Returns whether this is a `Some` variant.
-    #[allow(dead_code)]
-    pub fn is_some(&self) -> bool {
-        !self.is_all()
+    /// Returns whether this is a `Some` variant.
+    #[allow(dead_code)]
+    pub fn is_some(&self) -> bool {
+        !self.is_all()
     }
 
-    /// Provides a shared reference to `T` if variant is `Some`.
-    pub fn as_ref(&self) -> Option<&T> {
-        match *self {
-            AllOrSome::All => None,
-            AllOrSome::Some(ref t) => Some(t),
+    /// Provides a shared reference to `T` if variant is `Some`.
+    pub fn as_ref(&self) -> Option<&T> {
+        match *self {
+            AllOrSome::All => None,
+            AllOrSome::Some(ref t) => Some(t),
         }
     }
 
-    /// Provides a mutable reference to `T` if variant is `Some`.
-    pub fn as_mut(&mut self) -> Option<&mut T> {
-        match *self {
-            AllOrSome::All => None,
-            AllOrSome::Some(ref mut t) => Some(t),
+    /// Provides a mutable reference to `T` if variant is `Some`.
+    pub fn as_mut(&mut self) -> Option<&mut T> {
+        match *self {
+            AllOrSome::All => None,
+            AllOrSome::Some(ref mut t) => Some(t),
         }
     }
 }
 
-#[cfg(test)]
-#[test]
-fn tests() {
-    assert!(AllOrSome::<()>::All.is_all());
-    assert!(!AllOrSome::<()>::All.is_some());
+#[cfg(test)]
+#[test]
+fn tests() {
+    assert!(AllOrSome::<()>::All.is_all());
+    assert!(!AllOrSome::<()>::All.is_some());
 
-    assert!(!AllOrSome::Some(()).is_all());
-    assert!(AllOrSome::Some(()).is_some());
+    assert!(!AllOrSome::Some(()).is_all());
+    assert!(AllOrSome::Some(()).is_some());
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_cors/builder.rs.html b/src/actix_cors/builder.rs.html index c912e3a94..91fabbfe6 100644 --- a/src/actix_cors/builder.rs.html +++ b/src/actix_cors/builder.rs.html @@ -641,646 +641,646 @@ 639 640 641 -
use std::{collections::HashSet, convert::TryInto, iter::FromIterator, rc::Rc};
+
use std::{collections::HashSet, convert::TryInto, iter::FromIterator, rc::Rc};
 
-use actix_utils::future::{self, Ready};
-use actix_web::{
-    body::{EitherBody, MessageBody},
-    dev::{RequestHead, Service, ServiceRequest, ServiceResponse, Transform},
-    error::HttpError,
-    http::{
-        header::{HeaderName, HeaderValue},
-        Method, Uri,
+use actix_utils::future::{self, Ready};
+use actix_web::{
+    body::{EitherBody, MessageBody},
+    dev::{RequestHead, Service, ServiceRequest, ServiceResponse, Transform},
+    error::HttpError,
+    http::{
+        header::{HeaderName, HeaderValue},
+        Method, Uri,
     },
-    Either, Error, Result,
+    Either, Error, Result,
 };
-use log::error;
-use once_cell::sync::Lazy;
-use smallvec::smallvec;
+use log::error;
+use once_cell::sync::Lazy;
+use smallvec::smallvec;
 
-use crate::{AllOrSome, CorsError, CorsMiddleware, Inner, OriginFn};
+use crate::{AllOrSome, CorsError, CorsMiddleware, Inner, OriginFn};
 
-/// Convenience for getting mut refs to inner. Cleaner than `Rc::get_mut`.
-/// Additionally, always causes first error (if any) to be reported during initialization.
-fn cors<'a>(
-    inner: &'a mut Rc<Inner>,
-    err: &Option<Either<HttpError, CorsError>>,
-) -> Option<&'a mut Inner> {
-    if err.is_some() {
-        return None;
+/// Convenience for getting mut refs to inner. Cleaner than `Rc::get_mut`.
+/// Additionally, always causes first error (if any) to be reported during initialization.
+fn cors<'a>(
+    inner: &'a mut Rc<Inner>,
+    err: &Option<Either<HttpError, CorsError>>,
+) -> Option<&'a mut Inner> {
+    if err.is_some() {
+        return None;
     }
 
-    Rc::get_mut(inner)
+    Rc::get_mut(inner)
 }
 
-static ALL_METHODS_SET: Lazy<HashSet<Method>> = Lazy::new(|| {
-    HashSet::from_iter(vec![
-        Method::GET,
-        Method::POST,
-        Method::PUT,
-        Method::DELETE,
-        Method::HEAD,
-        Method::OPTIONS,
-        Method::CONNECT,
-        Method::PATCH,
-        Method::TRACE,
+static ALL_METHODS_SET: Lazy<HashSet<Method>> = Lazy::new(|| {
+    HashSet::from_iter(vec![
+        Method::GET,
+        Method::POST,
+        Method::PUT,
+        Method::DELETE,
+        Method::HEAD,
+        Method::OPTIONS,
+        Method::CONNECT,
+        Method::PATCH,
+        Method::TRACE,
     ])
 });
 
-/// Builder for CORS middleware.
-///
-/// To construct a CORS middleware, call [`Cors::default()`] to create a blank, restrictive builder.
-/// Then use any of the builder methods to customize CORS behavior.
-///
-/// The alternative [`Cors::permissive()`] constructor is available for local development, allowing
-/// all origins and headers, etc. **The permissive constructor should not be used in production.**
-///
-/// # Errors
-/// Errors surface in the middleware initialization phase. This means that, if you have logs enabled
-/// in Actix Web (using `env_logger` or other crate that exposes logs from the `log` crate), error
-/// messages will outline what is wrong with the CORS configuration in the server logs and the
-/// server will fail to start up or serve requests.
-///
-/// # Example
-/// ```
-/// use actix_cors::Cors;
-/// use actix_web::http::header;
-///
-/// let cors = Cors::default()
-///     .allowed_origin("https://www.rust-lang.org")
-///     .allowed_methods(vec!["GET", "POST"])
-///     .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
-///     .allowed_header(header::CONTENT_TYPE)
-///     .max_age(3600);
-///
-/// // `cors` can now be used in `App::wrap`.
-/// ```
-#[derive(Debug)]
-pub struct Cors {
-    inner: Rc<Inner>,
-    error: Option<Either<HttpError, CorsError>>,
+/// Builder for CORS middleware.
+///
+/// To construct a CORS middleware, call [`Cors::default()`] to create a blank, restrictive builder.
+/// Then use any of the builder methods to customize CORS behavior.
+///
+/// The alternative [`Cors::permissive()`] constructor is available for local development, allowing
+/// all origins and headers, etc. **The permissive constructor should not be used in production.**
+///
+/// # Errors
+/// Errors surface in the middleware initialization phase. This means that, if you have logs enabled
+/// in Actix Web (using `env_logger` or other crate that exposes logs from the `log` crate), error
+/// messages will outline what is wrong with the CORS configuration in the server logs and the
+/// server will fail to start up or serve requests.
+///
+/// # Example
+/// ```
+/// use actix_cors::Cors;
+/// use actix_web::http::header;
+///
+/// let cors = Cors::default()
+///     .allowed_origin("https://www.rust-lang.org")
+///     .allowed_methods(vec!["GET", "POST"])
+///     .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
+///     .allowed_header(header::CONTENT_TYPE)
+///     .max_age(3600);
+///
+/// // `cors` can now be used in `App::wrap`.
+/// ```
+#[derive(Debug)]
+pub struct Cors {
+    inner: Rc<Inner>,
+    error: Option<Either<HttpError, CorsError>>,
 }
 
-impl Cors {
-    /// A very permissive set of default for quick development. Not recommended for production use.
-    ///
-    /// *All* origins, methods, request headers and exposed headers allowed. Credentials supported.
-    /// Max age 1 hour. Does not send wildcard.
-    pub fn permissive() -> Self {
-        let inner = Inner {
-            allowed_origins: AllOrSome::All,
-            allowed_origins_fns: smallvec![],
+impl Cors {
+    /// A very permissive set of default for quick development. Not recommended for production use.
+    ///
+    /// *All* origins, methods, request headers and exposed headers allowed. Credentials supported.
+    /// Max age 1 hour. Does not send wildcard.
+    pub fn permissive() -> Self {
+        let inner = Inner {
+            allowed_origins: AllOrSome::All,
+            allowed_origins_fns: smallvec![],
 
-            allowed_methods: ALL_METHODS_SET.clone(),
-            allowed_methods_baked: None,
+            allowed_methods: ALL_METHODS_SET.clone(),
+            allowed_methods_baked: None,
 
-            allowed_headers: AllOrSome::All,
-            allowed_headers_baked: None,
+            allowed_headers: AllOrSome::All,
+            allowed_headers_baked: None,
 
-            expose_headers: AllOrSome::All,
-            expose_headers_baked: None,
+            expose_headers: AllOrSome::All,
+            expose_headers_baked: None,
 
-            max_age: Some(3600),
-            preflight: true,
-            send_wildcard: false,
-            supports_credentials: true,
-            vary_header: true,
+            max_age: Some(3600),
+            preflight: true,
+            send_wildcard: false,
+            supports_credentials: true,
+            vary_header: true,
         };
 
-        Cors {
-            inner: Rc::new(inner),
-            error: None,
+        Cors {
+            inner: Rc::new(inner),
+            error: None,
         }
     }
 
-    /// Resets allowed origin list to a state where any origin is accepted.
-    ///
-    /// See [`Cors::allowed_origin`] for more info on allowed origins.
-    pub fn allow_any_origin(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.allowed_origins = AllOrSome::All;
+    /// Resets allowed origin list to a state where any origin is accepted.
+    ///
+    /// See [`Cors::allowed_origin`] for more info on allowed origins.
+    pub fn allow_any_origin(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.allowed_origins = AllOrSome::All;
         }
 
-        self
-    }
+        self
+    }
 
-    /// Add an origin that is allowed to make requests.
-    ///
-    /// By default, requests from all origins are accepted by CORS logic. This method allows to
-    /// specify a finite set of origins to verify the value of the `Origin` request header.
-    ///
-    /// These are `origin-or-null` types in the [Fetch Standard].
-    ///
-    /// When this list is set, the client's `Origin` request header will be checked in a
-    /// case-sensitive manner.
-    ///
-    /// When all origins are allowed and `send_wildcard` is set, `*` will be sent in the
-    /// `Access-Control-Allow-Origin` response header. If `send_wildcard` is not set, the client's
-    /// `Origin` request header will be echoed back in the `Access-Control-Allow-Origin`
-    /// response header.
-    ///
-    /// If the origin of the request doesn't match any allowed origins and at least one
-    /// `allowed_origin_fn` function is set, these functions will be used to determinate
-    /// allowed origins.
-    ///
-    /// # Initialization Errors
-    /// - If supplied origin is not valid uri
-    /// - If supplied origin is a wildcard (`*`). [`Cors::send_wildcard`] should be used instead.
-    ///
-    /// [Fetch Standard]: https://fetch.spec.whatwg.org/#origin-header
-    pub fn allowed_origin(mut self, origin: &str) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            match TryInto::<Uri>::try_into(origin) {
-                Ok(_) if origin == "*" => {
+    /// Add an origin that is allowed to make requests.
+    ///
+    /// By default, requests from all origins are accepted by CORS logic. This method allows to
+    /// specify a finite set of origins to verify the value of the `Origin` request header.
+    ///
+    /// These are `origin-or-null` types in the [Fetch Standard].
+    ///
+    /// When this list is set, the client's `Origin` request header will be checked in a
+    /// case-sensitive manner.
+    ///
+    /// When all origins are allowed and `send_wildcard` is set, `*` will be sent in the
+    /// `Access-Control-Allow-Origin` response header. If `send_wildcard` is not set, the client's
+    /// `Origin` request header will be echoed back in the `Access-Control-Allow-Origin`
+    /// response header.
+    ///
+    /// If the origin of the request doesn't match any allowed origins and at least one
+    /// `allowed_origin_fn` function is set, these functions will be used to determinate
+    /// allowed origins.
+    ///
+    /// # Initialization Errors
+    /// - If supplied origin is not valid uri
+    /// - If supplied origin is a wildcard (`*`). [`Cors::send_wildcard`] should be used instead.
+    ///
+    /// [Fetch Standard]: https://fetch.spec.whatwg.org/#origin-header
+    pub fn allowed_origin(mut self, origin: &str) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            match TryInto::<Uri>::try_into(origin) {
+                Ok(_) if origin == "*" => {
                     error!("Wildcard in `allowed_origin` is not allowed. Use `send_wildcard`.");
-                    self.error = Some(Either::Right(CorsError::WildcardOrigin));
+                    self.error = Some(Either::Right(CorsError::WildcardOrigin));
                 }
 
                 Ok(_) => {
-                    if cors.allowed_origins.is_all() {
-                        cors.allowed_origins = AllOrSome::Some(HashSet::with_capacity(8));
+                    if cors.allowed_origins.is_all() {
+                        cors.allowed_origins = AllOrSome::Some(HashSet::with_capacity(8));
                     }
 
-                    if let Some(origins) = cors.allowed_origins.as_mut() {
-                        // any uri is a valid header value
-                        let hv = origin.try_into().unwrap();
-                        origins.insert(hv);
+                    if let Some(origins) = cors.allowed_origins.as_mut() {
+                        // any uri is a valid header value
+                        let hv = origin.try_into().unwrap();
+                        origins.insert(hv);
                     }
                 }
 
-                Err(err) => {
-                    self.error = Some(Either::Left(err.into()));
+                Err(err) => {
+                    self.error = Some(Either::Left(err.into()));
                 }
             }
         }
 
-        self
-    }
+        self
+    }
 
-    /// Determinate allowed origins by processing requests which didn't match any origins specified
-    /// in the `allowed_origin`.
-    ///
-    /// The function will receive two parameters, the Origin header value, and the `RequestHead` of
-    /// each request, which can be used to determine whether to allow the request or not.
-    ///
-    /// If the function returns `true`, the client's `Origin` request header will be echoed back
-    /// into the `Access-Control-Allow-Origin` response header.
-    pub fn allowed_origin_fn<F>(mut self, f: F) -> Cors
-    where
-        F: (Fn(&HeaderValue, &RequestHead) -> bool) + 'static,
+    /// Determinate allowed origins by processing requests which didn't match any origins specified
+    /// in the `allowed_origin`.
+    ///
+    /// The function will receive two parameters, the Origin header value, and the `RequestHead` of
+    /// each request, which can be used to determine whether to allow the request or not.
+    ///
+    /// If the function returns `true`, the client's `Origin` request header will be echoed back
+    /// into the `Access-Control-Allow-Origin` response header.
+    pub fn allowed_origin_fn<F>(mut self, f: F) -> Cors
+    where
+        F: (Fn(&HeaderValue, &RequestHead) -> bool) + 'static,
     {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.allowed_origins_fns.push(OriginFn {
-                boxed_fn: Rc::new(f),
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.allowed_origins_fns.push(OriginFn {
+                boxed_fn: Rc::new(f),
             });
         }
 
-        self
-    }
+        self
+    }
 
-    /// Resets allowed methods list to all methods.
-    ///
-    /// See [`Cors::allowed_methods`] for more info on allowed methods.
-    pub fn allow_any_method(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.allowed_methods = ALL_METHODS_SET.clone();
+    /// Resets allowed methods list to all methods.
+    ///
+    /// See [`Cors::allowed_methods`] for more info on allowed methods.
+    pub fn allow_any_method(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.allowed_methods = ALL_METHODS_SET.clone();
         }
 
-        self
-    }
+        self
+    }
 
-    /// Set a list of methods which allowed origins can perform.
-    ///
-    /// These will be sent in the `Access-Control-Allow-Methods` response header as specified in
-    /// the [Fetch Standard CORS protocol].
-    ///
-    /// Defaults to `[GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]`
-    ///
-    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
-    pub fn allowed_methods<U, M>(mut self, methods: U) -> Cors
-    where
-        U: IntoIterator<Item = M>,
-        M: TryInto<Method>,
-        <M as TryInto<Method>>::Error: Into<HttpError>,
+    /// Set a list of methods which allowed origins can perform.
+    ///
+    /// These will be sent in the `Access-Control-Allow-Methods` response header as specified in
+    /// the [Fetch Standard CORS protocol].
+    ///
+    /// Defaults to `[GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]`
+    ///
+    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
+    pub fn allowed_methods<U, M>(mut self, methods: U) -> Cors
+    where
+        U: IntoIterator<Item = M>,
+        M: TryInto<Method>,
+        <M as TryInto<Method>>::Error: Into<HttpError>,
     {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            for m in methods {
-                match m.try_into() {
-                    Ok(method) => {
-                        cors.allowed_methods.insert(method);
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            for m in methods {
+                match m.try_into() {
+                    Ok(method) => {
+                        cors.allowed_methods.insert(method);
                     }
 
-                    Err(err) => {
-                        self.error = Some(Either::Left(err.into()));
+                    Err(err) => {
+                        self.error = Some(Either::Left(err.into()));
                         break;
                     }
                 }
             }
         }
 
-        self
-    }
+        self
+    }
 
-    /// Resets allowed request header list to a state where any header is accepted.
-    ///
-    /// See [`Cors::allowed_headers`] for more info on allowed request headers.
-    pub fn allow_any_header(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.allowed_headers = AllOrSome::All;
+    /// Resets allowed request header list to a state where any header is accepted.
+    ///
+    /// See [`Cors::allowed_headers`] for more info on allowed request headers.
+    pub fn allow_any_header(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.allowed_headers = AllOrSome::All;
         }
 
-        self
-    }
+        self
+    }
 
-    /// Add an allowed request header.
-    ///
-    /// See [`Cors::allowed_headers`] for more info on allowed request headers.
-    pub fn allowed_header<H>(mut self, header: H) -> Cors
-    where
-        H: TryInto<HeaderName>,
-        <H as TryInto<HeaderName>>::Error: Into<HttpError>,
+    /// Add an allowed request header.
+    ///
+    /// See [`Cors::allowed_headers`] for more info on allowed request headers.
+    pub fn allowed_header<H>(mut self, header: H) -> Cors
+    where
+        H: TryInto<HeaderName>,
+        <H as TryInto<HeaderName>>::Error: Into<HttpError>,
     {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            match header.try_into() {
-                Ok(method) => {
-                    if cors.allowed_headers.is_all() {
-                        cors.allowed_headers = AllOrSome::Some(HashSet::with_capacity(8));
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            match header.try_into() {
+                Ok(method) => {
+                    if cors.allowed_headers.is_all() {
+                        cors.allowed_headers = AllOrSome::Some(HashSet::with_capacity(8));
                     }
 
-                    if let AllOrSome::Some(ref mut headers) = cors.allowed_headers {
-                        headers.insert(method);
+                    if let AllOrSome::Some(ref mut headers) = cors.allowed_headers {
+                        headers.insert(method);
                     }
                 }
 
-                Err(err) => self.error = Some(Either::Left(err.into())),
+                Err(err) => self.error = Some(Either::Left(err.into())),
             }
         }
 
-        self
-    }
+        self
+    }
 
-    /// Set a list of request header field names which can be used when this resource is accessed by
-    /// allowed origins.
-    ///
-    /// If `All` is set, whatever is requested by the client in `Access-Control-Request-Headers`
-    /// will be echoed back in the `Access-Control-Allow-Headers` header as specified in
-    /// the [Fetch Standard CORS protocol].
-    ///
-    /// Defaults to `All`.
-    ///
-    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
-    pub fn allowed_headers<U, H>(mut self, headers: U) -> Cors
-    where
-        U: IntoIterator<Item = H>,
-        H: TryInto<HeaderName>,
-        <H as TryInto<HeaderName>>::Error: Into<HttpError>,
+    /// Set a list of request header field names which can be used when this resource is accessed by
+    /// allowed origins.
+    ///
+    /// If `All` is set, whatever is requested by the client in `Access-Control-Request-Headers`
+    /// will be echoed back in the `Access-Control-Allow-Headers` header as specified in
+    /// the [Fetch Standard CORS protocol].
+    ///
+    /// Defaults to `All`.
+    ///
+    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
+    pub fn allowed_headers<U, H>(mut self, headers: U) -> Cors
+    where
+        U: IntoIterator<Item = H>,
+        H: TryInto<HeaderName>,
+        <H as TryInto<HeaderName>>::Error: Into<HttpError>,
     {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            for h in headers {
-                match h.try_into() {
-                    Ok(method) => {
-                        if cors.allowed_headers.is_all() {
-                            cors.allowed_headers = AllOrSome::Some(HashSet::with_capacity(8));
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            for h in headers {
+                match h.try_into() {
+                    Ok(method) => {
+                        if cors.allowed_headers.is_all() {
+                            cors.allowed_headers = AllOrSome::Some(HashSet::with_capacity(8));
                         }
 
-                        if let AllOrSome::Some(ref mut headers) = cors.allowed_headers {
-                            headers.insert(method);
+                        if let AllOrSome::Some(ref mut headers) = cors.allowed_headers {
+                            headers.insert(method);
                         }
                     }
-                    Err(err) => {
-                        self.error = Some(Either::Left(err.into()));
+                    Err(err) => {
+                        self.error = Some(Either::Left(err.into()));
                         break;
                     }
                 }
             }
         }
 
-        self
-    }
+        self
+    }
 
-    /// Resets exposed response header list to a state where all headers are exposed.
-    ///
-    /// See [`Cors::expose_headers`] for more info on exposed response headers.
-    pub fn expose_any_header(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.expose_headers = AllOrSome::All;
+    /// Resets exposed response header list to a state where all headers are exposed.
+    ///
+    /// See [`Cors::expose_headers`] for more info on exposed response headers.
+    pub fn expose_any_header(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.expose_headers = AllOrSome::All;
         }
 
-        self
-    }
+        self
+    }
 
-    /// Set a list of headers which are safe to expose to the API of a CORS API specification.
-    /// This corresponds to the `Access-Control-Expose-Headers` response header as specified in
-    /// the [Fetch Standard CORS protocol].
-    ///
-    /// This defaults to an empty set.
-    ///
-    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
-    pub fn expose_headers<U, H>(mut self, headers: U) -> Cors
-    where
-        U: IntoIterator<Item = H>,
-        H: TryInto<HeaderName>,
-        <H as TryInto<HeaderName>>::Error: Into<HttpError>,
+    /// Set a list of headers which are safe to expose to the API of a CORS API specification.
+    /// This corresponds to the `Access-Control-Expose-Headers` response header as specified in
+    /// the [Fetch Standard CORS protocol].
+    ///
+    /// This defaults to an empty set.
+    ///
+    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
+    pub fn expose_headers<U, H>(mut self, headers: U) -> Cors
+    where
+        U: IntoIterator<Item = H>,
+        H: TryInto<HeaderName>,
+        <H as TryInto<HeaderName>>::Error: Into<HttpError>,
     {
-        for h in headers {
-            match h.try_into() {
-                Ok(header) => {
-                    if let Some(cors) = cors(&mut self.inner, &self.error) {
-                        if cors.expose_headers.is_all() {
-                            cors.expose_headers = AllOrSome::Some(HashSet::with_capacity(8));
+        for h in headers {
+            match h.try_into() {
+                Ok(header) => {
+                    if let Some(cors) = cors(&mut self.inner, &self.error) {
+                        if cors.expose_headers.is_all() {
+                            cors.expose_headers = AllOrSome::Some(HashSet::with_capacity(8));
                         }
-                        if let AllOrSome::Some(ref mut headers) = cors.expose_headers {
-                            headers.insert(header);
+                        if let AllOrSome::Some(ref mut headers) = cors.expose_headers {
+                            headers.insert(header);
                         }
                     }
                 }
-                Err(err) => {
-                    self.error = Some(Either::Left(err.into()));
+                Err(err) => {
+                    self.error = Some(Either::Left(err.into()));
                     break;
                 }
             }
         }
 
-        self
-    }
+        self
+    }
 
-    /// Set a maximum time (in seconds) for which this CORS request may be cached. This value is set
-    /// as the `Access-Control-Max-Age` header as specified in the [Fetch Standard CORS protocol].
-    ///
-    /// Pass a number (of seconds) or use None to disable sending max age header.
-    ///
-    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
-    pub fn max_age(mut self, max_age: impl Into<Option<usize>>) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.max_age = max_age.into()
+    /// Set a maximum time (in seconds) for which this CORS request may be cached. This value is set
+    /// as the `Access-Control-Max-Age` header as specified in the [Fetch Standard CORS protocol].
+    ///
+    /// Pass a number (of seconds) or use None to disable sending max age header.
+    ///
+    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
+    pub fn max_age(mut self, max_age: impl Into<Option<usize>>) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.max_age = max_age.into()
         }
 
-        self
-    }
+        self
+    }
 
-    /// Set to use wildcard origins.
-    ///
-    /// If send wildcard is set and the `allowed_origins` parameter is `All`, a wildcard
-    /// `Access-Control-Allow-Origin` response header is sent, rather than the request’s
-    /// `Origin` header.
-    ///
-    /// This **CANNOT** be used in conjunction with `allowed_origins` set to `All` and
-    /// `allow_credentials` set to `true`. Depending on the mode of usage, this will either result
-    /// in an `CorsError::CredentialsWithWildcardOrigin` error during actix launch or runtime.
-    ///
-    /// Defaults to `false`.
-    pub fn send_wildcard(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.send_wildcard = true
-        }
+    /// Set to use wildcard origins.
+    ///
+    /// If send wildcard is set and the `allowed_origins` parameter is `All`, a wildcard
+    /// `Access-Control-Allow-Origin` response header is sent, rather than the request’s
+    /// `Origin` header.
+    ///
+    /// This **CANNOT** be used in conjunction with `allowed_origins` set to `All` and
+    /// `allow_credentials` set to `true`. Depending on the mode of usage, this will either result
+    /// in an `CorsError::CredentialsWithWildcardOrigin` error during actix launch or runtime.
+    ///
+    /// Defaults to `false`.
+    pub fn send_wildcard(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.send_wildcard = true
+        }
 
-        self
-    }
+        self
+    }
 
-    /// Allows users to make authenticated requests
-    ///
-    /// If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows
-    /// cookies and credentials to be submitted across domains as specified in
-    /// the [Fetch Standard CORS protocol].
-    ///
-    /// This option cannot be used in conjunction with an `allowed_origin` set to `All` and
-    /// `send_wildcards` set to `true`.
-    ///
-    /// Defaults to `false`.
-    ///
-    /// A server initialization error will occur if credentials are allowed, but the Origin is set
-    /// to send wildcards (`*`); this is not allowed by the CORS protocol.
-    ///
-    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
-    pub fn supports_credentials(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.supports_credentials = true
-        }
+    /// Allows users to make authenticated requests
+    ///
+    /// If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows
+    /// cookies and credentials to be submitted across domains as specified in
+    /// the [Fetch Standard CORS protocol].
+    ///
+    /// This option cannot be used in conjunction with an `allowed_origin` set to `All` and
+    /// `send_wildcards` set to `true`.
+    ///
+    /// Defaults to `false`.
+    ///
+    /// A server initialization error will occur if credentials are allowed, but the Origin is set
+    /// to send wildcards (`*`); this is not allowed by the CORS protocol.
+    ///
+    /// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
+    pub fn supports_credentials(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.supports_credentials = true
+        }
 
-        self
-    }
+        self
+    }
 
-    /// Disable `Vary` header support.
-    ///
-    /// When enabled the header `Vary: Origin` will be returned as per the Fetch Standard
-    /// implementation guidelines.
-    ///
-    /// Setting this header when the `Access-Control-Allow-Origin` is dynamically generated
-    /// (eg. when there is more than one allowed origin, and an Origin other than '*' is returned)
-    /// informs CDNs and other caches that the CORS headers are dynamic, and cannot be cached.
-    ///
-    /// By default, `Vary` header support is enabled.
-    pub fn disable_vary_header(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.vary_header = false
-        }
+    /// Disable `Vary` header support.
+    ///
+    /// When enabled the header `Vary: Origin` will be returned as per the Fetch Standard
+    /// implementation guidelines.
+    ///
+    /// Setting this header when the `Access-Control-Allow-Origin` is dynamically generated
+    /// (eg. when there is more than one allowed origin, and an Origin other than '*' is returned)
+    /// informs CDNs and other caches that the CORS headers are dynamic, and cannot be cached.
+    ///
+    /// By default, `Vary` header support is enabled.
+    pub fn disable_vary_header(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.vary_header = false
+        }
 
-        self
-    }
+        self
+    }
 
-    /// Disable support for preflight requests.
-    ///
-    /// When enabled CORS middleware automatically handles `OPTIONS` requests.
-    /// This is useful for application level middleware.
-    ///
-    /// By default *preflight* support is enabled.
-    pub fn disable_preflight(mut self) -> Cors {
-        if let Some(cors) = cors(&mut self.inner, &self.error) {
-            cors.preflight = false
-        }
+    /// Disable support for preflight requests.
+    ///
+    /// When enabled CORS middleware automatically handles `OPTIONS` requests.
+    /// This is useful for application level middleware.
+    ///
+    /// By default *preflight* support is enabled.
+    pub fn disable_preflight(mut self) -> Cors {
+        if let Some(cors) = cors(&mut self.inner, &self.error) {
+            cors.preflight = false
+        }
 
-        self
-    }
+        self
+    }
 }
 
-impl Default for Cors {
-    /// A restrictive (security paranoid) set of defaults.
-    ///
-    /// *No* allowed origins, methods, request headers or exposed headers. Credentials
-    /// not supported. No max age (will use browser's default).
-    fn default() -> Cors {
-        let inner = Inner {
-            allowed_origins: AllOrSome::Some(HashSet::with_capacity(8)),
-            allowed_origins_fns: smallvec![],
+impl Default for Cors {
+    /// A restrictive (security paranoid) set of defaults.
+    ///
+    /// *No* allowed origins, methods, request headers or exposed headers. Credentials
+    /// not supported. No max age (will use browser's default).
+    fn default() -> Cors {
+        let inner = Inner {
+            allowed_origins: AllOrSome::Some(HashSet::with_capacity(8)),
+            allowed_origins_fns: smallvec![],
 
-            allowed_methods: HashSet::with_capacity(8),
-            allowed_methods_baked: None,
+            allowed_methods: HashSet::with_capacity(8),
+            allowed_methods_baked: None,
 
-            allowed_headers: AllOrSome::Some(HashSet::with_capacity(8)),
-            allowed_headers_baked: None,
+            allowed_headers: AllOrSome::Some(HashSet::with_capacity(8)),
+            allowed_headers_baked: None,
 
-            expose_headers: AllOrSome::Some(HashSet::with_capacity(8)),
-            expose_headers_baked: None,
+            expose_headers: AllOrSome::Some(HashSet::with_capacity(8)),
+            expose_headers_baked: None,
 
-            max_age: None,
-            preflight: true,
-            send_wildcard: false,
-            supports_credentials: false,
-            vary_header: true,
+            max_age: None,
+            preflight: true,
+            send_wildcard: false,
+            supports_credentials: false,
+            vary_header: true,
         };
 
-        Cors {
-            inner: Rc::new(inner),
-            error: None,
+        Cors {
+            inner: Rc::new(inner),
+            error: None,
         }
     }
 }
 
-impl<S, B> Transform<S, ServiceRequest> for Cors
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
-    S::Future: 'static,
+impl<S, B> Transform<S, ServiceRequest> for Cors
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
+    S::Future: 'static,
 
-    B: MessageBody + 'static,
+    B: MessageBody + 'static,
 {
-    type Response = ServiceResponse<EitherBody<B>>;
-    type Error = Error;
-    type InitError = ();
-    type Transform = CorsMiddleware<S>;
-    type Future = Ready<Result<Self::Transform, Self::InitError>>;
+    type Response = ServiceResponse<EitherBody<B>>;
+    type Error = Error;
+    type InitError = ();
+    type Transform = CorsMiddleware<S>;
+    type Future = Ready<Result<Self::Transform, Self::InitError>>;
 
-    fn new_transform(&self, service: S) -> Self::Future {
-        if let Some(ref err) = self.error {
-            match err {
-                Either::Left(err) => error!("{}", err),
-                Either::Right(err) => error!("{}", err),
+    fn new_transform(&self, service: S) -> Self::Future {
+        if let Some(ref err) = self.error {
+            match err {
+                Either::Left(err) => error!("{}", err),
+                Either::Right(err) => error!("{}", err),
             }
 
-            return future::err(());
+            return future::err(());
         }
 
-        let mut inner = Rc::clone(&self.inner);
+        let mut inner = Rc::clone(&self.inner);
 
-        if inner.supports_credentials && inner.send_wildcard && inner.allowed_origins.is_all() {
+        if inner.supports_credentials && inner.send_wildcard && inner.allowed_origins.is_all() {
             error!(
                 "Illegal combination of CORS options: credentials can not be supported when all \
-                    origins are allowed and `send_wildcard` is enabled."
-            );
-            return future::err(());
+                    origins are allowed and `send_wildcard` is enabled."
+            );
+            return future::err(());
         }
 
-        // bake allowed headers value if Some and not empty
-        match inner.allowed_headers.as_ref() {
-            Some(header_set) if !header_set.is_empty() => {
-                let allowed_headers_str = intersperse_header_values(header_set);
-                Rc::make_mut(&mut inner).allowed_headers_baked = Some(allowed_headers_str);
+        // bake allowed headers value if Some and not empty
+        match inner.allowed_headers.as_ref() {
+            Some(header_set) if !header_set.is_empty() => {
+                let allowed_headers_str = intersperse_header_values(header_set);
+                Rc::make_mut(&mut inner).allowed_headers_baked = Some(allowed_headers_str);
             }
-            _ => {}
+            _ => {}
         }
 
-        // bake allowed methods value if not empty
-        if !inner.allowed_methods.is_empty() {
-            let allowed_methods_str = intersperse_header_values(&inner.allowed_methods);
-            Rc::make_mut(&mut inner).allowed_methods_baked = Some(allowed_methods_str);
+        // bake allowed methods value if not empty
+        if !inner.allowed_methods.is_empty() {
+            let allowed_methods_str = intersperse_header_values(&inner.allowed_methods);
+            Rc::make_mut(&mut inner).allowed_methods_baked = Some(allowed_methods_str);
         }
 
-        // bake exposed headers value if Some and not empty
-        match inner.expose_headers.as_ref() {
-            Some(header_set) if !header_set.is_empty() => {
-                let expose_headers_str = intersperse_header_values(header_set);
-                Rc::make_mut(&mut inner).expose_headers_baked = Some(expose_headers_str);
+        // bake exposed headers value if Some and not empty
+        match inner.expose_headers.as_ref() {
+            Some(header_set) if !header_set.is_empty() => {
+                let expose_headers_str = intersperse_header_values(header_set);
+                Rc::make_mut(&mut inner).expose_headers_baked = Some(expose_headers_str);
             }
-            _ => {}
+            _ => {}
         }
 
-        future::ok(CorsMiddleware { service, inner })
+        future::ok(CorsMiddleware { service, inner })
     }
 }
 
-/// Only call when values are guaranteed to be valid header values and set is not empty.
-pub(crate) fn intersperse_header_values<T>(val_set: &HashSet<T>) -> HeaderValue
-where
-    T: AsRef<str>,
+/// Only call when values are guaranteed to be valid header values and set is not empty.
+pub(crate) fn intersperse_header_values<T>(val_set: &HashSet<T>) -> HeaderValue
+where
+    T: AsRef<str>,
 {
     debug_assert!(
-        !val_set.is_empty(),
-        "only call `intersperse_header_values` when set is not empty"
-    );
+        !val_set.is_empty(),
+        "only call `intersperse_header_values` when set is not empty"
+    );
 
-    val_set
-        .iter()
-        .fold(String::with_capacity(64), |mut acc, val| {
-            acc.push_str(", ");
-            acc.push_str(val.as_ref());
-            acc
+    val_set
+        .iter()
+        .fold(String::with_capacity(64), |mut acc, val| {
+            acc.push_str(", ");
+            acc.push_str(val.as_ref());
+            acc
         })
-        // set is not empty so string will always have leading ", " to trim
-        [2..]
-        .try_into()
-        // all method names are valid header values
-        .unwrap()
+        // set is not empty so string will always have leading ", " to trim
+        [2..]
+        .try_into()
+        // all method names are valid header values
+        .unwrap()
 }
 
-#[cfg(test)]
-mod test {
-    use std::convert::{Infallible, TryInto};
+#[cfg(test)]
+mod test {
+    use std::convert::{Infallible, TryInto};
 
-    use actix_web::{
-        body,
-        dev::{fn_service, Transform},
-        http::{header::HeaderName, StatusCode},
-        test::{self, TestRequest},
-        HttpResponse,
+    use actix_web::{
+        body,
+        dev::{fn_service, Transform},
+        http::{header::HeaderName, StatusCode},
+        test::{self, TestRequest},
+        HttpResponse,
     };
 
-    use super::*;
+    use super::*;
 
-    #[test]
-    fn illegal_allow_credentials() {
-        // using the permissive defaults (all origins allowed) and adding send_wildcard
-        // and supports_credentials should error on construction
+    #[test]
+    fn illegal_allow_credentials() {
+        // using the permissive defaults (all origins allowed) and adding send_wildcard
+        // and supports_credentials should error on construction
 
-        assert!(Cors::permissive()
-            .supports_credentials()
-            .send_wildcard()
-            .new_transform(test::ok_service())
-            .into_inner()
-            .is_err());
+        assert!(Cors::permissive()
+            .supports_credentials()
+            .send_wildcard()
+            .new_transform(test::ok_service())
+            .into_inner()
+            .is_err());
     }
 
-    #[actix_web::test]
-    async fn restrictive_defaults() {
-        let cors = Cors::default()
-            .new_transform(test::ok_service())
-            .await
-            .unwrap();
+    #[actix_web::test]
+    async fn restrictive_defaults() {
+        let cors = Cors::default()
+            .new_transform(test::ok_service())
+            .await
+            .unwrap();
 
-        let req = TestRequest::default()
-            .insert_header(("Origin", "https://www.example.com"))
-            .to_srv_request();
+        let req = TestRequest::default()
+            .insert_header(("Origin", "https://www.example.com"))
+            .to_srv_request();
 
-        let resp = test::call_service(&cors, req).await;
-        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+        let resp = test::call_service(&cors, req).await;
+        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
     }
 
-    #[actix_web::test]
-    async fn allowed_header_try_from() {
-        let _cors = Cors::default().allowed_header("Content-Type");
+    #[actix_web::test]
+    async fn allowed_header_try_from() {
+        let _cors = Cors::default().allowed_header("Content-Type");
     }
 
-    #[actix_web::test]
-    async fn allowed_header_try_into() {
-        struct ContentType;
+    #[actix_web::test]
+    async fn allowed_header_try_into() {
+        struct ContentType;
 
-        impl TryInto<HeaderName> for ContentType {
-            type Error = Infallible;
+        impl TryInto<HeaderName> for ContentType {
+            type Error = Infallible;
 
-            fn try_into(self) -> Result<HeaderName, Self::Error> {
-                Ok(HeaderName::from_static("content-type"))
+            fn try_into(self) -> Result<HeaderName, Self::Error> {
+                Ok(HeaderName::from_static("content-type"))
             }
         }
 
-        let _cors = Cors::default().allowed_header(ContentType);
+        let _cors = Cors::default().allowed_header(ContentType);
     }
 
-    #[actix_web::test]
-    async fn middleware_generic_over_body_type() {
-        let srv = fn_service(|req: ServiceRequest| async move {
-            Ok(req.into_response(HttpResponse::with_body(StatusCode::OK, body::None::new())))
+    #[actix_web::test]
+    async fn middleware_generic_over_body_type() {
+        let srv = fn_service(|req: ServiceRequest| async move {
+            Ok(req.into_response(HttpResponse::with_body(StatusCode::OK, body::None::new())))
         });
 
-        Cors::default().new_transform(srv).await.unwrap();
+        Cors::default().new_transform(srv).await.unwrap();
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_cors/error.rs.html b/src/actix_cors/error.rs.html index aa0db66ff..faada63ba 100644 --- a/src/actix_cors/error.rs.html +++ b/src/actix_cors/error.rs.html @@ -49,54 +49,54 @@ 47 48 49 -
use actix_web::{http::StatusCode, HttpResponse, ResponseError};
-use derive_more::{Display, Error};
+
use actix_web::{http::StatusCode, HttpResponse, ResponseError};
+use derive_more::{Display, Error};
 
-/// Errors that can occur when processing CORS guarded requests.
-#[derive(Debug, Clone, Display, Error)]
-#[non_exhaustive]
-pub enum CorsError {
-    /// Allowed origin argument must not be wildcard (`*`).
-    #[display(fmt = "`allowed_origin` argument must not be wildcard (`*`)")]
-    WildcardOrigin,
+/// Errors that can occur when processing CORS guarded requests.
+#[derive(Debug, Clone, Display, Error)]
+#[non_exhaustive]
+pub enum CorsError {
+    /// Allowed origin argument must not be wildcard (`*`).
+    #[display(fmt = "`allowed_origin` argument must not be wildcard (`*`)")]
+    WildcardOrigin,
 
-    /// Request header `Origin` is required but was not provided.
-    #[display(fmt = "Request header `Origin` is required but was not provided")]
-    MissingOrigin,
+    /// Request header `Origin` is required but was not provided.
+    #[display(fmt = "Request header `Origin` is required but was not provided")]
+    MissingOrigin,
 
-    /// Request header `Access-Control-Request-Method` is required but is missing.
-    #[display(fmt = "Request header `Access-Control-Request-Method` is required but is missing")]
-    MissingRequestMethod,
+    /// Request header `Access-Control-Request-Method` is required but is missing.
+    #[display(fmt = "Request header `Access-Control-Request-Method` is required but is missing")]
+    MissingRequestMethod,
 
-    /// Request header `Access-Control-Request-Method` has an invalid value.
-    #[display(fmt = "Request header `Access-Control-Request-Method` has an invalid value")]
-    BadRequestMethod,
+    /// Request header `Access-Control-Request-Method` has an invalid value.
+    #[display(fmt = "Request header `Access-Control-Request-Method` has an invalid value")]
+    BadRequestMethod,
 
-    /// Request header `Access-Control-Request-Headers` has an invalid value.
-    #[display(fmt = "Request header `Access-Control-Request-Headers` has an invalid value")]
-    BadRequestHeaders,
+    /// Request header `Access-Control-Request-Headers` has an invalid value.
+    #[display(fmt = "Request header `Access-Control-Request-Headers` has an invalid value")]
+    BadRequestHeaders,
 
-    /// Origin is not allowed to make this request.
-    #[display(fmt = "Origin is not allowed to make this request")]
-    OriginNotAllowed,
+    /// Origin is not allowed to make this request.
+    #[display(fmt = "Origin is not allowed to make this request")]
+    OriginNotAllowed,
 
-    /// Request method is not allowed.
-    #[display(fmt = "Requested method is not allowed")]
-    MethodNotAllowed,
+    /// Request method is not allowed.
+    #[display(fmt = "Requested method is not allowed")]
+    MethodNotAllowed,
 
-    /// One or more request headers are not allowed.
-    #[display(fmt = "One or more request headers are not allowed")]
-    HeadersNotAllowed,
+    /// One or more request headers are not allowed.
+    #[display(fmt = "One or more request headers are not allowed")]
+    HeadersNotAllowed,
 }
 
-impl ResponseError for CorsError {
-    fn status_code(&self) -> StatusCode {
-        StatusCode::BAD_REQUEST
+impl ResponseError for CorsError {
+    fn status_code(&self) -> StatusCode {
+        StatusCode::BAD_REQUEST
     }
 
-    fn error_response(&self) -> HttpResponse {
-        HttpResponse::with_body(self.status_code(), self.to_string()).map_into_boxed_body()
+    fn error_response(&self) -> HttpResponse {
+        HttpResponse::with_body(self.status_code(), self.to_string()).map_into_boxed_body()
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_cors/inner.rs.html b/src/actix_cors/inner.rs.html index 6c0510253..bca82e6f4 100644 --- a/src/actix_cors/inner.rs.html +++ b/src/actix_cors/inner.rs.html @@ -383,388 +383,388 @@ 381 382 383 -
use std::{collections::HashSet, convert::TryFrom, convert::TryInto, fmt, rc::Rc};
+
use std::{collections::HashSet, convert::TryFrom, convert::TryInto, fmt, rc::Rc};
 
-use actix_web::{
-    dev::RequestHead,
-    error::Result,
-    http::{
-        header::{self, HeaderMap, HeaderName, HeaderValue},
-        Method,
+use actix_web::{
+    dev::RequestHead,
+    error::Result,
+    http::{
+        header::{self, HeaderMap, HeaderName, HeaderValue},
+        Method,
     },
 };
-use once_cell::sync::Lazy;
-use smallvec::SmallVec;
+use once_cell::sync::Lazy;
+use smallvec::SmallVec;
 
-use crate::{AllOrSome, CorsError};
+use crate::{AllOrSome, CorsError};
 
-#[derive(Clone)]
-pub(crate) struct OriginFn {
-    #[allow(clippy::type_complexity)]
-    pub(crate) boxed_fn: Rc<dyn Fn(&HeaderValue, &RequestHead) -> bool>,
+#[derive(Clone)]
+pub(crate) struct OriginFn {
+    #[allow(clippy::type_complexity)]
+    pub(crate) boxed_fn: Rc<dyn Fn(&HeaderValue, &RequestHead) -> bool>,
 }
 
-impl Default for OriginFn {
-    /// Dummy default for use in tiny_vec. Do not use.
-    fn default() -> Self {
-        let boxed_fn: Rc<dyn Fn(&_, &_) -> _> = Rc::new(|_origin, _req_head| false);
-        Self { boxed_fn }
+impl Default for OriginFn {
+    /// Dummy default for use in tiny_vec. Do not use.
+    fn default() -> Self {
+        let boxed_fn: Rc<dyn Fn(&_, &_) -> _> = Rc::new(|_origin, _req_head| false);
+        Self { boxed_fn }
     }
 }
 
-impl fmt::Debug for OriginFn {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.write_str("origin_fn")
+impl fmt::Debug for OriginFn {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("origin_fn")
     }
 }
 
-/// Try to parse header value as HTTP method.
-pub(crate) fn header_value_try_into_method(hdr: &HeaderValue) -> Option<Method> {
-    hdr.to_str()
-        .ok()
-        .and_then(|meth| Method::try_from(meth).ok())
+/// Try to parse header value as HTTP method.
+pub(crate) fn header_value_try_into_method(hdr: &HeaderValue) -> Option<Method> {
+    hdr.to_str()
+        .ok()
+        .and_then(|meth| Method::try_from(meth).ok())
 }
 
-#[derive(Debug, Clone)]
-pub(crate) struct Inner {
-    pub(crate) allowed_origins: AllOrSome<HashSet<HeaderValue>>,
-    pub(crate) allowed_origins_fns: SmallVec<[OriginFn; 4]>,
+#[derive(Debug, Clone)]
+pub(crate) struct Inner {
+    pub(crate) allowed_origins: AllOrSome<HashSet<HeaderValue>>,
+    pub(crate) allowed_origins_fns: SmallVec<[OriginFn; 4]>,
 
-    pub(crate) allowed_methods: HashSet<Method>,
-    pub(crate) allowed_methods_baked: Option<HeaderValue>,
+    pub(crate) allowed_methods: HashSet<Method>,
+    pub(crate) allowed_methods_baked: Option<HeaderValue>,
 
-    pub(crate) allowed_headers: AllOrSome<HashSet<HeaderName>>,
-    pub(crate) allowed_headers_baked: Option<HeaderValue>,
+    pub(crate) allowed_headers: AllOrSome<HashSet<HeaderName>>,
+    pub(crate) allowed_headers_baked: Option<HeaderValue>,
 
-    /// `All` will echo back `Access-Control-Request-Header` list.
-    pub(crate) expose_headers: AllOrSome<HashSet<HeaderName>>,
-    pub(crate) expose_headers_baked: Option<HeaderValue>,
+    /// `All` will echo back `Access-Control-Request-Header` list.
+    pub(crate) expose_headers: AllOrSome<HashSet<HeaderName>>,
+    pub(crate) expose_headers_baked: Option<HeaderValue>,
 
-    pub(crate) max_age: Option<usize>,
-    pub(crate) preflight: bool,
-    pub(crate) send_wildcard: bool,
-    pub(crate) supports_credentials: bool,
-    pub(crate) vary_header: bool,
+    pub(crate) max_age: Option<usize>,
+    pub(crate) preflight: bool,
+    pub(crate) send_wildcard: bool,
+    pub(crate) supports_credentials: bool,
+    pub(crate) vary_header: bool,
 }
 
-static EMPTY_ORIGIN_SET: Lazy<HashSet<HeaderValue>> = Lazy::new(HashSet::new);
+static EMPTY_ORIGIN_SET: Lazy<HashSet<HeaderValue>> = Lazy::new(HashSet::new);
 
-impl Inner {
-    pub(crate) fn validate_origin(&self, req: &RequestHead) -> Result<(), CorsError> {
-        // return early if all origins are allowed or get ref to allowed origins set
-        #[allow(clippy::mutable_key_type)]
-        let allowed_origins = match &self.allowed_origins {
-            AllOrSome::All if self.allowed_origins_fns.is_empty() => return Ok(()),
-            AllOrSome::Some(allowed_origins) => allowed_origins,
-            // only function origin validators are defined
-            _ => &EMPTY_ORIGIN_SET,
+impl Inner {
+    pub(crate) fn validate_origin(&self, req: &RequestHead) -> Result<(), CorsError> {
+        // return early if all origins are allowed or get ref to allowed origins set
+        #[allow(clippy::mutable_key_type)]
+        let allowed_origins = match &self.allowed_origins {
+            AllOrSome::All if self.allowed_origins_fns.is_empty() => return Ok(()),
+            AllOrSome::Some(allowed_origins) => allowed_origins,
+            // only function origin validators are defined
+            _ => &EMPTY_ORIGIN_SET,
         };
 
-        // get origin header and try to parse as string
-        match req.headers().get(header::ORIGIN) {
-            // origin header exists and is a string
-            Some(origin) => {
-                if allowed_origins.contains(origin) || self.validate_origin_fns(origin, req) {
+        // get origin header and try to parse as string
+        match req.headers().get(header::ORIGIN) {
+            // origin header exists and is a string
+            Some(origin) => {
+                if allowed_origins.contains(origin) || self.validate_origin_fns(origin, req) {
                     Ok(())
-                } else {
-                    Err(CorsError::OriginNotAllowed)
+                } else {
+                    Err(CorsError::OriginNotAllowed)
                 }
             }
 
-            // origin header is missing
-            // note: with our implementation, the origin header is required for OPTIONS request or
-            // else this would be unreachable
-            None => Err(CorsError::MissingOrigin),
+            // origin header is missing
+            // note: with our implementation, the origin header is required for OPTIONS request or
+            // else this would be unreachable
+            None => Err(CorsError::MissingOrigin),
         }
     }
 
-    /// Accepts origin if _ANY_ functions return true. Only called when Origin exists.
-    fn validate_origin_fns(&self, origin: &HeaderValue, req: &RequestHead) -> bool {
-        self.allowed_origins_fns
-            .iter()
-            .any(|origin_fn| (origin_fn.boxed_fn)(origin, req))
+    /// Accepts origin if _ANY_ functions return true. Only called when Origin exists.
+    fn validate_origin_fns(&self, origin: &HeaderValue, req: &RequestHead) -> bool {
+        self.allowed_origins_fns
+            .iter()
+            .any(|origin_fn| (origin_fn.boxed_fn)(origin, req))
     }
 
-    /// Only called if origin exists and always after it's validated.
-    pub(crate) fn access_control_allow_origin(&self, req: &RequestHead) -> Option<HeaderValue> {
-        let origin = req.headers().get(header::ORIGIN);
+    /// Only called if origin exists and always after it's validated.
+    pub(crate) fn access_control_allow_origin(&self, req: &RequestHead) -> Option<HeaderValue> {
+        let origin = req.headers().get(header::ORIGIN);
 
-        match self.allowed_origins {
-            AllOrSome::All => {
-                if self.send_wildcard {
-                    Some(HeaderValue::from_static("*"))
-                } else {
-                    // see note below about why `.cloned()` is correct
-                    origin.cloned()
+        match self.allowed_origins {
+            AllOrSome::All => {
+                if self.send_wildcard {
+                    Some(HeaderValue::from_static("*"))
+                } else {
+                    // see note below about why `.cloned()` is correct
+                    origin.cloned()
                 }
             }
 
-            AllOrSome::Some(_) => {
-                // since origin (if it exists) is known to be allowed if this method is called
-                // then cloning the option is all that is required to be used as an echoed back
-                // header value (or omitted if None)
-                origin.cloned()
+            AllOrSome::Some(_) => {
+                // since origin (if it exists) is known to be allowed if this method is called
+                // then cloning the option is all that is required to be used as an echoed back
+                // header value (or omitted if None)
+                origin.cloned()
             }
         }
     }
 
-    /// Use in preflight checks and therefore operates on header list in
-    /// `Access-Control-Request-Headers` not the actual header set.
-    pub(crate) fn validate_allowed_method(&self, req: &RequestHead) -> Result<(), CorsError> {
-        // extract access control header and try to parse as method
-        let request_method = req
-            .headers()
-            .get(header::ACCESS_CONTROL_REQUEST_METHOD)
-            .map(header_value_try_into_method);
+    /// Use in preflight checks and therefore operates on header list in
+    /// `Access-Control-Request-Headers` not the actual header set.
+    pub(crate) fn validate_allowed_method(&self, req: &RequestHead) -> Result<(), CorsError> {
+        // extract access control header and try to parse as method
+        let request_method = req
+            .headers()
+            .get(header::ACCESS_CONTROL_REQUEST_METHOD)
+            .map(header_value_try_into_method);
 
-        match request_method {
-            // method valid and allowed
-            Some(Some(method)) if self.allowed_methods.contains(&method) => Ok(()),
+        match request_method {
+            // method valid and allowed
+            Some(Some(method)) if self.allowed_methods.contains(&method) => Ok(()),
 
-            // method valid but not allowed
-            Some(Some(_)) => Err(CorsError::MethodNotAllowed),
+            // method valid but not allowed
+            Some(Some(_)) => Err(CorsError::MethodNotAllowed),
 
-            // method invalid
-            Some(_) => Err(CorsError::BadRequestMethod),
+            // method invalid
+            Some(_) => Err(CorsError::BadRequestMethod),
 
-            // method missing so this is not a preflight request
-            None => Err(CorsError::MissingRequestMethod),
+            // method missing so this is not a preflight request
+            None => Err(CorsError::MissingRequestMethod),
         }
     }
 
-    pub(crate) fn validate_allowed_headers(&self, req: &RequestHead) -> Result<(), CorsError> {
-        // return early if all headers are allowed or get ref to allowed origins set
-        #[allow(clippy::mutable_key_type)]
-        let allowed_headers = match &self.allowed_headers {
-            AllOrSome::All => return Ok(()),
-            AllOrSome::Some(allowed_headers) => allowed_headers,
+    pub(crate) fn validate_allowed_headers(&self, req: &RequestHead) -> Result<(), CorsError> {
+        // return early if all headers are allowed or get ref to allowed origins set
+        #[allow(clippy::mutable_key_type)]
+        let allowed_headers = match &self.allowed_headers {
+            AllOrSome::All => return Ok(()),
+            AllOrSome::Some(allowed_headers) => allowed_headers,
         };
 
-        // extract access control header as string
-        // header format should be comma separated header names
-        let request_headers = req
-            .headers()
-            .get(header::ACCESS_CONTROL_REQUEST_HEADERS)
-            .map(|hdr| hdr.to_str());
+        // extract access control header as string
+        // header format should be comma separated header names
+        let request_headers = req
+            .headers()
+            .get(header::ACCESS_CONTROL_REQUEST_HEADERS)
+            .map(|hdr| hdr.to_str());
 
-        match request_headers {
-            // header list is valid string
-            Some(Ok(headers)) => {
-                // the set is ephemeral we take care not to mutate the
-                // inserted keys so this lint exception is acceptable
-                #[allow(clippy::mutable_key_type)]
-                let mut request_headers = HashSet::with_capacity(8);
+        match request_headers {
+            // header list is valid string
+            Some(Ok(headers)) => {
+                // the set is ephemeral we take care not to mutate the
+                // inserted keys so this lint exception is acceptable
+                #[allow(clippy::mutable_key_type)]
+                let mut request_headers = HashSet::with_capacity(8);
 
-                // try to convert each header name in the comma-separated list
-                for hdr in headers.split(',') {
-                    match hdr.trim().try_into() {
-                        Ok(hdr) => request_headers.insert(hdr),
-                        Err(_) => return Err(CorsError::BadRequestHeaders),
+                // try to convert each header name in the comma-separated list
+                for hdr in headers.split(',') {
+                    match hdr.trim().try_into() {
+                        Ok(hdr) => request_headers.insert(hdr),
+                        Err(_) => return Err(CorsError::BadRequestHeaders),
                     };
                 }
 
-                // header list must contain 1 or more header name
-                if request_headers.is_empty() {
-                    return Err(CorsError::BadRequestHeaders);
+                // header list must contain 1 or more header name
+                if request_headers.is_empty() {
+                    return Err(CorsError::BadRequestHeaders);
                 }
 
-                // request header list must be a subset of allowed headers
-                if !request_headers.is_subset(allowed_headers) {
-                    return Err(CorsError::HeadersNotAllowed);
+                // request header list must be a subset of allowed headers
+                if !request_headers.is_subset(allowed_headers) {
+                    return Err(CorsError::HeadersNotAllowed);
                 }
 
                 Ok(())
             }
 
-            // header list is not a string
-            Some(Err(_)) => Err(CorsError::BadRequestHeaders),
+            // header list is not a string
+            Some(Err(_)) => Err(CorsError::BadRequestHeaders),
 
-            // header list missing
-            None => Ok(()),
+            // header list missing
+            None => Ok(()),
         }
     }
 }
 
-/// Add CORS related request headers to response's Vary header.
-///
-/// See <https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches>.
-pub(crate) fn add_vary_header(headers: &mut HeaderMap) {
-    let value = match headers.get(header::VARY) {
-        Some(hdr) => {
-            let mut val: Vec<u8> = Vec::with_capacity(hdr.len() + 71);
-            val.extend(hdr.as_bytes());
-            val.extend(b", Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
-            val.try_into().unwrap()
+/// Add CORS related request headers to response's Vary header.
+///
+/// See <https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches>.
+pub(crate) fn add_vary_header(headers: &mut HeaderMap) {
+    let value = match headers.get(header::VARY) {
+        Some(hdr) => {
+            let mut val: Vec<u8> = Vec::with_capacity(hdr.len() + 71);
+            val.extend(hdr.as_bytes());
+            val.extend(b", Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
+            val.try_into().unwrap()
         }
-        None => HeaderValue::from_static(
+        None => HeaderValue::from_static(
             "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
         ),
     };
 
-    headers.insert(header::VARY, value);
+    headers.insert(header::VARY, value);
 }
 
-#[cfg(test)]
-mod test {
-    use std::rc::Rc;
+#[cfg(test)]
+mod test {
+    use std::rc::Rc;
 
-    use actix_web::{
-        dev::Transform,
-        http::{
-            header::{self, HeaderValue},
-            Method, StatusCode,
+    use actix_web::{
+        dev::Transform,
+        http::{
+            header::{self, HeaderValue},
+            Method, StatusCode,
         },
-        test::{self, TestRequest},
+        test::{self, TestRequest},
     };
 
-    use crate::Cors;
+    use crate::Cors;
 
-    fn val_as_str(val: &HeaderValue) -> &str {
-        val.to_str().unwrap()
+    fn val_as_str(val: &HeaderValue) -> &str {
+        val.to_str().unwrap()
     }
 
-    #[actix_web::test]
-    async fn test_validate_not_allowed_origin() {
-        let cors = Cors::default()
-            .allowed_origin("https://www.example.com")
-            .new_transform(test::ok_service())
-            .await
-            .unwrap();
+    #[actix_web::test]
+    async fn test_validate_not_allowed_origin() {
+        let cors = Cors::default()
+            .allowed_origin("https://www.example.com")
+            .new_transform(test::ok_service())
+            .await
+            .unwrap();
 
-        let req = TestRequest::get()
-            .insert_header((header::ORIGIN, "https://www.unknown.com"))
-            .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "DNT"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .insert_header((header::ORIGIN, "https://www.unknown.com"))
+            .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "DNT"))
+            .to_srv_request();
 
-        assert!(cors.inner.validate_origin(req.head()).is_err());
-        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
-        assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
+        assert!(cors.inner.validate_origin(req.head()).is_err());
+        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
+        assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
     }
 
-    #[actix_web::test]
-    async fn test_preflight() {
-        let mut cors = Cors::default()
-            .allow_any_origin()
-            .send_wildcard()
-            .max_age(3600)
-            .allowed_methods(vec![Method::GET, Method::OPTIONS, Method::POST])
-            .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
-            .allowed_header(header::CONTENT_TYPE)
-            .new_transform(test::ok_service())
-            .await
-            .unwrap();
+    #[actix_web::test]
+    async fn test_preflight() {
+        let mut cors = Cors::default()
+            .allow_any_origin()
+            .send_wildcard()
+            .max_age(3600)
+            .allowed_methods(vec![Method::GET, Method::OPTIONS, Method::POST])
+            .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
+            .allowed_header(header::CONTENT_TYPE)
+            .new_transform(test::ok_service())
+            .await
+            .unwrap();
 
-        let req = TestRequest::default()
-            .method(Method::OPTIONS)
-            .insert_header(("Origin", "https://www.example.com"))
-            .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed"))
-            .to_srv_request();
+        let req = TestRequest::default()
+            .method(Method::OPTIONS)
+            .insert_header(("Origin", "https://www.example.com"))
+            .insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed"))
+            .to_srv_request();
 
-        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
-        assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
-        let resp = test::call_service(&cors, req).await;
-        assert_eq!(resp.status(), StatusCode::OK);
+        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
+        assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
+        let resp = test::call_service(&cors, req).await;
+        assert_eq!(resp.status(), StatusCode::OK);
 
-        let req = TestRequest::default()
-            .method(Method::OPTIONS)
-            .insert_header(("Origin", "https://www.example.com"))
-            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "put"))
-            .to_srv_request();
+        let req = TestRequest::default()
+            .method(Method::OPTIONS)
+            .insert_header(("Origin", "https://www.example.com"))
+            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "put"))
+            .to_srv_request();
 
-        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
-        assert!(cors.inner.validate_allowed_headers(req.head()).is_ok());
+        assert!(cors.inner.validate_allowed_method(req.head()).is_err());
+        assert!(cors.inner.validate_allowed_headers(req.head()).is_ok());
 
-        let req = TestRequest::default()
-            .method(Method::OPTIONS)
-            .insert_header(("Origin", "https://www.example.com"))
-            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
-            .insert_header((
-                header::ACCESS_CONTROL_REQUEST_HEADERS,
+        let req = TestRequest::default()
+            .method(Method::OPTIONS)
+            .insert_header(("Origin", "https://www.example.com"))
+            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
+            .insert_header((
+                header::ACCESS_CONTROL_REQUEST_HEADERS,
                 "AUTHORIZATION,ACCEPT",
             ))
-            .to_srv_request();
+            .to_srv_request();
 
-        let resp = test::call_service(&cors, req).await;
+        let resp = test::call_service(&cors, req).await;
         assert_eq!(
             Some(&b"*"[..]),
-            resp.headers()
-                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
-                .map(HeaderValue::as_bytes)
+            resp.headers()
+                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+                .map(HeaderValue::as_bytes)
         );
         assert_eq!(
             Some(&b"3600"[..]),
-            resp.headers()
-                .get(header::ACCESS_CONTROL_MAX_AGE)
-                .map(HeaderValue::as_bytes)
+            resp.headers()
+                .get(header::ACCESS_CONTROL_MAX_AGE)
+                .map(HeaderValue::as_bytes)
         );
 
-        let hdr = resp
-            .headers()
-            .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
-            .map(val_as_str)
-            .unwrap();
-        assert!(hdr.contains("authorization"));
-        assert!(hdr.contains("accept"));
-        assert!(hdr.contains("content-type"));
+        let hdr = resp
+            .headers()
+            .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
+            .map(val_as_str)
+            .unwrap();
+        assert!(hdr.contains("authorization"));
+        assert!(hdr.contains("accept"));
+        assert!(hdr.contains("content-type"));
 
-        let methods = resp
-            .headers()
-            .get(header::ACCESS_CONTROL_ALLOW_METHODS)
-            .unwrap()
-            .to_str()
-            .unwrap();
-        assert!(methods.contains("POST"));
-        assert!(methods.contains("GET"));
-        assert!(methods.contains("OPTIONS"));
+        let methods = resp
+            .headers()
+            .get(header::ACCESS_CONTROL_ALLOW_METHODS)
+            .unwrap()
+            .to_str()
+            .unwrap();
+        assert!(methods.contains("POST"));
+        assert!(methods.contains("GET"));
+        assert!(methods.contains("OPTIONS"));
 
-        Rc::get_mut(&mut cors.inner).unwrap().preflight = false;
+        Rc::get_mut(&mut cors.inner).unwrap().preflight = false;
 
-        let req = TestRequest::default()
-            .method(Method::OPTIONS)
-            .insert_header(("Origin", "https://www.example.com"))
-            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
-            .insert_header((
-                header::ACCESS_CONTROL_REQUEST_HEADERS,
+        let req = TestRequest::default()
+            .method(Method::OPTIONS)
+            .insert_header(("Origin", "https://www.example.com"))
+            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
+            .insert_header((
+                header::ACCESS_CONTROL_REQUEST_HEADERS,
                 "AUTHORIZATION,ACCEPT",
             ))
-            .to_srv_request();
+            .to_srv_request();
 
-        let resp = test::call_service(&cors, req).await;
-        assert_eq!(resp.status(), StatusCode::OK);
+        let resp = test::call_service(&cors, req).await;
+        assert_eq!(resp.status(), StatusCode::OK);
     }
 
-    #[actix_web::test]
-    async fn allow_fn_origin_equals_head_origin() {
-        let cors = Cors::default()
-            .allowed_origin_fn(|origin, head| {
-                let head_origin = head
-                    .headers()
-                    .get(header::ORIGIN)
-                    .expect("unwrapping origin header should never fail in allowed_origin_fn");
-                assert!(origin == head_origin);
-                true
-            })
-            .allow_any_method()
-            .allow_any_header()
-            .new_transform(test::status_service(StatusCode::NO_CONTENT))
-            .await
-            .unwrap();
+    #[actix_web::test]
+    async fn allow_fn_origin_equals_head_origin() {
+        let cors = Cors::default()
+            .allowed_origin_fn(|origin, head| {
+                let head_origin = head
+                    .headers()
+                    .get(header::ORIGIN)
+                    .expect("unwrapping origin header should never fail in allowed_origin_fn");
+                assert!(origin == head_origin);
+                true
+            })
+            .allow_any_method()
+            .allow_any_header()
+            .new_transform(test::status_service(StatusCode::NO_CONTENT))
+            .await
+            .unwrap();
 
-        let req = TestRequest::default()
-            .method(Method::OPTIONS)
-            .insert_header(("Origin", "https://www.example.com"))
-            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
-            .to_srv_request();
-        let resp = test::call_service(&cors, req).await;
-        assert_eq!(resp.status(), StatusCode::OK);
+        let req = TestRequest::default()
+            .method(Method::OPTIONS)
+            .insert_header(("Origin", "https://www.example.com"))
+            .insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
+            .to_srv_request();
+        let resp = test::call_service(&cors, req).await;
+        assert_eq!(resp.status(), StatusCode::OK);
 
-        let req = TestRequest::default()
-            .method(Method::GET)
-            .insert_header(("Origin", "https://www.example.com"))
-            .to_srv_request();
-        let resp = test::call_service(&cors, req).await;
-        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
+        let req = TestRequest::default()
+            .method(Method::GET)
+            .insert_header(("Origin", "https://www.example.com"))
+            .to_srv_request();
+        let resp = test::call_service(&cors, req).await;
+        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_cors/lib.rs.html b/src/actix_cors/lib.rs.html index 4726151ab..4e7a2e7dc 100644 --- a/src/actix_cors/lib.rs.html +++ b/src/actix_cors/lib.rs.html @@ -60,65 +60,65 @@ 58 59 60 -
//! Cross-Origin Resource Sharing (CORS) controls for Actix Web.
-//!
-//! This middleware can be applied to both applications and resources. Once built, a
-//! [`Cors`] builder can be used as an argument for Actix Web's `App::wrap()`,
-//! `Scope::wrap()`, or `Resource::wrap()` methods.
-//!
-//! This CORS middleware automatically handles `OPTIONS` preflight requests.
-//!
-//! # Example
-//! ```no_run
-//! use actix_cors::Cors;
-//! use actix_web::{get, http, web, App, HttpRequest, HttpResponse, HttpServer};
-//!
-//! #[get("/index.html")]
-//! async fn index(req: HttpRequest) -> &'static str {
-//!     "<p>Hello World!</p>"
-//! }
-//!
-//! #[actix_web::main]
-//! async fn main() -> std::io::Result<()> {
-//!     HttpServer::new(|| {
-//!         let cors = Cors::default()
-//!               .allowed_origin("https://www.rust-lang.org/")
-//!               .allowed_origin_fn(|origin, _req_head| {
-//!                   origin.as_bytes().ends_with(b".rust-lang.org")
-//!               })
-//!               .allowed_methods(vec!["GET", "POST"])
-//!               .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
-//!               .allowed_header(http::header::CONTENT_TYPE)
-//!               .max_age(3600);
-//!
-//!         App::new()
-//!             .wrap(cors)
-//!             .service(index)
-//!     })
-//!     .bind(("127.0.0.1", 8080))?
-//!     .run()
-//!     .await;
-//!
-//!     Ok(())
-//! }
-//! ```
+
//! Cross-Origin Resource Sharing (CORS) controls for Actix Web.
+//!
+//! This middleware can be applied to both applications and resources. Once built, a
+//! [`Cors`] builder can be used as an argument for Actix Web's `App::wrap()`,
+//! `Scope::wrap()`, or `Resource::wrap()` methods.
+//!
+//! This CORS middleware automatically handles `OPTIONS` preflight requests.
+//!
+//! # Example
+//! ```no_run
+//! use actix_cors::Cors;
+//! use actix_web::{get, http, web, App, HttpRequest, HttpResponse, HttpServer};
+//!
+//! #[get("/index.html")]
+//! async fn index(req: HttpRequest) -> &'static str {
+//!     "<p>Hello World!</p>"
+//! }
+//!
+//! #[actix_web::main]
+//! async fn main() -> std::io::Result<()> {
+//!     HttpServer::new(|| {
+//!         let cors = Cors::default()
+//!               .allowed_origin("https://www.rust-lang.org/")
+//!               .allowed_origin_fn(|origin, _req_head| {
+//!                   origin.as_bytes().ends_with(b".rust-lang.org")
+//!               })
+//!               .allowed_methods(vec!["GET", "POST"])
+//!               .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
+//!               .allowed_header(http::header::CONTENT_TYPE)
+//!               .max_age(3600);
+//!
+//!         App::new()
+//!             .wrap(cors)
+//!             .service(index)
+//!     })
+//!     .bind(("127.0.0.1", 8080))?
+//!     .run()
+//!     .await;
+//!
+//!     Ok(())
+//! }
+//! ```
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style)]
-#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
-#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
-#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
 
-mod all_or_some;
-mod builder;
-mod error;
-mod inner;
-mod middleware;
+mod all_or_some;
+mod builder;
+mod error;
+mod inner;
+mod middleware;
 
-use all_or_some::AllOrSome;
-pub use builder::Cors;
-pub use error::CorsError;
-use inner::{Inner, OriginFn};
-pub use middleware::CorsMiddleware;
+use all_or_some::AllOrSome;
+pub use builder::Cors;
+pub use error::CorsError;
+use inner::{Inner, OriginFn};
+pub use middleware::CorsMiddleware;
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_cors/middleware.rs.html b/src/actix_cors/middleware.rs.html index 568faf4da..c4716cd27 100644 --- a/src/actix_cors/middleware.rs.html +++ b/src/actix_cors/middleware.rs.html @@ -263,268 +263,268 @@ 261 262 263 -
use std::{collections::HashSet, rc::Rc};
+
use std::{collections::HashSet, rc::Rc};
 
-use actix_utils::future::ok;
-use actix_web::{
-    body::{EitherBody, MessageBody},
-    dev::{forward_ready, Service, ServiceRequest, ServiceResponse},
-    http::{
-        header::{self, HeaderValue},
-        Method,
+use actix_utils::future::ok;
+use actix_web::{
+    body::{EitherBody, MessageBody},
+    dev::{forward_ready, Service, ServiceRequest, ServiceResponse},
+    http::{
+        header::{self, HeaderValue},
+        Method,
     },
-    Error, HttpResponse, Result,
+    Error, HttpResponse, Result,
 };
-use futures_util::future::{FutureExt as _, LocalBoxFuture};
-use log::debug;
+use futures_util::future::{FutureExt as _, LocalBoxFuture};
+use log::debug;
 
-use crate::{
-    builder::intersperse_header_values,
-    inner::{add_vary_header, header_value_try_into_method},
-    AllOrSome, Inner,
+use crate::{
+    builder::intersperse_header_values,
+    inner::{add_vary_header, header_value_try_into_method},
+    AllOrSome, Inner,
 };
 
-/// Service wrapper for Cross-Origin Resource Sharing support.
-///
-/// This struct contains the settings for CORS requests to be validated and for responses to
-/// be generated.
-#[doc(hidden)]
-#[derive(Debug, Clone)]
-pub struct CorsMiddleware<S> {
-    pub(crate) service: S,
-    pub(crate) inner: Rc<Inner>,
+/// Service wrapper for Cross-Origin Resource Sharing support.
+///
+/// This struct contains the settings for CORS requests to be validated and for responses to
+/// be generated.
+#[doc(hidden)]
+#[derive(Debug, Clone)]
+pub struct CorsMiddleware<S> {
+    pub(crate) service: S,
+    pub(crate) inner: Rc<Inner>,
 }
 
-impl<S> CorsMiddleware<S> {
-    /// Returns true if request is `OPTIONS` and contains an `Access-Control-Request-Method` header.
-    fn is_request_preflight(req: &ServiceRequest) -> bool {
-        // check request method is OPTIONS
-        if req.method() != Method::OPTIONS {
-            return false;
+impl<S> CorsMiddleware<S> {
+    /// Returns true if request is `OPTIONS` and contains an `Access-Control-Request-Method` header.
+    fn is_request_preflight(req: &ServiceRequest) -> bool {
+        // check request method is OPTIONS
+        if req.method() != Method::OPTIONS {
+            return false;
         }
 
-        // check follow-up request method is present and valid
-        if req
-            .headers()
-            .get(header::ACCESS_CONTROL_REQUEST_METHOD)
-            .and_then(header_value_try_into_method)
-            .is_none()
+        // check follow-up request method is present and valid
+        if req
+            .headers()
+            .get(header::ACCESS_CONTROL_REQUEST_METHOD)
+            .and_then(header_value_try_into_method)
+            .is_none()
         {
-            return false;
+            return false;
         }
 
-        true
-    }
+        true
+    }
 
-    /// Validates preflight request headers against configuration and constructs preflight response.
-    ///
-    /// Checks:
-    /// - `Origin` header is acceptable;
-    /// - `Access-Control-Request-Method` header is acceptable;
-    /// - `Access-Control-Request-Headers` header is acceptable.
-    fn handle_preflight(&self, req: ServiceRequest) -> ServiceResponse {
-        let inner = Rc::clone(&self.inner);
+    /// Validates preflight request headers against configuration and constructs preflight response.
+    ///
+    /// Checks:
+    /// - `Origin` header is acceptable;
+    /// - `Access-Control-Request-Method` header is acceptable;
+    /// - `Access-Control-Request-Headers` header is acceptable.
+    fn handle_preflight(&self, req: ServiceRequest) -> ServiceResponse {
+        let inner = Rc::clone(&self.inner);
 
-        if let Err(err) = inner
-            .validate_origin(req.head())
-            .and_then(|_| inner.validate_allowed_method(req.head()))
-            .and_then(|_| inner.validate_allowed_headers(req.head()))
+        if let Err(err) = inner
+            .validate_origin(req.head())
+            .and_then(|_| inner.validate_allowed_method(req.head()))
+            .and_then(|_| inner.validate_allowed_headers(req.head()))
         {
-            return req.error_response(err);
+            return req.error_response(err);
         }
 
-        let mut res = HttpResponse::Ok();
+        let mut res = HttpResponse::Ok();
 
-        if let Some(origin) = inner.access_control_allow_origin(req.head()) {
-            res.insert_header((header::ACCESS_CONTROL_ALLOW_ORIGIN, origin));
+        if let Some(origin) = inner.access_control_allow_origin(req.head()) {
+            res.insert_header((header::ACCESS_CONTROL_ALLOW_ORIGIN, origin));
         }
 
-        if let Some(ref allowed_methods) = inner.allowed_methods_baked {
-            res.insert_header((
-                header::ACCESS_CONTROL_ALLOW_METHODS,
-                allowed_methods.clone(),
+        if let Some(ref allowed_methods) = inner.allowed_methods_baked {
+            res.insert_header((
+                header::ACCESS_CONTROL_ALLOW_METHODS,
+                allowed_methods.clone(),
             ));
         }
 
-        if let Some(ref headers) = inner.allowed_headers_baked {
-            res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
-        } else if let Some(headers) = req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) {
-            // all headers allowed, return
-            res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
+        if let Some(ref headers) = inner.allowed_headers_baked {
+            res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
+        } else if let Some(headers) = req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) {
+            // all headers allowed, return
+            res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
         }
 
-        if inner.supports_credentials {
-            res.insert_header((
-                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
-                HeaderValue::from_static("true"),
+        if inner.supports_credentials {
+            res.insert_header((
+                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
+                HeaderValue::from_static("true"),
             ));
         }
 
-        if let Some(max_age) = inner.max_age {
-            res.insert_header((header::ACCESS_CONTROL_MAX_AGE, max_age.to_string()));
+        if let Some(max_age) = inner.max_age {
+            res.insert_header((header::ACCESS_CONTROL_MAX_AGE, max_age.to_string()));
         }
 
-        let mut res = res.finish();
+        let mut res = res.finish();
 
-        if inner.vary_header {
-            add_vary_header(res.headers_mut());
+        if inner.vary_header {
+            add_vary_header(res.headers_mut());
         }
 
-        req.into_response(res)
+        req.into_response(res)
     }
 
-    fn augment_response<B>(inner: &Inner, mut res: ServiceResponse<B>) -> ServiceResponse<B> {
-        if let Some(origin) = inner.access_control_allow_origin(res.request().head()) {
-            res.headers_mut()
-                .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
+    fn augment_response<B>(inner: &Inner, mut res: ServiceResponse<B>) -> ServiceResponse<B> {
+        if let Some(origin) = inner.access_control_allow_origin(res.request().head()) {
+            res.headers_mut()
+                .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
         };
 
-        if let Some(ref expose) = inner.expose_headers_baked {
-            log::trace!("exposing selected headers: {:?}", expose);
+        if let Some(ref expose) = inner.expose_headers_baked {
+            log::trace!("exposing selected headers: {:?}", expose);
 
-            res.headers_mut()
-                .insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, expose.clone());
-        } else if matches!(inner.expose_headers, AllOrSome::All) {
-            // intersperse_header_values requires that argument is non-empty
-            if !res.headers().is_empty() {
-                // extract header names from request
-                let expose_all_request_headers = res
-                    .headers()
-                    .keys()
-                    .into_iter()
-                    .map(|name| name.as_str())
-                    .collect::<HashSet<_>>();
+            res.headers_mut()
+                .insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, expose.clone());
+        } else if matches!(inner.expose_headers, AllOrSome::All) {
+            // intersperse_header_values requires that argument is non-empty
+            if !res.headers().is_empty() {
+                // extract header names from request
+                let expose_all_request_headers = res
+                    .headers()
+                    .keys()
+                    .into_iter()
+                    .map(|name| name.as_str())
+                    .collect::<HashSet<_>>();
 
-                // create comma separated string of header names
-                let expose_headers_value = intersperse_header_values(&expose_all_request_headers);
+                // create comma separated string of header names
+                let expose_headers_value = intersperse_header_values(&expose_all_request_headers);
 
                 log::trace!(
                     "exposing all headers from request: {:?}",
-                    expose_headers_value
+                    expose_headers_value
                 );
 
-                // add header names to expose response header
-                res.headers_mut()
-                    .insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, expose_headers_value);
+                // add header names to expose response header
+                res.headers_mut()
+                    .insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, expose_headers_value);
             }
         }
 
-        if inner.supports_credentials {
-            res.headers_mut().insert(
-                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
-                HeaderValue::from_static("true"),
+        if inner.supports_credentials {
+            res.headers_mut().insert(
+                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
+                HeaderValue::from_static("true"),
             );
         }
 
-        if inner.vary_header {
-            add_vary_header(res.headers_mut());
+        if inner.vary_header {
+            add_vary_header(res.headers_mut());
         }
 
-        res
+        res
     }
 }
 
-impl<S, B> Service<ServiceRequest> for CorsMiddleware<S>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
-    S::Future: 'static,
+impl<S, B> Service<ServiceRequest> for CorsMiddleware<S>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
+    S::Future: 'static,
 
-    B: MessageBody + 'static,
+    B: MessageBody + 'static,
 {
-    type Response = ServiceResponse<EitherBody<B>>;
-    type Error = Error;
-    type Future = LocalBoxFuture<'static, Result<ServiceResponse<EitherBody<B>>, Error>>;
+    type Response = ServiceResponse<EitherBody<B>>;
+    type Error = Error;
+    type Future = LocalBoxFuture<'static, Result<ServiceResponse<EitherBody<B>>, Error>>;
 
-    forward_ready!(service);
+    forward_ready!(service);
 
-    fn call(&self, req: ServiceRequest) -> Self::Future {
-        let origin = req.headers().get(header::ORIGIN);
+    fn call(&self, req: ServiceRequest) -> Self::Future {
+        let origin = req.headers().get(header::ORIGIN);
 
-        // handle preflight requests
-        if self.inner.preflight && Self::is_request_preflight(&req) {
-            let res = self.handle_preflight(req);
-            return ok(res.map_into_right_body()).boxed_local();
+        // handle preflight requests
+        if self.inner.preflight && Self::is_request_preflight(&req) {
+            let res = self.handle_preflight(req);
+            return ok(res.map_into_right_body()).boxed_local();
         }
 
-        // only check actual requests with a origin header
-        if origin.is_some() {
-            if let Err(err) = self.inner.validate_origin(req.head()) {
+        // only check actual requests with a origin header
+        if origin.is_some() {
+            if let Err(err) = self.inner.validate_origin(req.head()) {
                 debug!("origin validation failed; inner service is not called");
-                let mut res = req.error_response(err);
+                let mut res = req.error_response(err);
 
-                if self.inner.vary_header {
-                    add_vary_header(res.headers_mut());
+                if self.inner.vary_header {
+                    add_vary_header(res.headers_mut());
                 }
 
-                return ok(res.map_into_right_body()).boxed_local();
+                return ok(res.map_into_right_body()).boxed_local();
             }
         }
 
-        let inner = Rc::clone(&self.inner);
-        let fut = self.service.call(req);
+        let inner = Rc::clone(&self.inner);
+        let fut = self.service.call(req);
 
-        Box::pin(async move {
-            let res = fut.await;
-            Ok(Self::augment_response(&inner, res?).map_into_left_body())
+        Box::pin(async move {
+            let res = fut.await;
+            Ok(Self::augment_response(&inner, res?).map_into_left_body())
         })
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use actix_web::{
-        dev::Transform,
-        middleware::Compat,
-        test::{self, TestRequest},
-        App,
+#[cfg(test)]
+mod tests {
+    use actix_web::{
+        dev::Transform,
+        middleware::Compat,
+        test::{self, TestRequest},
+        App,
     };
 
-    use super::*;
-    use crate::Cors;
+    use super::*;
+    use crate::Cors;
 
-    #[test]
-    fn compat_compat() {
-        let _ = App::new().wrap(Compat::new(Cors::default()));
+    #[test]
+    fn compat_compat() {
+        let _ = App::new().wrap(Compat::new(Cors::default()));
     }
 
-    #[actix_web::test]
-    async fn test_options_no_origin() {
-        // Tests case where allowed_origins is All but there are validate functions to run incase.
-        // In this case, origins are only allowed when the DNT header is sent.
+    #[actix_web::test]
+    async fn test_options_no_origin() {
+        // Tests case where allowed_origins is All but there are validate functions to run incase.
+        // In this case, origins are only allowed when the DNT header is sent.
 
-        let cors = Cors::default()
-            .allow_any_origin()
-            .allowed_origin_fn(|origin, req_head| {
-                assert_eq!(&origin, req_head.headers.get(header::ORIGIN).unwrap());
-                req_head.headers().contains_key(header::DNT)
+        let cors = Cors::default()
+            .allow_any_origin()
+            .allowed_origin_fn(|origin, req_head| {
+                assert_eq!(&origin, req_head.headers.get(header::ORIGIN).unwrap());
+                req_head.headers().contains_key(header::DNT)
             })
-            .new_transform(test::ok_service())
-            .await
-            .unwrap();
+            .new_transform(test::ok_service())
+            .await
+            .unwrap();
 
-        let req = TestRequest::get()
-            .insert_header((header::ORIGIN, "http://example.com"))
-            .to_srv_request();
-        let res = cors.call(req).await.unwrap();
+        let req = TestRequest::get()
+            .insert_header((header::ORIGIN, "http://example.com"))
+            .to_srv_request();
+        let res = cors.call(req).await.unwrap();
         assert_eq!(
             None,
-            res.headers()
-                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
-                .map(HeaderValue::as_bytes)
+            res.headers()
+                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+                .map(HeaderValue::as_bytes)
         );
 
-        let req = TestRequest::get()
-            .insert_header((header::ORIGIN, "http://example.com"))
-            .insert_header((header::DNT, "1"))
-            .to_srv_request();
-        let res = cors.call(req).await.unwrap();
+        let req = TestRequest::get()
+            .insert_header((header::ORIGIN, "http://example.com"))
+            .insert_header((header::DNT, "1"))
+            .to_srv_request();
+        let res = cors.call(req).await.unwrap();
         assert_eq!(
             Some(&b"http://example.com"[..]),
-            res.headers()
-                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
-                .map(HeaderValue::as_bytes)
+            res.headers()
+                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+                .map(HeaderValue::as_bytes)
         );
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_identity/config.rs.html b/src/actix_identity/config.rs.html index bc059cf9a..3256c4776 100644 --- a/src/actix_identity/config.rs.html +++ b/src/actix_identity/config.rs.html @@ -99,106 +99,106 @@ 99 100 101 -
//! Configuration options to tune the behaviour of [`IdentityMiddleware`].
+
//! Configuration options to tune the behaviour of [`IdentityMiddleware`].
 
-use std::time::Duration;
+use std::time::Duration;
 
-use crate::IdentityMiddleware;
+use crate::IdentityMiddleware;
 
-#[derive(Debug, Clone)]
-pub(crate) struct Configuration {
-    pub(crate) on_logout: LogoutBehaviour,
-    pub(crate) login_deadline: Option<Duration>,
-    pub(crate) visit_deadline: Option<Duration>,
+#[derive(Debug, Clone)]
+pub(crate) struct Configuration {
+    pub(crate) on_logout: LogoutBehaviour,
+    pub(crate) login_deadline: Option<Duration>,
+    pub(crate) visit_deadline: Option<Duration>,
 }
 
-impl Default for Configuration {
-    fn default() -> Self {
-        Self {
-            on_logout: LogoutBehaviour::PurgeSession,
-            login_deadline: None,
-            visit_deadline: None,
+impl Default for Configuration {
+    fn default() -> Self {
+        Self {
+            on_logout: LogoutBehaviour::PurgeSession,
+            login_deadline: None,
+            visit_deadline: None,
         }
     }
 }
 
-/// `LogoutBehaviour` controls what actions are going to be performed when [`Identity::logout`] is
-/// invoked.
-///
-/// [`Identity::logout`]: crate::Identity::logout
-#[derive(Debug, Clone)]
-#[non_exhaustive]
-pub enum LogoutBehaviour {
-    /// When [`Identity::logout`](crate::Identity::logout) is called, purge the current session.
-    ///
-    /// This behaviour might be desirable when you have stored additional information in the
-    /// session state that are tied to the user's identity and should not be retained after logout.
-    PurgeSession,
+/// `LogoutBehaviour` controls what actions are going to be performed when [`Identity::logout`] is
+/// invoked.
+///
+/// [`Identity::logout`]: crate::Identity::logout
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub enum LogoutBehaviour {
+    /// When [`Identity::logout`](crate::Identity::logout) is called, purge the current session.
+    ///
+    /// This behaviour might be desirable when you have stored additional information in the
+    /// session state that are tied to the user's identity and should not be retained after logout.
+    PurgeSession,
 
-    /// When [`Identity::logout`](crate::Identity::logout) is called, remove the identity
-    /// information from the current session state. The session itself is not destroyed.
-    ///
-    /// This behaviour might be desirable when you have stored information in the session state that
-    /// is not tied to the user's identity and should be retained after logout.
-    DeleteIdentityKeys,
+    /// When [`Identity::logout`](crate::Identity::logout) is called, remove the identity
+    /// information from the current session state. The session itself is not destroyed.
+    ///
+    /// This behaviour might be desirable when you have stored information in the session state that
+    /// is not tied to the user's identity and should be retained after logout.
+    DeleteIdentityKeys,
 }
 
-/// A fluent builder to construct an [`IdentityMiddleware`] instance with custom configuration
-/// parameters.
-///
-/// Use [`IdentityMiddleware::builder`] to get started!
-#[derive(Debug, Clone)]
-pub struct IdentityMiddlewareBuilder {
-    configuration: Configuration,
+/// A fluent builder to construct an [`IdentityMiddleware`] instance with custom configuration
+/// parameters.
+///
+/// Use [`IdentityMiddleware::builder`] to get started!
+#[derive(Debug, Clone)]
+pub struct IdentityMiddlewareBuilder {
+    configuration: Configuration,
 }
 
-impl IdentityMiddlewareBuilder {
-    pub(crate) fn new() -> Self {
-        Self {
-            configuration: Configuration::default(),
+impl IdentityMiddlewareBuilder {
+    pub(crate) fn new() -> Self {
+        Self {
+            configuration: Configuration::default(),
         }
     }
 
-    /// Determines how [`Identity::logout`](crate::Identity::logout) affects the current session.
-    ///
-    /// By default, the current session is purged ([`LogoutBehaviour::PurgeSession`]).
-    pub fn logout_behaviour(mut self, logout_behaviour: LogoutBehaviour) -> Self {
-        self.configuration.on_logout = logout_behaviour;
-        self
-    }
+    /// Determines how [`Identity::logout`](crate::Identity::logout) affects the current session.
+    ///
+    /// By default, the current session is purged ([`LogoutBehaviour::PurgeSession`]).
+    pub fn logout_behaviour(mut self, logout_behaviour: LogoutBehaviour) -> Self {
+        self.configuration.on_logout = logout_behaviour;
+        self
+    }
 
-    /// Automatically logs out users after a certain amount of time has passed since they logged in,
-    /// regardless of their activity pattern.
-    ///
-    /// If set to:
-    /// - `None`: login deadline is disabled.
-    /// - `Some(duration)`: login deadline is enabled and users will be logged out after `duration`
-    ///   has passed since their login.
-    ///
-    /// By default, login deadline is disabled.
-    pub fn login_deadline(mut self, deadline: Option<Duration>) -> Self {
-        self.configuration.login_deadline = deadline;
-        self
-    }
+    /// Automatically logs out users after a certain amount of time has passed since they logged in,
+    /// regardless of their activity pattern.
+    ///
+    /// If set to:
+    /// - `None`: login deadline is disabled.
+    /// - `Some(duration)`: login deadline is enabled and users will be logged out after `duration`
+    ///   has passed since their login.
+    ///
+    /// By default, login deadline is disabled.
+    pub fn login_deadline(mut self, deadline: Option<Duration>) -> Self {
+        self.configuration.login_deadline = deadline;
+        self
+    }
 
-    /// Automatically logs out users after a certain amount of time has passed since their last
-    /// visit.
-    ///
-    /// If set to:
-    /// - `None`: visit deadline is disabled.
-    /// - `Some(duration)`: visit deadline is enabled and users will be logged out after `duration`
-    ///   has passed since their last visit.
-    ///
-    /// By default, visit deadline is disabled.
-    pub fn visit_deadline(mut self, deadline: Option<Duration>) -> Self {
-        self.configuration.visit_deadline = deadline;
-        self
-    }
+    /// Automatically logs out users after a certain amount of time has passed since their last
+    /// visit.
+    ///
+    /// If set to:
+    /// - `None`: visit deadline is disabled.
+    /// - `Some(duration)`: visit deadline is enabled and users will be logged out after `duration`
+    ///   has passed since their last visit.
+    ///
+    /// By default, visit deadline is disabled.
+    pub fn visit_deadline(mut self, deadline: Option<Duration>) -> Self {
+        self.configuration.visit_deadline = deadline;
+        self
+    }
 
-    /// Finalises the builder and returns an [`IdentityMiddleware`] instance.
-    pub fn build(self) -> IdentityMiddleware {
-        IdentityMiddleware::new(self.configuration)
+    /// Finalises the builder and returns an [`IdentityMiddleware`] instance.
+    pub fn build(self) -> IdentityMiddleware {
+        IdentityMiddleware::new(self.configuration)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_identity/identity.rs.html b/src/actix_identity/identity.rs.html index a67a6a775..d764a2f5f 100644 --- a/src/actix_identity/identity.rs.html +++ b/src/actix_identity/identity.rs.html @@ -263,92 +263,92 @@ 263 264 265 -
use actix_session::Session;
-use actix_utils::future::{ready, Ready};
-use actix_web::{
-    cookie::time::OffsetDateTime,
-    dev::{Extensions, Payload},
-    http::StatusCode,
-    Error, FromRequest, HttpMessage, HttpRequest, HttpResponse,
+
use actix_session::Session;
+use actix_utils::future::{ready, Ready};
+use actix_web::{
+    cookie::time::OffsetDateTime,
+    dev::{Extensions, Payload},
+    http::StatusCode,
+    Error, FromRequest, HttpMessage, HttpRequest, HttpResponse,
 };
-use anyhow::{anyhow, Context};
+use anyhow::{anyhow, Context};
 
-use crate::config::LogoutBehaviour;
+use crate::config::LogoutBehaviour;
 
-/// A verified user identity. It can be used as a request extractor.
-///
-/// The lifecycle of a user identity is tied to the lifecycle of the underlying session. If the
-/// session is destroyed (e.g. the session expired), the user identity will be forgotten, de-facto
-/// forcing a user log out.
-///
-/// # Examples
-/// ```
-/// use actix_web::{
-///     get, post, Responder, HttpRequest, HttpMessage, HttpResponse
-/// };
-/// use actix_identity::Identity;
-///
-/// #[get("/")]
-/// async fn index(user: Option<Identity>) -> impl Responder {
-///     if let Some(user) = user {
-///         format!("Welcome! {}", user.id().unwrap())
-///     } else {
-///         "Welcome Anonymous!".to_owned()
-///     }
-/// }
-///
-/// #[post("/login")]
-/// async fn login(request: HttpRequest) -> impl Responder {
-///     Identity::login(&request.extensions(), "User1".into());
-///     HttpResponse::Ok()
-/// }
-///
-/// #[post("/logout")]
-/// async fn logout(user: Identity) -> impl Responder {
-///     user.logout();
-///     HttpResponse::Ok()
-/// }
-/// ```
-///
-/// # Extractor Behaviour
-/// What happens if you try to extract an `Identity` out of a request that does not have a valid
-/// identity attached? The API will return a `401 UNAUTHORIZED` to the caller.
-///
-/// If you want to customise this behaviour, consider extracting `Option<Identity>` or
-/// `Result<Identity, actix_web::Error>` instead of a bare `Identity`: you will then be fully in
-/// control of the error path.
-///
-/// ## Examples
-/// ```
-/// use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
-/// use actix_identity::Identity;
-///
-/// #[get("/")]
-/// async fn index(user: Option<Identity>) -> impl Responder {
-///     if let Some(user) = user {
-///         HttpResponse::Ok().finish()
-///     } else {
-///         // Redirect to login page if unauthenticated
-///         HttpResponse::TemporaryRedirect()
-///             .insert_header((LOCATION, "/login"))
-///             .finish()
-///     }
-/// }
-/// ```
-pub struct Identity(IdentityInner);
+/// A verified user identity. It can be used as a request extractor.
+///
+/// The lifecycle of a user identity is tied to the lifecycle of the underlying session. If the
+/// session is destroyed (e.g. the session expired), the user identity will be forgotten, de-facto
+/// forcing a user log out.
+///
+/// # Examples
+/// ```
+/// use actix_web::{
+///     get, post, Responder, HttpRequest, HttpMessage, HttpResponse
+/// };
+/// use actix_identity::Identity;
+///
+/// #[get("/")]
+/// async fn index(user: Option<Identity>) -> impl Responder {
+///     if let Some(user) = user {
+///         format!("Welcome! {}", user.id().unwrap())
+///     } else {
+///         "Welcome Anonymous!".to_owned()
+///     }
+/// }
+///
+/// #[post("/login")]
+/// async fn login(request: HttpRequest) -> impl Responder {
+///     Identity::login(&request.extensions(), "User1".into());
+///     HttpResponse::Ok()
+/// }
+///
+/// #[post("/logout")]
+/// async fn logout(user: Identity) -> impl Responder {
+///     user.logout();
+///     HttpResponse::Ok()
+/// }
+/// ```
+///
+/// # Extractor Behaviour
+/// What happens if you try to extract an `Identity` out of a request that does not have a valid
+/// identity attached? The API will return a `401 UNAUTHORIZED` to the caller.
+///
+/// If you want to customise this behaviour, consider extracting `Option<Identity>` or
+/// `Result<Identity, actix_web::Error>` instead of a bare `Identity`: you will then be fully in
+/// control of the error path.
+///
+/// ## Examples
+/// ```
+/// use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
+/// use actix_identity::Identity;
+///
+/// #[get("/")]
+/// async fn index(user: Option<Identity>) -> impl Responder {
+///     if let Some(user) = user {
+///         HttpResponse::Ok().finish()
+///     } else {
+///         // Redirect to login page if unauthenticated
+///         HttpResponse::TemporaryRedirect()
+///             .insert_header((LOCATION, "/login"))
+///             .finish()
+///     }
+/// }
+/// ```
+pub struct Identity(IdentityInner);
 
-#[derive(Clone)]
-pub(crate) struct IdentityInner {
-    pub(crate) session: Session,
-    pub(crate) logout_behaviour: LogoutBehaviour,
-    pub(crate) is_login_deadline_enabled: bool,
-    pub(crate) is_visit_deadline_enabled: bool,
+#[derive(Clone)]
+pub(crate) struct IdentityInner {
+    pub(crate) session: Session,
+    pub(crate) logout_behaviour: LogoutBehaviour,
+    pub(crate) is_login_deadline_enabled: bool,
+    pub(crate) is_visit_deadline_enabled: bool,
 }
 
-impl IdentityInner {
-    fn extract(ext: &Extensions) -> Self {
-        ext.get::<Self>()
-            .expect(
+impl IdentityInner {
+    fn extract(ext: &Extensions) -> Self {
+        ext.get::<Self>()
+            .expect(
                 "No `IdentityInner` instance was found in the extensions attached to the \
                 incoming request. This usually means that `IdentityMiddleware` has not been \
                 registered as an application middleware via `App::wrap`. `Identity` cannot be used \
@@ -356,177 +356,177 @@
                 a middleware for your application to fix this panic. If the problem persists, \
                 please file an issue on GitHub.",
             )
-            .to_owned()
+            .to_owned()
     }
 
-    /// Retrieve the user id attached to the current session.
-    fn get_identity(&self) -> Result<String, anyhow::Error> {
-        self.session
-            .get::<String>(ID_KEY)
-            .context("Failed to deserialize the user identifier attached to the current session")?
-            .ok_or_else(|| {
+    /// Retrieve the user id attached to the current session.
+    fn get_identity(&self) -> Result<String, anyhow::Error> {
+        self.session
+            .get::<String>(ID_KEY)
+            .context("Failed to deserialize the user identifier attached to the current session")?
+            .ok_or_else(|| {
                 anyhow!("There is no identity information attached to the current session")
             })
     }
 }
 
-pub(crate) const ID_KEY: &str = "actix_identity.user_id";
-pub(crate) const LAST_VISIT_UNIX_TIMESTAMP_KEY: &str = "actix_identity.last_visited_at";
-pub(crate) const LOGIN_UNIX_TIMESTAMP_KEY: &str = "actix_identity.logged_in_at";
+pub(crate) const ID_KEY: &str = "actix_identity.user_id";
+pub(crate) const LAST_VISIT_UNIX_TIMESTAMP_KEY: &str = "actix_identity.last_visited_at";
+pub(crate) const LOGIN_UNIX_TIMESTAMP_KEY: &str = "actix_identity.logged_in_at";
 
-impl Identity {
-    /// Return the user id associated to the current session.
-    ///
-    /// # Examples
-    /// ```
-    /// use actix_web::{get, Responder};
-    /// use actix_identity::Identity;
-    ///
-    /// #[get("/")]
-    /// async fn index(user: Option<Identity>) -> impl Responder {
-    ///     if let Some(user) = user {
-    ///         format!("Welcome! {}", user.id().unwrap())
-    ///     } else {
-    ///         "Welcome Anonymous!".to_owned()
-    ///     }
-    /// }
-    /// ```
-    pub fn id(&self) -> Result<String, anyhow::Error> {
-        self.0.session.get(ID_KEY)?.ok_or_else(|| {
+impl Identity {
+    /// Return the user id associated to the current session.
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_web::{get, Responder};
+    /// use actix_identity::Identity;
+    ///
+    /// #[get("/")]
+    /// async fn index(user: Option<Identity>) -> impl Responder {
+    ///     if let Some(user) = user {
+    ///         format!("Welcome! {}", user.id().unwrap())
+    ///     } else {
+    ///         "Welcome Anonymous!".to_owned()
+    ///     }
+    /// }
+    /// ```
+    pub fn id(&self) -> Result<String, anyhow::Error> {
+        self.0.session.get(ID_KEY)?.ok_or_else(|| {
             anyhow!("Bug: the identity information attached to the current session has disappeared")
         })
     }
 
-    /// Attach a valid user identity to the current session.
-    ///
-    /// This method should be called after you have successfully authenticated the user. After
-    /// `login` has been called, the user will be able to access all routes that require a valid
-    /// [`Identity`].
-    ///
-    /// # Examples
-    /// ```
-    /// use actix_web::{post, Responder, HttpRequest, HttpMessage, HttpResponse};
-    /// use actix_identity::Identity;
-    ///
-    /// #[post("/login")]
-    /// async fn login(request: HttpRequest) -> impl Responder {
-    ///     Identity::login(&request.extensions(), "User1".into());
-    ///     HttpResponse::Ok()
-    /// }
-    /// ```
-    pub fn login(ext: &Extensions, id: String) -> Result<Self, anyhow::Error> {
-        let inner = IdentityInner::extract(ext);
-        inner.session.insert(ID_KEY, id)?;
-        let now = OffsetDateTime::now_utc().unix_timestamp();
-        if inner.is_login_deadline_enabled {
-            inner.session.insert(LOGIN_UNIX_TIMESTAMP_KEY, now)?;
+    /// Attach a valid user identity to the current session.
+    ///
+    /// This method should be called after you have successfully authenticated the user. After
+    /// `login` has been called, the user will be able to access all routes that require a valid
+    /// [`Identity`].
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_web::{post, Responder, HttpRequest, HttpMessage, HttpResponse};
+    /// use actix_identity::Identity;
+    ///
+    /// #[post("/login")]
+    /// async fn login(request: HttpRequest) -> impl Responder {
+    ///     Identity::login(&request.extensions(), "User1".into());
+    ///     HttpResponse::Ok()
+    /// }
+    /// ```
+    pub fn login(ext: &Extensions, id: String) -> Result<Self, anyhow::Error> {
+        let inner = IdentityInner::extract(ext);
+        inner.session.insert(ID_KEY, id)?;
+        let now = OffsetDateTime::now_utc().unix_timestamp();
+        if inner.is_login_deadline_enabled {
+            inner.session.insert(LOGIN_UNIX_TIMESTAMP_KEY, now)?;
         }
-        if inner.is_visit_deadline_enabled {
-            inner.session.insert(LAST_VISIT_UNIX_TIMESTAMP_KEY, now)?;
+        if inner.is_visit_deadline_enabled {
+            inner.session.insert(LAST_VISIT_UNIX_TIMESTAMP_KEY, now)?;
         }
-        inner.session.renew();
-        Ok(Self(inner))
+        inner.session.renew();
+        Ok(Self(inner))
     }
 
-    /// Remove the user identity from the current session.
-    ///
-    /// After `logout` has been called, the user will no longer be able to access routes that
-    /// require a valid [`Identity`].
-    ///
-    /// The behaviour on logout is determined by [`IdentityMiddlewareBuilder::logout_behaviour`].
-    ///
-    /// # Examples
-    /// ```
-    /// use actix_web::{post, Responder, HttpResponse};
-    /// use actix_identity::Identity;
-    ///
-    /// #[post("/logout")]
-    /// async fn logout(user: Identity) -> impl Responder {
-    ///     user.logout();
-    ///     HttpResponse::Ok()
-    /// }
-    /// ```
-    ///
-    /// [`IdentityMiddlewareBuilder::logout_behaviour`]: crate::config::IdentityMiddlewareBuilder::logout_behaviour
-    pub fn logout(self) {
-        match self.0.logout_behaviour {
-            LogoutBehaviour::PurgeSession => {
-                self.0.session.purge();
+    /// Remove the user identity from the current session.
+    ///
+    /// After `logout` has been called, the user will no longer be able to access routes that
+    /// require a valid [`Identity`].
+    ///
+    /// The behaviour on logout is determined by [`IdentityMiddlewareBuilder::logout_behaviour`].
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_web::{post, Responder, HttpResponse};
+    /// use actix_identity::Identity;
+    ///
+    /// #[post("/logout")]
+    /// async fn logout(user: Identity) -> impl Responder {
+    ///     user.logout();
+    ///     HttpResponse::Ok()
+    /// }
+    /// ```
+    ///
+    /// [`IdentityMiddlewareBuilder::logout_behaviour`]: crate::config::IdentityMiddlewareBuilder::logout_behaviour
+    pub fn logout(self) {
+        match self.0.logout_behaviour {
+            LogoutBehaviour::PurgeSession => {
+                self.0.session.purge();
             }
-            LogoutBehaviour::DeleteIdentityKeys => {
-                self.0.session.remove(ID_KEY);
-                if self.0.is_login_deadline_enabled {
-                    self.0.session.remove(LOGIN_UNIX_TIMESTAMP_KEY);
+            LogoutBehaviour::DeleteIdentityKeys => {
+                self.0.session.remove(ID_KEY);
+                if self.0.is_login_deadline_enabled {
+                    self.0.session.remove(LOGIN_UNIX_TIMESTAMP_KEY);
                 }
-                if self.0.is_visit_deadline_enabled {
-                    self.0.session.remove(LAST_VISIT_UNIX_TIMESTAMP_KEY);
+                if self.0.is_visit_deadline_enabled {
+                    self.0.session.remove(LAST_VISIT_UNIX_TIMESTAMP_KEY);
                 }
             }
         }
     }
 
-    pub(crate) fn extract(ext: &Extensions) -> Result<Self, anyhow::Error> {
-        let inner = IdentityInner::extract(ext);
-        inner.get_identity()?;
-        Ok(Self(inner))
+    pub(crate) fn extract(ext: &Extensions) -> Result<Self, anyhow::Error> {
+        let inner = IdentityInner::extract(ext);
+        inner.get_identity()?;
+        Ok(Self(inner))
     }
 
-    pub(crate) fn logged_at(&self) -> Result<Option<OffsetDateTime>, anyhow::Error> {
-        self.0
-            .session
-            .get(LOGIN_UNIX_TIMESTAMP_KEY)?
-            .map(OffsetDateTime::from_unix_timestamp)
-            .transpose()
-            .map_err(anyhow::Error::from)
+    pub(crate) fn logged_at(&self) -> Result<Option<OffsetDateTime>, anyhow::Error> {
+        self.0
+            .session
+            .get(LOGIN_UNIX_TIMESTAMP_KEY)?
+            .map(OffsetDateTime::from_unix_timestamp)
+            .transpose()
+            .map_err(anyhow::Error::from)
     }
 
-    pub(crate) fn last_visited_at(&self) -> Result<Option<OffsetDateTime>, anyhow::Error> {
-        self.0
-            .session
-            .get(LAST_VISIT_UNIX_TIMESTAMP_KEY)?
-            .map(OffsetDateTime::from_unix_timestamp)
-            .transpose()
-            .map_err(anyhow::Error::from)
+    pub(crate) fn last_visited_at(&self) -> Result<Option<OffsetDateTime>, anyhow::Error> {
+        self.0
+            .session
+            .get(LAST_VISIT_UNIX_TIMESTAMP_KEY)?
+            .map(OffsetDateTime::from_unix_timestamp)
+            .transpose()
+            .map_err(anyhow::Error::from)
     }
 
-    pub(crate) fn set_last_visited_at(&self) -> Result<(), anyhow::Error> {
-        let now = OffsetDateTime::now_utc().unix_timestamp();
-        self.0.session.insert(LAST_VISIT_UNIX_TIMESTAMP_KEY, now)?;
+    pub(crate) fn set_last_visited_at(&self) -> Result<(), anyhow::Error> {
+        let now = OffsetDateTime::now_utc().unix_timestamp();
+        self.0.session.insert(LAST_VISIT_UNIX_TIMESTAMP_KEY, now)?;
         Ok(())
     }
 }
 
-/// Extractor implementation for [`Identity`].
-///
-/// # Examples
-/// ```
-/// use actix_web::{get, Responder};
-/// use actix_identity::Identity;
-///
-/// #[get("/")]
-/// async fn index(user: Option<Identity>) -> impl Responder {
-///     if let Some(user) = user {
-///         format!("Welcome! {}", user.id().unwrap())
-///     } else {
-///         "Welcome Anonymous!".to_owned()
-///     }
-/// }
-/// ```
-impl FromRequest for Identity {
-    type Error = Error;
-    type Future = Ready<Result<Self, Self::Error>>;
+/// Extractor implementation for [`Identity`].
+///
+/// # Examples
+/// ```
+/// use actix_web::{get, Responder};
+/// use actix_identity::Identity;
+///
+/// #[get("/")]
+/// async fn index(user: Option<Identity>) -> impl Responder {
+///     if let Some(user) = user {
+///         format!("Welcome! {}", user.id().unwrap())
+///     } else {
+///         "Welcome Anonymous!".to_owned()
+///     }
+/// }
+/// ```
+impl FromRequest for Identity {
+    type Error = Error;
+    type Future = Ready<Result<Self, Self::Error>>;
 
-    #[inline]
-    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
-        ready(Identity::extract(&req.extensions()).map_err(|err| {
-            let res = actix_web::error::InternalError::from_response(
-                err,
-                HttpResponse::new(StatusCode::UNAUTHORIZED),
+    #[inline]
+    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
+        ready(Identity::extract(&req.extensions()).map_err(|err| {
+            let res = actix_web::error::InternalError::from_response(
+                err,
+                HttpResponse::new(StatusCode::UNAUTHORIZED),
             );
 
-            actix_web::Error::from(res)
+            actix_web::Error::from(res)
         }))
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_identity/identity_ext.rs.html b/src/actix_identity/identity_ext.rs.html index d418f25d3..c5b32bf6e 100644 --- a/src/actix_identity/identity_ext.rs.html +++ b/src/actix_identity/identity_ext.rs.html @@ -25,32 +25,32 @@ 25 26 27 -
use actix_web::{dev::ServiceRequest, guard::GuardContext, HttpMessage, HttpRequest};
+
use actix_web::{dev::ServiceRequest, guard::GuardContext, HttpMessage, HttpRequest};
 
-use crate::Identity;
+use crate::Identity;
 
-/// Helper trait to retrieve an [`Identity`] instance from various `actix-web`'s types.
-pub trait IdentityExt {
-    /// Retrieve the identity attached to the current session, if available.
-    fn get_identity(&self) -> Result<Identity, anyhow::Error>;
+/// Helper trait to retrieve an [`Identity`] instance from various `actix-web`'s types.
+pub trait IdentityExt {
+    /// Retrieve the identity attached to the current session, if available.
+    fn get_identity(&self) -> Result<Identity, anyhow::Error>;
 }
 
-impl IdentityExt for HttpRequest {
-    fn get_identity(&self) -> Result<Identity, anyhow::Error> {
-        Identity::extract(&self.extensions())
+impl IdentityExt for HttpRequest {
+    fn get_identity(&self) -> Result<Identity, anyhow::Error> {
+        Identity::extract(&self.extensions())
     }
 }
 
-impl IdentityExt for ServiceRequest {
-    fn get_identity(&self) -> Result<Identity, anyhow::Error> {
-        Identity::extract(&self.extensions())
+impl IdentityExt for ServiceRequest {
+    fn get_identity(&self) -> Result<Identity, anyhow::Error> {
+        Identity::extract(&self.extensions())
     }
 }
 
-impl<'a> IdentityExt for GuardContext<'a> {
-    fn get_identity(&self) -> Result<Identity, anyhow::Error> {
-        Identity::extract(&self.req_data())
+impl<'a> IdentityExt for GuardContext<'a> {
+    fn get_identity(&self) -> Result<Identity, anyhow::Error> {
+        Identity::extract(&self.req_data())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_identity/lib.rs.html b/src/actix_identity/lib.rs.html index 5b6d08b84..c3710b866 100644 --- a/src/actix_identity/lib.rs.html +++ b/src/actix_identity/lib.rs.html @@ -98,105 +98,105 @@ 98 99 100 -
//! Identity management for Actix Web.
-//!
-//! `actix-identity` can be used to track identity of a user across multiple requests. It is built
-//! on top of HTTP sessions, via [`actix-session`](https://docs.rs/actix-session).
-//!
-//! # Getting started
-//! To start using identity management in your Actix Web application you must register
-//! [`IdentityMiddleware`] and `SessionMiddleware` as middleware on your `App`:
-//!
-//! ```no_run
-//! # use actix_web::web;
-//! use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
-//! use actix_identity::IdentityMiddleware;
-//! use actix_session::{storage::RedisSessionStore, SessionMiddleware};
-//!
-//! #[actix_web::main]
-//! async fn main() {
-//!     let secret_key = Key::generate();
-//!     let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
-//!         .await
-//!         .unwrap();
-//!
-//!     HttpServer::new(move || {
-//!         App::new()
-//!             // Install the identity framework first.
-//!             .wrap(IdentityMiddleware::default())
-//!             // The identity system is built on top of sessions. You must install the session
-//!             // middleware to leverage `actix-identity`. The session middleware must be mounted
-//!             // AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
-//!             // order of registration when it receives an incoming request.
-//!             .wrap(SessionMiddleware::new(
-//!                  redis_store.clone(),
-//!                  secret_key.clone()
-//!             ))
-//!             // Your request handlers [...]
-//!             # .default_service(web::to(|| HttpResponse::Ok()))
-//!     })
-//! # ;
-//! }
-//! ```
-//!
-//! User identities can be created, accessed and destroyed using the [`Identity`] extractor in your
-//! request handlers:
-//!
-//! ```no_run
-//! use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
-//! use actix_identity::Identity;
-//! use actix_session::storage::RedisSessionStore;
-//!
-//! #[get("/")]
-//! async fn index(user: Option<Identity>) -> impl Responder {
-//!     if let Some(user) = user {
-//!         format!("Welcome! {}", user.id().unwrap())
-//!     } else {
-//!         "Welcome Anonymous!".to_owned()
-//!     }
-//! }
-//!
-//! #[post("/login")]
-//! async fn login(request: HttpRequest) -> impl Responder {
-//!     // Some kind of authentication should happen here
-//!     // e.g. password-based, biometric, etc.
-//!     // [...]
-//!
-//!     // attach a verified user identity to the active session
-//!     Identity::login(&request.extensions(), "User1".into()).unwrap();
-//!
-//!     HttpResponse::Ok()
-//! }
-//!
-//! #[post("/logout")]
-//! async fn logout(user: Identity) -> impl Responder {
-//!     user.logout();
-//!     HttpResponse::Ok()
-//! }
-//! ```
-//!
-//! # Advanced configuration
-//! By default, `actix-identity` does not automatically log out users. You can change this behaviour
-//! by customising the configuration for [`IdentityMiddleware`] via [`IdentityMiddleware::builder`].
-//!
-//! In particular, you can automatically log out users who:
-//! - have been inactive for a while (see [`IdentityMiddlewareBuilder::visit_deadline`];
-//! - logged in too long ago (see [`IdentityMiddlewareBuilder::login_deadline`]).
-//!
-//! [`IdentityMiddlewareBuilder::visit_deadline`]: config::IdentityMiddlewareBuilder::visit_deadline
-//! [`IdentityMiddlewareBuilder::login_deadline`]: config::IdentityMiddlewareBuilder::login_deadline
+
//! Identity management for Actix Web.
+//!
+//! `actix-identity` can be used to track identity of a user across multiple requests. It is built
+//! on top of HTTP sessions, via [`actix-session`](https://docs.rs/actix-session).
+//!
+//! # Getting started
+//! To start using identity management in your Actix Web application you must register
+//! [`IdentityMiddleware`] and `SessionMiddleware` as middleware on your `App`:
+//!
+//! ```no_run
+//! # use actix_web::web;
+//! use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
+//! use actix_identity::IdentityMiddleware;
+//! use actix_session::{storage::RedisSessionStore, SessionMiddleware};
+//!
+//! #[actix_web::main]
+//! async fn main() {
+//!     let secret_key = Key::generate();
+//!     let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
+//!         .await
+//!         .unwrap();
+//!
+//!     HttpServer::new(move || {
+//!         App::new()
+//!             // Install the identity framework first.
+//!             .wrap(IdentityMiddleware::default())
+//!             // The identity system is built on top of sessions. You must install the session
+//!             // middleware to leverage `actix-identity`. The session middleware must be mounted
+//!             // AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
+//!             // order of registration when it receives an incoming request.
+//!             .wrap(SessionMiddleware::new(
+//!                  redis_store.clone(),
+//!                  secret_key.clone()
+//!             ))
+//!             // Your request handlers [...]
+//!             # .default_service(web::to(|| HttpResponse::Ok()))
+//!     })
+//! # ;
+//! }
+//! ```
+//!
+//! User identities can be created, accessed and destroyed using the [`Identity`] extractor in your
+//! request handlers:
+//!
+//! ```no_run
+//! use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
+//! use actix_identity::Identity;
+//! use actix_session::storage::RedisSessionStore;
+//!
+//! #[get("/")]
+//! async fn index(user: Option<Identity>) -> impl Responder {
+//!     if let Some(user) = user {
+//!         format!("Welcome! {}", user.id().unwrap())
+//!     } else {
+//!         "Welcome Anonymous!".to_owned()
+//!     }
+//! }
+//!
+//! #[post("/login")]
+//! async fn login(request: HttpRequest) -> impl Responder {
+//!     // Some kind of authentication should happen here
+//!     // e.g. password-based, biometric, etc.
+//!     // [...]
+//!
+//!     // attach a verified user identity to the active session
+//!     Identity::login(&request.extensions(), "User1".into()).unwrap();
+//!
+//!     HttpResponse::Ok()
+//! }
+//!
+//! #[post("/logout")]
+//! async fn logout(user: Identity) -> impl Responder {
+//!     user.logout();
+//!     HttpResponse::Ok()
+//! }
+//! ```
+//!
+//! # Advanced configuration
+//! By default, `actix-identity` does not automatically log out users. You can change this behaviour
+//! by customising the configuration for [`IdentityMiddleware`] via [`IdentityMiddleware::builder`].
+//!
+//! In particular, you can automatically log out users who:
+//! - have been inactive for a while (see [`IdentityMiddlewareBuilder::visit_deadline`];
+//! - logged in too long ago (see [`IdentityMiddlewareBuilder::login_deadline`]).
+//!
+//! [`IdentityMiddlewareBuilder::visit_deadline`]: config::IdentityMiddlewareBuilder::visit_deadline
+//! [`IdentityMiddlewareBuilder::login_deadline`]: config::IdentityMiddlewareBuilder::login_deadline
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style, missing_docs)]
-#![warn(future_incompatible)]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style, missing_docs)]
+#![warn(future_incompatible)]
 
-pub mod config;
-mod identity;
-mod identity_ext;
-mod middleware;
+pub mod config;
+mod identity;
+mod identity_ext;
+mod middleware;
 
-pub use self::identity::Identity;
-pub use self::identity_ext::IdentityExt;
-pub use self::middleware::IdentityMiddleware;
+pub use self::identity::Identity;
+pub use self::identity_ext::IdentityExt;
+pub use self::middleware::IdentityMiddleware;
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_identity/middleware.rs.html b/src/actix_identity/middleware.rs.html index e88572f76..bd235ee60 100644 --- a/src/actix_identity/middleware.rs.html +++ b/src/actix_identity/middleware.rs.html @@ -254,261 +254,261 @@ 254 255 256 -
use std::rc::Rc;
+
use std::rc::Rc;
 
-use actix_session::SessionExt;
-use actix_utils::future::{ready, Ready};
-use actix_web::{
-    body::MessageBody,
-    cookie::time::{format_description::well_known::Rfc3339, OffsetDateTime},
-    dev::{Service, ServiceRequest, ServiceResponse, Transform},
-    Error, HttpMessage as _, Result,
+use actix_session::SessionExt;
+use actix_utils::future::{ready, Ready};
+use actix_web::{
+    body::MessageBody,
+    cookie::time::{format_description::well_known::Rfc3339, OffsetDateTime},
+    dev::{Service, ServiceRequest, ServiceResponse, Transform},
+    Error, HttpMessage as _, Result,
 };
-use futures_core::future::LocalBoxFuture;
+use futures_core::future::LocalBoxFuture;
 
-use crate::{
-    config::{Configuration, IdentityMiddlewareBuilder},
-    identity::IdentityInner,
-    Identity,
+use crate::{
+    config::{Configuration, IdentityMiddlewareBuilder},
+    identity::IdentityInner,
+    Identity,
 };
 
-/// Identity management middleware.
-///
-/// ```no_run
-/// use actix_web::{cookie::Key, App, HttpServer};
-/// use actix_session::storage::RedisSessionStore;
-/// use actix_identity::{Identity, IdentityMiddleware};
-/// use actix_session::{Session, SessionMiddleware};
-///
-/// #[actix_web::main]
-/// async fn main() {
-///     let secret_key = Key::generate();
-///     let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379").await.unwrap();
-///
-///     HttpServer::new(move || {
-///        App::new()
-///            // Install the identity framework first.
-///            .wrap(IdentityMiddleware::default())
-///            // The identity system is built on top of sessions.
-///            // You must install the session middleware to leverage `actix-identity`.
-///            .wrap(SessionMiddleware::new(redis_store.clone(), secret_key.clone()))
-///     })
-/// # ;
-/// }
-/// ```
-#[derive(Default, Clone)]
-pub struct IdentityMiddleware {
-    configuration: Rc<Configuration>,
+/// Identity management middleware.
+///
+/// ```no_run
+/// use actix_web::{cookie::Key, App, HttpServer};
+/// use actix_session::storage::RedisSessionStore;
+/// use actix_identity::{Identity, IdentityMiddleware};
+/// use actix_session::{Session, SessionMiddleware};
+///
+/// #[actix_web::main]
+/// async fn main() {
+///     let secret_key = Key::generate();
+///     let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379").await.unwrap();
+///
+///     HttpServer::new(move || {
+///        App::new()
+///            // Install the identity framework first.
+///            .wrap(IdentityMiddleware::default())
+///            // The identity system is built on top of sessions.
+///            // You must install the session middleware to leverage `actix-identity`.
+///            .wrap(SessionMiddleware::new(redis_store.clone(), secret_key.clone()))
+///     })
+/// # ;
+/// }
+/// ```
+#[derive(Default, Clone)]
+pub struct IdentityMiddleware {
+    configuration: Rc<Configuration>,
 }
 
-impl IdentityMiddleware {
-    pub(crate) fn new(configuration: Configuration) -> Self {
-        Self {
-            configuration: Rc::new(configuration),
+impl IdentityMiddleware {
+    pub(crate) fn new(configuration: Configuration) -> Self {
+        Self {
+            configuration: Rc::new(configuration),
         }
     }
 
-    /// A fluent API to configure [`IdentityMiddleware`].
-    pub fn builder() -> IdentityMiddlewareBuilder {
-        IdentityMiddlewareBuilder::new()
+    /// A fluent API to configure [`IdentityMiddleware`].
+    pub fn builder() -> IdentityMiddlewareBuilder {
+        IdentityMiddlewareBuilder::new()
     }
 }
 
-impl<S, B> Transform<S, ServiceRequest> for IdentityMiddleware
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
-    S::Future: 'static,
-    B: MessageBody + 'static,
+impl<S, B> Transform<S, ServiceRequest> for IdentityMiddleware
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
+    S::Future: 'static,
+    B: MessageBody + 'static,
 {
-    type Response = ServiceResponse<B>;
-    type Error = Error;
-    type Transform = InnerIdentityMiddleware<S>;
-    type InitError = ();
-    type Future = Ready<Result<Self::Transform, Self::InitError>>;
+    type Response = ServiceResponse<B>;
+    type Error = Error;
+    type Transform = InnerIdentityMiddleware<S>;
+    type InitError = ();
+    type Future = Ready<Result<Self::Transform, Self::InitError>>;
 
-    fn new_transform(&self, service: S) -> Self::Future {
-        ready(Ok(InnerIdentityMiddleware {
-            service: Rc::new(service),
-            configuration: Rc::clone(&self.configuration),
+    fn new_transform(&self, service: S) -> Self::Future {
+        ready(Ok(InnerIdentityMiddleware {
+            service: Rc::new(service),
+            configuration: Rc::clone(&self.configuration),
         }))
     }
 }
 
-#[doc(hidden)]
-pub struct InnerIdentityMiddleware<S> {
-    service: Rc<S>,
-    configuration: Rc<Configuration>,
+#[doc(hidden)]
+pub struct InnerIdentityMiddleware<S> {
+    service: Rc<S>,
+    configuration: Rc<Configuration>,
 }
 
-impl<S> Clone for InnerIdentityMiddleware<S> {
-    fn clone(&self) -> Self {
-        Self {
-            service: Rc::clone(&self.service),
-            configuration: Rc::clone(&self.configuration),
+impl<S> Clone for InnerIdentityMiddleware<S> {
+    fn clone(&self) -> Self {
+        Self {
+            service: Rc::clone(&self.service),
+            configuration: Rc::clone(&self.configuration),
         }
     }
 }
 
-impl<S, B> Service<ServiceRequest> for InnerIdentityMiddleware<S>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
-    S::Future: 'static,
-    B: MessageBody + 'static,
+impl<S, B> Service<ServiceRequest> for InnerIdentityMiddleware<S>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
+    S::Future: 'static,
+    B: MessageBody + 'static,
 {
-    type Response = ServiceResponse<B>;
-    type Error = Error;
-    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
+    type Response = ServiceResponse<B>;
+    type Error = Error;
+    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
 
-    actix_service::forward_ready!(service);
+    actix_service::forward_ready!(service);
 
-    fn call(&self, req: ServiceRequest) -> Self::Future {
-        let srv = Rc::clone(&self.service);
-        let configuration = Rc::clone(&self.configuration);
-        Box::pin(async move {
-            let identity_inner = IdentityInner {
-                session: req.get_session(),
-                logout_behaviour: configuration.on_logout.clone(),
-                is_login_deadline_enabled: configuration.login_deadline.is_some(),
-                is_visit_deadline_enabled: configuration.visit_deadline.is_some(),
+    fn call(&self, req: ServiceRequest) -> Self::Future {
+        let srv = Rc::clone(&self.service);
+        let configuration = Rc::clone(&self.configuration);
+        Box::pin(async move {
+            let identity_inner = IdentityInner {
+                session: req.get_session(),
+                logout_behaviour: configuration.on_logout.clone(),
+                is_login_deadline_enabled: configuration.login_deadline.is_some(),
+                is_visit_deadline_enabled: configuration.visit_deadline.is_some(),
             };
-            req.extensions_mut().insert(identity_inner);
-            enforce_policies(&req, &configuration);
-            srv.call(req).await
-        })
+            req.extensions_mut().insert(identity_inner);
+            enforce_policies(&req, &configuration);
+            srv.call(req).await
+        })
     }
 }
 
-// easier to scan with returns where they are
-// especially if the function body were to evolve in the future
-#[allow(clippy::needless_return)]
-fn enforce_policies(req: &ServiceRequest, configuration: &Configuration) {
-    let must_extract_identity =
-        configuration.login_deadline.is_some() || configuration.visit_deadline.is_some();
+// easier to scan with returns where they are
+// especially if the function body were to evolve in the future
+#[allow(clippy::needless_return)]
+fn enforce_policies(req: &ServiceRequest, configuration: &Configuration) {
+    let must_extract_identity =
+        configuration.login_deadline.is_some() || configuration.visit_deadline.is_some();
 
-    if !must_extract_identity {
+    if !must_extract_identity {
         return;
     }
 
-    let identity = match Identity::extract(&req.extensions()) {
-        Ok(identity) => identity,
-        Err(err) => {
+    let identity = match Identity::extract(&req.extensions()) {
+        Ok(identity) => identity,
+        Err(err) => {
             tracing::debug!(
-                error.display = %err,
-                error.debug = ?err,
-                "Failed to extract an `Identity` from the incoming request."
-            );
+                error.display = %err,
+                error.debug = ?err,
+                "Failed to extract an `Identity` from the incoming request."
+            );
             return;
         }
     };
 
-    if let Some(login_deadline) = configuration.login_deadline {
-        if matches!(
-            enforce_login_deadline(&identity, login_deadline),
-            PolicyDecision::LogOut
+    if let Some(login_deadline) = configuration.login_deadline {
+        if matches!(
+            enforce_login_deadline(&identity, login_deadline),
+            PolicyDecision::LogOut
         ) {
-            identity.logout();
+            identity.logout();
             return;
         }
     }
 
-    if let Some(visit_deadline) = configuration.visit_deadline {
-        if matches!(
-            enforce_visit_deadline(&identity, visit_deadline),
-            PolicyDecision::LogOut
+    if let Some(visit_deadline) = configuration.visit_deadline {
+        if matches!(
+            enforce_visit_deadline(&identity, visit_deadline),
+            PolicyDecision::LogOut
         ) {
-            identity.logout();
+            identity.logout();
             return;
-        } else if let Err(err) = identity.set_last_visited_at() {
+        } else if let Err(err) = identity.set_last_visited_at() {
             tracing::warn!(
-                error.display = %err,
-                error.debug = ?err,
-                "Failed to set the last visited timestamp on `Identity` for an incoming request."
-            );
+                error.display = %err,
+                error.debug = ?err,
+                "Failed to set the last visited timestamp on `Identity` for an incoming request."
+            );
         }
     }
 }
 
-fn enforce_login_deadline(
-    identity: &Identity,
-    login_deadline: std::time::Duration,
-) -> PolicyDecision {
-    match identity.logged_at() {
+fn enforce_login_deadline(
+    identity: &Identity,
+    login_deadline: std::time::Duration,
+) -> PolicyDecision {
+    match identity.logged_at() {
         Ok(None) => {
             tracing::info!(
                 "Login deadline is enabled, but there is no login timestamp in the session \
-                state attached to the incoming request. Logging the user out."
-            );
-            PolicyDecision::LogOut
+                state attached to the incoming request. Logging the user out."
+            );
+            PolicyDecision::LogOut
         }
-        Err(err) => {
+        Err(err) => {
             tracing::info!(
-                error.display = %err,
-                error.debug = ?err,
+                error.display = %err,
+                error.debug = ?err,
                 "Login deadline is enabled but we failed to extract the login timestamp from the \
-                session state attached to the incoming request. Logging the user out."
-            );
-            PolicyDecision::LogOut
+                session state attached to the incoming request. Logging the user out."
+            );
+            PolicyDecision::LogOut
         }
-        Ok(Some(logged_in_at)) => {
-            let elapsed = OffsetDateTime::now_utc() - logged_in_at;
-            if elapsed > login_deadline {
+        Ok(Some(logged_in_at)) => {
+            let elapsed = OffsetDateTime::now_utc() - logged_in_at;
+            if elapsed > login_deadline {
                 tracing::info!(
-                    user.logged_in_at = %logged_in_at.format(&Rfc3339).unwrap_or_default(),
-                    identity.login_deadline_seconds = login_deadline.as_secs(),
-                    identity.elapsed_since_login_seconds = elapsed.whole_seconds(),
+                    user.logged_in_at = %logged_in_at.format(&Rfc3339).unwrap_or_default(),
+                    identity.login_deadline_seconds = login_deadline.as_secs(),
+                    identity.elapsed_since_login_seconds = elapsed.whole_seconds(),
                     "Login deadline is enabled and too much time has passed since the user logged \
-                    in. Logging the user out."
-                );
-                PolicyDecision::LogOut
-            } else {
-                PolicyDecision::StayLoggedIn
+                    in. Logging the user out."
+                );
+                PolicyDecision::LogOut
+            } else {
+                PolicyDecision::StayLoggedIn
             }
         }
     }
 }
 
-fn enforce_visit_deadline(
-    identity: &Identity,
-    visit_deadline: std::time::Duration,
-) -> PolicyDecision {
-    match identity.last_visited_at() {
+fn enforce_visit_deadline(
+    identity: &Identity,
+    visit_deadline: std::time::Duration,
+) -> PolicyDecision {
+    match identity.last_visited_at() {
         Ok(None) => {
             tracing::info!(
                 "Last visit deadline is enabled, but there is no last visit timestamp in the \
-                session state attached to the incoming request. Logging the user out."
-            );
-            PolicyDecision::LogOut
+                session state attached to the incoming request. Logging the user out."
+            );
+            PolicyDecision::LogOut
         }
-        Err(err) => {
+        Err(err) => {
             tracing::info!(
-                error.display = %err,
-                error.debug = ?err,
+                error.display = %err,
+                error.debug = ?err,
                 "Last visit deadline is enabled but we failed to extract the last visit timestamp \
-                from the session state attached to the incoming request. Logging the user out."
-            );
-            PolicyDecision::LogOut
+                from the session state attached to the incoming request. Logging the user out."
+            );
+            PolicyDecision::LogOut
         }
-        Ok(Some(last_visited_at)) => {
-            let elapsed = OffsetDateTime::now_utc() - last_visited_at;
-            if elapsed > visit_deadline {
+        Ok(Some(last_visited_at)) => {
+            let elapsed = OffsetDateTime::now_utc() - last_visited_at;
+            if elapsed > visit_deadline {
                 tracing::info!(
-                    user.last_visited_at = %last_visited_at.format(&Rfc3339).unwrap_or_default(),
-                    identity.visit_deadline_seconds = visit_deadline.as_secs(),
-                    identity.elapsed_since_last_visit_seconds = elapsed.whole_seconds(),
+                    user.last_visited_at = %last_visited_at.format(&Rfc3339).unwrap_or_default(),
+                    identity.visit_deadline_seconds = visit_deadline.as_secs(),
+                    identity.elapsed_since_last_visit_seconds = elapsed.whole_seconds(),
                     "Last visit deadline is enabled and too much time has passed since the last \
-                    time the user visited. Logging the user out."
-                );
-                PolicyDecision::LogOut
-            } else {
-                PolicyDecision::StayLoggedIn
+                    time the user visited. Logging the user out."
+                );
+                PolicyDecision::LogOut
+            } else {
+                PolicyDecision::StayLoggedIn
             }
         }
     }
 }
 
-enum PolicyDecision {
-    StayLoggedIn,
-    LogOut,
+enum PolicyDecision {
+    StayLoggedIn,
+    LogOut,
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_limitation/builder.rs.html b/src/actix_limitation/builder.rs.html index 64a457f71..a2826722b 100644 --- a/src/actix_limitation/builder.rs.html +++ b/src/actix_limitation/builder.rs.html @@ -121,126 +121,126 @@ 119 120 121 -
use std::{borrow::Cow, time::Duration};
+
use std::{borrow::Cow, time::Duration};
 
-use redis::Client;
+use redis::Client;
 
-use crate::{errors::Error, Limiter};
+use crate::{errors::Error, Limiter};
 
-/// Rate limiter builder.
-#[derive(Debug)]
-pub struct Builder {
-    pub(crate) redis_url: String,
-    pub(crate) limit: usize,
-    pub(crate) period: Duration,
-    pub(crate) cookie_name: Cow<'static, str>,
-    pub(crate) session_key: Cow<'static, str>,
+/// Rate limiter builder.
+#[derive(Debug)]
+pub struct Builder {
+    pub(crate) redis_url: String,
+    pub(crate) limit: usize,
+    pub(crate) period: Duration,
+    pub(crate) cookie_name: Cow<'static, str>,
+    pub(crate) session_key: Cow<'static, str>,
 }
 
-impl Builder {
-    /// Set upper limit.
-    pub fn limit(&mut self, limit: usize) -> &mut Self {
-        self.limit = limit;
-        self
-    }
+impl Builder {
+    /// Set upper limit.
+    pub fn limit(&mut self, limit: usize) -> &mut Self {
+        self.limit = limit;
+        self
+    }
 
-    /// Set limit window/period.
-    pub fn period(&mut self, period: Duration) -> &mut Self {
-        self.period = period;
-        self
-    }
+    /// Set limit window/period.
+    pub fn period(&mut self, period: Duration) -> &mut Self {
+        self.period = period;
+        self
+    }
 
-    /// Set name of cookie to be sent.
-    pub fn cookie_name(&mut self, cookie_name: impl Into<Cow<'static, str>>) -> &mut Self {
-        self.cookie_name = cookie_name.into();
-        self
-    }
+    /// Set name of cookie to be sent.
+    pub fn cookie_name(&mut self, cookie_name: impl Into<Cow<'static, str>>) -> &mut Self {
+        self.cookie_name = cookie_name.into();
+        self
+    }
 
-    /// Set session key to be used in backend.
-    pub fn session_key(&mut self, session_key: impl Into<Cow<'static, str>>) -> &mut Self {
-        self.session_key = session_key.into();
-        self
-    }
+    /// Set session key to be used in backend.
+    pub fn session_key(&mut self, session_key: impl Into<Cow<'static, str>>) -> &mut Self {
+        self.session_key = session_key.into();
+        self
+    }
 
-    /// Finalizes and returns a `Limiter`.
-    ///
-    /// Note that this method will connect to the Redis server to test its connection which is a
-    /// **synchronous** operation.
-    pub fn build(&self) -> Result<Limiter, Error> {
-        Ok(Limiter {
-            client: Client::open(self.redis_url.as_str())?,
-            limit: self.limit,
-            period: self.period,
-            cookie_name: self.cookie_name.clone(),
-            session_key: self.session_key.clone(),
+    /// Finalizes and returns a `Limiter`.
+    ///
+    /// Note that this method will connect to the Redis server to test its connection which is a
+    /// **synchronous** operation.
+    pub fn build(&self) -> Result<Limiter, Error> {
+        Ok(Limiter {
+            client: Client::open(self.redis_url.as_str())?,
+            limit: self.limit,
+            period: self.period,
+            cookie_name: self.cookie_name.clone(),
+            session_key: self.session_key.clone(),
         })
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn test_create_builder() {
-        let redis_url = "redis://127.0.0.1";
-        let period = Duration::from_secs(10);
-        let builder = Builder {
-            redis_url: redis_url.to_owned(),
-            limit: 100,
-            period,
-            cookie_name: Cow::Owned("session".to_string()),
-            session_key: Cow::Owned("rate-api".to_string()),
+    #[test]
+    fn test_create_builder() {
+        let redis_url = "redis://127.0.0.1";
+        let period = Duration::from_secs(10);
+        let builder = Builder {
+            redis_url: redis_url.to_owned(),
+            limit: 100,
+            period,
+            cookie_name: Cow::Owned("session".to_string()),
+            session_key: Cow::Owned("rate-api".to_string()),
         };
 
-        assert_eq!(builder.redis_url, redis_url);
-        assert_eq!(builder.limit, 100);
-        assert_eq!(builder.period, period);
-        assert_eq!(builder.session_key, "rate-api");
-        assert_eq!(builder.cookie_name, "session");
+        assert_eq!(builder.redis_url, redis_url);
+        assert_eq!(builder.limit, 100);
+        assert_eq!(builder.period, period);
+        assert_eq!(builder.session_key, "rate-api");
+        assert_eq!(builder.cookie_name, "session");
     }
 
-    #[test]
-    fn test_create_limiter() {
-        let redis_url = "redis://127.0.0.1";
-        let period = Duration::from_secs(20);
-        let mut builder = Builder {
-            redis_url: redis_url.to_owned(),
-            limit: 100,
-            period: Duration::from_secs(10),
-            session_key: Cow::Borrowed("key"),
-            cookie_name: Cow::Borrowed("sid"),
+    #[test]
+    fn test_create_limiter() {
+        let redis_url = "redis://127.0.0.1";
+        let period = Duration::from_secs(20);
+        let mut builder = Builder {
+            redis_url: redis_url.to_owned(),
+            limit: 100,
+            period: Duration::from_secs(10),
+            session_key: Cow::Borrowed("key"),
+            cookie_name: Cow::Borrowed("sid"),
         };
 
-        let limiter = builder
-            .limit(200)
-            .period(period)
-            .cookie_name("session".to_string())
-            .session_key("rate-api".to_string())
-            .build()
-            .unwrap();
+        let limiter = builder
+            .limit(200)
+            .period(period)
+            .cookie_name("session".to_string())
+            .session_key("rate-api".to_string())
+            .build()
+            .unwrap();
 
-        assert_eq!(limiter.limit, 200);
-        assert_eq!(limiter.period, period);
-        assert_eq!(limiter.session_key, "rate-api");
-        assert_eq!(limiter.cookie_name, "session");
+        assert_eq!(limiter.limit, 200);
+        assert_eq!(limiter.period, period);
+        assert_eq!(limiter.session_key, "rate-api");
+        assert_eq!(limiter.cookie_name, "session");
     }
 
-    #[test]
-    #[should_panic = "Redis URL did not parse"]
-    fn test_create_limiter_error() {
-        let redis_url = "127.0.0.1";
-        let period = Duration::from_secs(20);
-        let mut builder = Builder {
-            redis_url: redis_url.to_owned(),
-            limit: 100,
-            period: Duration::from_secs(10),
-            session_key: Cow::Borrowed("key"),
-            cookie_name: Cow::Borrowed("sid"),
+    #[test]
+    #[should_panic = "Redis URL did not parse"]
+    fn test_create_limiter_error() {
+        let redis_url = "127.0.0.1";
+        let period = Duration::from_secs(20);
+        let mut builder = Builder {
+            redis_url: redis_url.to_owned(),
+            limit: 100,
+            period: Duration::from_secs(10),
+            session_key: Cow::Borrowed("key"),
+            cookie_name: Cow::Borrowed("sid"),
         };
 
-        builder.limit(200).period(period).build().unwrap();
+        builder.limit(200).period(period).build().unwrap();
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_limitation/errors.rs.html b/src/actix_limitation/errors.rs.html index 8c47fc568..ab324cf6b 100644 --- a/src/actix_limitation/errors.rs.html +++ b/src/actix_limitation/errors.rs.html @@ -42,47 +42,47 @@ 40 41 42 -
use derive_more::{Display, Error, From};
+
use derive_more::{Display, Error, From};
 
-use crate::status::Status;
+use crate::status::Status;
 
-/// Failure modes of the rate limiter.
-#[derive(Debug, Display, Error, From)]
-pub enum Error {
-    /// Redis client failed to connect or run a query.
-    #[display(fmt = "Redis client failed to connect or run a query")]
-    Client(redis::RedisError),
+/// Failure modes of the rate limiter.
+#[derive(Debug, Display, Error, From)]
+pub enum Error {
+    /// Redis client failed to connect or run a query.
+    #[display(fmt = "Redis client failed to connect or run a query")]
+    Client(redis::RedisError),
 
-    /// Limit is exceeded for a key.
-    #[display(fmt = "Limit is exceeded for a key")]
-    #[from(ignore)]
-    LimitExceeded(#[error(not(source))] Status),
+    /// Limit is exceeded for a key.
+    #[display(fmt = "Limit is exceeded for a key")]
+    #[from(ignore)]
+    LimitExceeded(#[error(not(source))] Status),
 
-    /// Time conversion failed.
-    #[display(fmt = "Time conversion failed")]
-    Time(time::error::ComponentRange),
+    /// Time conversion failed.
+    #[display(fmt = "Time conversion failed")]
+    Time(time::error::ComponentRange),
 
-    /// Generic error.
-    #[display(fmt = "Generic error")]
-    #[from(ignore)]
-    Other(#[error(not(source))] String),
+    /// Generic error.
+    #[display(fmt = "Generic error")]
+    #[from(ignore)]
+    Other(#[error(not(source))] String),
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    static_assertions::assert_impl_all! {
-        Error:
-        From<redis::RedisError>,
-        From<time::error::ComponentRange>,
+    static_assertions::assert_impl_all! {
+        Error:
+        From<redis::RedisError>,
+        From<time::error::ComponentRange>,
     }
 
-    static_assertions::assert_not_impl_any! {
-        Error:
-        From<String>,
-        From<Status>,
+    static_assertions::assert_not_impl_any! {
+        Error:
+        From<String>,
+        From<Status>,
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_limitation/lib.rs.html b/src/actix_limitation/lib.rs.html index 76ca18d5b..48121d21f 100644 --- a/src/actix_limitation/lib.rs.html +++ b/src/actix_limitation/lib.rs.html @@ -159,164 +159,164 @@ 157 158 159 -
//! Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web.
-//!
-//! ```toml
-//! [dependencies]
-//! actix-web = "4"
-#![doc = concat!("actix-limitation = \"", env!("CARGO_PKG_VERSION_MAJOR"), ".", env!("CARGO_PKG_VERSION_MINOR"),"\"")]
-//! ```
-//!
-//! ```no_run
-//! use std::time::Duration;
-//! use actix_web::{get, web, App, HttpServer, Responder};
-//! use actix_limitation::{Limiter, RateLimiter};
-//!
-//! #[get("/{id}/{name}")]
-//! async fn index(info: web::Path<(u32, String)>) -> impl Responder {
-//!     format!("Hello {}! id:{}", info.1, info.0)
-//! }
-//!
-//! #[actix_web::main]
-//! async fn main() -> std::io::Result<()> {
-//!     let limiter = web::Data::new(
-//!         Limiter::builder("redis://127.0.0.1")
-//!             .cookie_name("session-id".to_owned())
-//!             .session_key("rate-api-id".to_owned())
-//!             .limit(5000)
-//!             .period(Duration::from_secs(3600)) // 60 minutes
-//!             .build()
-//!             .unwrap(),
-//!     );
-//!
-//!     HttpServer::new(move || {
-//!         App::new()
-//!             .wrap(RateLimiter::default())
-//!             .app_data(limiter.clone())
-//!             .service(index)
-//!     })
-//!     .bind(("127.0.0.1", 8080))?
-//!     .run()
-//!     .await
-//! }
-//! ```
+
//! Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web.
+//!
+//! ```toml
+//! [dependencies]
+//! actix-web = "4"
+#![doc = concat!("actix-limitation = \"", env!("CARGO_PKG_VERSION_MAJOR"), ".", env!("CARGO_PKG_VERSION_MINOR"),"\"")]
+//! ```
+//!
+//! ```no_run
+//! use std::time::Duration;
+//! use actix_web::{get, web, App, HttpServer, Responder};
+//! use actix_limitation::{Limiter, RateLimiter};
+//!
+//! #[get("/{id}/{name}")]
+//! async fn index(info: web::Path<(u32, String)>) -> impl Responder {
+//!     format!("Hello {}! id:{}", info.1, info.0)
+//! }
+//!
+//! #[actix_web::main]
+//! async fn main() -> std::io::Result<()> {
+//!     let limiter = web::Data::new(
+//!         Limiter::builder("redis://127.0.0.1")
+//!             .cookie_name("session-id".to_owned())
+//!             .session_key("rate-api-id".to_owned())
+//!             .limit(5000)
+//!             .period(Duration::from_secs(3600)) // 60 minutes
+//!             .build()
+//!             .unwrap(),
+//!     );
+//!
+//!     HttpServer::new(move || {
+//!         App::new()
+//!             .wrap(RateLimiter::default())
+//!             .app_data(limiter.clone())
+//!             .service(index)
+//!     })
+//!     .bind(("127.0.0.1", 8080))?
+//!     .run()
+//!     .await
+//! }
+//! ```
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style)]
-#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
-#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
-#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
 
-use std::{borrow::Cow, time::Duration};
+use std::{borrow::Cow, time::Duration};
 
-use redis::Client;
+use redis::Client;
 
-mod builder;
-mod errors;
-mod middleware;
-mod status;
+mod builder;
+mod errors;
+mod middleware;
+mod status;
 
-pub use self::builder::Builder;
-pub use self::errors::Error;
-pub use self::middleware::RateLimiter;
-pub use self::status::Status;
+pub use self::builder::Builder;
+pub use self::errors::Error;
+pub use self::middleware::RateLimiter;
+pub use self::status::Status;
 
-/// Default request limit.
-pub const DEFAULT_REQUEST_LIMIT: usize = 5000;
+/// Default request limit.
+pub const DEFAULT_REQUEST_LIMIT: usize = 5000;
 
-/// Default period (in seconds).
-pub const DEFAULT_PERIOD_SECS: u64 = 3600;
+/// Default period (in seconds).
+pub const DEFAULT_PERIOD_SECS: u64 = 3600;
 
-/// Default cookie name.
-pub const DEFAULT_COOKIE_NAME: &str = "sid";
+/// Default cookie name.
+pub const DEFAULT_COOKIE_NAME: &str = "sid";
 
-/// Default session key.
-pub const DEFAULT_SESSION_KEY: &str = "rate-api-id";
+/// Default session key.
+pub const DEFAULT_SESSION_KEY: &str = "rate-api-id";
 
-/// Rate limiter.
-#[derive(Debug, Clone)]
-pub struct Limiter {
-    client: Client,
-    limit: usize,
-    period: Duration,
-    cookie_name: Cow<'static, str>,
-    session_key: Cow<'static, str>,
+/// Rate limiter.
+#[derive(Debug, Clone)]
+pub struct Limiter {
+    client: Client,
+    limit: usize,
+    period: Duration,
+    cookie_name: Cow<'static, str>,
+    session_key: Cow<'static, str>,
 }
 
-impl Limiter {
-    /// Construct rate limiter builder with defaults.
-    ///
-    /// See [`redis-rs` docs](https://docs.rs/redis/0.21/redis/#connection-parameters) on connection
-    /// parameters for how to set the Redis URL.
-    #[must_use]
-    pub fn builder(redis_url: impl Into<String>) -> Builder {
-        Builder {
-            redis_url: redis_url.into(),
-            limit: DEFAULT_REQUEST_LIMIT,
-            period: Duration::from_secs(DEFAULT_PERIOD_SECS),
-            cookie_name: Cow::Borrowed(DEFAULT_COOKIE_NAME),
-            session_key: Cow::Borrowed(DEFAULT_SESSION_KEY),
+impl Limiter {
+    /// Construct rate limiter builder with defaults.
+    ///
+    /// See [`redis-rs` docs](https://docs.rs/redis/0.21/redis/#connection-parameters) on connection
+    /// parameters for how to set the Redis URL.
+    #[must_use]
+    pub fn builder(redis_url: impl Into<String>) -> Builder {
+        Builder {
+            redis_url: redis_url.into(),
+            limit: DEFAULT_REQUEST_LIMIT,
+            period: Duration::from_secs(DEFAULT_PERIOD_SECS),
+            cookie_name: Cow::Borrowed(DEFAULT_COOKIE_NAME),
+            session_key: Cow::Borrowed(DEFAULT_SESSION_KEY),
         }
     }
 
-    /// Consumes one rate limit unit, returning the status.
-    pub async fn count(&self, key: impl Into<String>) -> Result<Status, Error> {
-        let (count, reset) = self.track(key).await?;
-        let status = Status::new(count, self.limit, reset);
+    /// Consumes one rate limit unit, returning the status.
+    pub async fn count(&self, key: impl Into<String>) -> Result<Status, Error> {
+        let (count, reset) = self.track(key).await?;
+        let status = Status::new(count, self.limit, reset);
 
-        if count > self.limit {
-            Err(Error::LimitExceeded(status))
-        } else {
-            Ok(status)
+        if count > self.limit {
+            Err(Error::LimitExceeded(status))
+        } else {
+            Ok(status)
         }
     }
 
-    /// Tracks the given key in a period and returns the count and TTL for the key in seconds.
-    async fn track(&self, key: impl Into<String>) -> Result<(usize, usize), Error> {
-        let key = key.into();
-        let expires = self.period.as_secs();
+    /// Tracks the given key in a period and returns the count and TTL for the key in seconds.
+    async fn track(&self, key: impl Into<String>) -> Result<(usize, usize), Error> {
+        let key = key.into();
+        let expires = self.period.as_secs();
 
-        let mut connection = self.client.get_tokio_connection().await?;
+        let mut connection = self.client.get_tokio_connection().await?;
 
-        // The seed of this approach is outlined Atul R in a blog post about rate limiting using
-        // NodeJS and Redis. For more details, see https://blog.atulr.com/rate-limiter
-        let mut pipe = redis::pipe();
-        pipe.atomic()
-            .cmd("SET") // Set key and value
-            .arg(&key)
-            .arg(0)
-            .arg("EX") // Set the specified expire time, in seconds.
-            .arg(expires)
-            .arg("NX") // Only set the key if it does not already exist.
-            .ignore() // --- ignore returned value of SET command ---
-            .cmd("INCR") // Increment key
-            .arg(&key)
-            .cmd("TTL") // Return time-to-live of key
-            .arg(&key);
+        // The seed of this approach is outlined Atul R in a blog post about rate limiting using
+        // NodeJS and Redis. For more details, see https://blog.atulr.com/rate-limiter
+        let mut pipe = redis::pipe();
+        pipe.atomic()
+            .cmd("SET") // Set key and value
+            .arg(&key)
+            .arg(0)
+            .arg("EX") // Set the specified expire time, in seconds.
+            .arg(expires)
+            .arg("NX") // Only set the key if it does not already exist.
+            .ignore() // --- ignore returned value of SET command ---
+            .cmd("INCR") // Increment key
+            .arg(&key)
+            .cmd("TTL") // Return time-to-live of key
+            .arg(&key);
 
-        let (count, ttl) = pipe.query_async(&mut connection).await?;
-        let reset = Status::epoch_utc_plus(Duration::from_secs(ttl))?;
+        let (count, ttl) = pipe.query_async(&mut connection).await?;
+        let reset = Status::epoch_utc_plus(Duration::from_secs(ttl))?;
 
-        Ok((count, reset))
+        Ok((count, reset))
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn test_create_limiter() {
-        let builder = Limiter::builder("redis://127.0.0.1:6379/1");
-        let limiter = builder.build();
-        assert!(limiter.is_ok());
+    #[test]
+    fn test_create_limiter() {
+        let builder = Limiter::builder("redis://127.0.0.1:6379/1");
+        let limiter = builder.build();
+        assert!(limiter.is_ok());
 
-        let limiter = limiter.unwrap();
-        assert_eq!(limiter.limit, 5000);
-        assert_eq!(limiter.period, Duration::from_secs(3600));
-        assert_eq!(limiter.cookie_name, DEFAULT_COOKIE_NAME);
-        assert_eq!(limiter.session_key, DEFAULT_SESSION_KEY);
+        let limiter = limiter.unwrap();
+        assert_eq!(limiter.limit, 5000);
+        assert_eq!(limiter.period, Duration::from_secs(3600));
+        assert_eq!(limiter.cookie_name, DEFAULT_COOKIE_NAME);
+        assert_eq!(limiter.session_key, DEFAULT_SESSION_KEY);
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_limitation/middleware.rs.html b/src/actix_limitation/middleware.rs.html index b1efc542b..9ba6deb95 100644 --- a/src/actix_limitation/middleware.rs.html +++ b/src/actix_limitation/middleware.rs.html @@ -103,108 +103,108 @@ 101 102 103 -
use std::{future::Future, pin::Pin, rc::Rc};
+
use std::{future::Future, pin::Pin, rc::Rc};
 
-use actix_session::SessionExt as _;
-use actix_utils::future::{ok, Ready};
-use actix_web::{
-    body::EitherBody,
-    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
-    http::StatusCode,
-    web, Error, HttpResponse,
+use actix_session::SessionExt as _;
+use actix_utils::future::{ok, Ready};
+use actix_web::{
+    body::EitherBody,
+    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
+    http::StatusCode,
+    web, Error, HttpResponse,
 };
 
-use crate::Limiter;
+use crate::Limiter;
 
-/// Rate limit middleware.
-#[derive(Debug, Default)]
-#[non_exhaustive]
-pub struct RateLimiter;
+/// Rate limit middleware.
+#[derive(Debug, Default)]
+#[non_exhaustive]
+pub struct RateLimiter;
 
-impl<S, B> Transform<S, ServiceRequest> for RateLimiter
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
-    S::Future: 'static,
-    B: 'static,
+impl<S, B> Transform<S, ServiceRequest> for RateLimiter
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
+    S::Future: 'static,
+    B: 'static,
 {
-    type Response = ServiceResponse<EitherBody<B>>;
-    type Error = Error;
-    type Transform = RateLimiterMiddleware<S>;
-    type InitError = ();
-    type Future = Ready<Result<Self::Transform, Self::InitError>>;
+    type Response = ServiceResponse<EitherBody<B>>;
+    type Error = Error;
+    type Transform = RateLimiterMiddleware<S>;
+    type InitError = ();
+    type Future = Ready<Result<Self::Transform, Self::InitError>>;
 
-    fn new_transform(&self, service: S) -> Self::Future {
-        ok(RateLimiterMiddleware {
-            service: Rc::new(service),
+    fn new_transform(&self, service: S) -> Self::Future {
+        ok(RateLimiterMiddleware {
+            service: Rc::new(service),
         })
     }
 }
 
-/// Rate limit middleware service.
-#[derive(Debug)]
-pub struct RateLimiterMiddleware<S> {
-    service: Rc<S>,
+/// Rate limit middleware service.
+#[derive(Debug)]
+pub struct RateLimiterMiddleware<S> {
+    service: Rc<S>,
 }
 
-impl<S, B> Service<ServiceRequest> for RateLimiterMiddleware<S>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
-    S::Future: 'static,
-    B: 'static,
+impl<S, B> Service<ServiceRequest> for RateLimiterMiddleware<S>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
+    S::Future: 'static,
+    B: 'static,
 {
-    type Response = ServiceResponse<EitherBody<B>>;
-    type Error = Error;
-    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
+    type Response = ServiceResponse<EitherBody<B>>;
+    type Error = Error;
+    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
 
-    forward_ready!(service);
+    forward_ready!(service);
 
-    fn call(&self, req: ServiceRequest) -> Self::Future {
-        // A mis-configuration of the Actix App will result in a **runtime** failure, so the expect
-        // method description is important context for the developer.
-        let limiter = req
-            .app_data::<web::Data<Limiter>>()
-            .expect("web::Data<Limiter> should be set in app data for RateLimiter middleware")
-            .clone();
+    fn call(&self, req: ServiceRequest) -> Self::Future {
+        // A mis-configuration of the Actix App will result in a **runtime** failure, so the expect
+        // method description is important context for the developer.
+        let limiter = req
+            .app_data::<web::Data<Limiter>>()
+            .expect("web::Data<Limiter> should be set in app data for RateLimiter middleware")
+            .clone();
 
-        let key = req.get_session().get(&limiter.session_key).unwrap_or(None);
-        let service = Rc::clone(&self.service);
+        let key = req.get_session().get(&limiter.session_key).unwrap_or(None);
+        let service = Rc::clone(&self.service);
 
-        let key = match key {
-            Some(key) => key,
-            None => {
-                let fallback = req.cookie(&limiter.cookie_name).map(|c| c.to_string());
+        let key = match key {
+            Some(key) => key,
+            None => {
+                let fallback = req.cookie(&limiter.cookie_name).map(|c| c.to_string());
 
-                match fallback {
-                    Some(key) => key,
-                    None => {
-                        return Box::pin(async move {
-                            service
-                                .call(req)
-                                .await
-                                .map(ServiceResponse::map_into_left_body)
+                match fallback {
+                    Some(key) => key,
+                    None => {
+                        return Box::pin(async move {
+                            service
+                                .call(req)
+                                .await
+                                .map(ServiceResponse::map_into_left_body)
                         });
                     }
                 }
             }
         };
 
-        Box::pin(async move {
-            let status = limiter.count(key.to_string()).await;
+        Box::pin(async move {
+            let status = limiter.count(key.to_string()).await;
 
-            if status.is_err() {
-                log::warn!("Rate limit exceed error for {}", key);
+            if status.is_err() {
+                log::warn!("Rate limit exceed error for {}", key);
 
-                Ok(req.into_response(
-                    HttpResponse::new(StatusCode::TOO_MANY_REQUESTS).map_into_right_body(),
+                Ok(req.into_response(
+                    HttpResponse::new(StatusCode::TOO_MANY_REQUESTS).map_into_right_body(),
                 ))
-            } else {
-                service
-                    .call(req)
-                    .await
-                    .map(ServiceResponse::map_into_left_body)
+            } else {
+                service
+                    .call(req)
+                    .await
+                    .map(ServiceResponse::map_into_left_body)
             }
         })
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_limitation/status.rs.html b/src/actix_limitation/status.rs.html index 75a405015..bb18832f6 100644 --- a/src/actix_limitation/status.rs.html +++ b/src/actix_limitation/status.rs.html @@ -118,123 +118,123 @@ 116 117 118 -
use std::{convert::TryInto, ops::Add, time::Duration};
+
use std::{convert::TryInto, ops::Add, time::Duration};
 
-use chrono::SubsecRound as _;
+use chrono::SubsecRound as _;
 
-use crate::Error as LimitationError;
+use crate::Error as LimitationError;
 
-/// A report for a given key containing the limit status.
-#[derive(Debug, Clone)]
-pub struct Status {
-    pub(crate) limit: usize,
-    pub(crate) remaining: usize,
-    pub(crate) reset_epoch_utc: usize,
+/// A report for a given key containing the limit status.
+#[derive(Debug, Clone)]
+pub struct Status {
+    pub(crate) limit: usize,
+    pub(crate) remaining: usize,
+    pub(crate) reset_epoch_utc: usize,
 }
 
-impl Status {
-    /// Constructs status limit status from parts.
-    #[must_use]
-    pub(crate) fn new(count: usize, limit: usize, reset_epoch_utc: usize) -> Self {
-        let remaining = if count >= limit { 0 } else { limit - count };
+impl Status {
+    /// Constructs status limit status from parts.
+    #[must_use]
+    pub(crate) fn new(count: usize, limit: usize, reset_epoch_utc: usize) -> Self {
+        let remaining = if count >= limit { 0 } else { limit - count };
 
-        Status {
-            limit,
-            remaining,
-            reset_epoch_utc,
+        Status {
+            limit,
+            remaining,
+            reset_epoch_utc,
         }
     }
 
-    /// Returns the maximum number of requests allowed in the current period.
-    #[must_use]
-    pub fn limit(&self) -> usize {
-        self.limit
+    /// Returns the maximum number of requests allowed in the current period.
+    #[must_use]
+    pub fn limit(&self) -> usize {
+        self.limit
     }
 
-    /// Returns how many requests are left in the current period.
-    #[must_use]
-    pub fn remaining(&self) -> usize {
-        self.remaining
+    /// Returns how many requests are left in the current period.
+    #[must_use]
+    pub fn remaining(&self) -> usize {
+        self.remaining
     }
 
-    /// Returns a UNIX timestamp in UTC approximately when the next period will begin.
-    #[must_use]
-    pub fn reset_epoch_utc(&self) -> usize {
-        self.reset_epoch_utc
+    /// Returns a UNIX timestamp in UTC approximately when the next period will begin.
+    #[must_use]
+    pub fn reset_epoch_utc(&self) -> usize {
+        self.reset_epoch_utc
     }
 
-    pub(crate) fn epoch_utc_plus(duration: Duration) -> Result<usize, LimitationError> {
-        match chrono::Duration::from_std(duration) {
-            Ok(value) => Ok(chrono::Utc::now()
-                .add(value)
-                .round_subsecs(0)
-                .timestamp()
-                .try_into()
-                .unwrap_or(0)),
+    pub(crate) fn epoch_utc_plus(duration: Duration) -> Result<usize, LimitationError> {
+        match chrono::Duration::from_std(duration) {
+            Ok(value) => Ok(chrono::Utc::now()
+                .add(value)
+                .round_subsecs(0)
+                .timestamp()
+                .try_into()
+                .unwrap_or(0)),
 
-            Err(_) => Err(LimitationError::Other(
-                "Source duration value is out of range for the target type".to_string(),
+            Err(_) => Err(LimitationError::Other(
+                "Source duration value is out of range for the target type".to_string(),
             )),
         }
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn test_create_status() {
-        let status = Status {
-            limit: 100,
-            remaining: 0,
-            reset_epoch_utc: 1000,
+    #[test]
+    fn test_create_status() {
+        let status = Status {
+            limit: 100,
+            remaining: 0,
+            reset_epoch_utc: 1000,
         };
 
-        assert_eq!(status.limit(), 100);
-        assert_eq!(status.remaining(), 0);
-        assert_eq!(status.reset_epoch_utc(), 1000);
+        assert_eq!(status.limit(), 100);
+        assert_eq!(status.remaining(), 0);
+        assert_eq!(status.reset_epoch_utc(), 1000);
     }
 
-    #[test]
-    fn test_build_status() {
-        let count = 200;
-        let limit = 100;
-        let status = Status::new(count, limit, 2000);
-        assert_eq!(status.limit(), limit);
-        assert_eq!(status.remaining(), 0);
-        assert_eq!(status.reset_epoch_utc(), 2000);
+    #[test]
+    fn test_build_status() {
+        let count = 200;
+        let limit = 100;
+        let status = Status::new(count, limit, 2000);
+        assert_eq!(status.limit(), limit);
+        assert_eq!(status.remaining(), 0);
+        assert_eq!(status.reset_epoch_utc(), 2000);
     }
 
-    #[test]
-    fn test_build_status_limit() {
-        let limit = 100;
-        let status = Status::new(0, limit, 2000);
-        assert_eq!(status.limit(), limit);
-        assert_eq!(status.remaining(), limit);
-        assert_eq!(status.reset_epoch_utc(), 2000);
+    #[test]
+    fn test_build_status_limit() {
+        let limit = 100;
+        let status = Status::new(0, limit, 2000);
+        assert_eq!(status.limit(), limit);
+        assert_eq!(status.remaining(), limit);
+        assert_eq!(status.reset_epoch_utc(), 2000);
     }
 
-    #[test]
-    fn test_epoch_utc_plus_zero() {
-        let duration = Duration::from_secs(0);
-        let seconds = Status::epoch_utc_plus(duration).unwrap();
-        assert!(seconds as u64 >= duration.as_secs());
+    #[test]
+    fn test_epoch_utc_plus_zero() {
+        let duration = Duration::from_secs(0);
+        let seconds = Status::epoch_utc_plus(duration).unwrap();
+        assert!(seconds as u64 >= duration.as_secs());
     }
 
-    #[test]
-    fn test_epoch_utc_plus() {
-        let duration = Duration::from_secs(10);
-        let seconds = Status::epoch_utc_plus(duration).unwrap();
-        assert!(seconds as u64 >= duration.as_secs() + 10);
+    #[test]
+    fn test_epoch_utc_plus() {
+        let duration = Duration::from_secs(10);
+        let seconds = Status::epoch_utc_plus(duration).unwrap();
+        assert!(seconds as u64 >= duration.as_secs() + 10);
     }
 
-    #[test]
-    #[should_panic = "Source duration value is out of range for the target type"]
-    fn test_epoch_utc_plus_overflow() {
-        let duration = Duration::from_secs(10000000000000000000);
-        Status::epoch_utc_plus(duration).unwrap();
+    #[test]
+    #[should_panic = "Source duration value is out of range for the target type"]
+    fn test_epoch_utc_plus_overflow() {
+        let duration = Duration::from_secs(10000000000000000000);
+        Status::epoch_utc_plus(duration).unwrap();
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_protobuf/lib.rs.html b/src/actix_protobuf/lib.rs.html index a0b312bbc..1b33be5d9 100644 --- a/src/actix_protobuf/lib.rs.html +++ b/src/actix_protobuf/lib.rs.html @@ -331,338 +331,342 @@ 331 332 333 -
//! Protobuf payload extractor for Actix Web.
+334
+335
+
//! Protobuf payload extractor for Actix Web.
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style)]
-#![warn(future_incompatible)]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible)]
 
-use std::{
-    fmt,
-    future::Future,
-    ops::{Deref, DerefMut},
-    pin::Pin,
-    task::{self, Poll},
+use std::{
+    fmt,
+    future::Future,
+    ops::{Deref, DerefMut},
+    pin::Pin,
+    task::{self, Poll},
 };
 
-use actix_web::{
-    body::BoxBody,
-    dev::Payload,
-    error::PayloadError,
-    http::header::{CONTENT_LENGTH, CONTENT_TYPE},
-    web::BytesMut,
-    Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
-    ResponseError,
+use actix_web::{
+    body::BoxBody,
+    dev::Payload,
+    error::PayloadError,
+    http::header::{CONTENT_LENGTH, CONTENT_TYPE},
+    web::BytesMut,
+    Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
+    ResponseError,
 };
-use derive_more::Display;
-use futures_util::{
-    future::{FutureExt as _, LocalBoxFuture},
-    stream::StreamExt as _,
+use derive_more::Display;
+use futures_util::{
+    future::{FutureExt as _, LocalBoxFuture},
+    stream::StreamExt as _,
 };
-use prost::{DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeError, Message};
+use prost::{DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeError, Message};
 
-#[derive(Debug, Display)]
-pub enum ProtoBufPayloadError {
-    /// Payload size is bigger than 256k
-    #[display(fmt = "Payload size is bigger than 256k")]
-    Overflow,
+#[derive(Debug, Display)]
+pub enum ProtoBufPayloadError {
+    /// Payload size is bigger than 256k
+    #[display(fmt = "Payload size is bigger than 256k")]
+    Overflow,
 
-    /// Content type error
-    #[display(fmt = "Content type error")]
-    ContentType,
+    /// Content type error
+    #[display(fmt = "Content type error")]
+    ContentType,
 
-    /// Serialize error
-    #[display(fmt = "ProtoBuf serialize error: {}", _0)]
-    Serialize(ProtoBufEncodeError),
+    /// Serialize error
+    #[display(fmt = "ProtoBuf serialize error: {}", _0)]
+    Serialize(ProtoBufEncodeError),
 
-    /// Deserialize error
-    #[display(fmt = "ProtoBuf deserialize error: {}", _0)]
-    Deserialize(ProtoBufDecodeError),
+    /// Deserialize error
+    #[display(fmt = "ProtoBuf deserialize error: {}", _0)]
+    Deserialize(ProtoBufDecodeError),
 
-    /// Payload error
-    #[display(fmt = "Error that occur during reading payload: {}", _0)]
-    Payload(PayloadError),
+    /// Payload error
+    #[display(fmt = "Error that occur during reading payload: {}", _0)]
+    Payload(PayloadError),
 }
 
-impl ResponseError for ProtoBufPayloadError {
-    fn error_response(&self) -> HttpResponse {
-        match *self {
-            ProtoBufPayloadError::Overflow => HttpResponse::PayloadTooLarge().into(),
-            _ => HttpResponse::BadRequest().into(),
+impl ResponseError for ProtoBufPayloadError {
+    fn error_response(&self) -> HttpResponse {
+        match *self {
+            ProtoBufPayloadError::Overflow => HttpResponse::PayloadTooLarge().into(),
+            _ => HttpResponse::BadRequest().into(),
         }
     }
 }
 
-impl From<PayloadError> for ProtoBufPayloadError {
-    fn from(err: PayloadError) -> ProtoBufPayloadError {
-        ProtoBufPayloadError::Payload(err)
+impl From<PayloadError> for ProtoBufPayloadError {
+    fn from(err: PayloadError) -> ProtoBufPayloadError {
+        ProtoBufPayloadError::Payload(err)
     }
 }
 
-impl From<ProtoBufDecodeError> for ProtoBufPayloadError {
-    fn from(err: ProtoBufDecodeError) -> ProtoBufPayloadError {
-        ProtoBufPayloadError::Deserialize(err)
+impl From<ProtoBufDecodeError> for ProtoBufPayloadError {
+    fn from(err: ProtoBufDecodeError) -> ProtoBufPayloadError {
+        ProtoBufPayloadError::Deserialize(err)
     }
 }
 
-pub struct ProtoBuf<T: Message>(pub T);
+pub struct ProtoBuf<T: Message>(pub T);
 
-impl<T: Message> Deref for ProtoBuf<T> {
-    type Target = T;
+impl<T: Message> Deref for ProtoBuf<T> {
+    type Target = T;
 
-    fn deref(&self) -> &T {
-        &self.0
-    }
+    fn deref(&self) -> &T {
+        &self.0
+    }
 }
 
-impl<T: Message> DerefMut for ProtoBuf<T> {
-    fn deref_mut(&mut self) -> &mut T {
-        &mut self.0
-    }
+impl<T: Message> DerefMut for ProtoBuf<T> {
+    fn deref_mut(&mut self) -> &mut T {
+        &mut self.0
+    }
 }
 
-impl<T: Message> fmt::Debug for ProtoBuf<T>
-where
-    T: fmt::Debug,
+impl<T: Message> fmt::Debug for ProtoBuf<T>
+where
+    T: fmt::Debug,
 {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "ProtoBuf: {:?}", self.0)
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "ProtoBuf: {:?}", self.0)
     }
 }
 
-impl<T: Message> fmt::Display for ProtoBuf<T>
-where
-    T: fmt::Display,
+impl<T: Message> fmt::Display for ProtoBuf<T>
+where
+    T: fmt::Display,
 {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        fmt::Display::fmt(&self.0, f)
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt::Display::fmt(&self.0, f)
     }
 }
 
-pub struct ProtoBufConfig {
-    limit: usize,
+pub struct ProtoBufConfig {
+    limit: usize,
 }
 
-impl ProtoBufConfig {
-    /// Change max size of payload. By default max size is 256Kb
-    pub fn limit(&mut self, limit: usize) -> &mut Self {
-        self.limit = limit;
-        self
+impl ProtoBufConfig {
+    /// Change max size of payload. By default max size is 256Kb
+    pub fn limit(&mut self, limit: usize) -> &mut Self {
+        self.limit = limit;
+        self
+    }
+}
+
+impl Default for ProtoBufConfig {
+    fn default() -> Self {
+        ProtoBufConfig { limit: 262_144 }
     }
 }
 
-impl Default for ProtoBufConfig {
-    fn default() -> Self {
-        ProtoBufConfig { limit: 262_144 }
-    }
-}
-
-impl<T> FromRequest for ProtoBuf<T>
-where
-    T: Message + Default + 'static,
+impl<T> FromRequest for ProtoBuf<T>
+where
+    T: Message + Default + 'static,
 {
-    type Error = Error;
-    type Future = LocalBoxFuture<'static, Result<Self, Error>>;
+    type Error = Error;
+    type Future = LocalBoxFuture<'static, Result<Self, Error>>;
 
-    #[inline]
-    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
-        let limit = req
-            .app_data::<ProtoBufConfig>()
-            .map(|c| c.limit)
-            .unwrap_or(262_144);
-        ProtoBufMessage::new(req, payload)
-            .limit(limit)
-            .map(move |res| match res {
-                Err(e) => Err(e.into()),
-                Ok(item) => Ok(ProtoBuf(item)),
+    #[inline]
+    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
+        let limit = req
+            .app_data::<ProtoBufConfig>()
+            .map(|c| c.limit)
+            .unwrap_or(262_144);
+        ProtoBufMessage::new(req, payload)
+            .limit(limit)
+            .map(move |res| match res {
+                Err(e) => Err(e.into()),
+                Ok(item) => Ok(ProtoBuf(item)),
             })
-            .boxed_local()
+            .boxed_local()
     }
 }
 
-impl<T: Message + Default> Responder for ProtoBuf<T> {
-    type Body = BoxBody;
+impl<T: Message + Default> Responder for ProtoBuf<T> {
+    type Body = BoxBody;
 
-    fn respond_to(self, _: &HttpRequest) -> HttpResponse {
-        let mut buf = Vec::new();
-        match self.0.encode(&mut buf) {
-            Ok(()) => HttpResponse::Ok()
-                .content_type("application/protobuf")
-                .body(buf),
-            Err(err) => HttpResponse::from_error(Error::from(ProtoBufPayloadError::Serialize(err))),
+    fn respond_to(self, _: &HttpRequest) -> HttpResponse {
+        let mut buf = Vec::new();
+        match self.0.encode(&mut buf) {
+            Ok(()) => HttpResponse::Ok()
+                .content_type("application/protobuf")
+                .body(buf),
+            Err(err) => HttpResponse::from_error(Error::from(ProtoBufPayloadError::Serialize(err))),
         }
     }
 }
 
-pub struct ProtoBufMessage<T: Message + Default> {
-    limit: usize,
-    length: Option<usize>,
-    stream: Option<Payload>,
-    err: Option<ProtoBufPayloadError>,
-    fut: Option<LocalBoxFuture<'static, Result<T, ProtoBufPayloadError>>>,
+pub struct ProtoBufMessage<T: Message + Default> {
+    limit: usize,
+    length: Option<usize>,
+    stream: Option<Payload>,
+    err: Option<ProtoBufPayloadError>,
+    fut: Option<LocalBoxFuture<'static, Result<T, ProtoBufPayloadError>>>,
 }
 
-impl<T: Message + Default> ProtoBufMessage<T> {
-    /// Create `ProtoBufMessage` for request.
-    pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
-        if req.content_type() != "application/protobuf" {
-            return ProtoBufMessage {
-                limit: 262_144,
-                length: None,
-                stream: None,
-                fut: None,
-                err: Some(ProtoBufPayloadError::ContentType),
+impl<T: Message + Default> ProtoBufMessage<T> {
+    /// Create `ProtoBufMessage` for request.
+    pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
+        if req.content_type() != "application/protobuf"
+            && req.content_type() != "application/x-protobuf"
+        {
+            return ProtoBufMessage {
+                limit: 262_144,
+                length: None,
+                stream: None,
+                fut: None,
+                err: Some(ProtoBufPayloadError::ContentType),
             };
         }
 
-        let mut len = None;
-        if let Some(l) = req.headers().get(CONTENT_LENGTH) {
-            if let Ok(s) = l.to_str() {
-                if let Ok(l) = s.parse::<usize>() {
-                    len = Some(l)
+        let mut len = None;
+        if let Some(l) = req.headers().get(CONTENT_LENGTH) {
+            if let Ok(s) = l.to_str() {
+                if let Ok(l) = s.parse::<usize>() {
+                    len = Some(l)
                 }
             }
         }
 
-        ProtoBufMessage {
-            limit: 262_144,
-            length: len,
-            stream: Some(payload.take()),
-            fut: None,
-            err: None,
+        ProtoBufMessage {
+            limit: 262_144,
+            length: len,
+            stream: Some(payload.take()),
+            fut: None,
+            err: None,
         }
     }
 
-    /// Change max size of payload. By default max size is 256Kb
-    pub fn limit(mut self, limit: usize) -> Self {
-        self.limit = limit;
-        self
-    }
+    /// Change max size of payload. By default max size is 256Kb
+    pub fn limit(mut self, limit: usize) -> Self {
+        self.limit = limit;
+        self
+    }
 }
 
-impl<T: Message + Default + 'static> Future for ProtoBufMessage<T> {
-    type Output = Result<T, ProtoBufPayloadError>;
+impl<T: Message + Default + 'static> Future for ProtoBufMessage<T> {
+    type Output = Result<T, ProtoBufPayloadError>;
 
-    fn poll(mut self: Pin<&mut Self>, task: &mut task::Context<'_>) -> Poll<Self::Output> {
-        if let Some(ref mut fut) = self.fut {
-            return Pin::new(fut).poll(task);
+    fn poll(mut self: Pin<&mut Self>, task: &mut task::Context<'_>) -> Poll<Self::Output> {
+        if let Some(ref mut fut) = self.fut {
+            return Pin::new(fut).poll(task);
         }
 
-        if let Some(err) = self.err.take() {
-            return Poll::Ready(Err(err));
+        if let Some(err) = self.err.take() {
+            return Poll::Ready(Err(err));
         }
 
-        let limit = self.limit;
-        if let Some(len) = self.length.take() {
-            if len > limit {
-                return Poll::Ready(Err(ProtoBufPayloadError::Overflow));
+        let limit = self.limit;
+        if let Some(len) = self.length.take() {
+            if len > limit {
+                return Poll::Ready(Err(ProtoBufPayloadError::Overflow));
             }
         }
 
-        let mut stream = self
-            .stream
-            .take()
-            .expect("ProtoBufMessage could not be used second time");
+        let mut stream = self
+            .stream
+            .take()
+            .expect("ProtoBufMessage could not be used second time");
 
-        self.fut = Some(
-            async move {
-                let mut body = BytesMut::with_capacity(8192);
+        self.fut = Some(
+            async move {
+                let mut body = BytesMut::with_capacity(8192);
 
-                while let Some(item) = stream.next().await {
-                    let chunk = item?;
-                    if (body.len() + chunk.len()) > limit {
-                        return Err(ProtoBufPayloadError::Overflow);
-                    } else {
-                        body.extend_from_slice(&chunk);
+                while let Some(item) = stream.next().await {
+                    let chunk = item?;
+                    if (body.len() + chunk.len()) > limit {
+                        return Err(ProtoBufPayloadError::Overflow);
+                    } else {
+                        body.extend_from_slice(&chunk);
                     }
                 }
 
-                Ok(<T>::decode(&mut body)?)
+                Ok(<T>::decode(&mut body)?)
             }
-            .boxed_local(),
+            .boxed_local(),
         );
-        self.poll(task)
+        self.poll(task)
     }
 }
 
-pub trait ProtoBufResponseBuilder {
-    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
+pub trait ProtoBufResponseBuilder {
+    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
 }
 
-impl ProtoBufResponseBuilder for HttpResponseBuilder {
-    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
-        self.insert_header((CONTENT_TYPE, "application/protobuf"));
+impl ProtoBufResponseBuilder for HttpResponseBuilder {
+    fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
+        self.insert_header((CONTENT_TYPE, "application/protobuf"));
 
-        let mut body = Vec::new();
-        value
-            .encode(&mut body)
-            .map_err(ProtoBufPayloadError::Serialize)?;
-        Ok(self.body(body))
+        let mut body = Vec::new();
+        value
+            .encode(&mut body)
+            .map_err(ProtoBufPayloadError::Serialize)?;
+        Ok(self.body(body))
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use actix_web::http::header;
-    use actix_web::test::TestRequest;
+#[cfg(test)]
+mod tests {
+    use actix_web::http::header;
+    use actix_web::test::TestRequest;
 
-    use super::*;
+    use super::*;
 
-    impl PartialEq for ProtoBufPayloadError {
-        fn eq(&self, other: &ProtoBufPayloadError) -> bool {
-            match *self {
-                ProtoBufPayloadError::Overflow => {
-                    matches!(*other, ProtoBufPayloadError::Overflow)
+    impl PartialEq for ProtoBufPayloadError {
+        fn eq(&self, other: &ProtoBufPayloadError) -> bool {
+            match *self {
+                ProtoBufPayloadError::Overflow => {
+                    matches!(*other, ProtoBufPayloadError::Overflow)
                 }
-                ProtoBufPayloadError::ContentType => {
-                    matches!(*other, ProtoBufPayloadError::ContentType)
+                ProtoBufPayloadError::ContentType => {
+                    matches!(*other, ProtoBufPayloadError::ContentType)
                 }
-                _ => false,
+                _ => false,
             }
         }
     }
 
-    #[derive(Clone, PartialEq, Eq, Message)]
-    pub struct MyObject {
-        #[prost(int32, tag = "1")]
-        pub number: i32,
-        #[prost(string, tag = "2")]
-        pub name: String,
+    #[derive(Clone, PartialEq, Eq, Message)]
+    pub struct MyObject {
+        #[prost(int32, tag = "1")]
+        pub number: i32,
+        #[prost(string, tag = "2")]
+        pub name: String,
     }
 
-    #[actix_web::test]
-    async fn test_protobuf() {
-        let protobuf = ProtoBuf(MyObject {
-            number: 9,
-            name: "test".to_owned(),
+    #[actix_web::test]
+    async fn test_protobuf() {
+        let protobuf = ProtoBuf(MyObject {
+            number: 9,
+            name: "test".to_owned(),
         });
-        let req = TestRequest::default().to_http_request();
-        let resp = protobuf.respond_to(&req);
-        let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
-        assert_eq!(ct, "application/protobuf");
+        let req = TestRequest::default().to_http_request();
+        let resp = protobuf.respond_to(&req);
+        let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
+        assert_eq!(ct, "application/protobuf");
     }
 
-    #[actix_web::test]
-    async fn test_protobuf_message() {
-        let (req, mut pl) = TestRequest::default().to_http_parts();
-        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
-        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
+    #[actix_web::test]
+    async fn test_protobuf_message() {
+        let (req, mut pl) = TestRequest::default().to_http_parts();
+        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
+        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
 
-        let (req, mut pl) = TestRequest::get()
-            .insert_header((header::CONTENT_TYPE, "application/text"))
-            .to_http_parts();
-        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
-        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
+        let (req, mut pl) = TestRequest::get()
+            .insert_header((header::CONTENT_TYPE, "application/text"))
+            .to_http_parts();
+        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl).await;
+        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::ContentType);
 
-        let (req, mut pl) = TestRequest::get()
-            .insert_header((header::CONTENT_TYPE, "application/protobuf"))
-            .insert_header((header::CONTENT_LENGTH, "10000"))
-            .to_http_parts();
-        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl)
-            .limit(100)
+        let (req, mut pl) = TestRequest::get()
+            .insert_header((header::CONTENT_TYPE, "application/protobuf"))
+            .insert_header((header::CONTENT_LENGTH, "10000"))
+            .to_http_parts();
+        let protobuf = ProtoBufMessage::<MyObject>::new(&req, &mut pl)
+            .limit(100)
             .await;
-        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::Overflow);
+        assert_eq!(protobuf.err().unwrap(), ProtoBufPayloadError::Overflow);
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_redis/lib.rs.html b/src/actix_redis/lib.rs.html index 8db65ca85..e56543e6c 100644 --- a/src/actix_redis/lib.rs.html +++ b/src/actix_redis/lib.rs.html @@ -27,34 +27,34 @@ 27 28 29 -
//! Redis integration for `actix`.
+
//! Redis integration for `actix`.
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style)]
-#![warn(future_incompatible)]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible)]
 
-use derive_more::{Display, Error, From};
-pub use redis_async::{error::Error as RespError, resp::RespValue, resp_array};
+use derive_more::{Display, Error, From};
+pub use redis_async::{error::Error as RespError, resp::RespValue, resp_array};
 
-mod redis;
-pub use self::redis::{Command, RedisActor};
+mod redis;
+pub use self::redis::{Command, RedisActor};
 
-/// General purpose `actix-redis` error.
-#[derive(Debug, Display, Error, From)]
-pub enum Error {
-    #[display(fmt = "Redis error: {}", _0)]
-    Redis(redis_async::error::Error),
+/// General purpose `actix-redis` error.
+#[derive(Debug, Display, Error, From)]
+pub enum Error {
+    #[display(fmt = "Redis error: {}", _0)]
+    Redis(redis_async::error::Error),
 
-    /// Receiving message during reconnecting.
-    #[display(fmt = "Redis: Not connected")]
-    NotConnected,
+    /// Receiving message during reconnecting.
+    #[display(fmt = "Redis: Not connected")]
+    NotConnected,
 
-    /// Cancel all waiters when connection is dropped.
-    #[display(fmt = "Redis: Disconnected")]
-    Disconnected,
+    /// Cancel all waiters when connection is dropped.
+    #[display(fmt = "Redis: Disconnected")]
+    Disconnected,
 }
 
-#[cfg(feature = "web")]
-impl actix_web::ResponseError for Error {}
+#[cfg(feature = "web")]
+impl actix_web::ResponseError for Error {}
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_redis/redis.rs.html b/src/actix_redis/redis.rs.html index cacc4fefe..fb51aa55d 100644 --- a/src/actix_redis/redis.rs.html +++ b/src/actix_redis/redis.rs.html @@ -141,148 +141,148 @@ 141 142 143 -
use std::{collections::VecDeque, io};
+
use std::{collections::VecDeque, io};
 
-use actix::prelude::*;
-use actix_rt::net::TcpStream;
-use actix_service::boxed::{self, BoxService};
-use actix_tls::connect::{ConnectError, ConnectInfo, Connection, ConnectorService};
-use backoff::{backoff::Backoff, ExponentialBackoff};
-use log::{error, info, warn};
-use redis_async::{
-    error::Error as RespError,
-    resp::{RespCodec, RespValue},
+use actix::prelude::*;
+use actix_rt::net::TcpStream;
+use actix_service::boxed::{self, BoxService};
+use actix_tls::connect::{ConnectError, ConnectInfo, Connection, ConnectorService};
+use backoff::{backoff::Backoff, ExponentialBackoff};
+use log::{error, info, warn};
+use redis_async::{
+    error::Error as RespError,
+    resp::{RespCodec, RespValue},
 };
-use tokio::{
-    io::{split, WriteHalf},
-    sync::oneshot,
+use tokio::{
+    io::{split, WriteHalf},
+    sync::oneshot,
 };
-use tokio_util::codec::FramedRead;
+use tokio_util::codec::FramedRead;
 
-use crate::Error;
+use crate::Error;
 
-/// Command for sending data to Redis.
-#[derive(Debug)]
-pub struct Command(pub RespValue);
+/// Command for sending data to Redis.
+#[derive(Debug)]
+pub struct Command(pub RespValue);
 
-impl Message for Command {
-    type Result = Result<RespValue, Error>;
+impl Message for Command {
+    type Result = Result<RespValue, Error>;
 }
 
-/// Redis communication actor.
-pub struct RedisActor {
-    addr: String,
-    connector: BoxService<ConnectInfo<String>, Connection<String, TcpStream>, ConnectError>,
-    backoff: ExponentialBackoff,
-    cell: Option<actix::io::FramedWrite<RespValue, WriteHalf<TcpStream>, RespCodec>>,
-    queue: VecDeque<oneshot::Sender<Result<RespValue, Error>>>,
+/// Redis communication actor.
+pub struct RedisActor {
+    addr: String,
+    connector: BoxService<ConnectInfo<String>, Connection<String, TcpStream>, ConnectError>,
+    backoff: ExponentialBackoff,
+    cell: Option<actix::io::FramedWrite<RespValue, WriteHalf<TcpStream>, RespCodec>>,
+    queue: VecDeque<oneshot::Sender<Result<RespValue, Error>>>,
 }
 
-impl RedisActor {
-    /// Start new `Supervisor` with `RedisActor`.
-    pub fn start<S: Into<String>>(addr: S) -> Addr<RedisActor> {
-        let addr = addr.into();
+impl RedisActor {
+    /// Start new `Supervisor` with `RedisActor`.
+    pub fn start<S: Into<String>>(addr: S) -> Addr<RedisActor> {
+        let addr = addr.into();
 
-        let backoff = ExponentialBackoff {
-            max_elapsed_time: None,
-            ..Default::default()
+        let backoff = ExponentialBackoff {
+            max_elapsed_time: None,
+            ..Default::default()
         };
 
-        Supervisor::start(|_| RedisActor {
-            addr,
-            connector: boxed::service(ConnectorService::default()),
-            cell: None,
-            backoff,
-            queue: VecDeque::new(),
+        Supervisor::start(|_| RedisActor {
+            addr,
+            connector: boxed::service(ConnectorService::default()),
+            cell: None,
+            backoff,
+            queue: VecDeque::new(),
         })
     }
 }
 
-impl Actor for RedisActor {
-    type Context = Context<Self>;
+impl Actor for RedisActor {
+    type Context = Context<Self>;
 
-    fn started(&mut self, ctx: &mut Context<Self>) {
-        let req = ConnectInfo::new(self.addr.to_owned());
-        self.connector
-            .call(req)
-            .into_actor(self)
-            .map(|res, act, ctx| match res {
-                Ok(conn) => {
-                    let stream = conn.into_parts().0;
-                    info!("Connected to redis server: {}", act.addr);
+    fn started(&mut self, ctx: &mut Context<Self>) {
+        let req = ConnectInfo::new(self.addr.to_owned());
+        self.connector
+            .call(req)
+            .into_actor(self)
+            .map(|res, act, ctx| match res {
+                Ok(conn) => {
+                    let stream = conn.into_parts().0;
+                    info!("Connected to redis server: {}", act.addr);
 
-                    let (r, w) = split(stream);
+                    let (r, w) = split(stream);
 
-                    // configure write side of the connection
-                    let framed = actix::io::FramedWrite::new(w, RespCodec, ctx);
-                    act.cell = Some(framed);
+                    // configure write side of the connection
+                    let framed = actix::io::FramedWrite::new(w, RespCodec, ctx);
+                    act.cell = Some(framed);
 
-                    // read side of the connection
-                    ctx.add_stream(FramedRead::new(r, RespCodec));
+                    // read side of the connection
+                    ctx.add_stream(FramedRead::new(r, RespCodec));
 
-                    act.backoff.reset();
+                    act.backoff.reset();
                 }
-                Err(err) => {
-                    error!("Can not connect to redis server: {}", err);
-                    // re-connect with backoff time.
-                    // we stop current context, supervisor will restart it.
-                    if let Some(timeout) = act.backoff.next_backoff() {
-                        ctx.run_later(timeout, |_, ctx| ctx.stop());
+                Err(err) => {
+                    error!("Can not connect to redis server: {}", err);
+                    // re-connect with backoff time.
+                    // we stop current context, supervisor will restart it.
+                    if let Some(timeout) = act.backoff.next_backoff() {
+                        ctx.run_later(timeout, |_, ctx| ctx.stop());
                     }
                 }
             })
-            .wait(ctx);
+            .wait(ctx);
     }
 }
 
-impl Supervised for RedisActor {
-    fn restarting(&mut self, _: &mut Self::Context) {
-        self.cell.take();
-        for tx in self.queue.drain(..) {
-            let _ = tx.send(Err(Error::Disconnected));
+impl Supervised for RedisActor {
+    fn restarting(&mut self, _: &mut Self::Context) {
+        self.cell.take();
+        for tx in self.queue.drain(..) {
+            let _ = tx.send(Err(Error::Disconnected));
         }
     }
 }
 
-impl actix::io::WriteHandler<io::Error> for RedisActor {
-    fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
-        warn!("Redis connection dropped: {} error: {}", self.addr, err);
-        Running::Stop
+impl actix::io::WriteHandler<io::Error> for RedisActor {
+    fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
+        warn!("Redis connection dropped: {} error: {}", self.addr, err);
+        Running::Stop
     }
 }
 
-impl StreamHandler<Result<RespValue, RespError>> for RedisActor {
-    fn handle(&mut self, msg: Result<RespValue, RespError>, ctx: &mut Self::Context) {
-        match msg {
-            Err(e) => {
-                if let Some(tx) = self.queue.pop_front() {
-                    let _ = tx.send(Err(e.into()));
+impl StreamHandler<Result<RespValue, RespError>> for RedisActor {
+    fn handle(&mut self, msg: Result<RespValue, RespError>, ctx: &mut Self::Context) {
+        match msg {
+            Err(e) => {
+                if let Some(tx) = self.queue.pop_front() {
+                    let _ = tx.send(Err(e.into()));
                 }
-                ctx.stop();
+                ctx.stop();
             }
-            Ok(val) => {
-                if let Some(tx) = self.queue.pop_front() {
-                    let _ = tx.send(Ok(val));
+            Ok(val) => {
+                if let Some(tx) = self.queue.pop_front() {
+                    let _ = tx.send(Ok(val));
                 }
             }
         }
     }
 }
 
-impl Handler<Command> for RedisActor {
-    type Result = ResponseFuture<Result<RespValue, Error>>;
+impl Handler<Command> for RedisActor {
+    type Result = ResponseFuture<Result<RespValue, Error>>;
 
-    fn handle(&mut self, msg: Command, _: &mut Self::Context) -> Self::Result {
-        let (tx, rx) = oneshot::channel();
-        if let Some(ref mut cell) = self.cell {
-            self.queue.push_back(tx);
-            cell.write(msg.0);
-        } else {
-            let _ = tx.send(Err(Error::NotConnected));
+    fn handle(&mut self, msg: Command, _: &mut Self::Context) -> Self::Result {
+        let (tx, rx) = oneshot::channel();
+        if let Some(ref mut cell) = self.cell {
+            self.queue.push_back(tx);
+            cell.write(msg.0);
+        } else {
+            let _ = tx.send(Err(Error::NotConnected));
         }
 
-        Box::pin(async move { rx.await.map_err(|_| Error::Disconnected)? })
+        Box::pin(async move { rx.await.map_err(|_| Error::Disconnected)? })
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/config.rs.html b/src/actix_session/config.rs.html index cb23fa4d0..6c9a5f848 100644 --- a/src/actix_session/config.rs.html +++ b/src/actix_session/config.rs.html @@ -396,401 +396,401 @@ 394 395 396 -
//! Configuration options to tune the behaviour of [`SessionMiddleware`].
+
//! Configuration options to tune the behaviour of [`SessionMiddleware`].
 
-use actix_web::cookie::{time::Duration, Key, SameSite};
-use derive_more::From;
+use actix_web::cookie::{time::Duration, Key, SameSite};
+use derive_more::From;
 
-use crate::{storage::SessionStore, SessionMiddleware};
+use crate::{storage::SessionStore, SessionMiddleware};
 
-/// Determines what type of session cookie should be used and how its lifecycle should be managed.
-///
-/// Used by [`SessionMiddlewareBuilder::session_lifecycle`].
-#[derive(Debug, Clone, From)]
-#[non_exhaustive]
-pub enum SessionLifecycle {
-    /// The session cookie will expire when the current browser session ends.
-    ///
-    /// When does a browser session end? It depends on the browser! Chrome, for example, will often
-    /// continue running in the background when the browser is closed—session cookies are not
-    /// deleted and they will still be available when the browser is opened again.
-    /// Check the documentation of the browsers you are targeting for up-to-date information.
-    BrowserSession(BrowserSession),
+/// Determines what type of session cookie should be used and how its lifecycle should be managed.
+///
+/// Used by [`SessionMiddlewareBuilder::session_lifecycle`].
+#[derive(Debug, Clone, From)]
+#[non_exhaustive]
+pub enum SessionLifecycle {
+    /// The session cookie will expire when the current browser session ends.
+    ///
+    /// When does a browser session end? It depends on the browser! Chrome, for example, will often
+    /// continue running in the background when the browser is closed—session cookies are not
+    /// deleted and they will still be available when the browser is opened again.
+    /// Check the documentation of the browsers you are targeting for up-to-date information.
+    BrowserSession(BrowserSession),
 
-    /// The session cookie will be a [persistent cookie].
-    ///
-    /// Persistent cookies have a pre-determined lifetime, specified via the `Max-Age` or `Expires`
-    /// attribute. They do not disappear when the current browser session ends.
-    ///
-    /// [persistent cookie]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
-    PersistentSession(PersistentSession),
+    /// The session cookie will be a [persistent cookie].
+    ///
+    /// Persistent cookies have a pre-determined lifetime, specified via the `Max-Age` or `Expires`
+    /// attribute. They do not disappear when the current browser session ends.
+    ///
+    /// [persistent cookie]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
+    PersistentSession(PersistentSession),
 }
 
-/// A [session lifecycle](SessionLifecycle) strategy where the session cookie expires when the
-/// browser's current session ends.
-///
-/// When does a browser session end? It depends on the browser. Chrome, for example, will often
-/// continue running in the background when the browser is closed—session cookies are not deleted
-/// and they will still be available when the browser is opened again. Check the documentation of
-/// the browsers you are targeting for up-to-date information.
-///
-/// Due to its `Into<SessionLifecycle>` implementation, a `BrowserSession` can be passed directly
-/// to [`SessionMiddlewareBuilder::session_lifecycle()`].
-#[derive(Debug, Clone)]
-pub struct BrowserSession {
-    state_ttl: Duration,
-    state_ttl_extension_policy: TtlExtensionPolicy,
+/// A [session lifecycle](SessionLifecycle) strategy where the session cookie expires when the
+/// browser's current session ends.
+///
+/// When does a browser session end? It depends on the browser. Chrome, for example, will often
+/// continue running in the background when the browser is closed—session cookies are not deleted
+/// and they will still be available when the browser is opened again. Check the documentation of
+/// the browsers you are targeting for up-to-date information.
+///
+/// Due to its `Into<SessionLifecycle>` implementation, a `BrowserSession` can be passed directly
+/// to [`SessionMiddlewareBuilder::session_lifecycle()`].
+#[derive(Debug, Clone)]
+pub struct BrowserSession {
+    state_ttl: Duration,
+    state_ttl_extension_policy: TtlExtensionPolicy,
 }
 
-impl BrowserSession {
-    /// Sets a time-to-live (TTL) when storing the session state in the storage backend.
-    ///
-    /// We do not want to store session states indefinitely, otherwise we will inevitably run out of
-    /// storage by holding on to the state of countless abandoned or expired sessions!
-    ///
-    /// We are dealing with the lifecycle of two uncorrelated object here: the session cookie
-    /// and the session state. It is not a big issue if the session state outlives the cookie—
-    /// we are wasting some space in the backend storage, but it will be cleaned up eventually.
-    /// What happens, instead, if the cookie outlives the session state? A new session starts—
-    /// e.g. if sessions are being used for authentication, the user is de-facto logged out.
-    ///
-    /// It is not possible to predict with certainty how long a browser session is going to
-    /// last—you need to provide a reasonable upper bound. You do so via `state_ttl`—it dictates
-    /// what TTL should be used for session state when the lifecycle of the session cookie is
-    /// tied to the browser session length. [`SessionMiddleware`] will default to 1 day if
-    /// `state_ttl` is left unspecified.
-    ///
-    /// You can mitigate the risk of the session cookie outliving the session state by
-    /// specifying a more aggressive state TTL extension policy - check out
-    /// [`BrowserSession::state_ttl_extension_policy`] for more details.
-    pub fn state_ttl(mut self, ttl: Duration) -> Self {
-        self.state_ttl = ttl;
-        self
-    }
+impl BrowserSession {
+    /// Sets a time-to-live (TTL) when storing the session state in the storage backend.
+    ///
+    /// We do not want to store session states indefinitely, otherwise we will inevitably run out of
+    /// storage by holding on to the state of countless abandoned or expired sessions!
+    ///
+    /// We are dealing with the lifecycle of two uncorrelated object here: the session cookie
+    /// and the session state. It is not a big issue if the session state outlives the cookie—
+    /// we are wasting some space in the backend storage, but it will be cleaned up eventually.
+    /// What happens, instead, if the cookie outlives the session state? A new session starts—
+    /// e.g. if sessions are being used for authentication, the user is de-facto logged out.
+    ///
+    /// It is not possible to predict with certainty how long a browser session is going to
+    /// last—you need to provide a reasonable upper bound. You do so via `state_ttl`—it dictates
+    /// what TTL should be used for session state when the lifecycle of the session cookie is
+    /// tied to the browser session length. [`SessionMiddleware`] will default to 1 day if
+    /// `state_ttl` is left unspecified.
+    ///
+    /// You can mitigate the risk of the session cookie outliving the session state by
+    /// specifying a more aggressive state TTL extension policy - check out
+    /// [`BrowserSession::state_ttl_extension_policy`] for more details.
+    pub fn state_ttl(mut self, ttl: Duration) -> Self {
+        self.state_ttl = ttl;
+        self
+    }
 
-    /// Determine under what circumstances the TTL of your session state should be extended.
-    ///
-    /// Defaults to [`TtlExtensionPolicy::OnStateChanges`] if left unspecified.
-    ///
-    /// See [`TtlExtensionPolicy`] for more details.
-    pub fn state_ttl_extension_policy(mut self, ttl_extension_policy: TtlExtensionPolicy) -> Self {
-        self.state_ttl_extension_policy = ttl_extension_policy;
-        self
-    }
+    /// Determine under what circumstances the TTL of your session state should be extended.
+    ///
+    /// Defaults to [`TtlExtensionPolicy::OnStateChanges`] if left unspecified.
+    ///
+    /// See [`TtlExtensionPolicy`] for more details.
+    pub fn state_ttl_extension_policy(mut self, ttl_extension_policy: TtlExtensionPolicy) -> Self {
+        self.state_ttl_extension_policy = ttl_extension_policy;
+        self
+    }
 }
 
-impl Default for BrowserSession {
-    fn default() -> Self {
-        Self {
-            state_ttl: default_ttl(),
-            state_ttl_extension_policy: default_ttl_extension_policy(),
+impl Default for BrowserSession {
+    fn default() -> Self {
+        Self {
+            state_ttl: default_ttl(),
+            state_ttl_extension_policy: default_ttl_extension_policy(),
         }
     }
 }
 
-/// A [session lifecycle](SessionLifecycle) strategy where the session cookie will be [persistent].
-///
-/// Persistent cookies have a pre-determined expiration, specified via the `Max-Age` or `Expires`
-/// attribute. They do not disappear when the current browser session ends.
-///
-/// Due to its `Into<SessionLifecycle>` implementation, a `PersistentSession` can be passed directly
-/// to [`SessionMiddlewareBuilder::session_lifecycle()`].
-///
-/// # Examples
-/// ```
-/// use actix_web::cookie::time::Duration;
-/// use actix_session::SessionMiddleware;
-/// use actix_session::config::{PersistentSession, TtlExtensionPolicy};
-///
-/// const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
-///
-/// // a session lifecycle with a time-to-live (expiry) of 1 week and default extension policy
-/// PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK));
-///
-/// // a session lifecycle with the default time-to-live (expiry) and a custom extension policy
-/// PersistentSession::default()
-///     // this policy causes the session state's TTL to be refreshed on every request
-///     .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest);
-/// ```
-///
-/// [persistent]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
-#[derive(Debug, Clone)]
-pub struct PersistentSession {
-    session_ttl: Duration,
-    ttl_extension_policy: TtlExtensionPolicy,
+/// A [session lifecycle](SessionLifecycle) strategy where the session cookie will be [persistent].
+///
+/// Persistent cookies have a pre-determined expiration, specified via the `Max-Age` or `Expires`
+/// attribute. They do not disappear when the current browser session ends.
+///
+/// Due to its `Into<SessionLifecycle>` implementation, a `PersistentSession` can be passed directly
+/// to [`SessionMiddlewareBuilder::session_lifecycle()`].
+///
+/// # Examples
+/// ```
+/// use actix_web::cookie::time::Duration;
+/// use actix_session::SessionMiddleware;
+/// use actix_session::config::{PersistentSession, TtlExtensionPolicy};
+///
+/// const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
+///
+/// // a session lifecycle with a time-to-live (expiry) of 1 week and default extension policy
+/// PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK));
+///
+/// // a session lifecycle with the default time-to-live (expiry) and a custom extension policy
+/// PersistentSession::default()
+///     // this policy causes the session state's TTL to be refreshed on every request
+///     .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest);
+/// ```
+///
+/// [persistent]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
+#[derive(Debug, Clone)]
+pub struct PersistentSession {
+    session_ttl: Duration,
+    ttl_extension_policy: TtlExtensionPolicy,
 }
 
-impl PersistentSession {
-    /// Specifies how long the session cookie should live.
-    ///
-    /// The session TTL is also used as the TTL for the session state in the storage backend.
-    ///
-    /// Defaults to 1 day.
-    ///
-    /// A persistent session can live more than the specified TTL if the TTL is extended.
-    /// See [`session_ttl_extension_policy`](Self::session_ttl_extension_policy) for more details.
-    pub fn session_ttl(mut self, session_ttl: Duration) -> Self {
-        self.session_ttl = session_ttl;
-        self
-    }
+impl PersistentSession {
+    /// Specifies how long the session cookie should live.
+    ///
+    /// The session TTL is also used as the TTL for the session state in the storage backend.
+    ///
+    /// Defaults to 1 day.
+    ///
+    /// A persistent session can live more than the specified TTL if the TTL is extended.
+    /// See [`session_ttl_extension_policy`](Self::session_ttl_extension_policy) for more details.
+    pub fn session_ttl(mut self, session_ttl: Duration) -> Self {
+        self.session_ttl = session_ttl;
+        self
+    }
 
-    /// Determines under what circumstances the TTL of your session should be extended.
-    /// See [`TtlExtensionPolicy`] for more details.
-    ///
-    /// Defaults to [`TtlExtensionPolicy::OnStateChanges`].
-    pub fn session_ttl_extension_policy(
-        mut self,
-        ttl_extension_policy: TtlExtensionPolicy,
-    ) -> Self {
-        self.ttl_extension_policy = ttl_extension_policy;
-        self
-    }
+    /// Determines under what circumstances the TTL of your session should be extended.
+    /// See [`TtlExtensionPolicy`] for more details.
+    ///
+    /// Defaults to [`TtlExtensionPolicy::OnStateChanges`].
+    pub fn session_ttl_extension_policy(
+        mut self,
+        ttl_extension_policy: TtlExtensionPolicy,
+    ) -> Self {
+        self.ttl_extension_policy = ttl_extension_policy;
+        self
+    }
 }
 
-impl Default for PersistentSession {
-    fn default() -> Self {
-        Self {
-            session_ttl: default_ttl(),
-            ttl_extension_policy: default_ttl_extension_policy(),
+impl Default for PersistentSession {
+    fn default() -> Self {
+        Self {
+            session_ttl: default_ttl(),
+            ttl_extension_policy: default_ttl_extension_policy(),
         }
     }
 }
 
-/// Configuration for which events should trigger an extension of the time-to-live for your session.
-///
-/// If you are using a [`BrowserSession`], `TtlExtensionPolicy` controls how often the TTL of the
-/// session state should be refreshed. The browser is in control of the lifecycle of the session
-/// cookie.
-///
-/// If you are using a [`PersistentSession`], `TtlExtensionPolicy` controls both the expiration of
-/// the session cookie and the TTL of the session state on the storage backend.
-#[derive(Debug, Clone)]
-#[non_exhaustive]
-pub enum TtlExtensionPolicy {
-    /// The TTL is refreshed every time the server receives a request associated with a session.
-    ///
-    /// # Performance impact
-    /// Refreshing the TTL on every request is not free. It implies a refresh of the TTL on the
-    /// session state. This translates into a request over the network if you are using a remote
-    /// system as storage backend (e.g. Redis). This impacts both the total load on your storage
-    /// backend (i.e. number of queries it has to handle) and the latency of the requests served by
-    /// your server.
-    OnEveryRequest,
+/// Configuration for which events should trigger an extension of the time-to-live for your session.
+///
+/// If you are using a [`BrowserSession`], `TtlExtensionPolicy` controls how often the TTL of the
+/// session state should be refreshed. The browser is in control of the lifecycle of the session
+/// cookie.
+///
+/// If you are using a [`PersistentSession`], `TtlExtensionPolicy` controls both the expiration of
+/// the session cookie and the TTL of the session state on the storage backend.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub enum TtlExtensionPolicy {
+    /// The TTL is refreshed every time the server receives a request associated with a session.
+    ///
+    /// # Performance impact
+    /// Refreshing the TTL on every request is not free. It implies a refresh of the TTL on the
+    /// session state. This translates into a request over the network if you are using a remote
+    /// system as storage backend (e.g. Redis). This impacts both the total load on your storage
+    /// backend (i.e. number of queries it has to handle) and the latency of the requests served by
+    /// your server.
+    OnEveryRequest,
 
-    /// The TTL is refreshed every time the session state changes or the session key is renewed.
-    OnStateChanges,
+    /// The TTL is refreshed every time the session state changes or the session key is renewed.
+    OnStateChanges,
 }
 
-/// Determines how to secure the content of the session cookie.
-///
-/// Used by [`SessionMiddlewareBuilder::cookie_content_security`].
-#[derive(Debug, Clone, Copy)]
-pub enum CookieContentSecurity {
-    /// The cookie content is encrypted when using `CookieContentSecurity::Private`.
-    ///
-    /// Encryption guarantees confidentiality and integrity: the client cannot tamper with the
-    /// cookie content nor decode it, as long as the encryption key remains confidential.
-    Private,
+/// Determines how to secure the content of the session cookie.
+///
+/// Used by [`SessionMiddlewareBuilder::cookie_content_security`].
+#[derive(Debug, Clone, Copy)]
+pub enum CookieContentSecurity {
+    /// The cookie content is encrypted when using `CookieContentSecurity::Private`.
+    ///
+    /// Encryption guarantees confidentiality and integrity: the client cannot tamper with the
+    /// cookie content nor decode it, as long as the encryption key remains confidential.
+    Private,
 
-    /// The cookie content is signed when using `CookieContentSecurity::Signed`.
-    ///
-    /// Signing guarantees integrity, but it doesn't ensure confidentiality: the client cannot
-    /// tamper with the cookie content, but they can read it.
-    Signed,
+    /// The cookie content is signed when using `CookieContentSecurity::Signed`.
+    ///
+    /// Signing guarantees integrity, but it doesn't ensure confidentiality: the client cannot
+    /// tamper with the cookie content, but they can read it.
+    Signed,
 }
 
-pub(crate) const fn default_ttl() -> Duration {
-    Duration::days(1)
+pub(crate) const fn default_ttl() -> Duration {
+    Duration::days(1)
 }
 
-pub(crate) const fn default_ttl_extension_policy() -> TtlExtensionPolicy {
-    TtlExtensionPolicy::OnStateChanges
+pub(crate) const fn default_ttl_extension_policy() -> TtlExtensionPolicy {
+    TtlExtensionPolicy::OnStateChanges
 }
 
-/// A fluent, customized [`SessionMiddleware`] builder.
-#[must_use]
-pub struct SessionMiddlewareBuilder<Store: SessionStore> {
-    storage_backend: Store,
-    configuration: Configuration,
+/// A fluent, customized [`SessionMiddleware`] builder.
+#[must_use]
+pub struct SessionMiddlewareBuilder<Store: SessionStore> {
+    storage_backend: Store,
+    configuration: Configuration,
 }
 
-impl<Store: SessionStore> SessionMiddlewareBuilder<Store> {
-    pub(crate) fn new(store: Store, configuration: Configuration) -> Self {
-        Self {
-            storage_backend: store,
-            configuration,
+impl<Store: SessionStore> SessionMiddlewareBuilder<Store> {
+    pub(crate) fn new(store: Store, configuration: Configuration) -> Self {
+        Self {
+            storage_backend: store,
+            configuration,
         }
     }
 
-    /// Set the name of the cookie used to store the session ID.
-    ///
-    /// Defaults to `id`.
-    pub fn cookie_name(mut self, name: String) -> Self {
-        self.configuration.cookie.name = name;
-        self
-    }
+    /// Set the name of the cookie used to store the session ID.
+    ///
+    /// Defaults to `id`.
+    pub fn cookie_name(mut self, name: String) -> Self {
+        self.configuration.cookie.name = name;
+        self
+    }
 
-    /// Set the `Secure` attribute for the cookie used to store the session ID.
-    ///
-    /// If the cookie is set as secure, it will only be transmitted when the connection is secure
-    /// (using `https`).
-    ///
-    /// Default is `true`.
-    pub fn cookie_secure(mut self, secure: bool) -> Self {
-        self.configuration.cookie.secure = secure;
-        self
-    }
+    /// Set the `Secure` attribute for the cookie used to store the session ID.
+    ///
+    /// If the cookie is set as secure, it will only be transmitted when the connection is secure
+    /// (using `https`).
+    ///
+    /// Default is `true`.
+    pub fn cookie_secure(mut self, secure: bool) -> Self {
+        self.configuration.cookie.secure = secure;
+        self
+    }
 
-    /// Determines what type of session cookie should be used and how its lifecycle should be managed.
-    /// Check out [`SessionLifecycle`]'s documentation for more details on the available options.
-    ///
-    /// Default is [`SessionLifecycle::BrowserSession`].
-    ///
-    /// # Examples
-    /// ```
-    /// use actix_web::cookie::{Key, time::Duration};
-    /// use actix_session::{SessionMiddleware, config::PersistentSession};
-    /// use actix_session::storage::CookieSessionStore;
-    ///
-    /// const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
-    ///
-    /// // creates a session middleware with a time-to-live (expiry) of 1 week
-    /// SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
-    ///     .session_lifecycle(
-    ///         PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK))
-    ///     )
-    ///     .build();
-    /// ```
-    pub fn session_lifecycle<S: Into<SessionLifecycle>>(mut self, session_lifecycle: S) -> Self {
-        match session_lifecycle.into() {
-            SessionLifecycle::BrowserSession(BrowserSession {
-                state_ttl,
-                state_ttl_extension_policy,
+    /// Determines what type of session cookie should be used and how its lifecycle should be managed.
+    /// Check out [`SessionLifecycle`]'s documentation for more details on the available options.
+    ///
+    /// Default is [`SessionLifecycle::BrowserSession`].
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_web::cookie::{Key, time::Duration};
+    /// use actix_session::{SessionMiddleware, config::PersistentSession};
+    /// use actix_session::storage::CookieSessionStore;
+    ///
+    /// const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
+    ///
+    /// // creates a session middleware with a time-to-live (expiry) of 1 week
+    /// SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
+    ///     .session_lifecycle(
+    ///         PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK))
+    ///     )
+    ///     .build();
+    /// ```
+    pub fn session_lifecycle<S: Into<SessionLifecycle>>(mut self, session_lifecycle: S) -> Self {
+        match session_lifecycle.into() {
+            SessionLifecycle::BrowserSession(BrowserSession {
+                state_ttl,
+                state_ttl_extension_policy,
             }) => {
-                self.configuration.cookie.max_age = None;
-                self.configuration.session.state_ttl = state_ttl;
-                self.configuration.ttl_extension_policy = state_ttl_extension_policy;
+                self.configuration.cookie.max_age = None;
+                self.configuration.session.state_ttl = state_ttl;
+                self.configuration.ttl_extension_policy = state_ttl_extension_policy;
             }
-            SessionLifecycle::PersistentSession(PersistentSession {
-                session_ttl,
-                ttl_extension_policy,
+            SessionLifecycle::PersistentSession(PersistentSession {
+                session_ttl,
+                ttl_extension_policy,
             }) => {
-                self.configuration.cookie.max_age = Some(session_ttl);
-                self.configuration.session.state_ttl = session_ttl;
-                self.configuration.ttl_extension_policy = ttl_extension_policy;
+                self.configuration.cookie.max_age = Some(session_ttl);
+                self.configuration.session.state_ttl = session_ttl;
+                self.configuration.ttl_extension_policy = ttl_extension_policy;
             }
         }
 
-        self
-    }
+        self
+    }
 
-    /// Set the `SameSite` attribute for the cookie used to store the session ID.
-    ///
-    /// By default, the attribute is set to `Lax`.
-    pub fn cookie_same_site(mut self, same_site: SameSite) -> Self {
-        self.configuration.cookie.same_site = same_site;
-        self
-    }
+    /// Set the `SameSite` attribute for the cookie used to store the session ID.
+    ///
+    /// By default, the attribute is set to `Lax`.
+    pub fn cookie_same_site(mut self, same_site: SameSite) -> Self {
+        self.configuration.cookie.same_site = same_site;
+        self
+    }
 
-    /// Set the `Path` attribute for the cookie used to store the session ID.
-    ///
-    /// By default, the attribute is set to `/`.
-    pub fn cookie_path(mut self, path: String) -> Self {
-        self.configuration.cookie.path = path;
-        self
-    }
+    /// Set the `Path` attribute for the cookie used to store the session ID.
+    ///
+    /// By default, the attribute is set to `/`.
+    pub fn cookie_path(mut self, path: String) -> Self {
+        self.configuration.cookie.path = path;
+        self
+    }
 
-    /// Set the `Domain` attribute for the cookie used to store the session ID.
-    ///
-    /// Use `None` to leave the attribute unspecified. If unspecified, the attribute defaults
-    /// to the same host that set the cookie, excluding subdomains.
-    ///
-    /// By default, the attribute is left unspecified.
-    pub fn cookie_domain(mut self, domain: Option<String>) -> Self {
-        self.configuration.cookie.domain = domain;
-        self
-    }
+    /// Set the `Domain` attribute for the cookie used to store the session ID.
+    ///
+    /// Use `None` to leave the attribute unspecified. If unspecified, the attribute defaults
+    /// to the same host that set the cookie, excluding subdomains.
+    ///
+    /// By default, the attribute is left unspecified.
+    pub fn cookie_domain(mut self, domain: Option<String>) -> Self {
+        self.configuration.cookie.domain = domain;
+        self
+    }
 
-    /// Choose how the session cookie content should be secured.
-    ///
-    /// - [`CookieContentSecurity::Private`] selects encrypted cookie content.
-    /// - [`CookieContentSecurity::Signed`] selects signed cookie content.
-    ///
-    /// # Default
-    /// By default, the cookie content is encrypted. Encrypted was chosen instead of signed as
-    /// default because it reduces the chances of sensitive information being exposed in the session
-    /// key by accident, regardless of [`SessionStore`] implementation you chose to use.
-    ///
-    /// For example, if you are using cookie-based storage, you definitely want the cookie content
-    /// to be encrypted—the whole session state is embedded in the cookie! If you are using
-    /// Redis-based storage, signed is more than enough - the cookie content is just a unique
-    /// tamper-proof session key.
-    pub fn cookie_content_security(mut self, content_security: CookieContentSecurity) -> Self {
-        self.configuration.cookie.content_security = content_security;
-        self
-    }
+    /// Choose how the session cookie content should be secured.
+    ///
+    /// - [`CookieContentSecurity::Private`] selects encrypted cookie content.
+    /// - [`CookieContentSecurity::Signed`] selects signed cookie content.
+    ///
+    /// # Default
+    /// By default, the cookie content is encrypted. Encrypted was chosen instead of signed as
+    /// default because it reduces the chances of sensitive information being exposed in the session
+    /// key by accident, regardless of [`SessionStore`] implementation you chose to use.
+    ///
+    /// For example, if you are using cookie-based storage, you definitely want the cookie content
+    /// to be encrypted—the whole session state is embedded in the cookie! If you are using
+    /// Redis-based storage, signed is more than enough - the cookie content is just a unique
+    /// tamper-proof session key.
+    pub fn cookie_content_security(mut self, content_security: CookieContentSecurity) -> Self {
+        self.configuration.cookie.content_security = content_security;
+        self
+    }
 
-    /// Set the `HttpOnly` attribute for the cookie used to store the session ID.
-    ///
-    /// If the cookie is set as `HttpOnly`, it will not be visible to any JavaScript snippets
-    /// running in the browser.
-    ///
-    /// Default is `true`.
-    pub fn cookie_http_only(mut self, http_only: bool) -> Self {
-        self.configuration.cookie.http_only = http_only;
-        self
-    }
+    /// Set the `HttpOnly` attribute for the cookie used to store the session ID.
+    ///
+    /// If the cookie is set as `HttpOnly`, it will not be visible to any JavaScript snippets
+    /// running in the browser.
+    ///
+    /// Default is `true`.
+    pub fn cookie_http_only(mut self, http_only: bool) -> Self {
+        self.configuration.cookie.http_only = http_only;
+        self
+    }
 
-    /// Finalise the builder and return a [`SessionMiddleware`] instance.
-    #[must_use]
-    pub fn build(self) -> SessionMiddleware<Store> {
-        SessionMiddleware::from_parts(self.storage_backend, self.configuration)
+    /// Finalise the builder and return a [`SessionMiddleware`] instance.
+    #[must_use]
+    pub fn build(self) -> SessionMiddleware<Store> {
+        SessionMiddleware::from_parts(self.storage_backend, self.configuration)
     }
 }
 
-#[derive(Clone)]
-pub(crate) struct Configuration {
-    pub(crate) cookie: CookieConfiguration,
-    pub(crate) session: SessionConfiguration,
-    pub(crate) ttl_extension_policy: TtlExtensionPolicy,
+#[derive(Clone)]
+pub(crate) struct Configuration {
+    pub(crate) cookie: CookieConfiguration,
+    pub(crate) session: SessionConfiguration,
+    pub(crate) ttl_extension_policy: TtlExtensionPolicy,
 }
 
-#[derive(Clone)]
-pub(crate) struct SessionConfiguration {
-    pub(crate) state_ttl: Duration,
+#[derive(Clone)]
+pub(crate) struct SessionConfiguration {
+    pub(crate) state_ttl: Duration,
 }
 
-#[derive(Clone)]
-pub(crate) struct CookieConfiguration {
-    pub(crate) secure: bool,
-    pub(crate) http_only: bool,
-    pub(crate) name: String,
-    pub(crate) same_site: SameSite,
-    pub(crate) path: String,
-    pub(crate) domain: Option<String>,
-    pub(crate) max_age: Option<Duration>,
-    pub(crate) content_security: CookieContentSecurity,
-    pub(crate) key: Key,
+#[derive(Clone)]
+pub(crate) struct CookieConfiguration {
+    pub(crate) secure: bool,
+    pub(crate) http_only: bool,
+    pub(crate) name: String,
+    pub(crate) same_site: SameSite,
+    pub(crate) path: String,
+    pub(crate) domain: Option<String>,
+    pub(crate) max_age: Option<Duration>,
+    pub(crate) content_security: CookieContentSecurity,
+    pub(crate) key: Key,
 }
 
-pub(crate) fn default_configuration(key: Key) -> Configuration {
-    Configuration {
-        cookie: CookieConfiguration {
-            secure: true,
-            http_only: true,
-            name: "id".into(),
-            same_site: SameSite::Lax,
-            path: "/".into(),
-            domain: None,
-            max_age: None,
-            content_security: CookieContentSecurity::Private,
-            key,
+pub(crate) fn default_configuration(key: Key) -> Configuration {
+    Configuration {
+        cookie: CookieConfiguration {
+            secure: true,
+            http_only: true,
+            name: "id".into(),
+            same_site: SameSite::Lax,
+            path: "/".into(),
+            domain: None,
+            max_age: None,
+            content_security: CookieContentSecurity::Private,
+            key,
         },
-        session: SessionConfiguration {
-            state_ttl: default_ttl(),
+        session: SessionConfiguration {
+            state_ttl: default_ttl(),
         },
-        ttl_extension_policy: default_ttl_extension_policy(),
+        ttl_extension_policy: default_ttl_extension_policy(),
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/lib.rs.html b/src/actix_session/lib.rs.html index 8b51eea2f..918f5d59f 100644 --- a/src/actix_session/lib.rs.html +++ b/src/actix_session/lib.rs.html @@ -732,737 +732,737 @@ 730 731 732 -
//! Session management for Actix Web.
-//!
-//! The HTTP protocol, at a first glance, is stateless: the client sends a request, the server
-//! parses its content, performs some processing and returns a response. The outcome is only
-//! influenced by the provided inputs (i.e. the request content) and whatever state the server
-//! queries while performing its processing.
-//!
-//! Stateless systems are easier to reason about, but they are not quite as powerful as we need them
-//! to be - e.g. how do you authenticate a user? The user would be forced to authenticate **for
-//! every single request**. That is, for example, how 'Basic' Authentication works. While it may
-//! work for a machine user (i.e. an API client), it is impractical for a person—you do not want a
-//! login prompt on every single page you navigate to!
-//!
-//! There is a solution - **sessions**. Using sessions the server can attach state to a set of
-//! requests coming from the same client. They are built on top of cookies - the server sets a
-//! cookie in the HTTP response (`Set-Cookie` header), the client (e.g. the browser) will store the
-//! cookie and play it back to the server when sending new requests (using the `Cookie` header).
-//!
-//! We refer to the cookie used for sessions as a **session cookie**. Its content is called
-//! **session key** (or **session ID**), while the state attached to the session is referred to as
-//! **session state**.
-//!
-//! `actix-session` provides an easy-to-use framework to manage sessions in applications built on
-//! top of Actix Web. [`SessionMiddleware`] is the middleware underpinning the functionality
-//! provided by `actix-session`; it takes care of all the session cookie handling and instructs the
-//! **storage backend** to create/delete/update the session state based on the operations performed
-//! against the active [`Session`].
-//!
-//! `actix-session` provides some built-in storage backends: ([`CookieSessionStore`],
-//! [`RedisSessionStore`], and [`RedisActorSessionStore`]) - you can create a custom storage backend
-//! by implementing the [`SessionStore`] trait.
-//!
-//! Further reading on sessions:
-//! - [RFC6265](https://datatracker.ietf.org/doc/html/rfc6265);
-//! - [OWASP's session management cheat-sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
-//!
-//! # Getting started
-//! To start using sessions in your Actix Web application you must register [`SessionMiddleware`]
-//! as a middleware on your `App`:
-//!
-//! ```no_run
-//! use actix_web::{web, App, HttpServer, HttpResponse, Error};
-//! use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
-//! use actix_web::cookie::Key;
-//!
-//! #[actix_web::main]
-//! async fn main() -> std::io::Result<()> {
-//!     // The secret key would usually be read from a configuration file/environment variables.
-//!     let secret_key = Key::generate();
-//!     let redis_connection_string = "127.0.0.1:6379";
-//!     HttpServer::new(move ||
-//!             App::new()
-//!             // Add session management to your application using Redis for session state storage
-//!             .wrap(
-//!                 SessionMiddleware::new(
-//!                     RedisActorSessionStore::new(redis_connection_string),
-//!                     secret_key.clone()
-//!                 )
-//!             )
-//!             .default_service(web::to(|| HttpResponse::Ok())))
-//!         .bind(("127.0.0.1", 8080))?
-//!         .run()
-//!         .await
-//! }
-//! ```
-//!
-//! The session state can be accessed and modified by your request handlers using the [`Session`]
-//! extractor.
-//!
-//! ```no_run
-//! use actix_web::Error;
-//! use actix_session::Session;
-//!
-//! fn index(session: Session) -> Result<&'static str, Error> {
-//!     // access the session state
-//!     if let Some(count) = session.get::<i32>("counter")? {
-//!         println!("SESSION value: {}", count);
-//!         // modify the session state
-//!         session.insert("counter", count + 1)?;
-//!     } else {
-//!         session.insert("counter", 1)?;
-//!     }
-//!
-//!     Ok("Welcome!")
-//! }
-//! ```
-//!
-//! # Choosing A Backend
-//!
-//! By default, `actix-session` does not provide any storage backend to retrieve and save the state
-//! attached to your sessions. You can enable:
-//!
-//! - a purely cookie-based "backend", [`CookieSessionStore`], using the `cookie-session` feature
-//!   flag.
-//!
-//!   ```toml
-//!   [dependencies]
-//!   # ...
-//!   actix-session = { version = "...", features = ["cookie-session"] }
-//!   ```
-//!
-//! - a Redis-based backend via [`actix-redis`](https://docs.rs/acitx-redis),
-//!   [`RedisActorSessionStore`], using the `redis-actor-session` feature flag.
-//!
-//!   ```toml
-//!   [dependencies]
-//!   # ...
-//!   actix-session = { version = "...", features = ["redis-actor-session"] }
-//!   ```
-//!
-//! - a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using
-//!   the `redis-rs-session` feature flag.
-//!
-//!   ```toml
-//!   [dependencies]
-//!   # ...
-//!   actix-session = { version = "...", features = ["redis-rs-session"] }
-//!   ```
-//!
-//!   Add the `redis-rs-tls-session` feature flag if you want to connect to Redis using a secured
-//!   connection:
-//!
-//!   ```toml
-//!   [dependencies]
-//!   # ...
-//!   actix-session = { version = "...", features = ["redis-rs-session", "redis-rs-tls-session"] }
-//!   ```
-//!
-//! You can implement your own session storage backend using the [`SessionStore`] trait.
-//!
-//! [`SessionStore`]: storage::SessionStore
-//! [`CookieSessionStore`]: storage::CookieSessionStore
-//! [`RedisSessionStore`]: storage::RedisSessionStore
-//! [`RedisActorSessionStore`]: storage::RedisActorSessionStore
+
//! Session management for Actix Web.
+//!
+//! The HTTP protocol, at a first glance, is stateless: the client sends a request, the server
+//! parses its content, performs some processing and returns a response. The outcome is only
+//! influenced by the provided inputs (i.e. the request content) and whatever state the server
+//! queries while performing its processing.
+//!
+//! Stateless systems are easier to reason about, but they are not quite as powerful as we need them
+//! to be - e.g. how do you authenticate a user? The user would be forced to authenticate **for
+//! every single request**. That is, for example, how 'Basic' Authentication works. While it may
+//! work for a machine user (i.e. an API client), it is impractical for a person—you do not want a
+//! login prompt on every single page you navigate to!
+//!
+//! There is a solution - **sessions**. Using sessions the server can attach state to a set of
+//! requests coming from the same client. They are built on top of cookies - the server sets a
+//! cookie in the HTTP response (`Set-Cookie` header), the client (e.g. the browser) will store the
+//! cookie and play it back to the server when sending new requests (using the `Cookie` header).
+//!
+//! We refer to the cookie used for sessions as a **session cookie**. Its content is called
+//! **session key** (or **session ID**), while the state attached to the session is referred to as
+//! **session state**.
+//!
+//! `actix-session` provides an easy-to-use framework to manage sessions in applications built on
+//! top of Actix Web. [`SessionMiddleware`] is the middleware underpinning the functionality
+//! provided by `actix-session`; it takes care of all the session cookie handling and instructs the
+//! **storage backend** to create/delete/update the session state based on the operations performed
+//! against the active [`Session`].
+//!
+//! `actix-session` provides some built-in storage backends: ([`CookieSessionStore`],
+//! [`RedisSessionStore`], and [`RedisActorSessionStore`]) - you can create a custom storage backend
+//! by implementing the [`SessionStore`] trait.
+//!
+//! Further reading on sessions:
+//! - [RFC6265](https://datatracker.ietf.org/doc/html/rfc6265);
+//! - [OWASP's session management cheat-sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
+//!
+//! # Getting started
+//! To start using sessions in your Actix Web application you must register [`SessionMiddleware`]
+//! as a middleware on your `App`:
+//!
+//! ```no_run
+//! use actix_web::{web, App, HttpServer, HttpResponse, Error};
+//! use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
+//! use actix_web::cookie::Key;
+//!
+//! #[actix_web::main]
+//! async fn main() -> std::io::Result<()> {
+//!     // The secret key would usually be read from a configuration file/environment variables.
+//!     let secret_key = Key::generate();
+//!     let redis_connection_string = "127.0.0.1:6379";
+//!     HttpServer::new(move ||
+//!             App::new()
+//!             // Add session management to your application using Redis for session state storage
+//!             .wrap(
+//!                 SessionMiddleware::new(
+//!                     RedisActorSessionStore::new(redis_connection_string),
+//!                     secret_key.clone()
+//!                 )
+//!             )
+//!             .default_service(web::to(|| HttpResponse::Ok())))
+//!         .bind(("127.0.0.1", 8080))?
+//!         .run()
+//!         .await
+//! }
+//! ```
+//!
+//! The session state can be accessed and modified by your request handlers using the [`Session`]
+//! extractor.
+//!
+//! ```no_run
+//! use actix_web::Error;
+//! use actix_session::Session;
+//!
+//! fn index(session: Session) -> Result<&'static str, Error> {
+//!     // access the session state
+//!     if let Some(count) = session.get::<i32>("counter")? {
+//!         println!("SESSION value: {}", count);
+//!         // modify the session state
+//!         session.insert("counter", count + 1)?;
+//!     } else {
+//!         session.insert("counter", 1)?;
+//!     }
+//!
+//!     Ok("Welcome!")
+//! }
+//! ```
+//!
+//! # Choosing A Backend
+//!
+//! By default, `actix-session` does not provide any storage backend to retrieve and save the state
+//! attached to your sessions. You can enable:
+//!
+//! - a purely cookie-based "backend", [`CookieSessionStore`], using the `cookie-session` feature
+//!   flag.
+//!
+//!   ```toml
+//!   [dependencies]
+//!   # ...
+//!   actix-session = { version = "...", features = ["cookie-session"] }
+//!   ```
+//!
+//! - a Redis-based backend via [`actix-redis`](https://docs.rs/acitx-redis),
+//!   [`RedisActorSessionStore`], using the `redis-actor-session` feature flag.
+//!
+//!   ```toml
+//!   [dependencies]
+//!   # ...
+//!   actix-session = { version = "...", features = ["redis-actor-session"] }
+//!   ```
+//!
+//! - a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using
+//!   the `redis-rs-session` feature flag.
+//!
+//!   ```toml
+//!   [dependencies]
+//!   # ...
+//!   actix-session = { version = "...", features = ["redis-rs-session"] }
+//!   ```
+//!
+//!   Add the `redis-rs-tls-session` feature flag if you want to connect to Redis using a secured
+//!   connection:
+//!
+//!   ```toml
+//!   [dependencies]
+//!   # ...
+//!   actix-session = { version = "...", features = ["redis-rs-session", "redis-rs-tls-session"] }
+//!   ```
+//!
+//! You can implement your own session storage backend using the [`SessionStore`] trait.
+//!
+//! [`SessionStore`]: storage::SessionStore
+//! [`CookieSessionStore`]: storage::CookieSessionStore
+//! [`RedisSessionStore`]: storage::RedisSessionStore
+//! [`RedisActorSessionStore`]: storage::RedisActorSessionStore
 
-#![forbid(unsafe_code)]
-#![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_cfg))]
+#![forbid(unsafe_code)]
+#![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_cfg))]
 
-pub mod config;
-mod middleware;
-mod session;
-mod session_ext;
-pub mod storage;
+pub mod config;
+mod middleware;
+mod session;
+mod session_ext;
+pub mod storage;
 
-pub use self::middleware::SessionMiddleware;
-pub use self::session::{Session, SessionGetError, SessionInsertError, SessionStatus};
-pub use self::session_ext::SessionExt;
+pub use self::middleware::SessionMiddleware;
+pub use self::session::{Session, SessionGetError, SessionInsertError, SessionStatus};
+pub use self::session_ext::SessionExt;
 
-#[cfg(test)]
-pub mod test_helpers {
-    use actix_web::cookie::Key;
+#[cfg(test)]
+pub mod test_helpers {
+    use actix_web::cookie::Key;
 
-    use crate::{config::CookieContentSecurity, storage::SessionStore};
+    use crate::{config::CookieContentSecurity, storage::SessionStore};
 
-    /// Generate a random cookie signing/encryption key.
-    pub fn key() -> Key {
-        Key::generate()
+    /// Generate a random cookie signing/encryption key.
+    pub fn key() -> Key {
+        Key::generate()
     }
 
-    /// A ready-to-go acceptance test suite to verify that sessions behave as expected
-    /// regardless of the underlying session store.
-    ///
-    /// `is_invalidation_supported` must be set to `true` if the backend supports
-    /// "remembering" that a session has been invalidated (e.g. by logging out).
-    /// It should be to `false` if the backend allows multiple cookies to be active
-    /// at the same time (e.g. cookie store backend).
-    pub async fn acceptance_test_suite<F, Store>(store_builder: F, is_invalidation_supported: bool)
-    where
-        Store: SessionStore + 'static,
-        F: Fn() -> Store + Clone + Send + 'static,
+    /// A ready-to-go acceptance test suite to verify that sessions behave as expected
+    /// regardless of the underlying session store.
+    ///
+    /// `is_invalidation_supported` must be set to `true` if the backend supports
+    /// "remembering" that a session has been invalidated (e.g. by logging out).
+    /// It should be to `false` if the backend allows multiple cookies to be active
+    /// at the same time (e.g. cookie store backend).
+    pub async fn acceptance_test_suite<F, Store>(store_builder: F, is_invalidation_supported: bool)
+    where
+        Store: SessionStore + 'static,
+        F: Fn() -> Store + Clone + Send + 'static,
     {
-        for policy in &[
-            CookieContentSecurity::Signed,
-            CookieContentSecurity::Private,
+        for policy in &[
+            CookieContentSecurity::Signed,
+            CookieContentSecurity::Private,
         ] {
-            println!("Using {:?} as cookie content security policy.", policy);
-            acceptance_tests::basic_workflow(store_builder.clone(), *policy).await;
-            acceptance_tests::expiration_is_refreshed_on_changes(store_builder.clone(), *policy)
+            println!("Using {:?} as cookie content security policy.", policy);
+            acceptance_tests::basic_workflow(store_builder.clone(), *policy).await;
+            acceptance_tests::expiration_is_refreshed_on_changes(store_builder.clone(), *policy)
                 .await;
-            acceptance_tests::expiration_is_always_refreshed_if_configured_to_refresh_on_every_request(
-                store_builder.clone(),
-                *policy,
+            acceptance_tests::expiration_is_always_refreshed_if_configured_to_refresh_on_every_request(
+                store_builder.clone(),
+                *policy,
             )
             .await;
-            acceptance_tests::complex_workflow(
-                store_builder.clone(),
-                is_invalidation_supported,
-                *policy,
+            acceptance_tests::complex_workflow(
+                store_builder.clone(),
+                is_invalidation_supported,
+                *policy,
             )
             .await;
-            acceptance_tests::guard(store_builder.clone(), *policy).await;
+            acceptance_tests::guard(store_builder.clone(), *policy).await;
         }
     }
 
-    mod acceptance_tests {
-        use actix_web::{
-            cookie::time,
-            dev::{Service, ServiceResponse},
-            guard, middleware, test,
-            web::{self, get, post, resource, Bytes},
-            App, HttpResponse, Result,
+    mod acceptance_tests {
+        use actix_web::{
+            cookie::time,
+            dev::{Service, ServiceResponse},
+            guard, middleware, test,
+            web::{self, get, post, resource, Bytes},
+            App, HttpResponse, Result,
         };
-        use serde::{Deserialize, Serialize};
-        use serde_json::json;
+        use serde::{Deserialize, Serialize};
+        use serde_json::json;
 
-        use crate::config::{CookieContentSecurity, PersistentSession, TtlExtensionPolicy};
-        use crate::{
-            storage::SessionStore, test_helpers::key, Session, SessionExt, SessionMiddleware,
+        use crate::config::{CookieContentSecurity, PersistentSession, TtlExtensionPolicy};
+        use crate::{
+            storage::SessionStore, test_helpers::key, Session, SessionExt, SessionMiddleware,
         };
 
-        pub(super) async fn basic_workflow<F, Store>(
-            store_builder: F,
-            policy: CookieContentSecurity,
-        ) where
-            Store: SessionStore + 'static,
-            F: Fn() -> Store + Clone + Send + 'static,
+        pub(super) async fn basic_workflow<F, Store>(
+            store_builder: F,
+            policy: CookieContentSecurity,
+        ) where
+            Store: SessionStore + 'static,
+            F: Fn() -> Store + Clone + Send + 'static,
         {
-            let app = test::init_service(
-                App::new()
-                    .wrap(
-                        SessionMiddleware::builder(store_builder(), key())
-                            .cookie_path("/test/".into())
-                            .cookie_name("actix-test".into())
-                            .cookie_domain(Some("localhost".into()))
-                            .cookie_content_security(policy)
-                            .session_lifecycle(
-                                PersistentSession::default()
-                                    .session_ttl(time::Duration::seconds(100)),
+            let app = test::init_service(
+                App::new()
+                    .wrap(
+                        SessionMiddleware::builder(store_builder(), key())
+                            .cookie_path("/test/".into())
+                            .cookie_name("actix-test".into())
+                            .cookie_domain(Some("localhost".into()))
+                            .cookie_content_security(policy)
+                            .session_lifecycle(
+                                PersistentSession::default()
+                                    .session_ttl(time::Duration::seconds(100)),
                             )
-                            .build(),
+                            .build(),
                     )
-                    .service(web::resource("/").to(|ses: Session| async move {
-                        let _ = ses.insert("counter", 100);
-                        "test"
-                    }))
-                    .service(web::resource("/test/").to(|ses: Session| async move {
-                        let val: usize = ses.get("counter").unwrap().unwrap();
-                        format!("counter: {}", val)
+                    .service(web::resource("/").to(|ses: Session| async move {
+                        let _ = ses.insert("counter", 100);
+                        "test"
+                    }))
+                    .service(web::resource("/test/").to(|ses: Session| async move {
+                        let val: usize = ses.get("counter").unwrap().unwrap();
+                        format!("counter: {}", val)
                     })),
             )
             .await;
 
-            let request = test::TestRequest::get().to_request();
-            let response = app.call(request).await.unwrap();
-            let cookie = response.get_cookie("actix-test").unwrap().clone();
-            assert_eq!(cookie.path().unwrap(), "/test/");
+            let request = test::TestRequest::get().to_request();
+            let response = app.call(request).await.unwrap();
+            let cookie = response.get_cookie("actix-test").unwrap().clone();
+            assert_eq!(cookie.path().unwrap(), "/test/");
 
-            let request = test::TestRequest::with_uri("/test/")
-                .cookie(cookie)
-                .to_request();
-            let body = test::call_and_read_body(&app, request).await;
-            assert_eq!(body, Bytes::from_static(b"counter: 100"));
+            let request = test::TestRequest::with_uri("/test/")
+                .cookie(cookie)
+                .to_request();
+            let body = test::call_and_read_body(&app, request).await;
+            assert_eq!(body, Bytes::from_static(b"counter: 100"));
         }
 
-        pub(super) async fn expiration_is_always_refreshed_if_configured_to_refresh_on_every_request<
-            F,
-            Store,
-        >(
-            store_builder: F,
-            policy: CookieContentSecurity,
-        ) where
-            Store: SessionStore + 'static,
-            F: Fn() -> Store + Clone + Send + 'static,
+        pub(super) async fn expiration_is_always_refreshed_if_configured_to_refresh_on_every_request<
+            F,
+            Store,
+        >(
+            store_builder: F,
+            policy: CookieContentSecurity,
+        ) where
+            Store: SessionStore + 'static,
+            F: Fn() -> Store + Clone + Send + 'static,
         {
-            let session_ttl = time::Duration::seconds(60);
-            let app = test::init_service(
-                App::new()
-                    .wrap(
-                        SessionMiddleware::builder(store_builder(), key())
-                            .cookie_content_security(policy)
-                            .session_lifecycle(
-                                PersistentSession::default()
-                                    .session_ttl(session_ttl)
-                                    .session_ttl_extension_policy(
-                                        TtlExtensionPolicy::OnEveryRequest,
+            let session_ttl = time::Duration::seconds(60);
+            let app = test::init_service(
+                App::new()
+                    .wrap(
+                        SessionMiddleware::builder(store_builder(), key())
+                            .cookie_content_security(policy)
+                            .session_lifecycle(
+                                PersistentSession::default()
+                                    .session_ttl(session_ttl)
+                                    .session_ttl_extension_policy(
+                                        TtlExtensionPolicy::OnEveryRequest,
                                     ),
                             )
-                            .build(),
+                            .build(),
                     )
-                    .service(web::resource("/").to(|ses: Session| async move {
-                        let _ = ses.insert("counter", 100);
-                        "test"
-                    }))
-                    .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
+                    .service(web::resource("/").to(|ses: Session| async move {
+                        let _ = ses.insert("counter", 100);
+                        "test"
+                    }))
+                    .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
             )
             .await;
 
-            // Create session
-            let request = test::TestRequest::get().to_request();
-            let response = app.call(request).await.unwrap();
-            let cookie_1 = response.get_cookie("id").expect("Cookie is set");
-            assert_eq!(cookie_1.max_age(), Some(session_ttl));
+            // Create session
+            let request = test::TestRequest::get().to_request();
+            let response = app.call(request).await.unwrap();
+            let cookie_1 = response.get_cookie("id").expect("Cookie is set");
+            assert_eq!(cookie_1.max_age(), Some(session_ttl));
 
-            // Fire a request that doesn't touch the session state, check
-            // that the session cookie is present and its expiry is set to the maximum we configured.
-            let request = test::TestRequest::with_uri("/test/")
-                .cookie(cookie_1)
-                .to_request();
-            let response = app.call(request).await.unwrap();
-            let cookie_2 = response.get_cookie("id").expect("Cookie is set");
-            assert_eq!(cookie_2.max_age(), Some(session_ttl));
+            // Fire a request that doesn't touch the session state, check
+            // that the session cookie is present and its expiry is set to the maximum we configured.
+            let request = test::TestRequest::with_uri("/test/")
+                .cookie(cookie_1)
+                .to_request();
+            let response = app.call(request).await.unwrap();
+            let cookie_2 = response.get_cookie("id").expect("Cookie is set");
+            assert_eq!(cookie_2.max_age(), Some(session_ttl));
         }
 
-        pub(super) async fn expiration_is_refreshed_on_changes<F, Store>(
-            store_builder: F,
-            policy: CookieContentSecurity,
-        ) where
-            Store: SessionStore + 'static,
-            F: Fn() -> Store + Clone + Send + 'static,
+        pub(super) async fn expiration_is_refreshed_on_changes<F, Store>(
+            store_builder: F,
+            policy: CookieContentSecurity,
+        ) where
+            Store: SessionStore + 'static,
+            F: Fn() -> Store + Clone + Send + 'static,
         {
-            let session_ttl = time::Duration::seconds(60);
-            let app = test::init_service(
-                App::new()
-                    .wrap(
-                        SessionMiddleware::builder(store_builder(), key())
-                            .cookie_content_security(policy)
-                            .session_lifecycle(
-                                PersistentSession::default().session_ttl(session_ttl),
+            let session_ttl = time::Duration::seconds(60);
+            let app = test::init_service(
+                App::new()
+                    .wrap(
+                        SessionMiddleware::builder(store_builder(), key())
+                            .cookie_content_security(policy)
+                            .session_lifecycle(
+                                PersistentSession::default().session_ttl(session_ttl),
                             )
-                            .build(),
+                            .build(),
                     )
-                    .service(web::resource("/").to(|ses: Session| async move {
-                        let _ = ses.insert("counter", 100);
-                        "test"
-                    }))
-                    .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
+                    .service(web::resource("/").to(|ses: Session| async move {
+                        let _ = ses.insert("counter", 100);
+                        "test"
+                    }))
+                    .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
             )
             .await;
 
-            let request = test::TestRequest::get().to_request();
-            let response = app.call(request).await.unwrap();
-            let cookie_1 = response.get_cookie("id").expect("Cookie is set");
-            assert_eq!(cookie_1.max_age(), Some(session_ttl));
+            let request = test::TestRequest::get().to_request();
+            let response = app.call(request).await.unwrap();
+            let cookie_1 = response.get_cookie("id").expect("Cookie is set");
+            assert_eq!(cookie_1.max_age(), Some(session_ttl));
 
-            let request = test::TestRequest::with_uri("/test/")
-                .cookie(cookie_1.clone())
-                .to_request();
-            let response = app.call(request).await.unwrap();
-            assert!(response.response().cookies().next().is_none());
+            let request = test::TestRequest::with_uri("/test/")
+                .cookie(cookie_1.clone())
+                .to_request();
+            let response = app.call(request).await.unwrap();
+            assert!(response.response().cookies().next().is_none());
 
-            let request = test::TestRequest::get().cookie(cookie_1).to_request();
-            let response = app.call(request).await.unwrap();
-            let cookie_2 = response.get_cookie("id").expect("Cookie is set");
-            assert_eq!(cookie_2.max_age(), Some(session_ttl));
+            let request = test::TestRequest::get().cookie(cookie_1).to_request();
+            let response = app.call(request).await.unwrap();
+            let cookie_2 = response.get_cookie("id").expect("Cookie is set");
+            assert_eq!(cookie_2.max_age(), Some(session_ttl));
         }
 
-        pub(super) async fn guard<F, Store>(store_builder: F, policy: CookieContentSecurity)
-        where
-            Store: SessionStore + 'static,
-            F: Fn() -> Store + Clone + Send + 'static,
+        pub(super) async fn guard<F, Store>(store_builder: F, policy: CookieContentSecurity)
+        where
+            Store: SessionStore + 'static,
+            F: Fn() -> Store + Clone + Send + 'static,
         {
-            let srv = actix_test::start(move || {
-                App::new()
-                    .wrap(
-                        SessionMiddleware::builder(store_builder(), key())
-                            .cookie_name("test-session".into())
-                            .cookie_content_security(policy)
-                            .session_lifecycle(
-                                PersistentSession::default().session_ttl(time::Duration::days(7)),
+            let srv = actix_test::start(move || {
+                App::new()
+                    .wrap(
+                        SessionMiddleware::builder(store_builder(), key())
+                            .cookie_name("test-session".into())
+                            .cookie_content_security(policy)
+                            .session_lifecycle(
+                                PersistentSession::default().session_ttl(time::Duration::days(7)),
                             )
-                            .build(),
+                            .build(),
                     )
-                    .wrap(middleware::Logger::default())
-                    .service(resource("/").route(get().to(index)))
-                    .service(resource("/do_something").route(post().to(do_something)))
-                    .service(resource("/login").route(post().to(login)))
-                    .service(resource("/logout").route(post().to(logout)))
-                    .service(
-                        web::scope("/protected")
-                            .guard(guard::fn_guard(|g| {
-                                g.get_session().get::<String>("user_id").unwrap().is_some()
+                    .wrap(middleware::Logger::default())
+                    .service(resource("/").route(get().to(index)))
+                    .service(resource("/do_something").route(post().to(do_something)))
+                    .service(resource("/login").route(post().to(login)))
+                    .service(resource("/logout").route(post().to(logout)))
+                    .service(
+                        web::scope("/protected")
+                            .guard(guard::fn_guard(|g| {
+                                g.get_session().get::<String>("user_id").unwrap().is_some()
                             }))
-                            .service(resource("/count").route(get().to(count))),
+                            .service(resource("/count").route(get().to(count))),
                     )
             });
 
-            // Step 1: GET without session info
-            //   - response should be a unsuccessful status
-            let req_1 = srv.get("/protected/count").send();
-            let resp_1 = req_1.await.unwrap();
-            assert!(!resp_1.status().is_success());
+            // Step 1: GET without session info
+            //   - response should be a unsuccessful status
+            let req_1 = srv.get("/protected/count").send();
+            let resp_1 = req_1.await.unwrap();
+            assert!(!resp_1.status().is_success());
 
-            // Step 2: POST to login
-            //   - set-cookie actix-session will be in response  (session cookie #1)
-            //   - updates session state: {"counter": 0, "user_id": "ferris"}
-            let req_2 = srv.post("/login").send_json(&json!({"user_id": "ferris"}));
-            let resp_2 = req_2.await.unwrap();
-            let cookie_1 = resp_2
-                .cookies()
-                .unwrap()
-                .clone()
-                .into_iter()
-                .find(|c| c.name() == "test-session")
-                .unwrap();
+            // Step 2: POST to login
+            //   - set-cookie actix-session will be in response  (session cookie #1)
+            //   - updates session state: {"counter": 0, "user_id": "ferris"}
+            let req_2 = srv.post("/login").send_json(&json!({"user_id": "ferris"}));
+            let resp_2 = req_2.await.unwrap();
+            let cookie_1 = resp_2
+                .cookies()
+                .unwrap()
+                .clone()
+                .into_iter()
+                .find(|c| c.name() == "test-session")
+                .unwrap();
 
-            // Step 3: POST to do_something
-            //   - adds new session state:  {"counter": 1, "user_id": "ferris" }
-            //   - set-cookie actix-session should be in response (session cookie #2)
-            //   - response should be: {"counter": 1, "user_id": None}
-            let req_3 = srv.post("/do_something").cookie(cookie_1.clone()).send();
-            let mut resp_3 = req_3.await.unwrap();
-            let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
+            // Step 3: POST to do_something
+            //   - adds new session state:  {"counter": 1, "user_id": "ferris" }
+            //   - set-cookie actix-session should be in response (session cookie #2)
+            //   - response should be: {"counter": 1, "user_id": None}
+            let req_3 = srv.post("/do_something").cookie(cookie_1.clone()).send();
+            let mut resp_3 = req_3.await.unwrap();
+            let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_3,
-                IndexResponse {
-                    user_id: Some("ferris".into()),
-                    counter: 1
-                }
+                result_3,
+                IndexResponse {
+                    user_id: Some("ferris".into()),
+                    counter: 1
+                }
             );
-            let cookie_2 = resp_3
-                .cookies()
-                .unwrap()
-                .clone()
-                .into_iter()
-                .find(|c| c.name() == "test-session")
-                .unwrap();
+            let cookie_2 = resp_3
+                .cookies()
+                .unwrap()
+                .clone()
+                .into_iter()
+                .find(|c| c.name() == "test-session")
+                .unwrap();
 
-            // Step 4: GET using a existing user id
-            //   - response should be: {"counter": 3, "user_id": "ferris"}
-            let req_4 = srv.get("/protected/count").cookie(cookie_2.clone()).send();
-            let mut resp_4 = req_4.await.unwrap();
-            let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
+            // Step 4: GET using a existing user id
+            //   - response should be: {"counter": 3, "user_id": "ferris"}
+            let req_4 = srv.get("/protected/count").cookie(cookie_2.clone()).send();
+            let mut resp_4 = req_4.await.unwrap();
+            let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_4,
-                IndexResponse {
-                    user_id: Some("ferris".into()),
-                    counter: 1
-                }
+                result_4,
+                IndexResponse {
+                    user_id: Some("ferris".into()),
+                    counter: 1
+                }
             );
         }
 
-        pub(super) async fn complex_workflow<F, Store>(
-            store_builder: F,
-            is_invalidation_supported: bool,
-            policy: CookieContentSecurity,
-        ) where
-            Store: SessionStore + 'static,
-            F: Fn() -> Store + Clone + Send + 'static,
+        pub(super) async fn complex_workflow<F, Store>(
+            store_builder: F,
+            is_invalidation_supported: bool,
+            policy: CookieContentSecurity,
+        ) where
+            Store: SessionStore + 'static,
+            F: Fn() -> Store + Clone + Send + 'static,
         {
-            let session_ttl = time::Duration::days(7);
-            let srv = actix_test::start(move || {
-                App::new()
-                    .wrap(
-                        SessionMiddleware::builder(store_builder(), key())
-                            .cookie_name("test-session".into())
-                            .cookie_content_security(policy)
-                            .session_lifecycle(
-                                PersistentSession::default().session_ttl(session_ttl),
+            let session_ttl = time::Duration::days(7);
+            let srv = actix_test::start(move || {
+                App::new()
+                    .wrap(
+                        SessionMiddleware::builder(store_builder(), key())
+                            .cookie_name("test-session".into())
+                            .cookie_content_security(policy)
+                            .session_lifecycle(
+                                PersistentSession::default().session_ttl(session_ttl),
                             )
-                            .build(),
+                            .build(),
                     )
-                    .wrap(middleware::Logger::default())
-                    .service(resource("/").route(get().to(index)))
-                    .service(resource("/do_something").route(post().to(do_something)))
-                    .service(resource("/login").route(post().to(login)))
-                    .service(resource("/logout").route(post().to(logout)))
+                    .wrap(middleware::Logger::default())
+                    .service(resource("/").route(get().to(index)))
+                    .service(resource("/do_something").route(post().to(do_something)))
+                    .service(resource("/login").route(post().to(login)))
+                    .service(resource("/logout").route(post().to(logout)))
             });
 
-            // Step 1:  GET index
-            //   - set-cookie actix-session should NOT be in response (session data is empty)
-            //   - response should be: {"counter": 0, "user_id": None}
-            let req_1a = srv.get("/").send();
-            let mut resp_1 = req_1a.await.unwrap();
-            assert!(resp_1.cookies().unwrap().is_empty());
-            let result_1 = resp_1.json::<IndexResponse>().await.unwrap();
+            // Step 1:  GET index
+            //   - set-cookie actix-session should NOT be in response (session data is empty)
+            //   - response should be: {"counter": 0, "user_id": None}
+            let req_1a = srv.get("/").send();
+            let mut resp_1 = req_1a.await.unwrap();
+            assert!(resp_1.cookies().unwrap().is_empty());
+            let result_1 = resp_1.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_1,
-                IndexResponse {
-                    user_id: None,
-                    counter: 0
-                }
+                result_1,
+                IndexResponse {
+                    user_id: None,
+                    counter: 0
+                }
             );
 
-            // Step 2: POST to do_something
-            //   - adds new session state in redis:  {"counter": 1}
-            //   - set-cookie actix-session should be in response (session cookie #1)
-            //   - response should be: {"counter": 1, "user_id": None}
-            let req_2 = srv.post("/do_something").send();
-            let mut resp_2 = req_2.await.unwrap();
-            let result_2 = resp_2.json::<IndexResponse>().await.unwrap();
+            // Step 2: POST to do_something
+            //   - adds new session state in redis:  {"counter": 1}
+            //   - set-cookie actix-session should be in response (session cookie #1)
+            //   - response should be: {"counter": 1, "user_id": None}
+            let req_2 = srv.post("/do_something").send();
+            let mut resp_2 = req_2.await.unwrap();
+            let result_2 = resp_2.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_2,
-                IndexResponse {
-                    user_id: None,
-                    counter: 1
-                }
+                result_2,
+                IndexResponse {
+                    user_id: None,
+                    counter: 1
+                }
             );
-            let cookie_1 = resp_2
-                .cookies()
-                .unwrap()
-                .clone()
-                .into_iter()
-                .find(|c| c.name() == "test-session")
-                .unwrap();
-            assert_eq!(cookie_1.max_age(), Some(session_ttl));
+            let cookie_1 = resp_2
+                .cookies()
+                .unwrap()
+                .clone()
+                .into_iter()
+                .find(|c| c.name() == "test-session")
+                .unwrap();
+            assert_eq!(cookie_1.max_age(), Some(session_ttl));
 
-            // Step 3:  GET index, including session cookie #1 in request
-            //   - set-cookie will *not* be in response
-            //   - response should be: {"counter": 1, "user_id": None}
-            let req_3 = srv.get("/").cookie(cookie_1.clone()).send();
-            let mut resp_3 = req_3.await.unwrap();
-            assert!(resp_3.cookies().unwrap().is_empty());
-            let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
+            // Step 3:  GET index, including session cookie #1 in request
+            //   - set-cookie will *not* be in response
+            //   - response should be: {"counter": 1, "user_id": None}
+            let req_3 = srv.get("/").cookie(cookie_1.clone()).send();
+            let mut resp_3 = req_3.await.unwrap();
+            assert!(resp_3.cookies().unwrap().is_empty());
+            let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_3,
-                IndexResponse {
-                    user_id: None,
-                    counter: 1
-                }
+                result_3,
+                IndexResponse {
+                    user_id: None,
+                    counter: 1
+                }
             );
 
-            // Step 4: POST again to do_something, including session cookie #1 in request
-            //   - set-cookie will be in response (session cookie #2)
-            //   - updates session state:  {"counter": 2}
-            //   - response should be: {"counter": 2, "user_id": None}
-            let req_4 = srv.post("/do_something").cookie(cookie_1.clone()).send();
-            let mut resp_4 = req_4.await.unwrap();
-            let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
+            // Step 4: POST again to do_something, including session cookie #1 in request
+            //   - set-cookie will be in response (session cookie #2)
+            //   - updates session state:  {"counter": 2}
+            //   - response should be: {"counter": 2, "user_id": None}
+            let req_4 = srv.post("/do_something").cookie(cookie_1.clone()).send();
+            let mut resp_4 = req_4.await.unwrap();
+            let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_4,
-                IndexResponse {
-                    user_id: None,
-                    counter: 2
-                }
+                result_4,
+                IndexResponse {
+                    user_id: None,
+                    counter: 2
+                }
             );
-            let cookie_2 = resp_4
-                .cookies()
-                .unwrap()
-                .clone()
-                .into_iter()
-                .find(|c| c.name() == "test-session")
-                .unwrap();
-            assert_eq!(cookie_2.max_age(), cookie_1.max_age());
+            let cookie_2 = resp_4
+                .cookies()
+                .unwrap()
+                .clone()
+                .into_iter()
+                .find(|c| c.name() == "test-session")
+                .unwrap();
+            assert_eq!(cookie_2.max_age(), cookie_1.max_age());
 
-            // Step 5: POST to login, including session cookie #2 in request
-            //   - set-cookie actix-session will be in response  (session cookie #3)
-            //   - updates session state: {"counter": 2, "user_id": "ferris"}
-            let req_5 = srv
-                .post("/login")
-                .cookie(cookie_2.clone())
-                .send_json(&json!({"user_id": "ferris"}));
-            let mut resp_5 = req_5.await.unwrap();
-            let cookie_3 = resp_5
-                .cookies()
-                .unwrap()
-                .clone()
-                .into_iter()
-                .find(|c| c.name() == "test-session")
-                .unwrap();
-            assert_ne!(cookie_2.value(), cookie_3.value());
+            // Step 5: POST to login, including session cookie #2 in request
+            //   - set-cookie actix-session will be in response  (session cookie #3)
+            //   - updates session state: {"counter": 2, "user_id": "ferris"}
+            let req_5 = srv
+                .post("/login")
+                .cookie(cookie_2.clone())
+                .send_json(&json!({"user_id": "ferris"}));
+            let mut resp_5 = req_5.await.unwrap();
+            let cookie_3 = resp_5
+                .cookies()
+                .unwrap()
+                .clone()
+                .into_iter()
+                .find(|c| c.name() == "test-session")
+                .unwrap();
+            assert_ne!(cookie_2.value(), cookie_3.value());
 
-            let result_5 = resp_5.json::<IndexResponse>().await.unwrap();
+            let result_5 = resp_5.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_5,
-                IndexResponse {
-                    user_id: Some("ferris".into()),
-                    counter: 2
-                }
+                result_5,
+                IndexResponse {
+                    user_id: Some("ferris".into()),
+                    counter: 2
+                }
             );
 
-            // Step 6: GET index, including session cookie #3 in request
-            //   - response should be: {"counter": 2, "user_id": "ferris"}
-            let req_6 = srv.get("/").cookie(cookie_3.clone()).send();
-            let mut resp_6 = req_6.await.unwrap();
-            let result_6 = resp_6.json::<IndexResponse>().await.unwrap();
+            // Step 6: GET index, including session cookie #3 in request
+            //   - response should be: {"counter": 2, "user_id": "ferris"}
+            let req_6 = srv.get("/").cookie(cookie_3.clone()).send();
+            let mut resp_6 = req_6.await.unwrap();
+            let result_6 = resp_6.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_6,
-                IndexResponse {
-                    user_id: Some("ferris".into()),
-                    counter: 2
-                }
+                result_6,
+                IndexResponse {
+                    user_id: Some("ferris".into()),
+                    counter: 2
+                }
             );
 
-            // Step 7: POST again to do_something, including session cookie #3 in request
-            //   - updates session state: {"counter": 3, "user_id": "ferris"}
-            //   - response should be: {"counter": 3, "user_id": "ferris"}
-            let req_7 = srv.post("/do_something").cookie(cookie_3.clone()).send();
-            let mut resp_7 = req_7.await.unwrap();
-            let result_7 = resp_7.json::<IndexResponse>().await.unwrap();
+            // Step 7: POST again to do_something, including session cookie #3 in request
+            //   - updates session state: {"counter": 3, "user_id": "ferris"}
+            //   - response should be: {"counter": 3, "user_id": "ferris"}
+            let req_7 = srv.post("/do_something").cookie(cookie_3.clone()).send();
+            let mut resp_7 = req_7.await.unwrap();
+            let result_7 = resp_7.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_7,
-                IndexResponse {
-                    user_id: Some("ferris".into()),
-                    counter: 3
-                }
+                result_7,
+                IndexResponse {
+                    user_id: Some("ferris".into()),
+                    counter: 3
+                }
             );
 
-            // Step 8: GET index, including session cookie #2 in request
-            // If invalidation is supported, no state will be found associated to this session.
-            // If invalidation is not supported, the old state will still be retrieved.
-            let req_8 = srv.get("/").cookie(cookie_2.clone()).send();
-            let mut resp_8 = req_8.await.unwrap();
-            if is_invalidation_supported {
-                assert!(resp_8.cookies().unwrap().is_empty());
-                let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
+            // Step 8: GET index, including session cookie #2 in request
+            // If invalidation is supported, no state will be found associated to this session.
+            // If invalidation is not supported, the old state will still be retrieved.
+            let req_8 = srv.get("/").cookie(cookie_2.clone()).send();
+            let mut resp_8 = req_8.await.unwrap();
+            if is_invalidation_supported {
+                assert!(resp_8.cookies().unwrap().is_empty());
+                let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
                 assert_eq!(
-                    result_8,
-                    IndexResponse {
-                        user_id: None,
-                        counter: 0
-                    }
+                    result_8,
+                    IndexResponse {
+                        user_id: None,
+                        counter: 0
+                    }
                 );
-            } else {
-                let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
+            } else {
+                let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
                 assert_eq!(
-                    result_8,
-                    IndexResponse {
-                        user_id: None,
-                        counter: 2
-                    }
+                    result_8,
+                    IndexResponse {
+                        user_id: None,
+                        counter: 2
+                    }
                 );
             }
 
-            // Step 9: POST to logout, including session cookie #3
-            //   - set-cookie actix-session will be in response with session cookie #3
-            //     invalidation logic
-            let req_9 = srv.post("/logout").cookie(cookie_3.clone()).send();
-            let resp_9 = req_9.await.unwrap();
-            let cookie_3 = resp_9
-                .cookies()
-                .unwrap()
-                .clone()
-                .into_iter()
-                .find(|c| c.name() == "test-session")
-                .unwrap();
-            assert_eq!(0, cookie_3.max_age().map(|t| t.whole_seconds()).unwrap());
-            assert_eq!("/", cookie_3.path().unwrap());
+            // Step 9: POST to logout, including session cookie #3
+            //   - set-cookie actix-session will be in response with session cookie #3
+            //     invalidation logic
+            let req_9 = srv.post("/logout").cookie(cookie_3.clone()).send();
+            let resp_9 = req_9.await.unwrap();
+            let cookie_3 = resp_9
+                .cookies()
+                .unwrap()
+                .clone()
+                .into_iter()
+                .find(|c| c.name() == "test-session")
+                .unwrap();
+            assert_eq!(0, cookie_3.max_age().map(|t| t.whole_seconds()).unwrap());
+            assert_eq!("/", cookie_3.path().unwrap());
 
-            // Step 10: GET index, including session cookie #3 in request
-            //   - set-cookie actix-session should NOT be in response if invalidation is supported
-            //   - response should be: {"counter": 0, "user_id": None}
-            let req_10 = srv.get("/").cookie(cookie_3.clone()).send();
-            let mut resp_10 = req_10.await.unwrap();
-            if is_invalidation_supported {
-                assert!(resp_10.cookies().unwrap().is_empty());
+            // Step 10: GET index, including session cookie #3 in request
+            //   - set-cookie actix-session should NOT be in response if invalidation is supported
+            //   - response should be: {"counter": 0, "user_id": None}
+            let req_10 = srv.get("/").cookie(cookie_3.clone()).send();
+            let mut resp_10 = req_10.await.unwrap();
+            if is_invalidation_supported {
+                assert!(resp_10.cookies().unwrap().is_empty());
             }
-            let result_10 = resp_10.json::<IndexResponse>().await.unwrap();
+            let result_10 = resp_10.json::<IndexResponse>().await.unwrap();
             assert_eq!(
-                result_10,
-                IndexResponse {
-                    user_id: None,
-                    counter: 0
-                }
+                result_10,
+                IndexResponse {
+                    user_id: None,
+                    counter: 0
+                }
             );
         }
 
-        #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
-        pub struct IndexResponse {
-            user_id: Option<String>,
-            counter: i32,
+        #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
+        pub struct IndexResponse {
+            user_id: Option<String>,
+            counter: i32,
         }
 
-        async fn index(session: Session) -> Result<HttpResponse> {
-            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
-            let counter: i32 = session
-                .get::<i32>("counter")
-                .unwrap_or(Some(0))
-                .unwrap_or(0);
+        async fn index(session: Session) -> Result<HttpResponse> {
+            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
+            let counter: i32 = session
+                .get::<i32>("counter")
+                .unwrap_or(Some(0))
+                .unwrap_or(0);
 
-            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
+            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
         }
 
-        async fn do_something(session: Session) -> Result<HttpResponse> {
-            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
-            let counter: i32 = session
-                .get::<i32>("counter")
-                .unwrap_or(Some(0))
-                .map_or(1, |inner| inner + 1);
-            session.insert("counter", &counter)?;
+        async fn do_something(session: Session) -> Result<HttpResponse> {
+            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
+            let counter: i32 = session
+                .get::<i32>("counter")
+                .unwrap_or(Some(0))
+                .map_or(1, |inner| inner + 1);
+            session.insert("counter", &counter)?;
 
-            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
+            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
         }
 
-        async fn count(session: Session) -> Result<HttpResponse> {
-            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
-            let counter: i32 = session.get::<i32>("counter").unwrap().unwrap();
+        async fn count(session: Session) -> Result<HttpResponse> {
+            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
+            let counter: i32 = session.get::<i32>("counter").unwrap().unwrap();
 
-            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
+            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
         }
 
-        #[derive(Deserialize)]
-        struct Identity {
-            user_id: String,
+        #[derive(Deserialize)]
+        struct Identity {
+            user_id: String,
         }
 
-        async fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
-            let id = user_id.into_inner().user_id;
-            session.insert("user_id", &id)?;
-            session.renew();
+        async fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
+            let id = user_id.into_inner().user_id;
+            session.insert("user_id", &id)?;
+            session.renew();
 
-            let counter: i32 = session
-                .get::<i32>("counter")
-                .unwrap_or(Some(0))
-                .unwrap_or(0);
+            let counter: i32 = session
+                .get::<i32>("counter")
+                .unwrap_or(Some(0))
+                .unwrap_or(0);
 
-            Ok(HttpResponse::Ok().json(&IndexResponse {
-                user_id: Some(id),
-                counter,
+            Ok(HttpResponse::Ok().json(&IndexResponse {
+                user_id: Some(id),
+                counter,
             }))
         }
 
-        async fn logout(session: Session) -> Result<HttpResponse> {
-            let id: Option<String> = session.get("user_id")?;
+        async fn logout(session: Session) -> Result<HttpResponse> {
+            let id: Option<String> = session.get("user_id")?;
 
-            let body = if let Some(x) = id {
-                session.purge();
-                format!("Logged out: {}", x)
-            } else {
-                "Could not log out anonymous user".to_owned()
+            let body = if let Some(x) = id {
+                session.purge();
+                format!("Logged out: {}", x)
+            } else {
+                "Could not log out anonymous user".to_owned()
             };
 
-            Ok(HttpResponse::Ok().body(body))
+            Ok(HttpResponse::Ok().body(body))
         }
 
-        trait ServiceResponseExt {
-            fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>>;
+        trait ServiceResponseExt {
+            fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>>;
         }
 
-        impl ServiceResponseExt for ServiceResponse {
-            fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>> {
-                self.response()
-                    .cookies()
-                    .into_iter()
-                    .find(|c| c.name() == cookie_name)
+        impl ServiceResponseExt for ServiceResponse {
+            fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>> {
+                self.response()
+                    .cookies()
+                    .into_iter()
+                    .find(|c| c.name() == cookie_name)
             }
         }
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/middleware.rs.html b/src/actix_session/middleware.rs.html index 0961762b8..a376317f6 100644 --- a/src/actix_session/middleware.rs.html +++ b/src/actix_session/middleware.rs.html @@ -463,313 +463,313 @@ 461 462 463 -
use std::{collections::HashMap, convert::TryInto, fmt, future::Future, pin::Pin, rc::Rc};
+
use std::{collections::HashMap, convert::TryInto, fmt, future::Future, pin::Pin, rc::Rc};
 
-use actix_utils::future::{ready, Ready};
-use actix_web::{
-    body::MessageBody,
-    cookie::{Cookie, CookieJar, Key},
-    dev::{forward_ready, ResponseHead, Service, ServiceRequest, ServiceResponse, Transform},
-    http::header::{HeaderValue, SET_COOKIE},
-    HttpResponse,
+use actix_utils::future::{ready, Ready};
+use actix_web::{
+    body::MessageBody,
+    cookie::{Cookie, CookieJar, Key},
+    dev::{forward_ready, ResponseHead, Service, ServiceRequest, ServiceResponse, Transform},
+    http::header::{HeaderValue, SET_COOKIE},
+    HttpResponse,
 };
-use anyhow::Context;
+use anyhow::Context;
 
-use crate::{
-    config::{
-        self, Configuration, CookieConfiguration, CookieContentSecurity, SessionMiddlewareBuilder,
-        TtlExtensionPolicy,
+use crate::{
+    config::{
+        self, Configuration, CookieConfiguration, CookieContentSecurity, SessionMiddlewareBuilder,
+        TtlExtensionPolicy,
     },
-    storage::{LoadError, SessionKey, SessionStore},
-    Session, SessionStatus,
+    storage::{LoadError, SessionKey, SessionStore},
+    Session, SessionStatus,
 };
 
-/// A middleware for session management in Actix Web applications.
-///
-/// [`SessionMiddleware`] takes care of a few jobs:
-///
-/// - Instructs the session storage backend to create/update/delete/retrieve the state attached to
-///   a session according to its status and the operations that have been performed against it;
-/// - Set/remove a cookie, on the client side, to enable a user to be consistently associated with
-///   the same session across multiple HTTP requests.
-///
-/// Use [`SessionMiddleware::new`] to initialize the session framework using the default parameters.
-/// To create a new instance of [`SessionMiddleware`] you need to provide:
-///
-/// - an instance of the session storage backend you wish to use (i.e. an implementation of
-///   [`SessionStore`]);
-/// - a secret key, to sign or encrypt the content of client-side session cookie.
-///
-/// # How did we choose defaults?
-/// You should not regret adding `actix-session` to your dependencies and going to production using
-/// the default configuration. That is why, when in doubt, we opt to use the most secure option for
-/// each configuration parameter.
-///
-/// We expose knobs to change the default to suit your needs—i.e., if you know what you are doing,
-/// we will not stop you. But being a subject-matter expert should not be a requirement to deploy
-/// reasonably secure implementation of sessions.
-///
-/// # Examples
-/// ```no_run
-/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
-/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
-/// use actix_web::cookie::Key;
-///
-/// // The secret key would usually be read from a configuration file/environment variables.
-/// fn get_secret_key() -> Key {
-///     # todo!()
-///     // [...]
-/// }
-///
-/// #[actix_web::main]
-/// async fn main() -> std::io::Result<()> {
-///     let secret_key = get_secret_key();
-///     let redis_connection_string = "127.0.0.1:6379";
-///     HttpServer::new(move ||
-///             App::new()
-///             // Add session management to your application using Redis for session state storage
-///             .wrap(
-///                 SessionMiddleware::new(
-///                     RedisActorSessionStore::new(redis_connection_string),
-///                     secret_key.clone()
-///                 )
-///             )
-///             .default_service(web::to(|| HttpResponse::Ok())))
-///         .bind(("127.0.0.1", 8080))?
-///         .run()
-///         .await
-/// }
-/// ```
-///
-/// If you want to customise use [`builder`](Self::builder) instead of [`new`](Self::new):
-///
-/// ```no_run
-/// use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web};
-/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
-/// use actix_session::config::PersistentSession;
-///
-/// // The secret key would usually be read from a configuration file/environment variables.
-/// fn get_secret_key() -> Key {
-///     # todo!()
-///     // [...]
-/// }
-///
-/// #[actix_web::main]
-/// async fn main() -> std::io::Result<()> {
-///     let secret_key = get_secret_key();
-///     let redis_connection_string = "127.0.0.1:6379";
-///     HttpServer::new(move ||
-///             App::new()
-///             // Customise session length!
-///             .wrap(
-///                 SessionMiddleware::builder(
-///                     RedisActorSessionStore::new(redis_connection_string),
-///                     secret_key.clone()
-///                 )
-///                 .session_lifecycle(
-///                     PersistentSession::default()
-///                         .session_ttl(time::Duration::days(5))
-///                 )
-///                 .build(),
-///             )
-///             .default_service(web::to(|| HttpResponse::Ok())))
-///         .bind(("127.0.0.1", 8080))?
-///         .run()
-///         .await
-/// }
-/// ```
-#[derive(Clone)]
-pub struct SessionMiddleware<Store: SessionStore> {
-    storage_backend: Rc<Store>,
-    configuration: Rc<Configuration>,
+/// A middleware for session management in Actix Web applications.
+///
+/// [`SessionMiddleware`] takes care of a few jobs:
+///
+/// - Instructs the session storage backend to create/update/delete/retrieve the state attached to
+///   a session according to its status and the operations that have been performed against it;
+/// - Set/remove a cookie, on the client side, to enable a user to be consistently associated with
+///   the same session across multiple HTTP requests.
+///
+/// Use [`SessionMiddleware::new`] to initialize the session framework using the default parameters.
+/// To create a new instance of [`SessionMiddleware`] you need to provide:
+///
+/// - an instance of the session storage backend you wish to use (i.e. an implementation of
+///   [`SessionStore`]);
+/// - a secret key, to sign or encrypt the content of client-side session cookie.
+///
+/// # How did we choose defaults?
+/// You should not regret adding `actix-session` to your dependencies and going to production using
+/// the default configuration. That is why, when in doubt, we opt to use the most secure option for
+/// each configuration parameter.
+///
+/// We expose knobs to change the default to suit your needs—i.e., if you know what you are doing,
+/// we will not stop you. But being a subject-matter expert should not be a requirement to deploy
+/// reasonably secure implementation of sessions.
+///
+/// # Examples
+/// ```no_run
+/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
+/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
+/// use actix_web::cookie::Key;
+///
+/// // The secret key would usually be read from a configuration file/environment variables.
+/// fn get_secret_key() -> Key {
+///     # todo!()
+///     // [...]
+/// }
+///
+/// #[actix_web::main]
+/// async fn main() -> std::io::Result<()> {
+///     let secret_key = get_secret_key();
+///     let redis_connection_string = "127.0.0.1:6379";
+///     HttpServer::new(move ||
+///             App::new()
+///             // Add session management to your application using Redis for session state storage
+///             .wrap(
+///                 SessionMiddleware::new(
+///                     RedisActorSessionStore::new(redis_connection_string),
+///                     secret_key.clone()
+///                 )
+///             )
+///             .default_service(web::to(|| HttpResponse::Ok())))
+///         .bind(("127.0.0.1", 8080))?
+///         .run()
+///         .await
+/// }
+/// ```
+///
+/// If you want to customise use [`builder`](Self::builder) instead of [`new`](Self::new):
+///
+/// ```no_run
+/// use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web};
+/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
+/// use actix_session::config::PersistentSession;
+///
+/// // The secret key would usually be read from a configuration file/environment variables.
+/// fn get_secret_key() -> Key {
+///     # todo!()
+///     // [...]
+/// }
+///
+/// #[actix_web::main]
+/// async fn main() -> std::io::Result<()> {
+///     let secret_key = get_secret_key();
+///     let redis_connection_string = "127.0.0.1:6379";
+///     HttpServer::new(move ||
+///             App::new()
+///             // Customise session length!
+///             .wrap(
+///                 SessionMiddleware::builder(
+///                     RedisActorSessionStore::new(redis_connection_string),
+///                     secret_key.clone()
+///                 )
+///                 .session_lifecycle(
+///                     PersistentSession::default()
+///                         .session_ttl(time::Duration::days(5))
+///                 )
+///                 .build(),
+///             )
+///             .default_service(web::to(|| HttpResponse::Ok())))
+///         .bind(("127.0.0.1", 8080))?
+///         .run()
+///         .await
+/// }
+/// ```
+#[derive(Clone)]
+pub struct SessionMiddleware<Store: SessionStore> {
+    storage_backend: Rc<Store>,
+    configuration: Rc<Configuration>,
 }
 
-impl<Store: SessionStore> SessionMiddleware<Store> {
-    /// Use [`SessionMiddleware::new`] to initialize the session framework using the default
-    /// parameters.
-    ///
-    /// To create a new instance of [`SessionMiddleware`] you need to provide:
-    /// - an instance of the session storage backend you wish to use (i.e. an implementation of
-    ///   [`SessionStore`]);
-    /// - a secret key, to sign or encrypt the content of client-side session cookie.
-    pub fn new(store: Store, key: Key) -> Self {
-        Self::builder(store, key).build()
+impl<Store: SessionStore> SessionMiddleware<Store> {
+    /// Use [`SessionMiddleware::new`] to initialize the session framework using the default
+    /// parameters.
+    ///
+    /// To create a new instance of [`SessionMiddleware`] you need to provide:
+    /// - an instance of the session storage backend you wish to use (i.e. an implementation of
+    ///   [`SessionStore`]);
+    /// - a secret key, to sign or encrypt the content of client-side session cookie.
+    pub fn new(store: Store, key: Key) -> Self {
+        Self::builder(store, key).build()
     }
 
-    /// A fluent API to configure [`SessionMiddleware`].
-    ///
-    /// It takes as input the two required inputs to create a new instance of [`SessionMiddleware`]:
-    /// - an instance of the session storage backend you wish to use (i.e. an implementation of
-    ///   [`SessionStore`]);
-    /// - a secret key, to sign or encrypt the content of client-side session cookie.
-    pub fn builder(store: Store, key: Key) -> SessionMiddlewareBuilder<Store> {
-        SessionMiddlewareBuilder::new(store, config::default_configuration(key))
+    /// A fluent API to configure [`SessionMiddleware`].
+    ///
+    /// It takes as input the two required inputs to create a new instance of [`SessionMiddleware`]:
+    /// - an instance of the session storage backend you wish to use (i.e. an implementation of
+    ///   [`SessionStore`]);
+    /// - a secret key, to sign or encrypt the content of client-side session cookie.
+    pub fn builder(store: Store, key: Key) -> SessionMiddlewareBuilder<Store> {
+        SessionMiddlewareBuilder::new(store, config::default_configuration(key))
     }
 
-    pub(crate) fn from_parts(store: Store, configuration: Configuration) -> Self {
-        Self {
-            storage_backend: Rc::new(store),
-            configuration: Rc::new(configuration),
+    pub(crate) fn from_parts(store: Store, configuration: Configuration) -> Self {
+        Self {
+            storage_backend: Rc::new(store),
+            configuration: Rc::new(configuration),
         }
     }
 }
 
-impl<S, B, Store> Transform<S, ServiceRequest> for SessionMiddleware<Store>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
-    S::Future: 'static,
-    B: MessageBody + 'static,
-    Store: SessionStore + 'static,
+impl<S, B, Store> Transform<S, ServiceRequest> for SessionMiddleware<Store>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
+    S::Future: 'static,
+    B: MessageBody + 'static,
+    Store: SessionStore + 'static,
 {
-    type Response = ServiceResponse<B>;
-    type Error = actix_web::Error;
-    type Transform = InnerSessionMiddleware<S, Store>;
-    type InitError = ();
-    type Future = Ready<Result<Self::Transform, Self::InitError>>;
+    type Response = ServiceResponse<B>;
+    type Error = actix_web::Error;
+    type Transform = InnerSessionMiddleware<S, Store>;
+    type InitError = ();
+    type Future = Ready<Result<Self::Transform, Self::InitError>>;
 
-    fn new_transform(&self, service: S) -> Self::Future {
-        ready(Ok(InnerSessionMiddleware {
-            service: Rc::new(service),
-            configuration: Rc::clone(&self.configuration),
-            storage_backend: Rc::clone(&self.storage_backend),
+    fn new_transform(&self, service: S) -> Self::Future {
+        ready(Ok(InnerSessionMiddleware {
+            service: Rc::new(service),
+            configuration: Rc::clone(&self.configuration),
+            storage_backend: Rc::clone(&self.storage_backend),
         }))
     }
 }
 
-/// Short-hand to create an `actix_web::Error` instance that will result in an `Internal Server
-/// Error` response while preserving the error root cause (e.g. in logs).
-fn e500<E: fmt::Debug + fmt::Display + 'static>(err: E) -> actix_web::Error {
-    // We do not use `actix_web::error::ErrorInternalServerError` because we do not want to
-    // leak internal implementation details to the caller.
-    //
-    // `actix_web::error::ErrorInternalServerError` includes the error Display representation
-    // as body of the error responses, leading to messages like "There was an issue persisting
-    // the session state" reaching API clients. We don't want that, we want opaque 500s.
-    actix_web::error::InternalError::from_response(
-        err,
-        HttpResponse::InternalServerError().finish(),
+/// Short-hand to create an `actix_web::Error` instance that will result in an `Internal Server
+/// Error` response while preserving the error root cause (e.g. in logs).
+fn e500<E: fmt::Debug + fmt::Display + 'static>(err: E) -> actix_web::Error {
+    // We do not use `actix_web::error::ErrorInternalServerError` because we do not want to
+    // leak internal implementation details to the caller.
+    //
+    // `actix_web::error::ErrorInternalServerError` includes the error Display representation
+    // as body of the error responses, leading to messages like "There was an issue persisting
+    // the session state" reaching API clients. We don't want that, we want opaque 500s.
+    actix_web::error::InternalError::from_response(
+        err,
+        HttpResponse::InternalServerError().finish(),
     )
-    .into()
+    .into()
 }
 
-#[doc(hidden)]
-#[non_exhaustive]
-pub struct InnerSessionMiddleware<S, Store: SessionStore + 'static> {
-    service: Rc<S>,
-    configuration: Rc<Configuration>,
-    storage_backend: Rc<Store>,
+#[doc(hidden)]
+#[non_exhaustive]
+pub struct InnerSessionMiddleware<S, Store: SessionStore + 'static> {
+    service: Rc<S>,
+    configuration: Rc<Configuration>,
+    storage_backend: Rc<Store>,
 }
 
-impl<S, B, Store> Service<ServiceRequest> for InnerSessionMiddleware<S, Store>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
-    S::Future: 'static,
-    Store: SessionStore + 'static,
+impl<S, B, Store> Service<ServiceRequest> for InnerSessionMiddleware<S, Store>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
+    S::Future: 'static,
+    Store: SessionStore + 'static,
 {
-    type Response = ServiceResponse<B>;
-    type Error = actix_web::Error;
-    #[allow(clippy::type_complexity)]
-    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
+    type Response = ServiceResponse<B>;
+    type Error = actix_web::Error;
+    #[allow(clippy::type_complexity)]
+    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
 
-    forward_ready!(service);
+    forward_ready!(service);
 
-    fn call(&self, mut req: ServiceRequest) -> Self::Future {
-        let service = Rc::clone(&self.service);
-        let storage_backend = Rc::clone(&self.storage_backend);
-        let configuration = Rc::clone(&self.configuration);
+    fn call(&self, mut req: ServiceRequest) -> Self::Future {
+        let service = Rc::clone(&self.service);
+        let storage_backend = Rc::clone(&self.storage_backend);
+        let configuration = Rc::clone(&self.configuration);
 
-        Box::pin(async move {
-            let session_key = extract_session_key(&req, &configuration.cookie);
-            let (session_key, session_state) =
-                load_session_state(session_key, storage_backend.as_ref()).await?;
+        Box::pin(async move {
+            let session_key = extract_session_key(&req, &configuration.cookie);
+            let (session_key, session_state) =
+                load_session_state(session_key, storage_backend.as_ref()).await?;
 
-            Session::set_session(&mut req, session_state);
+            Session::set_session(&mut req, session_state);
 
-            let mut res = service.call(req).await?;
-            let (status, session_state) = Session::get_changes(&mut res);
+            let mut res = service.call(req).await?;
+            let (status, session_state) = Session::get_changes(&mut res);
 
-            match session_key {
-                None => {
-                    // we do not create an entry in the session store if there is no state attached
-                    // to a fresh session
-                    if !session_state.is_empty() {
-                        let session_key = storage_backend
-                            .save(session_state, &configuration.session.state_ttl)
-                            .await
-                            .map_err(e500)?;
+            match session_key {
+                None => {
+                    // we do not create an entry in the session store if there is no state attached
+                    // to a fresh session
+                    if !session_state.is_empty() {
+                        let session_key = storage_backend
+                            .save(session_state, &configuration.session.state_ttl)
+                            .await
+                            .map_err(e500)?;
 
-                        set_session_cookie(
-                            res.response_mut().head_mut(),
-                            session_key,
-                            &configuration.cookie,
+                        set_session_cookie(
+                            res.response_mut().head_mut(),
+                            session_key,
+                            &configuration.cookie,
                         )
-                        .map_err(e500)?;
+                        .map_err(e500)?;
                     }
                 }
 
-                Some(session_key) => {
-                    match status {
-                        SessionStatus::Changed => {
-                            let session_key = storage_backend
-                                .update(
-                                    session_key,
-                                    session_state,
-                                    &configuration.session.state_ttl,
+                Some(session_key) => {
+                    match status {
+                        SessionStatus::Changed => {
+                            let session_key = storage_backend
+                                .update(
+                                    session_key,
+                                    session_state,
+                                    &configuration.session.state_ttl,
                                 )
-                                .await
-                                .map_err(e500)?;
+                                .await
+                                .map_err(e500)?;
 
-                            set_session_cookie(
-                                res.response_mut().head_mut(),
-                                session_key,
-                                &configuration.cookie,
+                            set_session_cookie(
+                                res.response_mut().head_mut(),
+                                session_key,
+                                &configuration.cookie,
                             )
-                            .map_err(e500)?;
+                            .map_err(e500)?;
                         }
 
-                        SessionStatus::Purged => {
-                            storage_backend.delete(&session_key).await.map_err(e500)?;
+                        SessionStatus::Purged => {
+                            storage_backend.delete(&session_key).await.map_err(e500)?;
 
-                            delete_session_cookie(
-                                res.response_mut().head_mut(),
-                                &configuration.cookie,
+                            delete_session_cookie(
+                                res.response_mut().head_mut(),
+                                &configuration.cookie,
                             )
-                            .map_err(e500)?;
+                            .map_err(e500)?;
                         }
 
-                        SessionStatus::Renewed => {
-                            storage_backend.delete(&session_key).await.map_err(e500)?;
+                        SessionStatus::Renewed => {
+                            storage_backend.delete(&session_key).await.map_err(e500)?;
 
-                            let session_key = storage_backend
-                                .save(session_state, &configuration.session.state_ttl)
-                                .await
-                                .map_err(e500)?;
+                            let session_key = storage_backend
+                                .save(session_state, &configuration.session.state_ttl)
+                                .await
+                                .map_err(e500)?;
 
-                            set_session_cookie(
-                                res.response_mut().head_mut(),
-                                session_key,
-                                &configuration.cookie,
+                            set_session_cookie(
+                                res.response_mut().head_mut(),
+                                session_key,
+                                &configuration.cookie,
                             )
-                            .map_err(e500)?;
+                            .map_err(e500)?;
                         }
 
-                        SessionStatus::Unchanged => {
-                            if matches!(
-                                configuration.ttl_extension_policy,
-                                TtlExtensionPolicy::OnEveryRequest
+                        SessionStatus::Unchanged => {
+                            if matches!(
+                                configuration.ttl_extension_policy,
+                                TtlExtensionPolicy::OnEveryRequest
                             ) {
-                                storage_backend
-                                    .update_ttl(&session_key, &configuration.session.state_ttl)
-                                    .await
-                                    .map_err(e500)?;
+                                storage_backend
+                                    .update_ttl(&session_key, &configuration.session.state_ttl)
+                                    .await
+                                    .map_err(e500)?;
 
-                                if configuration.cookie.max_age.is_some() {
-                                    set_session_cookie(
-                                        res.response_mut().head_mut(),
-                                        session_key,
-                                        &configuration.cookie,
+                                if configuration.cookie.max_age.is_some() {
+                                    set_session_cookie(
+                                        res.response_mut().head_mut(),
+                                        session_key,
+                                        &configuration.cookie,
                                     )
-                                    .map_err(e500)?;
+                                    .map_err(e500)?;
                                 }
                             }
                         }
@@ -777,154 +777,154 @@
                 }
             }
 
-            Ok(res)
+            Ok(res)
         })
     }
 }
 
-/// Examines the session cookie attached to the incoming request, if there is one, and tries
-/// to extract the session key.
-///
-/// It returns `None` if there is no session cookie or if the session cookie is considered invalid
-/// (e.g., when failing a signature check).
-fn extract_session_key(req: &ServiceRequest, config: &CookieConfiguration) -> Option<SessionKey> {
-    let cookies = req.cookies().ok()?;
-    let session_cookie = cookies
-        .iter()
-        .find(|&cookie| cookie.name() == config.name)?;
+/// Examines the session cookie attached to the incoming request, if there is one, and tries
+/// to extract the session key.
+///
+/// It returns `None` if there is no session cookie or if the session cookie is considered invalid
+/// (e.g., when failing a signature check).
+fn extract_session_key(req: &ServiceRequest, config: &CookieConfiguration) -> Option<SessionKey> {
+    let cookies = req.cookies().ok()?;
+    let session_cookie = cookies
+        .iter()
+        .find(|&cookie| cookie.name() == config.name)?;
 
-    let mut jar = CookieJar::new();
-    jar.add_original(session_cookie.clone());
+    let mut jar = CookieJar::new();
+    jar.add_original(session_cookie.clone());
 
-    let verification_result = match config.content_security {
-        CookieContentSecurity::Signed => jar.signed(&config.key).get(&config.name),
-        CookieContentSecurity::Private => jar.private(&config.key).get(&config.name),
+    let verification_result = match config.content_security {
+        CookieContentSecurity::Signed => jar.signed(&config.key).get(&config.name),
+        CookieContentSecurity::Private => jar.private(&config.key).get(&config.name),
     };
 
-    if verification_result.is_none() {
+    if verification_result.is_none() {
         tracing::warn!(
             "The session cookie attached to the incoming request failed to pass cryptographic \
-            checks (signature verification/decryption)."
-        );
+            checks (signature verification/decryption)."
+        );
     }
 
-    match verification_result?.value().to_owned().try_into() {
-        Ok(session_key) => Some(session_key),
-        Err(err) => {
+    match verification_result?.value().to_owned().try_into() {
+        Ok(session_key) => Some(session_key),
+        Err(err) => {
             tracing::warn!(
-                error.message = %err,
-                error.cause_chain = ?err,
-                "Invalid session key, ignoring."
-            );
+                error.message = %err,
+                error.cause_chain = ?err,
+                "Invalid session key, ignoring."
+            );
 
-            None
-        }
+            None
+        }
     }
 }
 
-async fn load_session_state<Store: SessionStore>(
-    session_key: Option<SessionKey>,
-    storage_backend: &Store,
-) -> Result<(Option<SessionKey>, HashMap<String, String>), actix_web::Error> {
-    if let Some(session_key) = session_key {
-        match storage_backend.load(&session_key).await {
-            Ok(state) => {
-                if let Some(state) = state {
-                    Ok((Some(session_key), state))
-                } else {
-                    // We discard the existing session key given that the state attached to it can
-                    // no longer be found (e.g. it expired or we suffered some data loss in the
-                    // storage). Regenerating the session key will trigger the `save` workflow
-                    // instead of the `update` workflow if the session state is modified during the
-                    // lifecycle of the current request.
+async fn load_session_state<Store: SessionStore>(
+    session_key: Option<SessionKey>,
+    storage_backend: &Store,
+) -> Result<(Option<SessionKey>, HashMap<String, String>), actix_web::Error> {
+    if let Some(session_key) = session_key {
+        match storage_backend.load(&session_key).await {
+            Ok(state) => {
+                if let Some(state) = state {
+                    Ok((Some(session_key), state))
+                } else {
+                    // We discard the existing session key given that the state attached to it can
+                    // no longer be found (e.g. it expired or we suffered some data loss in the
+                    // storage). Regenerating the session key will trigger the `save` workflow
+                    // instead of the `update` workflow if the session state is modified during the
+                    // lifecycle of the current request.
 
-                    tracing::info!(
+                    tracing::info!(
                         "No session state has been found for a valid session key, creating a new \
-                        empty session."
-                    );
+                        empty session."
+                    );
 
-                    Ok((None, HashMap::new()))
+                    Ok((None, HashMap::new()))
                 }
             }
 
-            Err(err) => match err {
-                LoadError::Deserialization(err) => {
+            Err(err) => match err {
+                LoadError::Deserialization(err) => {
                     tracing::warn!(
-                        error.message = %err,
-                        error.cause_chain = ?err,
-                        "Invalid session state, creating a new empty session."
-                    );
+                        error.message = %err,
+                        error.cause_chain = ?err,
+                        "Invalid session state, creating a new empty session."
+                    );
 
-                    Ok((Some(session_key), HashMap::new()))
+                    Ok((Some(session_key), HashMap::new()))
                 }
 
-                LoadError::Other(err) => Err(e500(err)),
+                LoadError::Other(err) => Err(e500(err)),
             },
         }
-    } else {
-        Ok((None, HashMap::new()))
+    } else {
+        Ok((None, HashMap::new()))
     }
 }
 
-fn set_session_cookie(
-    response: &mut ResponseHead,
-    session_key: SessionKey,
-    config: &CookieConfiguration,
-) -> Result<(), anyhow::Error> {
-    let value: String = session_key.into();
-    let mut cookie = Cookie::new(config.name.clone(), value);
+fn set_session_cookie(
+    response: &mut ResponseHead,
+    session_key: SessionKey,
+    config: &CookieConfiguration,
+) -> Result<(), anyhow::Error> {
+    let value: String = session_key.into();
+    let mut cookie = Cookie::new(config.name.clone(), value);
 
-    cookie.set_secure(config.secure);
-    cookie.set_http_only(config.http_only);
-    cookie.set_same_site(config.same_site);
-    cookie.set_path(config.path.clone());
+    cookie.set_secure(config.secure);
+    cookie.set_http_only(config.http_only);
+    cookie.set_same_site(config.same_site);
+    cookie.set_path(config.path.clone());
 
-    if let Some(max_age) = config.max_age {
-        cookie.set_max_age(max_age);
+    if let Some(max_age) = config.max_age {
+        cookie.set_max_age(max_age);
     }
 
-    if let Some(ref domain) = config.domain {
-        cookie.set_domain(domain.clone());
+    if let Some(ref domain) = config.domain {
+        cookie.set_domain(domain.clone());
     }
 
-    let mut jar = CookieJar::new();
-    match config.content_security {
-        CookieContentSecurity::Signed => jar.signed_mut(&config.key).add(cookie),
-        CookieContentSecurity::Private => jar.private_mut(&config.key).add(cookie),
+    let mut jar = CookieJar::new();
+    match config.content_security {
+        CookieContentSecurity::Signed => jar.signed_mut(&config.key).add(cookie),
+        CookieContentSecurity::Private => jar.private_mut(&config.key).add(cookie),
     }
 
-    // set cookie
-    let cookie = jar.delta().next().unwrap();
-    let val = HeaderValue::from_str(&cookie.encoded().to_string())
-        .context("Failed to attach a session cookie to the outgoing response")?;
+    // set cookie
+    let cookie = jar.delta().next().unwrap();
+    let val = HeaderValue::from_str(&cookie.encoded().to_string())
+        .context("Failed to attach a session cookie to the outgoing response")?;
 
-    response.headers_mut().append(SET_COOKIE, val);
+    response.headers_mut().append(SET_COOKIE, val);
 
     Ok(())
 }
 
-fn delete_session_cookie(
-    response: &mut ResponseHead,
-    config: &CookieConfiguration,
-) -> Result<(), anyhow::Error> {
-    let removal_cookie = Cookie::build(config.name.clone(), "")
-        .path(config.path.clone())
-        .http_only(config.http_only);
+fn delete_session_cookie(
+    response: &mut ResponseHead,
+    config: &CookieConfiguration,
+) -> Result<(), anyhow::Error> {
+    let removal_cookie = Cookie::build(config.name.clone(), "")
+        .path(config.path.clone())
+        .http_only(config.http_only);
 
-    let mut removal_cookie = if let Some(ref domain) = config.domain {
-        removal_cookie.domain(domain)
-    } else {
-        removal_cookie
+    let mut removal_cookie = if let Some(ref domain) = config.domain {
+        removal_cookie.domain(domain)
+    } else {
+        removal_cookie
     }
-    .finish();
+    .finish();
 
-    removal_cookie.make_removal();
+    removal_cookie.make_removal();
 
-    let val = HeaderValue::from_str(&removal_cookie.to_string())
-        .context("Failed to attach a session removal cookie to the outgoing response")?;
-    response.headers_mut().append(SET_COOKIE, val);
+    let val = HeaderValue::from_str(&removal_cookie.to_string())
+        .context("Failed to attach a session removal cookie to the outgoing response")?;
+    response.headers_mut().append(SET_COOKIE, val);
 
     Ok(())
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/session.rs.html b/src/actix_session/session.rs.html index 5a4be6650..97f5a4764 100644 --- a/src/actix_session/session.rs.html +++ b/src/actix_session/session.rs.html @@ -324,329 +324,329 @@ 322 323 324 -
use std::{
-    cell::{Ref, RefCell},
-    collections::HashMap,
-    error::Error as StdError,
-    mem,
-    rc::Rc,
+
use std::{
+    cell::{Ref, RefCell},
+    collections::HashMap,
+    error::Error as StdError,
+    mem,
+    rc::Rc,
 };
 
-use actix_utils::future::{ready, Ready};
-use actix_web::{
-    body::BoxBody,
-    dev::{Extensions, Payload, ServiceRequest, ServiceResponse},
-    error::Error,
-    FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
+use actix_utils::future::{ready, Ready};
+use actix_web::{
+    body::BoxBody,
+    dev::{Extensions, Payload, ServiceRequest, ServiceResponse},
+    error::Error,
+    FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
 };
-use anyhow::Context;
-use derive_more::{Display, From};
-use serde::{de::DeserializeOwned, Serialize};
+use anyhow::Context;
+use derive_more::{Display, From};
+use serde::{de::DeserializeOwned, Serialize};
 
-/// The primary interface to access and modify session state.
-///
-/// [`Session`] is an [extractor](#impl-FromRequest)—you can specify it as an input type for your
-/// request handlers and it will be automatically extracted from the incoming request.
-///
-/// ```
-/// use actix_session::Session;
-///
-/// async fn index(session: Session) -> actix_web::Result<&'static str> {
-///     // access session data
-///     if let Some(count) = session.get::<i32>("counter")? {
-///         session.insert("counter", count + 1)?;
-///     } else {
-///         session.insert("counter", 1)?;
-///     }
-///
-///     Ok("Welcome!")
-/// }
-/// # actix_web::web::to(index);
-/// ```
-///
-/// You can also retrieve a [`Session`] object from an `HttpRequest` or a `ServiceRequest` using
-/// [`SessionExt`].
-///
-/// [`SessionExt`]: crate::SessionExt
-#[derive(Clone)]
-pub struct Session(Rc<RefCell<SessionInner>>);
+/// The primary interface to access and modify session state.
+///
+/// [`Session`] is an [extractor](#impl-FromRequest)—you can specify it as an input type for your
+/// request handlers and it will be automatically extracted from the incoming request.
+///
+/// ```
+/// use actix_session::Session;
+///
+/// async fn index(session: Session) -> actix_web::Result<&'static str> {
+///     // access session data
+///     if let Some(count) = session.get::<i32>("counter")? {
+///         session.insert("counter", count + 1)?;
+///     } else {
+///         session.insert("counter", 1)?;
+///     }
+///
+///     Ok("Welcome!")
+/// }
+/// # actix_web::web::to(index);
+/// ```
+///
+/// You can also retrieve a [`Session`] object from an `HttpRequest` or a `ServiceRequest` using
+/// [`SessionExt`].
+///
+/// [`SessionExt`]: crate::SessionExt
+#[derive(Clone)]
+pub struct Session(Rc<RefCell<SessionInner>>);
 
-/// Status of a [`Session`].
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum SessionStatus {
-    /// Session state has been updated - the changes will have to be persisted to the backend.
-    Changed,
+/// Status of a [`Session`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SessionStatus {
+    /// Session state has been updated - the changes will have to be persisted to the backend.
+    Changed,
 
-    /// The session has been flagged for deletion - the session cookie will be removed from
-    /// the client and the session state will be deleted from the session store.
-    ///
-    /// Most operations on the session after it has been marked for deletion will have no effect.
-    Purged,
+    /// The session has been flagged for deletion - the session cookie will be removed from
+    /// the client and the session state will be deleted from the session store.
+    ///
+    /// Most operations on the session after it has been marked for deletion will have no effect.
+    Purged,
 
-    /// The session has been flagged for renewal.
-    ///
-    /// The session key will be regenerated and the time-to-live of the session state will be
-    /// extended.
-    Renewed,
+    /// The session has been flagged for renewal.
+    ///
+    /// The session key will be regenerated and the time-to-live of the session state will be
+    /// extended.
+    Renewed,
 
-    /// The session state has not been modified since its creation/retrieval.
-    Unchanged,
+    /// The session state has not been modified since its creation/retrieval.
+    Unchanged,
 }
 
-impl Default for SessionStatus {
-    fn default() -> SessionStatus {
-        SessionStatus::Unchanged
+impl Default for SessionStatus {
+    fn default() -> SessionStatus {
+        SessionStatus::Unchanged
     }
 }
 
-#[derive(Default)]
-struct SessionInner {
-    state: HashMap<String, String>,
-    status: SessionStatus,
+#[derive(Default)]
+struct SessionInner {
+    state: HashMap<String, String>,
+    status: SessionStatus,
 }
 
-impl Session {
-    /// Get a `value` from the session.
-    ///
-    /// It returns an error if it fails to deserialize as `T` the JSON value associated with `key`.
-    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, SessionGetError> {
-        if let Some(val_str) = self.0.borrow().state.get(key) {
+impl Session {
+    /// Get a `value` from the session.
+    ///
+    /// It returns an error if it fails to deserialize as `T` the JSON value associated with `key`.
+    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, SessionGetError> {
+        if let Some(val_str) = self.0.borrow().state.get(key) {
             Ok(Some(
-                serde_json::from_str(val_str)
-                    .with_context(|| {
+                serde_json::from_str(val_str)
+                    .with_context(|| {
                         format!(
                             "Failed to deserialize the JSON-encoded session data attached to key \
                             `{}` as a `{}` type",
-                            key,
-                            std::any::type_name::<T>()
+                            key,
+                            std::any::type_name::<T>()
                         )
                     })
-                    .map_err(SessionGetError)?,
+                    .map_err(SessionGetError)?,
             ))
-        } else {
+        } else {
             Ok(None)
         }
     }
 
-    /// Get all raw key-value data from the session.
-    ///
-    /// Note that values are JSON encoded.
-    pub fn entries(&self) -> Ref<'_, HashMap<String, String>> {
-        Ref::map(self.0.borrow(), |inner| &inner.state)
+    /// Get all raw key-value data from the session.
+    ///
+    /// Note that values are JSON encoded.
+    pub fn entries(&self) -> Ref<'_, HashMap<String, String>> {
+        Ref::map(self.0.borrow(), |inner| &inner.state)
     }
 
-    /// Returns session status.
-    pub fn status(&self) -> SessionStatus {
-        Ref::map(self.0.borrow(), |inner| &inner.status).clone()
+    /// Returns session status.
+    pub fn status(&self) -> SessionStatus {
+        Ref::map(self.0.borrow(), |inner| &inner.status).clone()
     }
 
-    /// Inserts a key-value pair into the session.
-    ///
-    /// Any serializable value can be used and will be encoded as JSON in session data, hence why
-    /// only a reference to the value is taken.
-    ///
-    /// It returns an error if it fails to serialize `value` to JSON.
-    pub fn insert<T: Serialize>(
+    /// Inserts a key-value pair into the session.
+    ///
+    /// Any serializable value can be used and will be encoded as JSON in session data, hence why
+    /// only a reference to the value is taken.
+    ///
+    /// It returns an error if it fails to serialize `value` to JSON.
+    pub fn insert<T: Serialize>(
         &self,
-        key: impl Into<String>,
-        value: T,
-    ) -> Result<(), SessionInsertError> {
-        let mut inner = self.0.borrow_mut();
+        key: impl Into<String>,
+        value: T,
+    ) -> Result<(), SessionInsertError> {
+        let mut inner = self.0.borrow_mut();
 
-        if inner.status != SessionStatus::Purged {
-            if inner.status != SessionStatus::Renewed {
-                inner.status = SessionStatus::Changed;
+        if inner.status != SessionStatus::Purged {
+            if inner.status != SessionStatus::Renewed {
+                inner.status = SessionStatus::Changed;
             }
 
-            let key = key.into();
-            let val = serde_json::to_string(&value)
-                .with_context(|| {
+            let key = key.into();
+            let val = serde_json::to_string(&value)
+                .with_context(|| {
                     format!(
                         "Failed to serialize the provided `{}` type instance as JSON in order to \
                         attach as session data to the `{}` key",
-                        std::any::type_name::<T>(),
-                        &key
+                        std::any::type_name::<T>(),
+                        &key
                     )
                 })
-                .map_err(SessionInsertError)?;
+                .map_err(SessionInsertError)?;
 
-            inner.state.insert(key, val);
+            inner.state.insert(key, val);
         }
 
         Ok(())
     }
 
-    /// Remove value from the session.
-    ///
-    /// If present, the JSON encoded value is returned.
-    pub fn remove(&self, key: &str) -> Option<String> {
-        let mut inner = self.0.borrow_mut();
+    /// Remove value from the session.
+    ///
+    /// If present, the JSON encoded value is returned.
+    pub fn remove(&self, key: &str) -> Option<String> {
+        let mut inner = self.0.borrow_mut();
 
-        if inner.status != SessionStatus::Purged {
-            if inner.status != SessionStatus::Renewed {
-                inner.status = SessionStatus::Changed;
+        if inner.status != SessionStatus::Purged {
+            if inner.status != SessionStatus::Renewed {
+                inner.status = SessionStatus::Changed;
             }
-            return inner.state.remove(key);
+            return inner.state.remove(key);
         }
 
-        None
-    }
+        None
+    }
 
-    /// Remove value from the session and deserialize.
-    ///
-    /// Returns `None` if key was not present in session. Returns `T` if deserialization succeeds,
-    /// otherwise returns un-deserialized JSON string.
-    pub fn remove_as<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, String>> {
-        self.remove(key)
-            .map(|val_str| match serde_json::from_str(&val_str) {
-                Ok(val) => Ok(val),
-                Err(_err) => {
+    /// Remove value from the session and deserialize.
+    ///
+    /// Returns `None` if key was not present in session. Returns `T` if deserialization succeeds,
+    /// otherwise returns un-deserialized JSON string.
+    pub fn remove_as<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, String>> {
+        self.remove(key)
+            .map(|val_str| match serde_json::from_str(&val_str) {
+                Ok(val) => Ok(val),
+                Err(_err) => {
                     tracing::debug!(
                         "Removed value (key: {}) could not be deserialized as {}",
-                        key,
-                        std::any::type_name::<T>()
+                        key,
+                        std::any::type_name::<T>()
                     );
 
-                    Err(val_str)
+                    Err(val_str)
                 }
             })
     }
 
-    /// Clear the session.
-    pub fn clear(&self) {
-        let mut inner = self.0.borrow_mut();
+    /// Clear the session.
+    pub fn clear(&self) {
+        let mut inner = self.0.borrow_mut();
 
-        if inner.status != SessionStatus::Purged {
-            if inner.status != SessionStatus::Renewed {
-                inner.status = SessionStatus::Changed;
+        if inner.status != SessionStatus::Purged {
+            if inner.status != SessionStatus::Renewed {
+                inner.status = SessionStatus::Changed;
             }
-            inner.state.clear()
+            inner.state.clear()
         }
     }
 
-    /// Removes session both client and server side.
-    pub fn purge(&self) {
-        let mut inner = self.0.borrow_mut();
-        inner.status = SessionStatus::Purged;
-        inner.state.clear();
+    /// Removes session both client and server side.
+    pub fn purge(&self) {
+        let mut inner = self.0.borrow_mut();
+        inner.status = SessionStatus::Purged;
+        inner.state.clear();
     }
 
-    /// Renews the session key, assigning existing session state to new key.
-    pub fn renew(&self) {
-        let mut inner = self.0.borrow_mut();
+    /// Renews the session key, assigning existing session state to new key.
+    pub fn renew(&self) {
+        let mut inner = self.0.borrow_mut();
 
-        if inner.status != SessionStatus::Purged {
-            inner.status = SessionStatus::Renewed;
+        if inner.status != SessionStatus::Purged {
+            inner.status = SessionStatus::Renewed;
         }
     }
 
-    /// Adds the given key-value pairs to the session on the request.
-    ///
-    /// Values that match keys already existing on the session will be overwritten. Values should
-    /// already be JSON serialized.
-    pub(crate) fn set_session(
-        req: &mut ServiceRequest,
-        data: impl IntoIterator<Item = (String, String)>,
+    /// Adds the given key-value pairs to the session on the request.
+    ///
+    /// Values that match keys already existing on the session will be overwritten. Values should
+    /// already be JSON serialized.
+    pub(crate) fn set_session(
+        req: &mut ServiceRequest,
+        data: impl IntoIterator<Item = (String, String)>,
     ) {
-        let session = Session::get_session(&mut *req.extensions_mut());
-        let mut inner = session.0.borrow_mut();
-        inner.state.extend(data);
+        let session = Session::get_session(&mut *req.extensions_mut());
+        let mut inner = session.0.borrow_mut();
+        inner.state.extend(data);
     }
 
-    /// Returns session status and iterator of key-value pairs of changes.
-    ///
-    /// This is a destructive operation - the session state is removed from the request extensions
-    /// typemap, leaving behind a new empty map. It should only be used when the session is being
-    /// finalised (i.e. in `SessionMiddleware`).
-    pub(crate) fn get_changes<B>(
-        res: &mut ServiceResponse<B>,
-    ) -> (SessionStatus, HashMap<String, String>) {
-        if let Some(s_impl) = res
-            .request()
-            .extensions()
-            .get::<Rc<RefCell<SessionInner>>>()
+    /// Returns session status and iterator of key-value pairs of changes.
+    ///
+    /// This is a destructive operation - the session state is removed from the request extensions
+    /// typemap, leaving behind a new empty map. It should only be used when the session is being
+    /// finalised (i.e. in `SessionMiddleware`).
+    pub(crate) fn get_changes<B>(
+        res: &mut ServiceResponse<B>,
+    ) -> (SessionStatus, HashMap<String, String>) {
+        if let Some(s_impl) = res
+            .request()
+            .extensions()
+            .get::<Rc<RefCell<SessionInner>>>()
         {
-            let state = mem::take(&mut s_impl.borrow_mut().state);
-            (s_impl.borrow().status.clone(), state)
-        } else {
-            (SessionStatus::Unchanged, HashMap::new())
+            let state = mem::take(&mut s_impl.borrow_mut().state);
+            (s_impl.borrow().status.clone(), state)
+        } else {
+            (SessionStatus::Unchanged, HashMap::new())
         }
     }
 
-    pub(crate) fn get_session(extensions: &mut Extensions) -> Session {
-        if let Some(s_impl) = extensions.get::<Rc<RefCell<SessionInner>>>() {
-            return Session(Rc::clone(s_impl));
+    pub(crate) fn get_session(extensions: &mut Extensions) -> Session {
+        if let Some(s_impl) = extensions.get::<Rc<RefCell<SessionInner>>>() {
+            return Session(Rc::clone(s_impl));
         }
 
-        let inner = Rc::new(RefCell::new(SessionInner::default()));
-        extensions.insert(inner.clone());
+        let inner = Rc::new(RefCell::new(SessionInner::default()));
+        extensions.insert(inner.clone());
 
-        Session(inner)
+        Session(inner)
     }
 }
 
-/// Extractor implementation for [`Session`]s.
-///
-/// # Examples
-/// ```
-/// # use actix_web::*;
-/// use actix_session::Session;
-///
-/// #[get("/")]
-/// async fn index(session: Session) -> Result<impl Responder> {
-///     // access session data
-///     if let Some(count) = session.get::<i32>("counter")? {
-///         session.insert("counter", count + 1)?;
-///     } else {
-///         session.insert("counter", 1)?;
-///     }
-///
-///     let count = session.get::<i32>("counter")?.unwrap();
-///     Ok(format!("Counter: {}", count))
-/// }
-/// ```
-impl FromRequest for Session {
-    type Error = Error;
-    type Future = Ready<Result<Session, Error>>;
+/// Extractor implementation for [`Session`]s.
+///
+/// # Examples
+/// ```
+/// # use actix_web::*;
+/// use actix_session::Session;
+///
+/// #[get("/")]
+/// async fn index(session: Session) -> Result<impl Responder> {
+///     // access session data
+///     if let Some(count) = session.get::<i32>("counter")? {
+///         session.insert("counter", count + 1)?;
+///     } else {
+///         session.insert("counter", 1)?;
+///     }
+///
+///     let count = session.get::<i32>("counter")?.unwrap();
+///     Ok(format!("Counter: {}", count))
+/// }
+/// ```
+impl FromRequest for Session {
+    type Error = Error;
+    type Future = Ready<Result<Session, Error>>;
 
-    #[inline]
-    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
-        ready(Ok(Session::get_session(&mut *req.extensions_mut())))
+    #[inline]
+    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
+        ready(Ok(Session::get_session(&mut *req.extensions_mut())))
     }
 }
 
-/// Error returned by [`Session::get`].
-#[derive(Debug, Display, From)]
-#[display(fmt = "{}", _0)]
-pub struct SessionGetError(anyhow::Error);
+/// Error returned by [`Session::get`].
+#[derive(Debug, Display, From)]
+#[display(fmt = "{}", _0)]
+pub struct SessionGetError(anyhow::Error);
 
-impl StdError for SessionGetError {
-    fn source(&self) -> Option<&(dyn StdError + 'static)> {
-        Some(self.0.as_ref())
+impl StdError for SessionGetError {
+    fn source(&self) -> Option<&(dyn StdError + 'static)> {
+        Some(self.0.as_ref())
     }
 }
 
-impl ResponseError for SessionGetError {
-    fn error_response(&self) -> HttpResponse<BoxBody> {
-        HttpResponse::new(self.status_code())
+impl ResponseError for SessionGetError {
+    fn error_response(&self) -> HttpResponse<BoxBody> {
+        HttpResponse::new(self.status_code())
     }
 }
 
-/// Error returned by [`Session::insert`].
-#[derive(Debug, Display, From)]
-#[display(fmt = "{}", _0)]
-pub struct SessionInsertError(anyhow::Error);
+/// Error returned by [`Session::insert`].
+#[derive(Debug, Display, From)]
+#[display(fmt = "{}", _0)]
+pub struct SessionInsertError(anyhow::Error);
 
-impl StdError for SessionInsertError {
-    fn source(&self) -> Option<&(dyn StdError + 'static)> {
-        Some(self.0.as_ref())
+impl StdError for SessionInsertError {
+    fn source(&self) -> Option<&(dyn StdError + 'static)> {
+        Some(self.0.as_ref())
     }
 }
 
-impl ResponseError for SessionInsertError {
-    fn error_response(&self) -> HttpResponse<BoxBody> {
-        HttpResponse::new(self.status_code())
+impl ResponseError for SessionInsertError {
+    fn error_response(&self) -> HttpResponse<BoxBody> {
+        HttpResponse::new(self.status_code())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/session_ext.rs.html b/src/actix_session/session_ext.rs.html index f5943ef62..9aefea1c8 100644 --- a/src/actix_session/session_ext.rs.html +++ b/src/actix_session/session_ext.rs.html @@ -38,43 +38,43 @@ 36 37 38 -
use actix_web::{
-    dev::{ServiceRequest, ServiceResponse},
-    guard::GuardContext,
-    HttpMessage, HttpRequest,
+
use actix_web::{
+    dev::{ServiceRequest, ServiceResponse},
+    guard::GuardContext,
+    HttpMessage, HttpRequest,
 };
 
-use crate::Session;
+use crate::Session;
 
-/// Extract a [`Session`] object from various `actix-web` types (e.g. `HttpRequest`,
-/// `ServiceRequest`, `ServiceResponse`).
-pub trait SessionExt {
-    /// Extract a [`Session`] object.
-    fn get_session(&self) -> Session;
+/// Extract a [`Session`] object from various `actix-web` types (e.g. `HttpRequest`,
+/// `ServiceRequest`, `ServiceResponse`).
+pub trait SessionExt {
+    /// Extract a [`Session`] object.
+    fn get_session(&self) -> Session;
 }
 
-impl SessionExt for HttpRequest {
-    fn get_session(&self) -> Session {
-        Session::get_session(&mut *self.extensions_mut())
+impl SessionExt for HttpRequest {
+    fn get_session(&self) -> Session {
+        Session::get_session(&mut *self.extensions_mut())
     }
 }
 
-impl SessionExt for ServiceRequest {
-    fn get_session(&self) -> Session {
-        Session::get_session(&mut *self.extensions_mut())
+impl SessionExt for ServiceRequest {
+    fn get_session(&self) -> Session {
+        Session::get_session(&mut *self.extensions_mut())
     }
 }
 
-impl SessionExt for ServiceResponse {
-    fn get_session(&self) -> Session {
-        self.request().get_session()
+impl SessionExt for ServiceResponse {
+    fn get_session(&self) -> Session {
+        self.request().get_session()
     }
 }
 
-impl<'a> SessionExt for GuardContext<'a> {
-    fn get_session(&self) -> Session {
-        Session::get_session(&mut *self.req_data_mut())
+impl<'a> SessionExt for GuardContext<'a> {
+    fn get_session(&self) -> Session {
+        Session::get_session(&mut *self.req_data_mut())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/cookie.rs.html b/src/actix_session/storage/cookie.rs.html index 38760bd90..c7dfd7815 100644 --- a/src/actix_session/storage/cookie.rs.html +++ b/src/actix_session/storage/cookie.rs.html @@ -121,126 +121,126 @@ 119 120 121 -
use std::convert::TryInto;
+
use std::convert::TryInto;
 
-use actix_web::cookie::time::Duration;
-use anyhow::Error;
+use actix_web::cookie::time::Duration;
+use anyhow::Error;
 
-use super::SessionKey;
-use crate::storage::{
-    interface::{LoadError, SaveError, SessionState, UpdateError},
-    SessionStore,
+use super::SessionKey;
+use crate::storage::{
+    interface::{LoadError, SaveError, SessionState, UpdateError},
+    SessionStore,
 };
 
-/// Use the session key, stored in the session cookie, as storage backend for the session state.
-///
-/// ```no_run
-/// use actix_web::{cookie::Key, web, App, HttpServer, HttpResponse, Error};
-/// use actix_session::{SessionMiddleware, storage::CookieSessionStore};
-///
-/// // The secret key would usually be read from a configuration file/environment variables.
-/// fn get_secret_key() -> Key {
-///     # todo!()
-///     // [...]
-/// }
-///
-/// #[actix_web::main]
-/// async fn main() -> std::io::Result<()> {
-///     let secret_key = get_secret_key();
-///     HttpServer::new(move ||
-///             App::new()
-///             .wrap(SessionMiddleware::new(CookieSessionStore::default(), secret_key.clone()))
-///             .default_service(web::to(|| HttpResponse::Ok())))
-///         .bind(("127.0.0.1", 8080))?
-///         .run()
-///         .await
-/// }
-/// ```
-///
-/// # Limitations
-/// Cookies are subject to size limits so we require session keys to be shorter than 4096 bytes.
-/// This translates into a limit on the maximum size of the session state when using cookies as
-/// storage backend.
-///
-/// The session cookie can always be inspected by end users via the developer tools exposed by their
-/// browsers. We strongly recommend setting the policy to [`CookieContentSecurity::Private`] when
-/// using cookies as storage backend.
-///
-/// There is no way to invalidate a session before its natural expiry when using cookies as the
-/// storage backend.
-///
-/// [`CookieContentSecurity::Private`]: crate::config::CookieContentSecurity::Private
-#[cfg_attr(docsrs, doc(cfg(feature = "cookie-session")))]
-#[derive(Default)]
-#[non_exhaustive]
-pub struct CookieSessionStore;
+/// Use the session key, stored in the session cookie, as storage backend for the session state.
+///
+/// ```no_run
+/// use actix_web::{cookie::Key, web, App, HttpServer, HttpResponse, Error};
+/// use actix_session::{SessionMiddleware, storage::CookieSessionStore};
+///
+/// // The secret key would usually be read from a configuration file/environment variables.
+/// fn get_secret_key() -> Key {
+///     # todo!()
+///     // [...]
+/// }
+///
+/// #[actix_web::main]
+/// async fn main() -> std::io::Result<()> {
+///     let secret_key = get_secret_key();
+///     HttpServer::new(move ||
+///             App::new()
+///             .wrap(SessionMiddleware::new(CookieSessionStore::default(), secret_key.clone()))
+///             .default_service(web::to(|| HttpResponse::Ok())))
+///         .bind(("127.0.0.1", 8080))?
+///         .run()
+///         .await
+/// }
+/// ```
+///
+/// # Limitations
+/// Cookies are subject to size limits so we require session keys to be shorter than 4096 bytes.
+/// This translates into a limit on the maximum size of the session state when using cookies as
+/// storage backend.
+///
+/// The session cookie can always be inspected by end users via the developer tools exposed by their
+/// browsers. We strongly recommend setting the policy to [`CookieContentSecurity::Private`] when
+/// using cookies as storage backend.
+///
+/// There is no way to invalidate a session before its natural expiry when using cookies as the
+/// storage backend.
+///
+/// [`CookieContentSecurity::Private`]: crate::config::CookieContentSecurity::Private
+#[cfg_attr(docsrs, doc(cfg(feature = "cookie-session")))]
+#[derive(Default)]
+#[non_exhaustive]
+pub struct CookieSessionStore;
 
-#[async_trait::async_trait(?Send)]
-impl SessionStore for CookieSessionStore {
-    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
-        serde_json::from_str(session_key.as_ref())
-            .map(Some)
-            .map_err(anyhow::Error::new)
-            .map_err(LoadError::Deserialization)
+#[async_trait::async_trait(?Send)]
+impl SessionStore for CookieSessionStore {
+    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
+        serde_json::from_str(session_key.as_ref())
+            .map(Some)
+            .map_err(anyhow::Error::new)
+            .map_err(LoadError::Deserialization)
     }
 
-    async fn save(
+    async fn save(
         &self,
-        session_state: SessionState,
-        _ttl: &Duration,
-    ) -> Result<SessionKey, SaveError> {
-        let session_key = serde_json::to_string(&session_state)
-            .map_err(anyhow::Error::new)
-            .map_err(SaveError::Serialization)?;
+        session_state: SessionState,
+        _ttl: &Duration,
+    ) -> Result<SessionKey, SaveError> {
+        let session_key = serde_json::to_string(&session_state)
+            .map_err(anyhow::Error::new)
+            .map_err(SaveError::Serialization)?;
 
-        Ok(session_key
-            .try_into()
-            .map_err(Into::into)
-            .map_err(SaveError::Other)?)
+        Ok(session_key
+            .try_into()
+            .map_err(Into::into)
+            .map_err(SaveError::Other)?)
     }
 
-    async fn update(
+    async fn update(
         &self,
-        _session_key: SessionKey,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, UpdateError> {
-        self.save(session_state, ttl)
-            .await
-            .map_err(|err| match err {
-                SaveError::Serialization(err) => UpdateError::Serialization(err),
-                SaveError::Other(err) => UpdateError::Other(err),
+        _session_key: SessionKey,
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, UpdateError> {
+        self.save(session_state, ttl)
+            .await
+            .map_err(|err| match err {
+                SaveError::Serialization(err) => UpdateError::Serialization(err),
+                SaveError::Other(err) => UpdateError::Other(err),
             })
     }
 
-    async fn update_ttl(&self, _session_key: &SessionKey, _ttl: &Duration) -> Result<(), Error> {
+    async fn update_ttl(&self, _session_key: &SessionKey, _ttl: &Duration) -> Result<(), Error> {
         Ok(())
     }
 
-    async fn delete(&self, _session_key: &SessionKey) -> Result<(), anyhow::Error> {
+    async fn delete(&self, _session_key: &SessionKey) -> Result<(), anyhow::Error> {
         Ok(())
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use crate::{storage::utils::generate_session_key, test_helpers::acceptance_test_suite};
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::{storage::utils::generate_session_key, test_helpers::acceptance_test_suite};
 
-    #[actix_web::test]
-    async fn test_session_workflow() {
-        acceptance_test_suite(CookieSessionStore::default, false).await;
+    #[actix_web::test]
+    async fn test_session_workflow() {
+        acceptance_test_suite(CookieSessionStore::default, false).await;
     }
 
-    #[actix_web::test]
-    async fn loading_a_random_session_key_returns_deserialization_error() {
-        let store = CookieSessionStore::default();
-        let session_key = generate_session_key();
+    #[actix_web::test]
+    async fn loading_a_random_session_key_returns_deserialization_error() {
+        let store = CookieSessionStore::default();
+        let session_key = generate_session_key();
         assert!(matches!(
-            store.load(&session_key).await.unwrap_err(),
-            LoadError::Deserialization(_),
+            store.load(&session_key).await.unwrap_err(),
+            LoadError::Deserialization(_),
         ));
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/interface.rs.html b/src/actix_session/storage/interface.rs.html index d650b6c79..f1ce1c07e 100644 --- a/src/actix_session/storage/interface.rs.html +++ b/src/actix_session/storage/interface.rs.html @@ -115,120 +115,120 @@ 113 114 115 -
use std::collections::HashMap;
+
use std::collections::HashMap;
 
-use actix_web::cookie::time::Duration;
-use derive_more::Display;
+use actix_web::cookie::time::Duration;
+use derive_more::Display;
 
-use super::SessionKey;
+use super::SessionKey;
 
-pub(crate) type SessionState = HashMap<String, String>;
+pub(crate) type SessionState = HashMap<String, String>;
 
-/// The interface to retrieve and save the current session data from/to the chosen storage backend.
-///
-/// You can provide your own custom session store backend by implementing this trait.
-///
-/// [`async-trait`](https://docs.rs/async-trait) is used for this trait's definition. Therefore, it
-/// is required for implementations, too. In particular, we use the send-optional variant:
-/// `#[async_trait(?Send)]`.
-#[async_trait::async_trait(?Send)]
-pub trait SessionStore {
-    /// Loads the session state associated to a session key.
-    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError>;
+/// The interface to retrieve and save the current session data from/to the chosen storage backend.
+///
+/// You can provide your own custom session store backend by implementing this trait.
+///
+/// [`async-trait`](https://docs.rs/async-trait) is used for this trait's definition. Therefore, it
+/// is required for implementations, too. In particular, we use the send-optional variant:
+/// `#[async_trait(?Send)]`.
+#[async_trait::async_trait(?Send)]
+pub trait SessionStore {
+    /// Loads the session state associated to a session key.
+    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError>;
 
-    /// Persist the session state for a newly created session.
-    ///
-    /// Returns the corresponding session key.
-    async fn save(
+    /// Persist the session state for a newly created session.
+    ///
+    /// Returns the corresponding session key.
+    async fn save(
         &self,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, SaveError>;
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, SaveError>;
 
-    /// Updates the session state associated to a pre-existing session key.
-    async fn update(
+    /// Updates the session state associated to a pre-existing session key.
+    async fn update(
         &self,
-        session_key: SessionKey,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, UpdateError>;
+        session_key: SessionKey,
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, UpdateError>;
 
-    /// Updates the TTL of the session state associated to a pre-existing session key.
-    async fn update_ttl(
+    /// Updates the TTL of the session state associated to a pre-existing session key.
+    async fn update_ttl(
         &self,
-        session_key: &SessionKey,
-        ttl: &Duration,
-    ) -> Result<(), anyhow::Error>;
+        session_key: &SessionKey,
+        ttl: &Duration,
+    ) -> Result<(), anyhow::Error>;
 
-    /// Deletes a session from the store.
-    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error>;
+    /// Deletes a session from the store.
+    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error>;
 }
 
-// We cannot derive the `Error` implementation using `derive_more` for our custom errors:
-// `derive_more`'s `#[error(source)]` attribute requires the source implement the `Error` trait,
-// while it's actually enough for it to be able to produce a reference to a dyn Error.
+// We cannot derive the `Error` implementation using `derive_more` for our custom errors:
+// `derive_more`'s `#[error(source)]` attribute requires the source implement the `Error` trait,
+// while it's actually enough for it to be able to produce a reference to a dyn Error.
 
-/// Possible failures modes for [`SessionStore::load`].
-#[derive(Debug, Display)]
-pub enum LoadError {
-    /// Failed to deserialize session state.
-    #[display(fmt = "Failed to deserialize session state")]
-    Deserialization(anyhow::Error),
+/// Possible failures modes for [`SessionStore::load`].
+#[derive(Debug, Display)]
+pub enum LoadError {
+    /// Failed to deserialize session state.
+    #[display(fmt = "Failed to deserialize session state")]
+    Deserialization(anyhow::Error),
 
-    /// Something went wrong when retrieving the session state.
-    #[display(fmt = "Something went wrong when retrieving the session state")]
-    Other(anyhow::Error),
+    /// Something went wrong when retrieving the session state.
+    #[display(fmt = "Something went wrong when retrieving the session state")]
+    Other(anyhow::Error),
 }
 
-impl std::error::Error for LoadError {
-    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
-        match self {
-            Self::Deserialization(err) => Some(err.as_ref()),
-            Self::Other(err) => Some(err.as_ref()),
+impl std::error::Error for LoadError {
+    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+        match self {
+            Self::Deserialization(err) => Some(err.as_ref()),
+            Self::Other(err) => Some(err.as_ref()),
         }
     }
 }
 
-/// Possible failures modes for [`SessionStore::save`].
-#[derive(Debug, Display)]
-pub enum SaveError {
-    /// Failed to serialize session state.
-    #[display(fmt = "Failed to serialize session state")]
-    Serialization(anyhow::Error),
+/// Possible failures modes for [`SessionStore::save`].
+#[derive(Debug, Display)]
+pub enum SaveError {
+    /// Failed to serialize session state.
+    #[display(fmt = "Failed to serialize session state")]
+    Serialization(anyhow::Error),
 
-    /// Something went wrong when persisting the session state.
-    #[display(fmt = "Something went wrong when persisting the session state")]
-    Other(anyhow::Error),
+    /// Something went wrong when persisting the session state.
+    #[display(fmt = "Something went wrong when persisting the session state")]
+    Other(anyhow::Error),
 }
 
-impl std::error::Error for SaveError {
-    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
-        match self {
-            Self::Serialization(err) => Some(err.as_ref()),
-            Self::Other(err) => Some(err.as_ref()),
+impl std::error::Error for SaveError {
+    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+        match self {
+            Self::Serialization(err) => Some(err.as_ref()),
+            Self::Other(err) => Some(err.as_ref()),
         }
     }
 }
 
-#[derive(Debug, Display)]
-/// Possible failures modes for [`SessionStore::update`].
-pub enum UpdateError {
-    /// Failed to serialize session state.
-    #[display(fmt = "Failed to serialize session state")]
-    Serialization(anyhow::Error),
+#[derive(Debug, Display)]
+/// Possible failures modes for [`SessionStore::update`].
+pub enum UpdateError {
+    /// Failed to serialize session state.
+    #[display(fmt = "Failed to serialize session state")]
+    Serialization(anyhow::Error),
 
-    /// Something went wrong when updating the session state.
-    #[display(fmt = "Something went wrong when updating the session state.")]
-    Other(anyhow::Error),
+    /// Something went wrong when updating the session state.
+    #[display(fmt = "Something went wrong when updating the session state.")]
+    Other(anyhow::Error),
 }
 
-impl std::error::Error for UpdateError {
-    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
-        match self {
-            Self::Serialization(err) => Some(err.as_ref()),
-            Self::Other(err) => Some(err.as_ref()),
+impl std::error::Error for UpdateError {
+    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+        match self {
+            Self::Serialization(err) => Some(err.as_ref()),
+            Self::Other(err) => Some(err.as_ref()),
         }
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/mod.rs.html b/src/actix_session/storage/mod.rs.html index b34009c3a..046a570de 100644 --- a/src/actix_session/storage/mod.rs.html +++ b/src/actix_session/storage/mod.rs.html @@ -26,31 +26,31 @@ 24 25 26 -
//! Pluggable storage backends for session state.
+
//! Pluggable storage backends for session state.
 
-mod interface;
-mod session_key;
+mod interface;
+mod session_key;
 
-pub use self::interface::{LoadError, SaveError, SessionStore, UpdateError};
-pub use self::session_key::SessionKey;
+pub use self::interface::{LoadError, SaveError, SessionStore, UpdateError};
+pub use self::session_key::SessionKey;
 
-#[cfg(feature = "cookie-session")]
-mod cookie;
+#[cfg(feature = "cookie-session")]
+mod cookie;
 
-#[cfg(feature = "redis-actor-session")]
-mod redis_actor;
+#[cfg(feature = "redis-actor-session")]
+mod redis_actor;
 
-#[cfg(feature = "redis-rs-session")]
-mod redis_rs;
+#[cfg(feature = "redis-rs-session")]
+mod redis_rs;
 
-#[cfg(any(feature = "redis-actor-session", feature = "redis-rs-session"))]
-mod utils;
+#[cfg(any(feature = "redis-actor-session", feature = "redis-rs-session"))]
+mod utils;
 
-#[cfg(feature = "cookie-session")]
-pub use cookie::CookieSessionStore;
-#[cfg(feature = "redis-actor-session")]
-pub use redis_actor::{RedisActorSessionStore, RedisActorSessionStoreBuilder};
-#[cfg(feature = "redis-rs-session")]
-pub use redis_rs::{RedisSessionStore, RedisSessionStoreBuilder};
+#[cfg(feature = "cookie-session")]
+pub use cookie::CookieSessionStore;
+#[cfg(feature = "redis-actor-session")]
+pub use redis_actor::{RedisActorSessionStore, RedisActorSessionStoreBuilder};
+#[cfg(feature = "redis-rs-session")]
+pub use redis_rs::{RedisSessionStore, RedisSessionStoreBuilder};
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/redis_actor.rs.html b/src/actix_session/storage/redis_actor.rs.html index df3541168..4dca2f2c4 100644 --- a/src/actix_session/storage/redis_actor.rs.html +++ b/src/actix_session/storage/redis_actor.rs.html @@ -315,320 +315,320 @@ 313 314 315 -
use actix::Addr;
-use actix_redis::{resp_array, Command, RedisActor, RespValue};
-use actix_web::cookie::time::Duration;
-use anyhow::Error;
+
use actix::Addr;
+use actix_redis::{resp_array, Command, RedisActor, RespValue};
+use actix_web::cookie::time::Duration;
+use anyhow::Error;
 
-use super::SessionKey;
-use crate::storage::{
-    interface::{LoadError, SaveError, SessionState, UpdateError},
-    utils::generate_session_key,
-    SessionStore,
+use super::SessionKey;
+use crate::storage::{
+    interface::{LoadError, SaveError, SessionState, UpdateError},
+    utils::generate_session_key,
+    SessionStore,
 };
 
-/// Use Redis as session storage backend.
-///
-/// ```no_run
-/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
-/// use actix_session::{SessionMiddleware, storage::RedisActorSessionStore};
-/// use actix_web::cookie::Key;
-///
-/// // The secret key would usually be read from a configuration file/environment variables.
-/// fn get_secret_key() -> Key {
-///     # todo!()
-///     // [...]
-/// }
-///
-/// #[actix_web::main]
-/// async fn main() -> std::io::Result<()> {
-///     let secret_key = get_secret_key();
-///     let redis_connection_string = "127.0.0.1:6379";
-///     HttpServer::new(move ||
-///             App::new()
-///             .wrap(
-///                 SessionMiddleware::new(
-///                     RedisActorSessionStore::new(redis_connection_string),
-///                     secret_key.clone()
-///                 )
-///             )
-///             .default_service(web::to(|| HttpResponse::Ok())))
-///         .bind(("127.0.0.1", 8080))?
-///         .run()
-///         .await
-/// }
-/// ```
-///
-/// # Implementation notes
-///
-/// `RedisActorSessionStore` leverages `actix-redis`'s `RedisActor` implementation - each thread
-/// worker gets its own connection to Redis.
-///
-/// ## Limitations
-///
-/// `RedisActorSessionStore` does not currently support establishing authenticated connections to
-/// Redis. Use [`RedisSessionStore`] if you need TLS support.
-///
-/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
-#[cfg_attr(docsrs, doc(cfg(feature = "redis-actor-session")))]
-pub struct RedisActorSessionStore {
-    configuration: CacheConfiguration,
-    addr: Addr<RedisActor>,
+/// Use Redis as session storage backend.
+///
+/// ```no_run
+/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
+/// use actix_session::{SessionMiddleware, storage::RedisActorSessionStore};
+/// use actix_web::cookie::Key;
+///
+/// // The secret key would usually be read from a configuration file/environment variables.
+/// fn get_secret_key() -> Key {
+///     # todo!()
+///     // [...]
+/// }
+///
+/// #[actix_web::main]
+/// async fn main() -> std::io::Result<()> {
+///     let secret_key = get_secret_key();
+///     let redis_connection_string = "127.0.0.1:6379";
+///     HttpServer::new(move ||
+///             App::new()
+///             .wrap(
+///                 SessionMiddleware::new(
+///                     RedisActorSessionStore::new(redis_connection_string),
+///                     secret_key.clone()
+///                 )
+///             )
+///             .default_service(web::to(|| HttpResponse::Ok())))
+///         .bind(("127.0.0.1", 8080))?
+///         .run()
+///         .await
+/// }
+/// ```
+///
+/// # Implementation notes
+///
+/// `RedisActorSessionStore` leverages `actix-redis`'s `RedisActor` implementation - each thread
+/// worker gets its own connection to Redis.
+///
+/// ## Limitations
+///
+/// `RedisActorSessionStore` does not currently support establishing authenticated connections to
+/// Redis. Use [`RedisSessionStore`] if you need TLS support.
+///
+/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
+#[cfg_attr(docsrs, doc(cfg(feature = "redis-actor-session")))]
+pub struct RedisActorSessionStore {
+    configuration: CacheConfiguration,
+    addr: Addr<RedisActor>,
 }
 
-impl RedisActorSessionStore {
-    /// A fluent API to configure [`RedisActorSessionStore`].
-    ///
-    /// It takes as input the only required input to create a new instance of
-    /// [`RedisActorSessionStore`]—a connection string for Redis.
-    pub fn builder<S: Into<String>>(connection_string: S) -> RedisActorSessionStoreBuilder {
-        RedisActorSessionStoreBuilder {
-            configuration: CacheConfiguration::default(),
-            connection_string: connection_string.into(),
+impl RedisActorSessionStore {
+    /// A fluent API to configure [`RedisActorSessionStore`].
+    ///
+    /// It takes as input the only required input to create a new instance of
+    /// [`RedisActorSessionStore`]—a connection string for Redis.
+    pub fn builder<S: Into<String>>(connection_string: S) -> RedisActorSessionStoreBuilder {
+        RedisActorSessionStoreBuilder {
+            configuration: CacheConfiguration::default(),
+            connection_string: connection_string.into(),
         }
     }
 
-    /// Create a new instance of [`RedisActorSessionStore`] using the default configuration.
-    /// It takes as input the only required input to create a new instance of [`RedisActorSessionStore`] - a
-    /// connection string for Redis.
-    pub fn new<S: Into<String>>(connection_string: S) -> RedisActorSessionStore {
-        Self::builder(connection_string).build()
+    /// Create a new instance of [`RedisActorSessionStore`] using the default configuration.
+    /// It takes as input the only required input to create a new instance of [`RedisActorSessionStore`] - a
+    /// connection string for Redis.
+    pub fn new<S: Into<String>>(connection_string: S) -> RedisActorSessionStore {
+        Self::builder(connection_string).build()
     }
 }
 
-struct CacheConfiguration {
-    cache_keygen: Box<dyn Fn(&str) -> String>,
+struct CacheConfiguration {
+    cache_keygen: Box<dyn Fn(&str) -> String>,
 }
 
-impl Default for CacheConfiguration {
-    fn default() -> Self {
-        Self {
-            cache_keygen: Box::new(str::to_owned),
+impl Default for CacheConfiguration {
+    fn default() -> Self {
+        Self {
+            cache_keygen: Box::new(str::to_owned),
         }
     }
 }
 
-/// A fluent builder to construct a [`RedisActorSessionStore`] instance with custom configuration
-/// parameters.
-#[cfg_attr(docsrs, doc(cfg(feature = "redis-actor-session")))]
-#[must_use]
-pub struct RedisActorSessionStoreBuilder {
-    connection_string: String,
-    configuration: CacheConfiguration,
+/// A fluent builder to construct a [`RedisActorSessionStore`] instance with custom configuration
+/// parameters.
+#[cfg_attr(docsrs, doc(cfg(feature = "redis-actor-session")))]
+#[must_use]
+pub struct RedisActorSessionStoreBuilder {
+    connection_string: String,
+    configuration: CacheConfiguration,
 }
 
-impl RedisActorSessionStoreBuilder {
-    /// Set a custom cache key generation strategy, expecting a session key as input.
-    pub fn cache_keygen<F>(mut self, keygen: F) -> Self
-    where
-        F: Fn(&str) -> String + 'static,
+impl RedisActorSessionStoreBuilder {
+    /// Set a custom cache key generation strategy, expecting a session key as input.
+    pub fn cache_keygen<F>(mut self, keygen: F) -> Self
+    where
+        F: Fn(&str) -> String + 'static,
     {
-        self.configuration.cache_keygen = Box::new(keygen);
-        self
-    }
+        self.configuration.cache_keygen = Box::new(keygen);
+        self
+    }
 
-    /// Finalise the builder and return a [`RedisActorSessionStore`] instance.
-    #[must_use]
-    pub fn build(self) -> RedisActorSessionStore {
-        RedisActorSessionStore {
-            configuration: self.configuration,
-            addr: RedisActor::start(self.connection_string),
+    /// Finalise the builder and return a [`RedisActorSessionStore`] instance.
+    #[must_use]
+    pub fn build(self) -> RedisActorSessionStore {
+        RedisActorSessionStore {
+            configuration: self.configuration,
+            addr: RedisActor::start(self.connection_string),
         }
     }
 }
 
-#[async_trait::async_trait(?Send)]
-impl SessionStore for RedisActorSessionStore {
-    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
-        let val = self
-            .addr
-            .send(Command(resp_array!["GET", cache_key]))
-            .await
-            .map_err(Into::into)
-            .map_err(LoadError::Other)?
-            .map_err(Into::into)
-            .map_err(LoadError::Other)?;
+#[async_trait::async_trait(?Send)]
+impl SessionStore for RedisActorSessionStore {
+    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+        let val = self
+            .addr
+            .send(Command(resp_array!["GET", cache_key]))
+            .await
+            .map_err(Into::into)
+            .map_err(LoadError::Other)?
+            .map_err(Into::into)
+            .map_err(LoadError::Other)?;
 
-        match val {
-            RespValue::Error(err) => Err(LoadError::Other(anyhow::anyhow!(err))),
+        match val {
+            RespValue::Error(err) => Err(LoadError::Other(anyhow::anyhow!(err))),
 
-            RespValue::SimpleString(s) => Ok(serde_json::from_str(&s)
-                .map_err(Into::into)
-                .map_err(LoadError::Deserialization)?),
+            RespValue::SimpleString(s) => Ok(serde_json::from_str(&s)
+                .map_err(Into::into)
+                .map_err(LoadError::Deserialization)?),
 
-            RespValue::BulkString(s) => Ok(serde_json::from_slice(&s)
-                .map_err(Into::into)
-                .map_err(LoadError::Deserialization)?),
+            RespValue::BulkString(s) => Ok(serde_json::from_slice(&s)
+                .map_err(Into::into)
+                .map_err(LoadError::Deserialization)?),
 
-            _ => Ok(None),
+            _ => Ok(None),
         }
     }
 
-    async fn save(
+    async fn save(
         &self,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, SaveError> {
-        let body = serde_json::to_string(&session_state)
-            .map_err(Into::into)
-            .map_err(SaveError::Serialization)?;
-        let session_key = generate_session_key();
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, SaveError> {
+        let body = serde_json::to_string(&session_state)
+            .map_err(Into::into)
+            .map_err(SaveError::Serialization)?;
+        let session_key = generate_session_key();
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        let cmd = Command(resp_array![
+        let cmd = Command(resp_array![
             "SET",
-            cache_key,
-            body,
-            "NX", // NX: only set the key if it does not already exist
-            "EX", // EX: set expiry
-            format!("{}", ttl.whole_seconds())
+            cache_key,
+            body,
+            "NX", // NX: only set the key if it does not already exist
+            "EX", // EX: set expiry
+            format!("{}", ttl.whole_seconds())
         ]);
 
-        let result = self
-            .addr
-            .send(cmd)
-            .await
-            .map_err(Into::into)
-            .map_err(SaveError::Other)?
-            .map_err(Into::into)
-            .map_err(SaveError::Other)?;
+        let result = self
+            .addr
+            .send(cmd)
+            .await
+            .map_err(Into::into)
+            .map_err(SaveError::Other)?
+            .map_err(Into::into)
+            .map_err(SaveError::Other)?;
 
-        match result {
-            RespValue::SimpleString(_) => Ok(session_key),
-            RespValue::Nil => Err(SaveError::Other(anyhow::anyhow!(
-                "Failed to save session state. A record with the same key already existed in Redis"
-            ))),
-            err => Err(SaveError::Other(anyhow::anyhow!(
+        match result {
+            RespValue::SimpleString(_) => Ok(session_key),
+            RespValue::Nil => Err(SaveError::Other(anyhow::anyhow!(
+                "Failed to save session state. A record with the same key already existed in Redis"
+            ))),
+            err => Err(SaveError::Other(anyhow::anyhow!(
                 "Failed to save session state. {:?}",
-                err
+                err
             ))),
         }
     }
 
-    async fn update(
+    async fn update(
         &self,
-        session_key: SessionKey,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, UpdateError> {
-        let body = serde_json::to_string(&session_state)
-            .map_err(Into::into)
-            .map_err(UpdateError::Serialization)?;
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+        session_key: SessionKey,
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, UpdateError> {
+        let body = serde_json::to_string(&session_state)
+            .map_err(Into::into)
+            .map_err(UpdateError::Serialization)?;
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        let cmd = Command(resp_array![
+        let cmd = Command(resp_array![
             "SET",
-            cache_key,
-            body,
-            "XX", // XX: Only set the key if it already exist.
-            "EX", // EX: set expiry
-            format!("{}", ttl.whole_seconds())
+            cache_key,
+            body,
+            "XX", // XX: Only set the key if it already exist.
+            "EX", // EX: set expiry
+            format!("{}", ttl.whole_seconds())
         ]);
 
-        let result = self
-            .addr
-            .send(cmd)
-            .await
-            .map_err(Into::into)
-            .map_err(UpdateError::Other)?
-            .map_err(Into::into)
-            .map_err(UpdateError::Other)?;
+        let result = self
+            .addr
+            .send(cmd)
+            .await
+            .map_err(Into::into)
+            .map_err(UpdateError::Other)?
+            .map_err(Into::into)
+            .map_err(UpdateError::Other)?;
 
-        match result {
-            RespValue::Nil => {
-                // The SET operation was not performed because the XX condition was not verified.
-                // This can happen if the session state expired between the load operation and the
-                // update operation. Unlucky, to say the least. We fall back to the `save` routine
-                // to ensure that the new key is unique.
-                self.save(session_state, ttl)
-                    .await
-                    .map_err(|err| match err {
-                        SaveError::Serialization(err) => UpdateError::Serialization(err),
-                        SaveError::Other(err) => UpdateError::Other(err),
+        match result {
+            RespValue::Nil => {
+                // The SET operation was not performed because the XX condition was not verified.
+                // This can happen if the session state expired between the load operation and the
+                // update operation. Unlucky, to say the least. We fall back to the `save` routine
+                // to ensure that the new key is unique.
+                self.save(session_state, ttl)
+                    .await
+                    .map_err(|err| match err {
+                        SaveError::Serialization(err) => UpdateError::Serialization(err),
+                        SaveError::Other(err) => UpdateError::Other(err),
                     })
             }
-            RespValue::SimpleString(_) => Ok(session_key),
-            val => Err(UpdateError::Other(anyhow::anyhow!(
+            RespValue::SimpleString(_) => Ok(session_key),
+            val => Err(UpdateError::Other(anyhow::anyhow!(
                 "Failed to update session state. {:?}",
-                val
+                val
             ))),
         }
     }
 
-    async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+    async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        let cmd = Command(resp_array![
+        let cmd = Command(resp_array![
             "EXPIRE",
-            cache_key,
-            ttl.whole_seconds().to_string()
+            cache_key,
+            ttl.whole_seconds().to_string()
         ]);
 
-        match self.addr.send(cmd).await? {
-            Ok(RespValue::Integer(_)) => Ok(()),
-            val => Err(anyhow::anyhow!(
+        match self.addr.send(cmd).await? {
+            Ok(RespValue::Integer(_)) => Ok(()),
+            val => Err(anyhow::anyhow!(
                 "Failed to update the session state TTL: {:?}",
-                val
+                val
             )),
         }
     }
 
-    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        let res = self
-            .addr
-            .send(Command(resp_array!["DEL", cache_key]))
+        let res = self
+            .addr
+            .send(Command(resp_array!["DEL", cache_key]))
             .await?;
 
-        match res {
-            // Redis returns the number of deleted records
-            Ok(RespValue::Integer(_)) => Ok(()),
-            val => Err(anyhow::anyhow!(
+        match res {
+            // Redis returns the number of deleted records
+            Ok(RespValue::Integer(_)) => Ok(()),
+            val => Err(anyhow::anyhow!(
                 "Failed to remove session from cache. {:?}",
-                val
+                val
             )),
         }
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use std::collections::HashMap;
+#[cfg(test)]
+mod tests {
+    use std::collections::HashMap;
 
-    use actix_web::cookie::time::Duration;
+    use actix_web::cookie::time::Duration;
 
-    use super::*;
-    use crate::test_helpers::acceptance_test_suite;
+    use super::*;
+    use crate::test_helpers::acceptance_test_suite;
 
-    fn redis_actor_store() -> RedisActorSessionStore {
-        RedisActorSessionStore::new("127.0.0.1:6379")
+    fn redis_actor_store() -> RedisActorSessionStore {
+        RedisActorSessionStore::new("127.0.0.1:6379")
     }
 
-    #[actix_web::test]
-    async fn test_session_workflow() {
-        acceptance_test_suite(redis_actor_store, true).await;
+    #[actix_web::test]
+    async fn test_session_workflow() {
+        acceptance_test_suite(redis_actor_store, true).await;
     }
 
-    #[actix_web::test]
-    async fn loading_a_missing_session_returns_none() {
-        let store = redis_actor_store();
-        let session_key = generate_session_key();
-        assert!(store.load(&session_key).await.unwrap().is_none());
+    #[actix_web::test]
+    async fn loading_a_missing_session_returns_none() {
+        let store = redis_actor_store();
+        let session_key = generate_session_key();
+        assert!(store.load(&session_key).await.unwrap().is_none());
     }
 
-    #[actix_web::test]
-    async fn updating_of_an_expired_state_is_handled_gracefully() {
-        let store = redis_actor_store();
-        let session_key = generate_session_key();
-        let initial_session_key = session_key.as_ref().to_owned();
-        let updated_session_key = store
-            .update(session_key, HashMap::new(), &Duration::seconds(1))
-            .await
-            .unwrap();
-        assert_ne!(initial_session_key, updated_session_key.as_ref());
+    #[actix_web::test]
+    async fn updating_of_an_expired_state_is_handled_gracefully() {
+        let store = redis_actor_store();
+        let session_key = generate_session_key();
+        let initial_session_key = session_key.as_ref().to_owned();
+        let updated_session_key = store
+            .update(session_key, HashMap::new(), &Duration::seconds(1))
+            .await
+            .unwrap();
+        assert_ne!(initial_session_key, updated_session_key.as_ref());
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/redis_rs.rs.html b/src/actix_session/storage/redis_rs.rs.html index 9597032d5..660ddd277 100644 --- a/src/actix_session/storage/redis_rs.rs.html +++ b/src/actix_session/storage/redis_rs.rs.html @@ -347,239 +347,239 @@ 345 346 347 -
use std::{convert::TryInto, sync::Arc};
+
use std::{convert::TryInto, sync::Arc};
 
-use actix_web::cookie::time::Duration;
-use anyhow::{Context, Error};
-use redis::{aio::ConnectionManager, AsyncCommands, Cmd, FromRedisValue, RedisResult, Value};
+use actix_web::cookie::time::Duration;
+use anyhow::{Context, Error};
+use redis::{aio::ConnectionManager, AsyncCommands, Cmd, FromRedisValue, RedisResult, Value};
 
-use super::SessionKey;
-use crate::storage::{
-    interface::{LoadError, SaveError, SessionState, UpdateError},
-    utils::generate_session_key,
-    SessionStore,
+use super::SessionKey;
+use crate::storage::{
+    interface::{LoadError, SaveError, SessionState, UpdateError},
+    utils::generate_session_key,
+    SessionStore,
 };
 
-/// Use Redis as session storage backend.
-///
-/// ```no_run
-/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
-/// use actix_session::{SessionMiddleware, storage::RedisSessionStore};
-/// use actix_web::cookie::Key;
-///
-/// // The secret key would usually be read from a configuration file/environment variables.
-/// fn get_secret_key() -> Key {
-///     # todo!()
-///     // [...]
-/// }
-///
-/// #[actix_web::main]
-/// async fn main() -> std::io::Result<()> {
-///     let secret_key = get_secret_key();
-///     let redis_connection_string = "redis://127.0.0.1:6379";
-///     let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
-///
-///     HttpServer::new(move ||
-///             App::new()
-///             .wrap(SessionMiddleware::new(
-///                 store.clone(),
-///                 secret_key.clone()
-///             ))
-///             .default_service(web::to(|| HttpResponse::Ok())))
-///         .bind(("127.0.0.1", 8080))?
-///         .run()
-///         .await
-/// }
-/// ```
-///
-/// # TLS support
-/// Add the `redis-rs-tls-session` feature flag to enable TLS support. You can then establish a TLS
-/// connection to Redis using the `rediss://` URL scheme:
-///
-/// ```no_run
-/// use actix_session::{storage::RedisSessionStore};
-///
-/// # actix_web::rt::System::new().block_on(async {
-/// let redis_connection_string = "rediss://127.0.0.1:6379";
-/// let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
-/// # })
-/// ```
-///
-/// # Implementation notes
-/// `RedisSessionStore` leverages [`redis-rs`] as Redis client.
-///
-/// [`redis-rs`]: https://github.com/mitsuhiko/redis-rs
-#[cfg_attr(docsrs, doc(cfg(feature = "redis-rs-session")))]
-#[derive(Clone)]
-pub struct RedisSessionStore {
-    configuration: CacheConfiguration,
-    client: ConnectionManager,
+/// Use Redis as session storage backend.
+///
+/// ```no_run
+/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
+/// use actix_session::{SessionMiddleware, storage::RedisSessionStore};
+/// use actix_web::cookie::Key;
+///
+/// // The secret key would usually be read from a configuration file/environment variables.
+/// fn get_secret_key() -> Key {
+///     # todo!()
+///     // [...]
+/// }
+///
+/// #[actix_web::main]
+/// async fn main() -> std::io::Result<()> {
+///     let secret_key = get_secret_key();
+///     let redis_connection_string = "redis://127.0.0.1:6379";
+///     let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
+///
+///     HttpServer::new(move ||
+///             App::new()
+///             .wrap(SessionMiddleware::new(
+///                 store.clone(),
+///                 secret_key.clone()
+///             ))
+///             .default_service(web::to(|| HttpResponse::Ok())))
+///         .bind(("127.0.0.1", 8080))?
+///         .run()
+///         .await
+/// }
+/// ```
+///
+/// # TLS support
+/// Add the `redis-rs-tls-session` feature flag to enable TLS support. You can then establish a TLS
+/// connection to Redis using the `rediss://` URL scheme:
+///
+/// ```no_run
+/// use actix_session::{storage::RedisSessionStore};
+///
+/// # actix_web::rt::System::new().block_on(async {
+/// let redis_connection_string = "rediss://127.0.0.1:6379";
+/// let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
+/// # })
+/// ```
+///
+/// # Implementation notes
+/// `RedisSessionStore` leverages [`redis-rs`] as Redis client.
+///
+/// [`redis-rs`]: https://github.com/mitsuhiko/redis-rs
+#[cfg_attr(docsrs, doc(cfg(feature = "redis-rs-session")))]
+#[derive(Clone)]
+pub struct RedisSessionStore {
+    configuration: CacheConfiguration,
+    client: ConnectionManager,
 }
 
-#[derive(Clone)]
-struct CacheConfiguration {
-    cache_keygen: Arc<dyn Fn(&str) -> String + Send + Sync>,
+#[derive(Clone)]
+struct CacheConfiguration {
+    cache_keygen: Arc<dyn Fn(&str) -> String + Send + Sync>,
 }
 
-impl Default for CacheConfiguration {
-    fn default() -> Self {
-        Self {
-            cache_keygen: Arc::new(str::to_owned),
+impl Default for CacheConfiguration {
+    fn default() -> Self {
+        Self {
+            cache_keygen: Arc::new(str::to_owned),
         }
     }
 }
 
-impl RedisSessionStore {
-    /// A fluent API to configure [`RedisSessionStore`].
-    /// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
-    /// connection string for Redis.
-    pub fn builder<S: Into<String>>(connection_string: S) -> RedisSessionStoreBuilder {
-        RedisSessionStoreBuilder {
-            configuration: CacheConfiguration::default(),
-            connection_string: connection_string.into(),
+impl RedisSessionStore {
+    /// A fluent API to configure [`RedisSessionStore`].
+    /// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
+    /// connection string for Redis.
+    pub fn builder<S: Into<String>>(connection_string: S) -> RedisSessionStoreBuilder {
+        RedisSessionStoreBuilder {
+            configuration: CacheConfiguration::default(),
+            connection_string: connection_string.into(),
         }
     }
 
-    /// Create a new instance of [`RedisSessionStore`] using the default configuration.
-    /// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
-    /// connection string for Redis.
-    pub async fn new<S: Into<String>>(
-        connection_string: S,
-    ) -> Result<RedisSessionStore, anyhow::Error> {
-        Self::builder(connection_string).build().await
-    }
+    /// Create a new instance of [`RedisSessionStore`] using the default configuration.
+    /// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
+    /// connection string for Redis.
+    pub async fn new<S: Into<String>>(
+        connection_string: S,
+    ) -> Result<RedisSessionStore, anyhow::Error> {
+        Self::builder(connection_string).build().await
+    }
 }
 
-/// A fluent builder to construct a [`RedisSessionStore`] instance with custom configuration
-/// parameters.
-///
-/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
-#[cfg_attr(docsrs, doc(cfg(feature = "redis-rs-session")))]
-#[must_use]
-pub struct RedisSessionStoreBuilder {
-    connection_string: String,
-    configuration: CacheConfiguration,
+/// A fluent builder to construct a [`RedisSessionStore`] instance with custom configuration
+/// parameters.
+///
+/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
+#[cfg_attr(docsrs, doc(cfg(feature = "redis-rs-session")))]
+#[must_use]
+pub struct RedisSessionStoreBuilder {
+    connection_string: String,
+    configuration: CacheConfiguration,
 }
 
-impl RedisSessionStoreBuilder {
-    /// Set a custom cache key generation strategy, expecting a session key as input.
-    pub fn cache_keygen<F>(mut self, keygen: F) -> Self
-    where
-        F: Fn(&str) -> String + 'static + Send + Sync,
+impl RedisSessionStoreBuilder {
+    /// Set a custom cache key generation strategy, expecting a session key as input.
+    pub fn cache_keygen<F>(mut self, keygen: F) -> Self
+    where
+        F: Fn(&str) -> String + 'static + Send + Sync,
     {
-        self.configuration.cache_keygen = Arc::new(keygen);
-        self
-    }
+        self.configuration.cache_keygen = Arc::new(keygen);
+        self
+    }
 
-    /// Finalise the builder and return a [`RedisActorSessionStore`] instance.
-    ///
-    /// [`RedisActorSessionStore`]: crate::storage::RedisActorSessionStore
-    pub async fn build(self) -> Result<RedisSessionStore, anyhow::Error> {
-        let client = ConnectionManager::new(redis::Client::open(self.connection_string)?).await?;
-        Ok(RedisSessionStore {
-            configuration: self.configuration,
-            client,
+    /// Finalise the builder and return a [`RedisActorSessionStore`] instance.
+    ///
+    /// [`RedisActorSessionStore`]: crate::storage::RedisActorSessionStore
+    pub async fn build(self) -> Result<RedisSessionStore, anyhow::Error> {
+        let client = ConnectionManager::new(redis::Client::open(self.connection_string)?).await?;
+        Ok(RedisSessionStore {
+            configuration: self.configuration,
+            client,
         })
     }
 }
 
-#[async_trait::async_trait(?Send)]
-impl SessionStore for RedisSessionStore {
-    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+#[async_trait::async_trait(?Send)]
+impl SessionStore for RedisSessionStore {
+    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        let value: Option<String> = self
-            .execute_command(redis::cmd("GET").arg(&[&cache_key]))
-            .await
-            .map_err(Into::into)
-            .map_err(LoadError::Other)?;
+        let value: Option<String> = self
+            .execute_command(redis::cmd("GET").arg(&[&cache_key]))
+            .await
+            .map_err(Into::into)
+            .map_err(LoadError::Other)?;
 
-        match value {
-            None => Ok(None),
-            Some(value) => Ok(serde_json::from_str(&value)
-                .map_err(Into::into)
-                .map_err(LoadError::Deserialization)?),
+        match value {
+            None => Ok(None),
+            Some(value) => Ok(serde_json::from_str(&value)
+                .map_err(Into::into)
+                .map_err(LoadError::Deserialization)?),
         }
     }
 
-    async fn save(
+    async fn save(
         &self,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, SaveError> {
-        let body = serde_json::to_string(&session_state)
-            .map_err(Into::into)
-            .map_err(SaveError::Serialization)?;
-        let session_key = generate_session_key();
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, SaveError> {
+        let body = serde_json::to_string(&session_state)
+            .map_err(Into::into)
+            .map_err(SaveError::Serialization)?;
+        let session_key = generate_session_key();
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        self.execute_command(redis::cmd("SET").arg(&[
-            &cache_key,
-            &body,
-            "NX", // NX: only set the key if it does not already exist
-            "EX", // EX: set expiry
-            &format!("{}", ttl.whole_seconds()),
+        self.execute_command(redis::cmd("SET").arg(&[
+            &cache_key,
+            &body,
+            "NX", // NX: only set the key if it does not already exist
+            "EX", // EX: set expiry
+            &format!("{}", ttl.whole_seconds()),
         ]))
-        .await
-        .map_err(Into::into)
-        .map_err(SaveError::Other)?;
+        .await
+        .map_err(Into::into)
+        .map_err(SaveError::Other)?;
 
-        Ok(session_key)
+        Ok(session_key)
     }
 
-    async fn update(
+    async fn update(
         &self,
-        session_key: SessionKey,
-        session_state: SessionState,
-        ttl: &Duration,
-    ) -> Result<SessionKey, UpdateError> {
-        let body = serde_json::to_string(&session_state)
-            .map_err(Into::into)
-            .map_err(UpdateError::Serialization)?;
+        session_key: SessionKey,
+        session_state: SessionState,
+        ttl: &Duration,
+    ) -> Result<SessionKey, UpdateError> {
+        let body = serde_json::to_string(&session_state)
+            .map_err(Into::into)
+            .map_err(UpdateError::Serialization)?;
 
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        let v: redis::Value = self
-            .execute_command(redis::cmd("SET").arg(&[
-                &cache_key,
-                &body,
-                "XX", // XX: Only set the key if it already exist.
-                "EX", // EX: set expiry
-                &format!("{}", ttl.whole_seconds()),
+        let v: redis::Value = self
+            .execute_command(redis::cmd("SET").arg(&[
+                &cache_key,
+                &body,
+                "XX", // XX: Only set the key if it already exist.
+                "EX", // EX: set expiry
+                &format!("{}", ttl.whole_seconds()),
             ]))
-            .await
-            .map_err(Into::into)
-            .map_err(UpdateError::Other)?;
+            .await
+            .map_err(Into::into)
+            .map_err(UpdateError::Other)?;
 
-        match v {
-            Value::Nil => {
-                // The SET operation was not performed because the XX condition was not verified.
-                // This can happen if the session state expired between the load operation and the
-                // update operation. Unlucky, to say the least. We fall back to the `save` routine
-                // to ensure that the new key is unique.
-                self.save(session_state, ttl)
-                    .await
-                    .map_err(|err| match err {
-                        SaveError::Serialization(err) => UpdateError::Serialization(err),
-                        SaveError::Other(err) => UpdateError::Other(err),
+        match v {
+            Value::Nil => {
+                // The SET operation was not performed because the XX condition was not verified.
+                // This can happen if the session state expired between the load operation and the
+                // update operation. Unlucky, to say the least. We fall back to the `save` routine
+                // to ensure that the new key is unique.
+                self.save(session_state, ttl)
+                    .await
+                    .map_err(|err| match err {
+                        SaveError::Serialization(err) => UpdateError::Serialization(err),
+                        SaveError::Other(err) => UpdateError::Other(err),
                     })
             }
-            Value::Int(_) | Value::Okay | Value::Status(_) => Ok(session_key),
-            val => Err(UpdateError::Other(anyhow::anyhow!(
+            Value::Int(_) | Value::Okay | Value::Status(_) => Ok(session_key),
+            val => Err(UpdateError::Other(anyhow::anyhow!(
                 "Failed to update session state. {:?}",
-                val
+                val
             ))),
         }
     }
 
-    async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+    async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
 
-        self.client
-            .clone()
-            .expire(
-                &cache_key,
-                ttl.whole_seconds().try_into().context(
+        self.client
+            .clone()
+            .expire(
+                &cache_key,
+                ttl.whole_seconds().try_into().context(
                     "Failed to convert the state TTL into the number of whole seconds remaining",
                 )?,
             )
@@ -587,49 +587,49 @@
         Ok(())
     }
 
-    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
-        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
-        self.execute_command(redis::cmd("DEL").arg(&[&cache_key]))
-            .await
-            .map_err(Into::into)
-            .map_err(UpdateError::Other)?;
+    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
+        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
+        self.execute_command(redis::cmd("DEL").arg(&[&cache_key]))
+            .await
+            .map_err(Into::into)
+            .map_err(UpdateError::Other)?;
 
         Ok(())
     }
 }
 
-impl RedisSessionStore {
-    /// Execute Redis command and retry once in certain cases.
-    ///
-    /// `ConnectionManager` automatically reconnects when it encounters an error talking to Redis.
-    /// The request that bumped into the error, though, fails.
-    ///
-    /// This is generally OK, but there is an unpleasant edge case: Redis client timeouts. The
-    /// server is configured to drop connections who have been active longer than a pre-determined
-    /// threshold. `redis-rs` does not proactively detect that the connection has been dropped - you
-    /// only find out when you try to use it.
-    ///
-    /// This helper method catches this case (`.is_connection_dropped`) to execute a retry. The
-    /// retry will be executed on a fresh connection, therefore it is likely to succeed (or fail for
-    /// a different more meaningful reason).
-    async fn execute_command<T: FromRedisValue>(&self, cmd: &mut Cmd) -> RedisResult<T> {
-        let mut can_retry = true;
+impl RedisSessionStore {
+    /// Execute Redis command and retry once in certain cases.
+    ///
+    /// `ConnectionManager` automatically reconnects when it encounters an error talking to Redis.
+    /// The request that bumped into the error, though, fails.
+    ///
+    /// This is generally OK, but there is an unpleasant edge case: Redis client timeouts. The
+    /// server is configured to drop connections who have been active longer than a pre-determined
+    /// threshold. `redis-rs` does not proactively detect that the connection has been dropped - you
+    /// only find out when you try to use it.
+    ///
+    /// This helper method catches this case (`.is_connection_dropped`) to execute a retry. The
+    /// retry will be executed on a fresh connection, therefore it is likely to succeed (or fail for
+    /// a different more meaningful reason).
+    async fn execute_command<T: FromRedisValue>(&self, cmd: &mut Cmd) -> RedisResult<T> {
+        let mut can_retry = true;
 
-        loop {
-            match cmd.query_async(&mut self.client.clone()).await {
-                Ok(value) => return Ok(value),
-                Err(err) => {
-                    if can_retry && err.is_connection_dropped() {
+        loop {
+            match cmd.query_async(&mut self.client.clone()).await {
+                Ok(value) => return Ok(value),
+                Err(err) => {
+                    if can_retry && err.is_connection_dropped() {
                         tracing::debug!(
-                            "Connection dropped while trying to talk to Redis. Retrying."
-                        );
+                            "Connection dropped while trying to talk to Redis. Retrying."
+                        );
 
-                        // Retry at most once
-                        can_retry = false;
+                        // Retry at most once
+                        can_retry = false;
 
                         continue;
-                    } else {
-                        return Err(err);
+                    } else {
+                        return Err(err);
                     }
                 }
             }
@@ -637,62 +637,62 @@
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use std::collections::HashMap;
+#[cfg(test)]
+mod tests {
+    use std::collections::HashMap;
 
-    use actix_web::cookie::time;
-    use redis::AsyncCommands;
+    use actix_web::cookie::time;
+    use redis::AsyncCommands;
 
-    use super::*;
-    use crate::test_helpers::acceptance_test_suite;
+    use super::*;
+    use crate::test_helpers::acceptance_test_suite;
 
-    async fn redis_store() -> RedisSessionStore {
-        RedisSessionStore::new("redis://127.0.0.1:6379")
-            .await
-            .unwrap()
+    async fn redis_store() -> RedisSessionStore {
+        RedisSessionStore::new("redis://127.0.0.1:6379")
+            .await
+            .unwrap()
     }
 
-    #[actix_web::test]
-    async fn test_session_workflow() {
-        let redis_store = redis_store().await;
-        acceptance_test_suite(move || redis_store.clone(), true).await;
+    #[actix_web::test]
+    async fn test_session_workflow() {
+        let redis_store = redis_store().await;
+        acceptance_test_suite(move || redis_store.clone(), true).await;
     }
 
-    #[actix_web::test]
-    async fn loading_a_missing_session_returns_none() {
-        let store = redis_store().await;
-        let session_key = generate_session_key();
-        assert!(store.load(&session_key).await.unwrap().is_none());
+    #[actix_web::test]
+    async fn loading_a_missing_session_returns_none() {
+        let store = redis_store().await;
+        let session_key = generate_session_key();
+        assert!(store.load(&session_key).await.unwrap().is_none());
     }
 
-    #[actix_web::test]
-    async fn loading_an_invalid_session_state_returns_deserialization_error() {
-        let store = redis_store().await;
-        let session_key = generate_session_key();
-        store
-            .client
-            .clone()
-            .set::<_, _, ()>(session_key.as_ref(), "random-thing-which-is-not-json")
-            .await
-            .unwrap();
+    #[actix_web::test]
+    async fn loading_an_invalid_session_state_returns_deserialization_error() {
+        let store = redis_store().await;
+        let session_key = generate_session_key();
+        store
+            .client
+            .clone()
+            .set::<_, _, ()>(session_key.as_ref(), "random-thing-which-is-not-json")
+            .await
+            .unwrap();
         assert!(matches!(
-            store.load(&session_key).await.unwrap_err(),
-            LoadError::Deserialization(_),
+            store.load(&session_key).await.unwrap_err(),
+            LoadError::Deserialization(_),
         ));
     }
 
-    #[actix_web::test]
-    async fn updating_of_an_expired_state_is_handled_gracefully() {
-        let store = redis_store().await;
-        let session_key = generate_session_key();
-        let initial_session_key = session_key.as_ref().to_owned();
-        let updated_session_key = store
-            .update(session_key, HashMap::new(), &time::Duration::seconds(1))
-            .await
-            .unwrap();
-        assert_ne!(initial_session_key, updated_session_key.as_ref());
+    #[actix_web::test]
+    async fn updating_of_an_expired_state_is_handled_gracefully() {
+        let store = redis_store().await;
+        let session_key = generate_session_key();
+        let initial_session_key = session_key.as_ref().to_owned();
+        let updated_session_key = store
+            .update(session_key, HashMap::new(), &time::Duration::seconds(1))
+            .await
+            .unwrap();
+        assert_ne!(initial_session_key, updated_session_key.as_ref());
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/session_key.rs.html b/src/actix_session/storage/session_key.rs.html index d0d823bcd..f22ffec73 100644 --- a/src/actix_session/storage/session_key.rs.html +++ b/src/actix_session/storage/session_key.rs.html @@ -58,63 +58,63 @@ 56 57 58 -
use std::convert::TryFrom;
+
use std::convert::TryFrom;
 
-use derive_more::{Display, From};
+use derive_more::{Display, From};
 
-/// A session key, the string stored in a client-side cookie to associate a user with its session
-/// state on the backend.
-///
-/// # Validation
-/// Session keys are stored as cookies, therefore they cannot be arbitrary long. Session keys are
-/// required to be smaller than 4064 bytes.
-///
-/// ```rust
-/// # use std::convert::TryInto;
-/// use actix_session::storage::SessionKey;
-///
-/// let key: String = std::iter::repeat('a').take(4065).collect();
-/// let session_key: Result<SessionKey, _> = key.try_into();
-/// assert!(session_key.is_err());
-/// ```
-#[derive(Debug, PartialEq, Eq)]
-pub struct SessionKey(String);
+/// A session key, the string stored in a client-side cookie to associate a user with its session
+/// state on the backend.
+///
+/// # Validation
+/// Session keys are stored as cookies, therefore they cannot be arbitrary long. Session keys are
+/// required to be smaller than 4064 bytes.
+///
+/// ```rust
+/// # use std::convert::TryInto;
+/// use actix_session::storage::SessionKey;
+///
+/// let key: String = std::iter::repeat('a').take(4065).collect();
+/// let session_key: Result<SessionKey, _> = key.try_into();
+/// assert!(session_key.is_err());
+/// ```
+#[derive(Debug, PartialEq, Eq)]
+pub struct SessionKey(String);
 
-impl TryFrom<String> for SessionKey {
-    type Error = InvalidSessionKeyError;
+impl TryFrom<String> for SessionKey {
+    type Error = InvalidSessionKeyError;
 
-    fn try_from(val: String) -> Result<Self, Self::Error> {
-        if val.len() > 4064 {
-            return Err(anyhow::anyhow!(
-                "The session key is bigger than 4064 bytes, the upper limit on cookie content."
-            )
-            .into());
+    fn try_from(val: String) -> Result<Self, Self::Error> {
+        if val.len() > 4064 {
+            return Err(anyhow::anyhow!(
+                "The session key is bigger than 4064 bytes, the upper limit on cookie content."
+            )
+            .into());
         }
 
-        Ok(SessionKey(val))
+        Ok(SessionKey(val))
     }
 }
 
-impl AsRef<str> for SessionKey {
-    fn as_ref(&self) -> &str {
-        &self.0
-    }
+impl AsRef<str> for SessionKey {
+    fn as_ref(&self) -> &str {
+        &self.0
+    }
 }
 
-impl From<SessionKey> for String {
-    fn from(key: SessionKey) -> Self {
-        key.0
-    }
+impl From<SessionKey> for String {
+    fn from(key: SessionKey) -> Self {
+        key.0
+    }
 }
 
-#[derive(Debug, Display, From)]
-#[display(fmt = "The provided string is not a valid session key")]
-pub struct InvalidSessionKeyError(anyhow::Error);
+#[derive(Debug, Display, From)]
+#[display(fmt = "The provided string is not a valid session key")]
+pub struct InvalidSessionKeyError(anyhow::Error);
 
-impl std::error::Error for InvalidSessionKeyError {
-    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
-        Some(self.0.as_ref())
+impl std::error::Error for InvalidSessionKeyError {
+    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+        Some(self.0.as_ref())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_session/storage/utils.rs.html b/src/actix_session/storage/utils.rs.html index 9ef57dcc6..cfb371317 100644 --- a/src/actix_session/storage/utils.rs.html +++ b/src/actix_session/storage/utils.rs.html @@ -19,24 +19,24 @@ 17 18 19 -
use std::convert::TryInto;
+
use std::convert::TryInto;
 
-use rand::{distributions::Alphanumeric, rngs::OsRng, Rng as _};
+use rand::{distributions::Alphanumeric, rngs::OsRng, Rng as _};
 
-use crate::storage::SessionKey;
+use crate::storage::SessionKey;
 
-/// Session key generation routine that follows [OWASP recommendations].
-///
-/// [OWASP recommendations]: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#session-id-entropy
-pub(crate) fn generate_session_key() -> SessionKey {
-    let value = std::iter::repeat(())
-        .map(|()| OsRng.sample(Alphanumeric))
-        .take(64)
-        .collect::<Vec<_>>();
+/// Session key generation routine that follows [OWASP recommendations].
+///
+/// [OWASP recommendations]: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#session-id-entropy
+pub(crate) fn generate_session_key() -> SessionKey {
+    let value = std::iter::repeat(())
+        .map(|()| OsRng.sample(Alphanumeric))
+        .take(64)
+        .collect::<Vec<_>>();
 
-    // These unwraps will never panic because pre-conditions are always verified
-    // (i.e. length and character set)
-    String::from_utf8(value).unwrap().try_into().unwrap()
+    // These unwraps will never panic because pre-conditions are always verified
+    // (i.e. length and character set)
+    String::from_utf8(value).unwrap().try_into().unwrap()
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/error.rs.html b/src/actix_settings/error.rs.html index 0462c3a66..f11ef0b0b 100644 --- a/src/actix_settings/error.rs.html +++ b/src/actix_settings/error.rs.html @@ -138,143 +138,143 @@ 136 137 138 -
use std::{env::VarError, io, num::ParseIntError, path::PathBuf, str::ParseBoolError};
+
use std::{env::VarError, io, num::ParseIntError, path::PathBuf, str::ParseBoolError};
 
-use toml::de::Error as TomlError;
+use toml::de::Error as TomlError;
 
-/// Errors that can be returned from methods in this crate.
-#[derive(Debug, Clone)]
-pub enum Error {
-    /// Environment variable does not exists or is invalid.
-    EnvVarError(VarError),
+/// Errors that can be returned from methods in this crate.
+#[derive(Debug, Clone)]
+pub enum Error {
+    /// Environment variable does not exists or is invalid.
+    EnvVarError(VarError),
 
-    /// File already exists on disk.
-    FileExists(PathBuf),
+    /// File already exists on disk.
+    FileExists(PathBuf),
 
-    /// Invalid value.
-    #[allow(missing_docs)]
-    InvalidValue {
-        expected: &'static str,
-        got: String,
-        file: &'static str,
-        line: u32,
-        column: u32,
+    /// Invalid value.
+    #[allow(missing_docs)]
+    InvalidValue {
+        expected: &'static str,
+        got: String,
+        file: &'static str,
+        line: u32,
+        column: u32,
     },
 
-    /// I/O error.
-    IoError(ioe::IoError),
+    /// I/O error.
+    IoError(ioe::IoError),
 
-    /// Value is not a boolean.
-    ParseBoolError(ParseBoolError),
+    /// Value is not a boolean.
+    ParseBoolError(ParseBoolError),
 
-    /// Value is not an integer.
-    ParseIntError(ParseIntError),
+    /// Value is not an integer.
+    ParseIntError(ParseIntError),
 
-    /// Value is not an address.
-    ParseAddressError(String),
+    /// Value is not an address.
+    ParseAddressError(String),
 
-    /// Error deserializing as TOML.
-    TomlError(TomlError),
+    /// Error deserializing as TOML.
+    TomlError(TomlError),
 }
 
-macro_rules! InvalidValue {
-    (expected: $expected:expr, got: $got:expr,) => {
-        crate::Error::InvalidValue {
-            expected: $expected,
-            got: $got.to_string(),
-            file: file!(),
-            line: line!(),
-            column: column!(),
+macro_rules! InvalidValue {
+    (expected: $expected:expr, got: $got:expr,) => {
+        crate::Error::InvalidValue {
+            expected: $expected,
+            got: $got.to_string(),
+            file: file!(),
+            line: line!(),
+            column: column!(),
         }
     };
 }
 
-impl From<io::Error> for Error {
-    fn from(err: io::Error) -> Self {
-        Self::IoError(ioe::IoError::from(err))
+impl From<io::Error> for Error {
+    fn from(err: io::Error) -> Self {
+        Self::IoError(ioe::IoError::from(err))
     }
 }
 
-impl From<ioe::IoError> for Error {
-    fn from(err: ioe::IoError) -> Self {
-        Self::IoError(err)
+impl From<ioe::IoError> for Error {
+    fn from(err: ioe::IoError) -> Self {
+        Self::IoError(err)
     }
 }
 
-impl From<ParseBoolError> for Error {
-    fn from(err: ParseBoolError) -> Self {
-        Self::ParseBoolError(err)
+impl From<ParseBoolError> for Error {
+    fn from(err: ParseBoolError) -> Self {
+        Self::ParseBoolError(err)
     }
 }
 
-impl From<ParseIntError> for Error {
-    fn from(err: ParseIntError) -> Self {
-        Self::ParseIntError(err)
+impl From<ParseIntError> for Error {
+    fn from(err: ParseIntError) -> Self {
+        Self::ParseIntError(err)
     }
 }
 
-impl From<TomlError> for Error {
-    fn from(err: TomlError) -> Self {
-        Self::TomlError(err)
+impl From<TomlError> for Error {
+    fn from(err: TomlError) -> Self {
+        Self::TomlError(err)
     }
 }
 
-impl From<VarError> for Error {
-    fn from(err: VarError) -> Self {
-        Self::EnvVarError(err)
+impl From<VarError> for Error {
+    fn from(err: VarError) -> Self {
+        Self::EnvVarError(err)
     }
 }
 
-impl From<Error> for io::Error {
-    fn from(err: Error) -> Self {
-        match err {
-            Error::EnvVarError(var_error) => {
-                let msg = format!("Env var error: {}", var_error);
-                io::Error::new(io::ErrorKind::InvalidInput, msg)
+impl From<Error> for io::Error {
+    fn from(err: Error) -> Self {
+        match err {
+            Error::EnvVarError(var_error) => {
+                let msg = format!("Env var error: {}", var_error);
+                io::Error::new(io::ErrorKind::InvalidInput, msg)
             }
 
-            Error::FileExists(path_buf) => {
-                let msg = format!("File exists: {}", path_buf.display());
-                io::Error::new(io::ErrorKind::AlreadyExists, msg)
+            Error::FileExists(path_buf) => {
+                let msg = format!("File exists: {}", path_buf.display());
+                io::Error::new(io::ErrorKind::AlreadyExists, msg)
             }
 
-            Error::InvalidValue {
-                expected,
-                ref got,
-                file,
-                line,
-                column,
+            Error::InvalidValue {
+                expected,
+                ref got,
+                file,
+                line,
+                column,
             } => {
-                let msg = format!(
+                let msg = format!(
                     "Expected {}, got {}  (@ {}:{}:{})",
-                    expected, got, file, line, column
+                    expected, got, file, line, column
                 );
-                io::Error::new(io::ErrorKind::InvalidInput, msg)
+                io::Error::new(io::ErrorKind::InvalidInput, msg)
             }
 
-            Error::IoError(io_error) => io_error.into(),
+            Error::IoError(io_error) => io_error.into(),
 
-            Error::ParseBoolError(parse_bool_error) => {
-                let msg = format!("Failed to parse boolean: {}", parse_bool_error);
-                io::Error::new(io::ErrorKind::InvalidInput, msg)
+            Error::ParseBoolError(parse_bool_error) => {
+                let msg = format!("Failed to parse boolean: {}", parse_bool_error);
+                io::Error::new(io::ErrorKind::InvalidInput, msg)
             }
 
-            Error::ParseIntError(parse_int_error) => {
-                let msg = format!("Failed to parse integer: {}", parse_int_error);
-                io::Error::new(io::ErrorKind::InvalidInput, msg)
+            Error::ParseIntError(parse_int_error) => {
+                let msg = format!("Failed to parse integer: {}", parse_int_error);
+                io::Error::new(io::ErrorKind::InvalidInput, msg)
             }
 
-            Error::ParseAddressError(string) => {
-                let msg = format!("Failed to parse address: {}", string);
-                io::Error::new(io::ErrorKind::InvalidInput, msg)
+            Error::ParseAddressError(string) => {
+                let msg = format!("Failed to parse address: {}", string);
+                io::Error::new(io::ErrorKind::InvalidInput, msg)
             }
 
-            Error::TomlError(toml_error) => {
-                let msg = format!("TOML error: {}", toml_error);
-                io::Error::new(io::ErrorKind::InvalidInput, msg)
+            Error::TomlError(toml_error) => {
+                let msg = format!("TOML error: {}", toml_error);
+                io::Error::new(io::ErrorKind::InvalidInput, msg)
             }
         }
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/lib.rs.html b/src/actix_settings/lib.rs.html index 3498451a4..b59b0daef 100644 --- a/src/actix_settings/lib.rs.html +++ b/src/actix_settings/lib.rs.html @@ -809,399 +809,399 @@ 807 808 809 -
//! Easily manage Actix Web's settings from a TOML file and environment variables.
-//!
-//! To get started add a [`Settings::parse_toml("./Server.toml")`](Settings::parse_toml) call to the
-//! top of your main function. This will create a template file with descriptions of all the
-//! configurable settings. You can change or remove anything in that file and it will be picked up
-//! the next time you run your application.
-//!
-//! Overriding parts of the file can be done from values using [`Settings::override_field`] or from
-//! the environment using [`Settings::override_field_with_env_var`].
-//!
-//! # Examples
-//!
-//! See examples folder on GitHub for complete example.
-//!
-//! ```ignore
-//! # use actix_web::{
-//! #     get,
-//! #     middleware::{Compress, Condition, Logger},
-//! #     web, App, HttpServer,
-//! # };
-//! use actix_settings::{ApplySettings as _, Mode, Settings};
-//!
-//! #[actix_web::main]
-//! async fn main() -> std::io::Result<()> {
-//!     let mut settings = Settings::parse_toml("./Server.toml")
-//!         .expect("Failed to parse `Settings` from Server.toml");
-//!
-//!     // If the environment variable `$APPLICATION__HOSTS` is set,
-//!     // have its value override the `settings.actix.hosts` setting:
-//!     Settings::override_field_with_env_var(&mut settings.actix.hosts, "APPLICATION__HOSTS")?;
-//!
-//!     init_logger(&settings);
-//!
-//!     HttpServer::new({
-//!         // clone settings into each worker thread
-//!         let settings = settings.clone();
-//!
-//!         move || {
-//!             App::new()
-//!                 // Include this `.wrap()` call for compression settings to take effect
-//!                 .wrap(Condition::new(
-//!                     settings.actix.enable_compression,
-//!                     Compress::default(),
-//!                 ))
-//!
-//!                 // add request logger
-//!                 .wrap(Logger::default())
-//!
-//!                 // make `Settings` available to handlers
-//!                 .app_data(web::Data::new(settings.clone()))
-//!
-//!                 // add request handlers as normal
-//!                 .service(index)
-//!         }
-//!     })
-//!     // apply the `Settings` to Actix Web's `HttpServer`
-//!     .apply_settings(&settings)
-//!     .run()
-//!     .await
-//! }
-//! ```
+
//! Easily manage Actix Web's settings from a TOML file and environment variables.
+//!
+//! To get started add a [`Settings::parse_toml("./Server.toml")`](Settings::parse_toml) call to the
+//! top of your main function. This will create a template file with descriptions of all the
+//! configurable settings. You can change or remove anything in that file and it will be picked up
+//! the next time you run your application.
+//!
+//! Overriding parts of the file can be done from values using [`Settings::override_field`] or from
+//! the environment using [`Settings::override_field_with_env_var`].
+//!
+//! # Examples
+//!
+//! See examples folder on GitHub for complete example.
+//!
+//! ```ignore
+//! # use actix_web::{
+//! #     get,
+//! #     middleware::{Compress, Condition, Logger},
+//! #     web, App, HttpServer,
+//! # };
+//! use actix_settings::{ApplySettings as _, Mode, Settings};
+//!
+//! #[actix_web::main]
+//! async fn main() -> std::io::Result<()> {
+//!     let mut settings = Settings::parse_toml("./Server.toml")
+//!         .expect("Failed to parse `Settings` from Server.toml");
+//!
+//!     // If the environment variable `$APPLICATION__HOSTS` is set,
+//!     // have its value override the `settings.actix.hosts` setting:
+//!     Settings::override_field_with_env_var(&mut settings.actix.hosts, "APPLICATION__HOSTS")?;
+//!
+//!     init_logger(&settings);
+//!
+//!     HttpServer::new({
+//!         // clone settings into each worker thread
+//!         let settings = settings.clone();
+//!
+//!         move || {
+//!             App::new()
+//!                 // Include this `.wrap()` call for compression settings to take effect
+//!                 .wrap(Condition::new(
+//!                     settings.actix.enable_compression,
+//!                     Compress::default(),
+//!                 ))
+//!
+//!                 // add request logger
+//!                 .wrap(Logger::default())
+//!
+//!                 // make `Settings` available to handlers
+//!                 .app_data(web::Data::new(settings.clone()))
+//!
+//!                 // add request handlers as normal
+//!                 .service(index)
+//!         }
+//!     })
+//!     // apply the `Settings` to Actix Web's `HttpServer`
+//!     .apply_settings(&settings)
+//!     .run()
+//!     .await
+//! }
+//! ```
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style)]
-#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
-#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
-#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
+#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
+#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
 
-use std::{
-    env, fmt,
-    fs::File,
-    io::{Read as _, Write as _},
-    path::Path,
-    time::Duration,
+use std::{
+    env, fmt,
+    fs::File,
+    io::{Read as _, Write as _},
+    path::Path,
+    time::Duration,
 };
 
-use actix_http::{Request, Response};
-use actix_service::IntoServiceFactory;
-use actix_web::{
-    body::MessageBody,
-    dev::{AppConfig, ServiceFactory},
-    http::KeepAlive as ActixKeepAlive,
-    Error as WebError, HttpServer,
+use actix_http::{Request, Response};
+use actix_service::IntoServiceFactory;
+use actix_web::{
+    body::MessageBody,
+    dev::{AppConfig, ServiceFactory},
+    http::KeepAlive as ActixKeepAlive,
+    Error as WebError, HttpServer,
 };
-use serde::{de, Deserialize};
+use serde::{de, Deserialize};
 
-#[macro_use]
-mod error;
-mod parse;
-mod settings;
+#[macro_use]
+mod error;
+mod parse;
+mod settings;
 
-pub use self::error::Error;
-pub use self::parse::Parse;
-pub use self::settings::{
-    ActixSettings, Address, Backlog, KeepAlive, MaxConnectionRate, MaxConnections, Mode,
-    NumWorkers, Timeout, Tls,
+pub use self::error::Error;
+pub use self::parse::Parse;
+pub use self::settings::{
+    ActixSettings, Address, Backlog, KeepAlive, MaxConnectionRate, MaxConnections, Mode,
+    NumWorkers, Timeout, Tls,
 };
 
-/// Convenience type alias for `Result<T, AtError>`.
-type AsResult<T> = std::result::Result<T, Error>;
+/// Convenience type alias for `Result<T, AtError>`.
+type AsResult<T> = std::result::Result<T, Error>;
 
-/// Wrapper for server and application-specific settings.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
-#[serde(bound = "A: Deserialize<'de>")]
-pub struct BasicSettings<A> {
-    /// Actix Web server settings.
-    pub actix: ActixSettings,
+/// Wrapper for server and application-specific settings.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
+#[serde(bound = "A: Deserialize<'de>")]
+pub struct BasicSettings<A> {
+    /// Actix Web server settings.
+    pub actix: ActixSettings,
 
-    /// Application-specific settings.
-    pub application: A,
+    /// Application-specific settings.
+    pub application: A,
 }
 
-/// Convenience type alias for [`BasicSettings`] with no defined application-specific settings.
-pub type Settings = BasicSettings<NoSettings>;
+/// Convenience type alias for [`BasicSettings`] with no defined application-specific settings.
+pub type Settings = BasicSettings<NoSettings>;
 
-/// Marker type representing no defined application-specific settings.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
-#[non_exhaustive]
-pub struct NoSettings {/* NOTE: turning this into a unit struct will cause deserialization failures. */}
+/// Marker type representing no defined application-specific settings.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
+#[non_exhaustive]
+pub struct NoSettings {/* NOTE: turning this into a unit struct will cause deserialization failures. */}
 
-impl<A> BasicSettings<A>
-where
-    A: de::DeserializeOwned,
+impl<A> BasicSettings<A>
+where
+    A: de::DeserializeOwned,
 {
-    // NOTE **DO NOT** mess with the ordering of the tables in the default template.
-    //      Especially the `[application]` table needs to be last in order
-    //      for some tests to keep working.
-    /// Default settings file contents.
-    pub(crate) const DEFAULT_TOML_TEMPLATE: &'static str = include_str!("./defaults.toml");
+    // NOTE **DO NOT** mess with the ordering of the tables in the default template.
+    //      Especially the `[application]` table needs to be last in order
+    //      for some tests to keep working.
+    /// Default settings file contents.
+    pub(crate) const DEFAULT_TOML_TEMPLATE: &'static str = include_str!("./defaults.toml");
 
-    /// Parse an instance of `Self` from a TOML file located at `filepath`.
-    ///
-    /// If the file doesn't exist, it is generated from the default TOML template, after which the
-    /// newly generated file is read in and parsed.
-    pub fn parse_toml<P>(filepath: P) -> AsResult<Self>
-    where
-        P: AsRef<Path>,
+    /// Parse an instance of `Self` from a TOML file located at `filepath`.
+    ///
+    /// If the file doesn't exist, it is generated from the default TOML template, after which the
+    /// newly generated file is read in and parsed.
+    pub fn parse_toml<P>(filepath: P) -> AsResult<Self>
+    where
+        P: AsRef<Path>,
     {
-        let filepath = filepath.as_ref();
+        let filepath = filepath.as_ref();
 
-        if !filepath.exists() {
-            Self::write_toml_file(filepath)?;
+        if !filepath.exists() {
+            Self::write_toml_file(filepath)?;
         }
 
-        let mut f = File::open(filepath)?;
-        let len_guess = f.metadata().map(|md| md.len()).unwrap_or(128);
+        let mut f = File::open(filepath)?;
+        let len_guess = f.metadata().map(|md| md.len()).unwrap_or(128);
 
-        let mut contents = String::with_capacity(len_guess as usize);
-        f.read_to_string(&mut contents)?;
+        let mut contents = String::with_capacity(len_guess as usize);
+        f.read_to_string(&mut contents)?;
 
-        Ok(toml::from_str::<Self>(&contents)?)
+        Ok(toml::from_str::<Self>(&contents)?)
     }
 
-    /// Parse an instance of `Self` straight from the default TOML template.
-    // TODO: make infallible
-    // TODO: consider "template" rename
-    pub fn from_default_template() -> AsResult<Self> {
-        Self::from_template(Self::DEFAULT_TOML_TEMPLATE)
+    /// Parse an instance of `Self` straight from the default TOML template.
+    // TODO: make infallible
+    // TODO: consider "template" rename
+    pub fn from_default_template() -> AsResult<Self> {
+        Self::from_template(Self::DEFAULT_TOML_TEMPLATE)
     }
 
-    /// Parse an instance of `Self` straight from the default TOML template.
-    // TODO: consider "template" rename
-    pub fn from_template(template: &str) -> AsResult<Self> {
-        Ok(toml::from_str(template)?)
+    /// Parse an instance of `Self` straight from the default TOML template.
+    // TODO: consider "template" rename
+    pub fn from_template(template: &str) -> AsResult<Self> {
+        Ok(toml::from_str(template)?)
     }
 
-    /// Writes the default TOML template to a new file, located at `filepath`.
-    ///
-    /// # Errors
-    /// Returns a [`FileExists`](crate::AtError::FileExists) error if a file already exists at that
-    /// location.
-    pub fn write_toml_file<P>(filepath: P) -> AsResult<()>
-    where
-        P: AsRef<Path>,
+    /// Writes the default TOML template to a new file, located at `filepath`.
+    ///
+    /// # Errors
+    /// Returns a [`FileExists`](crate::AtError::FileExists) error if a file already exists at that
+    /// location.
+    pub fn write_toml_file<P>(filepath: P) -> AsResult<()>
+    where
+        P: AsRef<Path>,
     {
-        let filepath = filepath.as_ref();
+        let filepath = filepath.as_ref();
 
-        if filepath.exists() {
-            return Err(Error::FileExists(filepath.to_path_buf()));
+        if filepath.exists() {
+            return Err(Error::FileExists(filepath.to_path_buf()));
         }
 
-        let mut file = File::create(filepath)?;
-        file.write_all(Self::DEFAULT_TOML_TEMPLATE.trim().as_bytes())?;
-        file.flush()?;
+        let mut file = File::create(filepath)?;
+        file.write_all(Self::DEFAULT_TOML_TEMPLATE.trim().as_bytes())?;
+        file.flush()?;
 
         Ok(())
     }
 
-    /// Attempts to parse `value` and override the referenced `field`.
-    ///
-    /// # Examples
-    /// ```
-    /// use actix_settings::{Settings, Mode};
-    ///
-    /// # fn inner() -> Result<(), actix_settings::Error> {
-    /// let mut settings = Settings::from_default_template()?;
-    /// assert_eq!(settings.actix.mode, Mode::Development);
-    ///
-    /// Settings::override_field(&mut settings.actix.mode, "production")?;
-    /// assert_eq!(settings.actix.mode, Mode::Production);
-    /// # Ok(()) }
-    /// ```
-    pub fn override_field<F, V>(field: &mut F, value: V) -> AsResult<()>
-    where
-        F: Parse,
-        V: AsRef<str>,
+    /// Attempts to parse `value` and override the referenced `field`.
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_settings::{Settings, Mode};
+    ///
+    /// # fn inner() -> Result<(), actix_settings::Error> {
+    /// let mut settings = Settings::from_default_template()?;
+    /// assert_eq!(settings.actix.mode, Mode::Development);
+    ///
+    /// Settings::override_field(&mut settings.actix.mode, "production")?;
+    /// assert_eq!(settings.actix.mode, Mode::Production);
+    /// # Ok(()) }
+    /// ```
+    pub fn override_field<F, V>(field: &mut F, value: V) -> AsResult<()>
+    where
+        F: Parse,
+        V: AsRef<str>,
     {
-        *field = F::parse(value.as_ref())?;
+        *field = F::parse(value.as_ref())?;
         Ok(())
     }
 
-    /// Attempts to read an environment variable, parse it, and override the referenced `field`.
-    ///
-    /// # Examples
-    /// ```
-    /// use actix_settings::{Settings, Mode};
-    ///
-    /// std::env::set_var("OVERRIDE__MODE", "production");
-    ///
-    /// # fn inner() -> Result<(), actix_settings::Error> {
-    /// let mut settings = Settings::from_default_template()?;
-    /// assert_eq!(settings.actix.mode, Mode::Development);
-    ///
-    /// Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE")?;
-    /// assert_eq!(settings.actix.mode, Mode::Production);
-    /// # Ok(()) }
-    /// ```
-    pub fn override_field_with_env_var<F, N>(field: &mut F, var_name: N) -> AsResult<()>
-    where
-        F: Parse,
-        N: AsRef<str>,
+    /// Attempts to read an environment variable, parse it, and override the referenced `field`.
+    ///
+    /// # Examples
+    /// ```
+    /// use actix_settings::{Settings, Mode};
+    ///
+    /// std::env::set_var("OVERRIDE__MODE", "production");
+    ///
+    /// # fn inner() -> Result<(), actix_settings::Error> {
+    /// let mut settings = Settings::from_default_template()?;
+    /// assert_eq!(settings.actix.mode, Mode::Development);
+    ///
+    /// Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE")?;
+    /// assert_eq!(settings.actix.mode, Mode::Production);
+    /// # Ok(()) }
+    /// ```
+    pub fn override_field_with_env_var<F, N>(field: &mut F, var_name: N) -> AsResult<()>
+    where
+        F: Parse,
+        N: AsRef<str>,
     {
-        match env::var(var_name.as_ref()) {
-            Err(env::VarError::NotPresent) => Ok((/*NOP*/)),
-            Err(var_error) => Err(Error::from(var_error)),
-            Ok(value) => Self::override_field(field, value),
+        match env::var(var_name.as_ref()) {
+            Err(env::VarError::NotPresent) => Ok((/*NOP*/)),
+            Err(var_error) => Err(Error::from(var_error)),
+            Ok(value) => Self::override_field(field, value),
         }
     }
 }
 
-/// Extension trait for applying parsed settings to the server object.
-pub trait ApplySettings {
-    /// Apply a [`BasicSettings`] value to `self`.
-    ///
-    /// [`BasicSettings`]: ./struct.BasicSettings.html
-    #[must_use]
-    fn apply_settings<A>(self, settings: &BasicSettings<A>) -> Self
-    where
-        A: de::DeserializeOwned;
+/// Extension trait for applying parsed settings to the server object.
+pub trait ApplySettings {
+    /// Apply a [`BasicSettings`] value to `self`.
+    ///
+    /// [`BasicSettings`]: ./struct.BasicSettings.html
+    #[must_use]
+    fn apply_settings<A>(self, settings: &BasicSettings<A>) -> Self
+    where
+        A: de::DeserializeOwned;
 }
 
-impl<F, I, S, B> ApplySettings for HttpServer<F, I, S, B>
-where
-    F: Fn() -> I + Send + Clone + 'static,
-    I: IntoServiceFactory<S, Request>,
-    S: ServiceFactory<Request, Config = AppConfig> + 'static,
-    S::Error: Into<WebError> + 'static,
-    S::InitError: fmt::Debug,
-    S::Response: Into<Response<B>> + 'static,
-    S::Future: 'static,
-    B: MessageBody + 'static,
+impl<F, I, S, B> ApplySettings for HttpServer<F, I, S, B>
+where
+    F: Fn() -> I + Send + Clone + 'static,
+    I: IntoServiceFactory<S, Request>,
+    S: ServiceFactory<Request, Config = AppConfig> + 'static,
+    S::Error: Into<WebError> + 'static,
+    S::InitError: fmt::Debug,
+    S::Response: Into<Response<B>> + 'static,
+    S::Future: 'static,
+    B: MessageBody + 'static,
 {
-    fn apply_settings<A>(mut self, settings: &BasicSettings<A>) -> Self
-    where
-        A: de::DeserializeOwned,
+    fn apply_settings<A>(mut self, settings: &BasicSettings<A>) -> Self
+    where
+        A: de::DeserializeOwned,
     {
-        if settings.actix.tls.enabled {
-            // for Address { host, port } in &settings.actix.hosts {
-            //     self = self.bind(format!("{}:{}", host, port))
-            //         .unwrap(/*TODO*/);
-            // }
-            todo!("[ApplySettings] TLS support has not been implemented yet.");
-        } else {
-            for Address { host, port } in &settings.actix.hosts {
-                self = self.bind(format!("{}:{}", host, port))
-                    .unwrap(/*TODO*/);
+        if settings.actix.tls.enabled {
+            // for Address { host, port } in &settings.actix.hosts {
+            //     self = self.bind(format!("{}:{}", host, port))
+            //         .unwrap(/*TODO*/);
+            // }
+            todo!("[ApplySettings] TLS support has not been implemented yet.");
+        } else {
+            for Address { host, port } in &settings.actix.hosts {
+                self = self.bind(format!("{}:{}", host, port))
+                    .unwrap(/*TODO*/);
             }
         }
 
-        self = match settings.actix.num_workers {
-            NumWorkers::Default => self,
-            NumWorkers::Manual(n) => self.workers(n),
+        self = match settings.actix.num_workers {
+            NumWorkers::Default => self,
+            NumWorkers::Manual(n) => self.workers(n),
         };
 
-        self = match settings.actix.backlog {
-            Backlog::Default => self,
-            Backlog::Manual(n) => self.backlog(n as u32),
+        self = match settings.actix.backlog {
+            Backlog::Default => self,
+            Backlog::Manual(n) => self.backlog(n as u32),
         };
 
-        self = match settings.actix.max_connections {
-            MaxConnections::Default => self,
-            MaxConnections::Manual(n) => self.max_connections(n),
+        self = match settings.actix.max_connections {
+            MaxConnections::Default => self,
+            MaxConnections::Manual(n) => self.max_connections(n),
         };
 
-        self = match settings.actix.max_connection_rate {
-            MaxConnectionRate::Default => self,
-            MaxConnectionRate::Manual(n) => self.max_connection_rate(n),
+        self = match settings.actix.max_connection_rate {
+            MaxConnectionRate::Default => self,
+            MaxConnectionRate::Manual(n) => self.max_connection_rate(n),
         };
 
-        self = match settings.actix.keep_alive {
-            KeepAlive::Default => self,
-            KeepAlive::Disabled => self.keep_alive(ActixKeepAlive::Disabled),
-            KeepAlive::Os => self.keep_alive(ActixKeepAlive::Os),
-            KeepAlive::Seconds(n) => self.keep_alive(Duration::from_secs(n as u64)),
+        self = match settings.actix.keep_alive {
+            KeepAlive::Default => self,
+            KeepAlive::Disabled => self.keep_alive(ActixKeepAlive::Disabled),
+            KeepAlive::Os => self.keep_alive(ActixKeepAlive::Os),
+            KeepAlive::Seconds(n) => self.keep_alive(Duration::from_secs(n as u64)),
         };
 
-        self = match settings.actix.client_timeout {
-            Timeout::Default => self,
-            Timeout::Milliseconds(n) => {
-                self.client_request_timeout(Duration::from_millis(n as u64))
+        self = match settings.actix.client_timeout {
+            Timeout::Default => self,
+            Timeout::Milliseconds(n) => {
+                self.client_request_timeout(Duration::from_millis(n as u64))
             }
-            Timeout::Seconds(n) => self.client_request_timeout(Duration::from_secs(n as u64)),
+            Timeout::Seconds(n) => self.client_request_timeout(Duration::from_secs(n as u64)),
         };
 
-        self = match settings.actix.client_shutdown {
-            Timeout::Default => self,
-            Timeout::Milliseconds(n) => {
-                self.client_disconnect_timeout(Duration::from_millis(n as u64))
+        self = match settings.actix.client_shutdown {
+            Timeout::Default => self,
+            Timeout::Milliseconds(n) => {
+                self.client_disconnect_timeout(Duration::from_millis(n as u64))
             }
-            Timeout::Seconds(n) => self.client_disconnect_timeout(Duration::from_secs(n as u64)),
+            Timeout::Seconds(n) => self.client_disconnect_timeout(Duration::from_secs(n as u64)),
         };
 
-        self = match settings.actix.shutdown_timeout {
-            Timeout::Default => self,
-            Timeout::Milliseconds(_) => self.shutdown_timeout(1),
-            Timeout::Seconds(n) => self.shutdown_timeout(n as u64),
+        self = match settings.actix.shutdown_timeout {
+            Timeout::Default => self,
+            Timeout::Milliseconds(_) => self.shutdown_timeout(1),
+            Timeout::Seconds(n) => self.shutdown_timeout(n as u64),
         };
 
-        self
-    }
+        self
+    }
 }
 
-#[cfg(test)]
-mod tests {
-    use actix_web::App;
+#[cfg(test)]
+mod tests {
+    use actix_web::App;
 
-    use super::*;
+    use super::*;
 
-    #[test]
-    fn apply_settings() {
-        let settings = Settings::parse_toml("Server.toml").unwrap();
-        let _ = HttpServer::new(App::new).apply_settings(&settings);
+    #[test]
+    fn apply_settings() {
+        let settings = Settings::parse_toml("Server.toml").unwrap();
+        let _ = HttpServer::new(App::new).apply_settings(&settings);
     }
 
-    #[test]
-    fn override_field_hosts() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_hosts() {
+        let mut settings = Settings::from_default_template().unwrap();
 
         assert_eq!(
-            settings.actix.hosts,
-            vec![Address {
-                host: "0.0.0.0".into(),
-                port: 9000
-            },]
+            settings.actix.hosts,
+            vec![Address {
+                host: "0.0.0.0".into(),
+                port: 9000
+            },]
         );
 
-        Settings::override_field(
-            &mut settings.actix.hosts,
+        Settings::override_field(
+            &mut settings.actix.hosts,
             r#"[
             ["0.0.0.0",   1234],
             ["localhost", 2345]
         ]"#,
         )
-        .unwrap();
+        .unwrap();
 
         assert_eq!(
-            settings.actix.hosts,
+            settings.actix.hosts,
             vec![
-                Address {
-                    host: "0.0.0.0".into(),
-                    port: 1234
-                },
-                Address {
-                    host: "localhost".into(),
-                    port: 2345
-                },
+                Address {
+                    host: "0.0.0.0".into(),
+                    port: 1234
+                },
+                Address {
+                    host: "localhost".into(),
+                    port: 2345
+                },
             ]
         );
     }
 
-    #[test]
-    fn override_field_with_env_var_hosts() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_with_env_var_hosts() {
+        let mut settings = Settings::from_default_template().unwrap();
 
         assert_eq!(
-            settings.actix.hosts,
-            vec![Address {
-                host: "0.0.0.0".into(),
-                port: 9000
-            },]
+            settings.actix.hosts,
+            vec![Address {
+                host: "0.0.0.0".into(),
+                port: 9000
+            },]
         );
 
-        std::env::set_var(
+        std::env::set_var(
             "OVERRIDE__HOSTS",
             r#"[
             ["0.0.0.0",   1234],
@@ -1209,414 +1209,414 @@
         ]"#,
         );
 
-        Settings::override_field_with_env_var(&mut settings.actix.hosts, "OVERRIDE__HOSTS")
-            .unwrap();
+        Settings::override_field_with_env_var(&mut settings.actix.hosts, "OVERRIDE__HOSTS")
+            .unwrap();
 
         assert_eq!(
-            settings.actix.hosts,
+            settings.actix.hosts,
             vec![
-                Address {
-                    host: "0.0.0.0".into(),
-                    port: 1234
-                },
-                Address {
-                    host: "localhost".into(),
-                    port: 2345
-                },
+                Address {
+                    host: "0.0.0.0".into(),
+                    port: 1234
+                },
+                Address {
+                    host: "localhost".into(),
+                    port: 2345
+                },
             ]
         );
     }
 
-    #[test]
-    fn override_field_mode() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.mode, Mode::Development);
-        Settings::override_field(&mut settings.actix.mode, "production").unwrap();
-        assert_eq!(settings.actix.mode, Mode::Production);
+    #[test]
+    fn override_field_mode() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.mode, Mode::Development);
+        Settings::override_field(&mut settings.actix.mode, "production").unwrap();
+        assert_eq!(settings.actix.mode, Mode::Production);
     }
 
-    #[test]
-    fn override_field_with_env_var_mode() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.mode, Mode::Development);
-        std::env::set_var("OVERRIDE__MODE", "production");
-        Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE").unwrap();
-        assert_eq!(settings.actix.mode, Mode::Production);
+    #[test]
+    fn override_field_with_env_var_mode() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.mode, Mode::Development);
+        std::env::set_var("OVERRIDE__MODE", "production");
+        Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE").unwrap();
+        assert_eq!(settings.actix.mode, Mode::Production);
     }
 
-    #[test]
-    fn override_field_enable_compression() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert!(settings.actix.enable_compression);
-        Settings::override_field(&mut settings.actix.enable_compression, "false").unwrap();
-        assert!(!settings.actix.enable_compression);
+    #[test]
+    fn override_field_enable_compression() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert!(settings.actix.enable_compression);
+        Settings::override_field(&mut settings.actix.enable_compression, "false").unwrap();
+        assert!(!settings.actix.enable_compression);
     }
 
-    #[test]
-    fn override_field_with_env_var_enable_compression() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert!(settings.actix.enable_compression);
-        std::env::set_var("OVERRIDE__ENABLE_COMPRESSION", "false");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.enable_compression,
+    #[test]
+    fn override_field_with_env_var_enable_compression() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert!(settings.actix.enable_compression);
+        std::env::set_var("OVERRIDE__ENABLE_COMPRESSION", "false");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.enable_compression,
             "OVERRIDE__ENABLE_COMPRESSION",
         )
-        .unwrap();
-        assert!(!settings.actix.enable_compression);
+        .unwrap();
+        assert!(!settings.actix.enable_compression);
     }
 
-    #[test]
-    fn override_field_enable_log() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert!(settings.actix.enable_log);
-        Settings::override_field(&mut settings.actix.enable_log, "false").unwrap();
-        assert!(!settings.actix.enable_log);
+    #[test]
+    fn override_field_enable_log() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert!(settings.actix.enable_log);
+        Settings::override_field(&mut settings.actix.enable_log, "false").unwrap();
+        assert!(!settings.actix.enable_log);
     }
 
-    #[test]
-    fn override_field_with_env_var_enable_log() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert!(settings.actix.enable_log);
-        std::env::set_var("OVERRIDE__ENABLE_LOG", "false");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.enable_log,
+    #[test]
+    fn override_field_with_env_var_enable_log() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert!(settings.actix.enable_log);
+        std::env::set_var("OVERRIDE__ENABLE_LOG", "false");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.enable_log,
             "OVERRIDE__ENABLE_LOG",
         )
-        .unwrap();
-        assert!(!settings.actix.enable_log);
+        .unwrap();
+        assert!(!settings.actix.enable_log);
     }
 
-    #[test]
-    fn override_field_num_workers() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.num_workers, NumWorkers::Default);
-        Settings::override_field(&mut settings.actix.num_workers, "42").unwrap();
-        assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
+    #[test]
+    fn override_field_num_workers() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.num_workers, NumWorkers::Default);
+        Settings::override_field(&mut settings.actix.num_workers, "42").unwrap();
+        assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_num_workers() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.num_workers, NumWorkers::Default);
-        std::env::set_var("OVERRIDE__NUM_WORKERS", "42");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.num_workers,
+    #[test]
+    fn override_field_with_env_var_num_workers() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.num_workers, NumWorkers::Default);
+        std::env::set_var("OVERRIDE__NUM_WORKERS", "42");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.num_workers,
             "OVERRIDE__NUM_WORKERS",
         )
-        .unwrap();
-        assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
+        .unwrap();
+        assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
     }
 
-    #[test]
-    fn override_field_backlog() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.backlog, Backlog::Default);
-        Settings::override_field(&mut settings.actix.backlog, "42").unwrap();
-        assert_eq!(settings.actix.backlog, Backlog::Manual(42));
+    #[test]
+    fn override_field_backlog() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.backlog, Backlog::Default);
+        Settings::override_field(&mut settings.actix.backlog, "42").unwrap();
+        assert_eq!(settings.actix.backlog, Backlog::Manual(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_backlog() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.backlog, Backlog::Default);
-        std::env::set_var("OVERRIDE__BACKLOG", "42");
-        Settings::override_field_with_env_var(&mut settings.actix.backlog, "OVERRIDE__BACKLOG")
-            .unwrap();
-        assert_eq!(settings.actix.backlog, Backlog::Manual(42));
+    #[test]
+    fn override_field_with_env_var_backlog() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.backlog, Backlog::Default);
+        std::env::set_var("OVERRIDE__BACKLOG", "42");
+        Settings::override_field_with_env_var(&mut settings.actix.backlog, "OVERRIDE__BACKLOG")
+            .unwrap();
+        assert_eq!(settings.actix.backlog, Backlog::Manual(42));
     }
 
-    #[test]
-    fn override_field_max_connections() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.max_connections, MaxConnections::Default);
-        Settings::override_field(&mut settings.actix.max_connections, "42").unwrap();
-        assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
+    #[test]
+    fn override_field_max_connections() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.max_connections, MaxConnections::Default);
+        Settings::override_field(&mut settings.actix.max_connections, "42").unwrap();
+        assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_max_connections() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.max_connections, MaxConnections::Default);
-        std::env::set_var("OVERRIDE__MAX_CONNECTIONS", "42");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.max_connections,
+    #[test]
+    fn override_field_with_env_var_max_connections() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.max_connections, MaxConnections::Default);
+        std::env::set_var("OVERRIDE__MAX_CONNECTIONS", "42");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.max_connections,
             "OVERRIDE__MAX_CONNECTIONS",
         )
-        .unwrap();
-        assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
+        .unwrap();
+        assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
     }
 
-    #[test]
-    fn override_field_max_connection_rate() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_max_connection_rate() {
+        let mut settings = Settings::from_default_template().unwrap();
         assert_eq!(
-            settings.actix.max_connection_rate,
-            MaxConnectionRate::Default
+            settings.actix.max_connection_rate,
+            MaxConnectionRate::Default
         );
-        Settings::override_field(&mut settings.actix.max_connection_rate, "42").unwrap();
+        Settings::override_field(&mut settings.actix.max_connection_rate, "42").unwrap();
         assert_eq!(
-            settings.actix.max_connection_rate,
-            MaxConnectionRate::Manual(42)
+            settings.actix.max_connection_rate,
+            MaxConnectionRate::Manual(42)
         );
     }
 
-    #[test]
-    fn override_field_with_env_var_max_connection_rate() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_with_env_var_max_connection_rate() {
+        let mut settings = Settings::from_default_template().unwrap();
         assert_eq!(
-            settings.actix.max_connection_rate,
-            MaxConnectionRate::Default
+            settings.actix.max_connection_rate,
+            MaxConnectionRate::Default
         );
-        std::env::set_var("OVERRIDE__MAX_CONNECTION_RATE", "42");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.max_connection_rate,
+        std::env::set_var("OVERRIDE__MAX_CONNECTION_RATE", "42");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.max_connection_rate,
             "OVERRIDE__MAX_CONNECTION_RATE",
         )
-        .unwrap();
+        .unwrap();
         assert_eq!(
-            settings.actix.max_connection_rate,
-            MaxConnectionRate::Manual(42)
+            settings.actix.max_connection_rate,
+            MaxConnectionRate::Manual(42)
         );
     }
 
-    #[test]
-    fn override_field_keep_alive() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
-        Settings::override_field(&mut settings.actix.keep_alive, "42 seconds").unwrap();
-        assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
+    #[test]
+    fn override_field_keep_alive() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
+        Settings::override_field(&mut settings.actix.keep_alive, "42 seconds").unwrap();
+        assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_keep_alive() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
-        std::env::set_var("OVERRIDE__KEEP_ALIVE", "42 seconds");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.keep_alive,
+    #[test]
+    fn override_field_with_env_var_keep_alive() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
+        std::env::set_var("OVERRIDE__KEEP_ALIVE", "42 seconds");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.keep_alive,
             "OVERRIDE__KEEP_ALIVE",
         )
-        .unwrap();
-        assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
+        .unwrap();
+        assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
     }
 
-    #[test]
-    fn override_field_client_timeout() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.client_timeout, Timeout::Default);
-        Settings::override_field(&mut settings.actix.client_timeout, "42 seconds").unwrap();
-        assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
+    #[test]
+    fn override_field_client_timeout() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.client_timeout, Timeout::Default);
+        Settings::override_field(&mut settings.actix.client_timeout, "42 seconds").unwrap();
+        assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_client_timeout() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.client_timeout, Timeout::Default);
-        std::env::set_var("OVERRIDE__CLIENT_TIMEOUT", "42 seconds");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.client_timeout,
+    #[test]
+    fn override_field_with_env_var_client_timeout() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.client_timeout, Timeout::Default);
+        std::env::set_var("OVERRIDE__CLIENT_TIMEOUT", "42 seconds");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.client_timeout,
             "OVERRIDE__CLIENT_TIMEOUT",
         )
-        .unwrap();
-        assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
+        .unwrap();
+        assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
     }
 
-    #[test]
-    fn override_field_client_shutdown() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.client_shutdown, Timeout::Default);
-        Settings::override_field(&mut settings.actix.client_shutdown, "42 seconds").unwrap();
-        assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
+    #[test]
+    fn override_field_client_shutdown() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.client_shutdown, Timeout::Default);
+        Settings::override_field(&mut settings.actix.client_shutdown, "42 seconds").unwrap();
+        assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_client_shutdown() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.client_shutdown, Timeout::Default);
-        std::env::set_var("OVERRIDE__CLIENT_SHUTDOWN", "42 seconds");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.client_shutdown,
+    #[test]
+    fn override_field_with_env_var_client_shutdown() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.client_shutdown, Timeout::Default);
+        std::env::set_var("OVERRIDE__CLIENT_SHUTDOWN", "42 seconds");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.client_shutdown,
             "OVERRIDE__CLIENT_SHUTDOWN",
         )
-        .unwrap();
-        assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
+        .unwrap();
+        assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
     }
 
-    #[test]
-    fn override_field_shutdown_timeout() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
-        Settings::override_field(&mut settings.actix.shutdown_timeout, "42 seconds").unwrap();
-        assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
+    #[test]
+    fn override_field_shutdown_timeout() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
+        Settings::override_field(&mut settings.actix.shutdown_timeout, "42 seconds").unwrap();
+        assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
     }
 
-    #[test]
-    fn override_field_with_env_var_shutdown_timeout() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
-        std::env::set_var("OVERRIDE__SHUTDOWN_TIMEOUT", "42 seconds");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.shutdown_timeout,
+    #[test]
+    fn override_field_with_env_var_shutdown_timeout() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
+        std::env::set_var("OVERRIDE__SHUTDOWN_TIMEOUT", "42 seconds");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.shutdown_timeout,
             "OVERRIDE__SHUTDOWN_TIMEOUT",
         )
-        .unwrap();
-        assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
+        .unwrap();
+        assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
     }
 
-    #[test]
-    fn override_field_tls_enabled() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert!(!settings.actix.tls.enabled);
-        Settings::override_field(&mut settings.actix.tls.enabled, "true").unwrap();
-        assert!(settings.actix.tls.enabled);
+    #[test]
+    fn override_field_tls_enabled() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert!(!settings.actix.tls.enabled);
+        Settings::override_field(&mut settings.actix.tls.enabled, "true").unwrap();
+        assert!(settings.actix.tls.enabled);
     }
 
-    #[test]
-    fn override_field_with_env_var_tls_enabled() {
-        let mut settings = Settings::from_default_template().unwrap();
-        assert!(!settings.actix.tls.enabled);
-        std::env::set_var("OVERRIDE__TLS_ENABLED", "true");
-        Settings::override_field_with_env_var(
-            &mut settings.actix.tls.enabled,
+    #[test]
+    fn override_field_with_env_var_tls_enabled() {
+        let mut settings = Settings::from_default_template().unwrap();
+        assert!(!settings.actix.tls.enabled);
+        std::env::set_var("OVERRIDE__TLS_ENABLED", "true");
+        Settings::override_field_with_env_var(
+            &mut settings.actix.tls.enabled,
             "OVERRIDE__TLS_ENABLED",
         )
-        .unwrap();
-        assert!(settings.actix.tls.enabled);
+        .unwrap();
+        assert!(settings.actix.tls.enabled);
     }
 
-    #[test]
-    fn override_field_tls_certificate() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_tls_certificate() {
+        let mut settings = Settings::from_default_template().unwrap();
         assert_eq!(
-            settings.actix.tls.certificate,
-            Path::new("path/to/cert/cert.pem")
+            settings.actix.tls.certificate,
+            Path::new("path/to/cert/cert.pem")
         );
-        Settings::override_field(
-            &mut settings.actix.tls.certificate,
+        Settings::override_field(
+            &mut settings.actix.tls.certificate,
             "/overridden/path/to/cert/cert.pem",
         )
-        .unwrap();
+        .unwrap();
         assert_eq!(
-            settings.actix.tls.certificate,
-            Path::new("/overridden/path/to/cert/cert.pem")
+            settings.actix.tls.certificate,
+            Path::new("/overridden/path/to/cert/cert.pem")
         );
     }
 
-    #[test]
-    fn override_field_with_env_var_tls_certificate() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_with_env_var_tls_certificate() {
+        let mut settings = Settings::from_default_template().unwrap();
         assert_eq!(
-            settings.actix.tls.certificate,
-            Path::new("path/to/cert/cert.pem")
+            settings.actix.tls.certificate,
+            Path::new("path/to/cert/cert.pem")
         );
-        std::env::set_var(
+        std::env::set_var(
             "OVERRIDE__TLS_CERTIFICATE",
             "/overridden/path/to/cert/cert.pem",
         );
-        Settings::override_field_with_env_var(
-            &mut settings.actix.tls.certificate,
+        Settings::override_field_with_env_var(
+            &mut settings.actix.tls.certificate,
             "OVERRIDE__TLS_CERTIFICATE",
         )
-        .unwrap();
+        .unwrap();
         assert_eq!(
-            settings.actix.tls.certificate,
-            Path::new("/overridden/path/to/cert/cert.pem")
+            settings.actix.tls.certificate,
+            Path::new("/overridden/path/to/cert/cert.pem")
         );
     }
 
-    #[test]
-    fn override_field_tls_private_key() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_tls_private_key() {
+        let mut settings = Settings::from_default_template().unwrap();
         assert_eq!(
-            settings.actix.tls.private_key,
-            Path::new("path/to/cert/key.pem")
+            settings.actix.tls.private_key,
+            Path::new("path/to/cert/key.pem")
         );
-        Settings::override_field(
-            &mut settings.actix.tls.private_key,
+        Settings::override_field(
+            &mut settings.actix.tls.private_key,
             "/overridden/path/to/cert/key.pem",
         )
-        .unwrap();
+        .unwrap();
         assert_eq!(
-            settings.actix.tls.private_key,
-            Path::new("/overridden/path/to/cert/key.pem")
+            settings.actix.tls.private_key,
+            Path::new("/overridden/path/to/cert/key.pem")
         );
     }
 
-    #[test]
-    fn override_field_with_env_var_tls_private_key() {
-        let mut settings = Settings::from_default_template().unwrap();
+    #[test]
+    fn override_field_with_env_var_tls_private_key() {
+        let mut settings = Settings::from_default_template().unwrap();
         assert_eq!(
-            settings.actix.tls.private_key,
-            Path::new("path/to/cert/key.pem")
+            settings.actix.tls.private_key,
+            Path::new("path/to/cert/key.pem")
         );
-        std::env::set_var(
+        std::env::set_var(
             "OVERRIDE__TLS_PRIVATE_KEY",
             "/overridden/path/to/cert/key.pem",
         );
-        Settings::override_field_with_env_var(
-            &mut settings.actix.tls.private_key,
+        Settings::override_field_with_env_var(
+            &mut settings.actix.tls.private_key,
             "OVERRIDE__TLS_PRIVATE_KEY",
         )
-        .unwrap();
+        .unwrap();
         assert_eq!(
-            settings.actix.tls.private_key,
-            Path::new("/overridden/path/to/cert/key.pem")
+            settings.actix.tls.private_key,
+            Path::new("/overridden/path/to/cert/key.pem")
         );
     }
 
-    #[test]
-    fn override_extended_field_with_custom_type() {
-        #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
-        struct NestedSetting {
-            foo: String,
-            bar: bool,
+    #[test]
+    fn override_extended_field_with_custom_type() {
+        #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+        struct NestedSetting {
+            foo: String,
+            bar: bool,
         }
 
-        #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
-        #[serde(rename_all = "kebab-case")]
-        struct AppSettings {
-            example_name: String,
-            nested_field: NestedSetting,
+        #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+        #[serde(rename_all = "kebab-case")]
+        struct AppSettings {
+            example_name: String,
+            nested_field: NestedSetting,
         }
 
-        type CustomSettings = BasicSettings<AppSettings>;
+        type CustomSettings = BasicSettings<AppSettings>;
 
-        let mut settings = CustomSettings::from_template(
-            &(CustomSettings::DEFAULT_TOML_TEMPLATE.to_string()
-                // NOTE: Add these entries to the `[application]` table:
-                + "\nexample-name = \"example value\""
-                + "\nnested-field = { foo = \"foo\", bar = false }"),
+        let mut settings = CustomSettings::from_template(
+            &(CustomSettings::DEFAULT_TOML_TEMPLATE.to_string()
+                // NOTE: Add these entries to the `[application]` table:
+                + "\nexample-name = \"example value\""
+                + "\nnested-field = { foo = \"foo\", bar = false }"),
         )
-        .unwrap();
+        .unwrap();
 
         assert_eq!(
-            settings.application,
-            AppSettings {
-                example_name: "example value".into(),
-                nested_field: NestedSetting {
-                    foo: "foo".into(),
-                    bar: false,
+            settings.application,
+            AppSettings {
+                example_name: "example value".into(),
+                nested_field: NestedSetting {
+                    foo: "foo".into(),
+                    bar: false,
                 },
             }
         );
 
-        CustomSettings::override_field(
-            &mut settings.application.example_name,
+        CustomSettings::override_field(
+            &mut settings.application.example_name,
             "/overridden/path/to/cert/key.pem",
         )
-        .unwrap();
+        .unwrap();
 
         assert_eq!(
-            settings.application,
-            AppSettings {
-                example_name: "/overridden/path/to/cert/key.pem".into(),
-                nested_field: NestedSetting {
-                    foo: "foo".into(),
-                    bar: false,
+            settings.application,
+            AppSettings {
+                example_name: "/overridden/path/to/cert/key.pem".into(),
+                nested_field: NestedSetting {
+                    foo: "foo".into(),
+                    bar: false,
                 },
             }
         );
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/parse.rs.html b/src/actix_settings/parse.rs.html index 8175f8dd4..b5cf551b6 100644 --- a/src/actix_settings/parse.rs.html +++ b/src/actix_settings/parse.rs.html @@ -40,45 +40,45 @@ 38 39 40 -
use std::{path::PathBuf, str::FromStr};
+
use std::{path::PathBuf, str::FromStr};
 
-use crate::Error;
+use crate::Error;
 
-/// A specialized `FromStr` trait that returns [`AtError`] errors
-pub trait Parse: Sized {
-    /// Parse `Self` from `string`.
-    fn parse(string: &str) -> Result<Self, Error>;
+/// A specialized `FromStr` trait that returns [`AtError`] errors
+pub trait Parse: Sized {
+    /// Parse `Self` from `string`.
+    fn parse(string: &str) -> Result<Self, Error>;
 }
 
-impl Parse for bool {
-    fn parse(string: &str) -> Result<Self, Error> {
-        Self::from_str(string).map_err(Error::from)
+impl Parse for bool {
+    fn parse(string: &str) -> Result<Self, Error> {
+        Self::from_str(string).map_err(Error::from)
     }
 }
 
-macro_rules! impl_parse_for_int_type {
-    ($($int_type:ty),+ $(,)?) => {
+macro_rules! impl_parse_for_int_type {
+    ($($int_type:ty),+ $(,)?) => {
         $(
-            impl Parse for $int_type {
-                fn parse(string: &str) -> Result<Self, Error> {
-                    Self::from_str(string).map_err(Error::from)
+            impl Parse for $int_type {
+                fn parse(string: &str) -> Result<Self, Error> {
+                    Self::from_str(string).map_err(Error::from)
                 }
             }
-        )+
+        )+
     }
 }
-impl_parse_for_int_type![i8, i16, i32, i64, i128, u8, u16, u32, u64, u128];
+impl_parse_for_int_type![i8, i16, i32, i64, i128, u8, u16, u32, u64, u128];
 
-impl Parse for String {
-    fn parse(string: &str) -> Result<Self, Error> {
-        Ok(string.to_string())
+impl Parse for String {
+    fn parse(string: &str) -> Result<Self, Error> {
+        Ok(string.to_string())
     }
 }
 
-impl Parse for PathBuf {
-    fn parse(string: &str) -> Result<Self, Error> {
-        Ok(PathBuf::from(string))
+impl Parse for PathBuf {
+    fn parse(string: &str) -> Result<Self, Error> {
+        Ok(PathBuf::from(string))
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/address.rs.html b/src/actix_settings/settings/address.rs.html index 3effb2991..9f9358c54 100644 --- a/src/actix_settings/settings/address.rs.html +++ b/src/actix_settings/settings/address.rs.html @@ -93,14 +93,14 @@ 91 92 93 -
use once_cell::sync::Lazy;
-use regex::Regex;
-use serde::Deserialize;
+
use once_cell::sync::Lazy;
+use regex::Regex;
+use serde::Deserialize;
 
-use crate::{Error, Parse};
+use crate::{Error, Parse};
 
-static ADDR_REGEX: Lazy<Regex> = Lazy::new(|| {
-    Regex::new(
+static ADDR_REGEX: Lazy<Regex> = Lazy::new(|| {
+    Regex::new(
         r#"(?x)
         \[                     # opening square bracket
         (\s)*                  # optional whitespace
@@ -112,11 +112,11 @@
         \]                     # closing square bracket
     "#,
     )
-    .expect("Failed to compile regex: ADDR_REGEX")
+    .expect("Failed to compile regex: ADDR_REGEX")
 });
 
-static ADDR_LIST_REGEX: Lazy<Regex> = Lazy::new(|| {
-    Regex::new(
+static ADDR_LIST_REGEX: Lazy<Regex> = Lazy::new(|| {
+    Regex::new(
         r#"(?x)
         \[                           # opening square bracket (list)
         (\s)*                        # optional whitespace
@@ -129,62 +129,62 @@
         \]                           # closing square bracket (list)
     "#,
     )
-    .expect("Failed to compile regex: ADDRS_REGEX")
+    .expect("Failed to compile regex: ADDRS_REGEX")
 });
 
-/// A host/port pair for the server to bind to.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
-pub struct Address {
-    /// Host part of address.
-    pub host: String,
+/// A host/port pair for the server to bind to.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
+pub struct Address {
+    /// Host part of address.
+    pub host: String,
 
-    /// Port part of address.
-    pub port: u16,
+    /// Port part of address.
+    pub port: u16,
 }
 
-impl Parse for Address {
-    fn parse(string: &str) -> Result<Self, Error> {
-        let mut items = string
-            .trim()
-            .trim_start_matches('[')
-            .trim_end_matches(']')
-            .split(',');
+impl Parse for Address {
+    fn parse(string: &str) -> Result<Self, Error> {
+        let mut items = string
+            .trim()
+            .trim_start_matches('[')
+            .trim_end_matches(']')
+            .split(',');
 
-        let parse_error = || Error::ParseAddressError(string.to_string());
+        let parse_error = || Error::ParseAddressError(string.to_string());
 
-        if !ADDR_REGEX.is_match(string) {
-            return Err(parse_error());
+        if !ADDR_REGEX.is_match(string) {
+            return Err(parse_error());
         }
 
-        Ok(Self {
-            host: items.next().ok_or_else(parse_error)?.trim().to_string(),
-            port: items.next().ok_or_else(parse_error)?.trim().parse()?,
+        Ok(Self {
+            host: items.next().ok_or_else(parse_error)?.trim().to_string(),
+            port: items.next().ok_or_else(parse_error)?.trim().parse()?,
         })
     }
 }
 
-impl Parse for Vec<Address> {
-    fn parse(string: &str) -> Result<Self, Error> {
-        let parse_error = || Error::ParseAddressError(string.to_string());
+impl Parse for Vec<Address> {
+    fn parse(string: &str) -> Result<Self, Error> {
+        let parse_error = || Error::ParseAddressError(string.to_string());
 
-        if !ADDR_LIST_REGEX.is_match(string) {
-            return Err(parse_error());
+        if !ADDR_LIST_REGEX.is_match(string) {
+            return Err(parse_error());
         }
 
-        let mut addrs = vec![];
+        let mut addrs = vec![];
 
-        for list_caps in ADDR_LIST_REGEX.captures_iter(string) {
-            let elements = &list_caps["elements"].trim();
-            for elt_caps in ADDR_REGEX.captures_iter(elements) {
-                addrs.push(Address {
-                    host: elt_caps["host"].to_string(),
-                    port: elt_caps["port"].parse()?,
+        for list_caps in ADDR_LIST_REGEX.captures_iter(string) {
+            let elements = &list_caps["elements"].trim();
+            for elt_caps in ADDR_REGEX.captures_iter(elements) {
+                addrs.push(Address {
+                    host: elt_caps["host"].to_string(),
+                    port: elt_caps["port"].parse()?,
                 });
             }
         }
 
-        Ok(addrs)
+        Ok(addrs)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/backlog.rs.html b/src/actix_settings/settings/backlog.rs.html index caf42e941..7317b978e 100644 --- a/src/actix_settings/settings/backlog.rs.html +++ b/src/actix_settings/settings/backlog.rs.html @@ -70,75 +70,75 @@ 68 69 70 -
use std::fmt;
+
use std::fmt;
 
-use serde::de;
+use serde::de;
 
-use crate::{AsResult, Error, Parse};
+use crate::{AsResult, Error, Parse};
 
-/// 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. The default value is 2048. Takes a string value: Either
-/// "default", or an integer N > 0 e.g. "6".
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum Backlog {
-    /// The default number of connections. See struct docs.
-    Default,
+/// 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. The default value is 2048. Takes a string value: Either
+/// "default", or an integer N > 0 e.g. "6".
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum Backlog {
+    /// The default number of connections. See struct docs.
+    Default,
 
-    /// A specific number of connections.
-    Manual(usize),
+    /// A specific number of connections.
+    Manual(usize),
 }
 
-impl Parse for Backlog {
-    fn parse(string: &str) -> AsResult<Self> {
-        match string {
-            "default" => Ok(Backlog::Default),
-            string => match string.parse::<usize>() {
-                Ok(val) => Ok(Backlog::Manual(val)),
-                Err(_) => Err(InvalidValue! {
-                    expected: "an integer > 0",
-                    got: string,
+impl Parse for Backlog {
+    fn parse(string: &str) -> AsResult<Self> {
+        match string {
+            "default" => Ok(Backlog::Default),
+            string => match string.parse::<usize>() {
+                Ok(val) => Ok(Backlog::Manual(val)),
+                Err(_) => Err(InvalidValue! {
+                    expected: "an integer > 0",
+                    got: string,
                 }),
             },
         }
     }
 }
 
-impl<'de> de::Deserialize<'de> for Backlog {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: de::Deserializer<'de>,
+impl<'de> de::Deserialize<'de> for Backlog {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: de::Deserializer<'de>,
     {
-        struct BacklogVisitor;
+        struct BacklogVisitor;
 
-        impl<'de> de::Visitor<'de> for BacklogVisitor {
-            type Value = Backlog;
+        impl<'de> de::Visitor<'de> for BacklogVisitor {
+            type Value = Backlog;
 
-            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                let msg = "Either \"default\" or a string containing an integer > 0";
-                f.write_str(msg)
+            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                let msg = "Either \"default\" or a string containing an integer > 0";
+                f.write_str(msg)
             }
 
-            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
-            where
-                E: de::Error,
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+            where
+                E: de::Error,
             {
-                match Backlog::parse(value) {
-                    Ok(backlog) => Ok(backlog),
-                    Err(Error::InvalidValue { expected, got, .. }) => Err(
-                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
+                match Backlog::parse(value) {
+                    Ok(backlog) => Ok(backlog),
+                    Err(Error::InvalidValue { expected, got, .. }) => Err(
+                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
                     ),
                     Err(_) => unreachable!(),
                 }
             }
         }
 
-        deserializer.deserialize_string(BacklogVisitor)
+        deserializer.deserialize_string(BacklogVisitor)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/keep_alive.rs.html b/src/actix_settings/settings/keep_alive.rs.html index 8585a5432..564aac185 100644 --- a/src/actix_settings/settings/keep_alive.rs.html +++ b/src/actix_settings/settings/keep_alive.rs.html @@ -95,100 +95,100 @@ 93 94 95 -
use std::fmt;
+
use std::fmt;
 
-use once_cell::sync::Lazy;
-use regex::Regex;
-use serde::de;
+use once_cell::sync::Lazy;
+use regex::Regex;
+use serde::de;
 
-use crate::{AsResult, Error, Parse};
+use crate::{AsResult, Error, Parse};
 
-/// The server keep-alive preference.
-///
-/// By default keep alive is set to 5 seconds. Takes a string value: Either "default", "disabled",
-/// "os", or a string of the format "N seconds" where N is an integer > 0 e.g. "6 seconds".
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum KeepAlive {
-    /// The default keep-alive as defined by Actix Web.
-    Default,
+/// The server keep-alive preference.
+///
+/// By default keep alive is set to 5 seconds. Takes a string value: Either "default", "disabled",
+/// "os", or a string of the format "N seconds" where N is an integer > 0 e.g. "6 seconds".
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum KeepAlive {
+    /// The default keep-alive as defined by Actix Web.
+    Default,
 
-    /// Disable keep-alive.
-    Disabled,
+    /// Disable keep-alive.
+    Disabled,
 
-    /// Let the OS determine keep-alive duration.
-    ///
-    /// Note: this is usually quite long.
-    Os,
+    /// Let the OS determine keep-alive duration.
+    ///
+    /// Note: this is usually quite long.
+    Os,
 
-    /// A specific keep-alive duration (in seconds).
-    Seconds(usize),
+    /// A specific keep-alive duration (in seconds).
+    Seconds(usize),
 }
 
-impl Parse for KeepAlive {
-    fn parse(string: &str) -> AsResult<Self> {
-        pub(crate) static FMT: Lazy<Regex> =
-            Lazy::new(|| Regex::new(r"^\d+ seconds$").expect("Failed to compile regex: FMT"));
+impl Parse for KeepAlive {
+    fn parse(string: &str) -> AsResult<Self> {
+        pub(crate) static FMT: Lazy<Regex> =
+            Lazy::new(|| Regex::new(r"^\d+ seconds$").expect("Failed to compile regex: FMT"));
 
-        pub(crate) static DIGITS: Lazy<Regex> =
-            Lazy::new(|| Regex::new(r"^\d+").expect("Failed to compile regex: FMT"));
+        pub(crate) static DIGITS: Lazy<Regex> =
+            Lazy::new(|| Regex::new(r"^\d+").expect("Failed to compile regex: FMT"));
 
-        macro_rules! invalid_value {
-            ($got:expr) => {
-                Err(InvalidValue! {
-                    expected: "a string of the format \"N seconds\" where N is an integer > 0",
-                    got: $got,
+        macro_rules! invalid_value {
+            ($got:expr) => {
+                Err(InvalidValue! {
+                    expected: "a string of the format \"N seconds\" where N is an integer > 0",
+                    got: $got,
                 })
             };
         }
 
-        let digits_in = |m: regex::Match<'_>| &string[m.start()..m.end()];
-        match string {
-            "default" => Ok(KeepAlive::Default),
-            "disabled" => Ok(KeepAlive::Disabled),
-            "OS" | "os" => Ok(KeepAlive::Os),
-            string if !FMT.is_match(string) => invalid_value!(string),
-            string => match DIGITS.find(string) {
-                None => invalid_value!(string),
-                Some(mat) => match digits_in(mat).parse() {
-                    Ok(val) => Ok(KeepAlive::Seconds(val)),
-                    Err(_) => invalid_value!(string),
+        let digits_in = |m: regex::Match<'_>| &string[m.start()..m.end()];
+        match string {
+            "default" => Ok(KeepAlive::Default),
+            "disabled" => Ok(KeepAlive::Disabled),
+            "OS" | "os" => Ok(KeepAlive::Os),
+            string if !FMT.is_match(string) => invalid_value!(string),
+            string => match DIGITS.find(string) {
+                None => invalid_value!(string),
+                Some(mat) => match digits_in(mat).parse() {
+                    Ok(val) => Ok(KeepAlive::Seconds(val)),
+                    Err(_) => invalid_value!(string),
                 },
             },
         }
     }
 }
 
-impl<'de> de::Deserialize<'de> for KeepAlive {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: de::Deserializer<'de>,
+impl<'de> de::Deserialize<'de> for KeepAlive {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: de::Deserializer<'de>,
     {
-        struct KeepAliveVisitor;
+        struct KeepAliveVisitor;
 
-        impl<'de> de::Visitor<'de> for KeepAliveVisitor {
-            type Value = KeepAlive;
+        impl<'de> de::Visitor<'de> for KeepAliveVisitor {
+            type Value = KeepAlive;
 
-            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                let msg = "Either \"default\", \"disabled\", \"os\", or a string of the format \"N seconds\" where N is an integer > 0";
-                f.write_str(msg)
+            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                let msg = "Either \"default\", \"disabled\", \"os\", or a string of the format \"N seconds\" where N is an integer > 0";
+                f.write_str(msg)
             }
 
-            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
-            where
-                E: de::Error,
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+            where
+                E: de::Error,
             {
-                match KeepAlive::parse(value) {
-                    Ok(keep_alive) => Ok(keep_alive),
-                    Err(Error::InvalidValue { expected, got, .. }) => Err(
-                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
+                match KeepAlive::parse(value) {
+                    Ok(keep_alive) => Ok(keep_alive),
+                    Err(Error::InvalidValue { expected, got, .. }) => Err(
+                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
                     ),
                     Err(_) => unreachable!(),
                 }
             }
         }
 
-        deserializer.deserialize_string(KeepAliveVisitor)
+        deserializer.deserialize_string(KeepAliveVisitor)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/max_connection_rate.rs.html b/src/actix_settings/settings/max_connection_rate.rs.html index 39e9d6d59..7d2e47cd0 100644 --- a/src/actix_settings/settings/max_connection_rate.rs.html +++ b/src/actix_settings/settings/max_connection_rate.rs.html @@ -67,72 +67,72 @@ 65 66 67 -
use std::fmt;
+
use std::fmt;
 
-use serde::de;
+use serde::de;
 
-use crate::{AsResult, Error, Parse};
+use crate::{AsResult, Error, Parse};
 
-/// The maximum per-worker concurrent TLS connection limit.
-///
-/// All listeners will stop accepting connections when this limit is reached. It can be used to
-/// limit the global TLS CPU usage. By default max connections is set to a 256. Takes a string
-/// value: Either "default", or an integer N > 0 e.g. "6".
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum MaxConnectionRate {
-    /// The default connection limit. See struct docs.
-    Default,
+/// The maximum per-worker concurrent TLS connection limit.
+///
+/// All listeners will stop accepting connections when this limit is reached. It can be used to
+/// limit the global TLS CPU usage. By default max connections is set to a 256. Takes a string
+/// value: Either "default", or an integer N > 0 e.g. "6".
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum MaxConnectionRate {
+    /// The default connection limit. See struct docs.
+    Default,
 
-    /// A specific connection limit.
-    Manual(usize),
+    /// A specific connection limit.
+    Manual(usize),
 }
 
-impl Parse for MaxConnectionRate {
-    fn parse(string: &str) -> AsResult<Self> {
-        match string {
-            "default" => Ok(MaxConnectionRate::Default),
-            string => match string.parse::<usize>() {
-                Ok(val) => Ok(MaxConnectionRate::Manual(val)),
-                Err(_) => Err(InvalidValue! {
-                    expected: "an integer > 0",
-                    got: string,
+impl Parse for MaxConnectionRate {
+    fn parse(string: &str) -> AsResult<Self> {
+        match string {
+            "default" => Ok(MaxConnectionRate::Default),
+            string => match string.parse::<usize>() {
+                Ok(val) => Ok(MaxConnectionRate::Manual(val)),
+                Err(_) => Err(InvalidValue! {
+                    expected: "an integer > 0",
+                    got: string,
                 }),
             },
         }
     }
 }
 
-impl<'de> de::Deserialize<'de> for MaxConnectionRate {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: de::Deserializer<'de>,
+impl<'de> de::Deserialize<'de> for MaxConnectionRate {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: de::Deserializer<'de>,
     {
-        struct MaxConnectionRateVisitor;
+        struct MaxConnectionRateVisitor;
 
-        impl<'de> de::Visitor<'de> for MaxConnectionRateVisitor {
-            type Value = MaxConnectionRate;
+        impl<'de> de::Visitor<'de> for MaxConnectionRateVisitor {
+            type Value = MaxConnectionRate;
 
-            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                let msg = "Either \"default\" or a string containing an integer > 0";
-                f.write_str(msg)
+            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                let msg = "Either \"default\" or a string containing an integer > 0";
+                f.write_str(msg)
             }
 
-            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
-            where
-                E: de::Error,
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+            where
+                E: de::Error,
             {
-                match MaxConnectionRate::parse(value) {
-                    Ok(max_connection_rate) => Ok(max_connection_rate),
-                    Err(Error::InvalidValue { expected, got, .. }) => Err(
-                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
+                match MaxConnectionRate::parse(value) {
+                    Ok(max_connection_rate) => Ok(max_connection_rate),
+                    Err(Error::InvalidValue { expected, got, .. }) => Err(
+                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
                     ),
                     Err(_) => unreachable!(),
                 }
             }
         }
 
-        deserializer.deserialize_string(MaxConnectionRateVisitor)
+        deserializer.deserialize_string(MaxConnectionRateVisitor)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/max_connections.rs.html b/src/actix_settings/settings/max_connections.rs.html index 1bc014c46..575096f5d 100644 --- a/src/actix_settings/settings/max_connections.rs.html +++ b/src/actix_settings/settings/max_connections.rs.html @@ -67,72 +67,72 @@ 65 66 67 -
use std::fmt;
+
use std::fmt;
 
-use serde::de;
+use serde::de;
 
-use crate::{AsResult, Error, Parse};
+use crate::{AsResult, Error, Parse};
 
-/// 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. Takes a string value: Either "default", or an
-/// integer N > 0 e.g. "6".
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum MaxConnections {
-    /// The default number of connections. See struct docs.
-    Default,
+/// 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. Takes a string value: Either "default", or an
+/// integer N > 0 e.g. "6".
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum MaxConnections {
+    /// The default number of connections. See struct docs.
+    Default,
 
-    /// A specific number of connections.
-    Manual(usize),
+    /// A specific number of connections.
+    Manual(usize),
 }
 
-impl Parse for MaxConnections {
-    fn parse(string: &str) -> AsResult<Self> {
-        match string {
-            "default" => Ok(MaxConnections::Default),
-            string => match string.parse::<usize>() {
-                Ok(val) => Ok(MaxConnections::Manual(val)),
-                Err(_) => Err(InvalidValue! {
-                    expected: "an integer > 0",
-                    got: string,
+impl Parse for MaxConnections {
+    fn parse(string: &str) -> AsResult<Self> {
+        match string {
+            "default" => Ok(MaxConnections::Default),
+            string => match string.parse::<usize>() {
+                Ok(val) => Ok(MaxConnections::Manual(val)),
+                Err(_) => Err(InvalidValue! {
+                    expected: "an integer > 0",
+                    got: string,
                 }),
             },
         }
     }
 }
 
-impl<'de> de::Deserialize<'de> for MaxConnections {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: de::Deserializer<'de>,
+impl<'de> de::Deserialize<'de> for MaxConnections {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: de::Deserializer<'de>,
     {
-        struct MaxConnectionsVisitor;
+        struct MaxConnectionsVisitor;
 
-        impl<'de> de::Visitor<'de> for MaxConnectionsVisitor {
-            type Value = MaxConnections;
+        impl<'de> de::Visitor<'de> for MaxConnectionsVisitor {
+            type Value = MaxConnections;
 
-            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                let msg = "Either \"default\" or a string containing an integer > 0";
-                f.write_str(msg)
+            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                let msg = "Either \"default\" or a string containing an integer > 0";
+                f.write_str(msg)
             }
 
-            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
-            where
-                E: de::Error,
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+            where
+                E: de::Error,
             {
-                match MaxConnections::parse(value) {
-                    Ok(max_connections) => Ok(max_connections),
-                    Err(Error::InvalidValue { expected, got, .. }) => Err(
-                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
+                match MaxConnections::parse(value) {
+                    Ok(max_connections) => Ok(max_connections),
+                    Err(Error::InvalidValue { expected, got, .. }) => Err(
+                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
                     ),
                     Err(_) => unreachable!(),
                 }
             }
         }
 
-        deserializer.deserialize_string(MaxConnectionsVisitor)
+        deserializer.deserialize_string(MaxConnectionsVisitor)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/mod.rs.html b/src/actix_settings/settings/mod.rs.html index 101b10efb..79f4ce881 100644 --- a/src/actix_settings/settings/mod.rs.html +++ b/src/actix_settings/settings/mod.rs.html @@ -65,70 +65,70 @@ 63 64 65 -
use serde::Deserialize;
+
use serde::Deserialize;
 
-mod address;
-mod backlog;
-mod keep_alive;
-mod max_connection_rate;
-mod max_connections;
-mod mode;
-mod num_workers;
-mod timeout;
-mod tls;
+mod address;
+mod backlog;
+mod keep_alive;
+mod max_connection_rate;
+mod max_connections;
+mod mode;
+mod num_workers;
+mod timeout;
+mod tls;
 
-pub use self::address::Address;
-pub use self::backlog::Backlog;
-pub use self::keep_alive::KeepAlive;
-pub use self::max_connection_rate::MaxConnectionRate;
-pub use self::max_connections::MaxConnections;
-pub use self::mode::Mode;
-pub use self::num_workers::NumWorkers;
-pub use self::timeout::Timeout;
-pub use self::tls::Tls;
+pub use self::address::Address;
+pub use self::backlog::Backlog;
+pub use self::keep_alive::KeepAlive;
+pub use self::max_connection_rate::MaxConnectionRate;
+pub use self::max_connections::MaxConnections;
+pub use self::mode::Mode;
+pub use self::num_workers::NumWorkers;
+pub use self::timeout::Timeout;
+pub use self::tls::Tls;
 
-/// Settings types for Actix Web.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
-#[serde(rename_all = "kebab-case")]
-pub struct ActixSettings {
-    /// List of addresses for the server to bind to.
-    pub hosts: Vec<Address>,
+/// Settings types for Actix Web.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct ActixSettings {
+    /// List of addresses for the server to bind to.
+    pub hosts: Vec<Address>,
 
-    /// Marker of intended deployment environment.
-    pub mode: Mode,
+    /// Marker of intended deployment environment.
+    pub mode: Mode,
 
-    /// True if the [`Compress`](actix_web::middleware::Compress) middleware should be enabled.
-    pub enable_compression: bool,
+    /// True if the [`Compress`](actix_web::middleware::Compress) middleware should be enabled.
+    pub enable_compression: bool,
 
-    /// True if the [`Logger`](actix_web::middleware::Logger) middleware should be enabled.
-    pub enable_log: bool,
+    /// True if the [`Logger`](actix_web::middleware::Logger) middleware should be enabled.
+    pub enable_log: bool,
 
-    /// The number of workers that the server should start.
-    pub num_workers: NumWorkers,
+    /// The number of workers that the server should start.
+    pub num_workers: NumWorkers,
 
-    /// The maximum number of pending connections.
-    pub backlog: Backlog,
+    /// The maximum number of pending connections.
+    pub backlog: Backlog,
 
-    /// The per-worker maximum number of concurrent connections.
-    pub max_connections: MaxConnections,
+    /// The per-worker maximum number of concurrent connections.
+    pub max_connections: MaxConnections,
 
-    /// The per-worker maximum concurrent TLS connection limit.
-    pub max_connection_rate: MaxConnectionRate,
+    /// The per-worker maximum concurrent TLS connection limit.
+    pub max_connection_rate: MaxConnectionRate,
 
-    /// Server keep-alive preference.
-    pub keep_alive: KeepAlive,
+    /// Server keep-alive preference.
+    pub keep_alive: KeepAlive,
 
-    /// Timeout duration for reading client request header.
-    pub client_timeout: Timeout,
+    /// Timeout duration for reading client request header.
+    pub client_timeout: Timeout,
 
-    /// Timeout duration for connection shutdown.
-    pub client_shutdown: Timeout,
+    /// Timeout duration for connection shutdown.
+    pub client_shutdown: Timeout,
 
-    /// Timeout duration for graceful worker shutdown.
-    pub shutdown_timeout: Timeout,
+    /// Timeout duration for graceful worker shutdown.
+    pub shutdown_timeout: Timeout,
 
-    /// TLS (HTTPS) configuration.
-    pub tls: Tls,
+    /// TLS (HTTPS) configuration.
+    pub tls: Tls,
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/mode.rs.html b/src/actix_settings/settings/mode.rs.html index cc643f49c..ed2942216 100644 --- a/src/actix_settings/settings/mode.rs.html +++ b/src/actix_settings/settings/mode.rs.html @@ -27,32 +27,32 @@ 25 26 27 -
use serde::Deserialize;
+
use serde::Deserialize;
 
-use crate::{AsResult, Parse};
+use crate::{AsResult, Parse};
 
-/// Marker of intended deployment environment.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum Mode {
-    /// Marks development environment.
-    Development,
+/// Marker of intended deployment environment.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Mode {
+    /// Marks development environment.
+    Development,
 
-    /// Marks production environment.
-    Production,
+    /// Marks production environment.
+    Production,
 }
 
-impl Parse for Mode {
-    fn parse(string: &str) -> AsResult<Self> {
-        match string {
-            "development" => Ok(Self::Development),
-            "production" => Ok(Self::Production),
-            _ => Err(InvalidValue! {
-                expected: "\"development\" | \"production\".",
-                got: string,
+impl Parse for Mode {
+    fn parse(string: &str) -> AsResult<Self> {
+        match string {
+            "development" => Ok(Self::Development),
+            "production" => Ok(Self::Production),
+            _ => Err(InvalidValue! {
+                expected: "\"development\" | \"production\".",
+                got: string,
             }),
         }
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/num_workers.rs.html b/src/actix_settings/settings/num_workers.rs.html index 664628f36..ea6c172fe 100644 --- a/src/actix_settings/settings/num_workers.rs.html +++ b/src/actix_settings/settings/num_workers.rs.html @@ -66,71 +66,71 @@ 64 65 66 -
use std::fmt;
+
use std::fmt;
 
-use serde::de;
+use serde::de;
 
-use crate::{AsResult, Error, Parse};
+use crate::{AsResult, Error, Parse};
 
-/// The number of workers that the server should start.
-///
-/// By default the number of available logical cpu cores is used. Takes a string value: Either
-/// "default", or an integer N > 0 e.g. "6".
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum NumWorkers {
-    /// The default number of workers. See struct docs.
-    Default,
+/// The number of workers that the server should start.
+///
+/// By default the number of available logical cpu cores is used. Takes a string value: Either
+/// "default", or an integer N > 0 e.g. "6".
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum NumWorkers {
+    /// The default number of workers. See struct docs.
+    Default,
 
-    /// A specific number of workers.
-    Manual(usize),
+    /// A specific number of workers.
+    Manual(usize),
 }
 
-impl Parse for NumWorkers {
-    fn parse(string: &str) -> AsResult<Self> {
-        match string {
-            "default" => Ok(NumWorkers::Default),
-            string => match string.parse::<usize>() {
-                Ok(val) => Ok(NumWorkers::Manual(val)),
-                Err(_) => Err(InvalidValue! {
-                    expected: "a positive integer",
-                    got: string,
+impl Parse for NumWorkers {
+    fn parse(string: &str) -> AsResult<Self> {
+        match string {
+            "default" => Ok(NumWorkers::Default),
+            string => match string.parse::<usize>() {
+                Ok(val) => Ok(NumWorkers::Manual(val)),
+                Err(_) => Err(InvalidValue! {
+                    expected: "a positive integer",
+                    got: string,
                 }),
             },
         }
     }
 }
 
-impl<'de> de::Deserialize<'de> for NumWorkers {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: de::Deserializer<'de>,
+impl<'de> de::Deserialize<'de> for NumWorkers {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: de::Deserializer<'de>,
     {
-        struct NumWorkersVisitor;
+        struct NumWorkersVisitor;
 
-        impl<'de> de::Visitor<'de> for NumWorkersVisitor {
-            type Value = NumWorkers;
+        impl<'de> de::Visitor<'de> for NumWorkersVisitor {
+            type Value = NumWorkers;
 
-            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                let msg = "Either \"default\" or a string containing an integer > 0";
-                f.write_str(msg)
+            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                let msg = "Either \"default\" or a string containing an integer > 0";
+                f.write_str(msg)
             }
 
-            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
-            where
-                E: de::Error,
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+            where
+                E: de::Error,
             {
-                match NumWorkers::parse(value) {
-                    Ok(num_workers) => Ok(num_workers),
-                    Err(Error::InvalidValue { expected, got, .. }) => Err(
-                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
+                match NumWorkers::parse(value) {
+                    Ok(num_workers) => Ok(num_workers),
+                    Err(Error::InvalidValue { expected, got, .. }) => Err(
+                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
                     ),
                     Err(_) => unreachable!(),
                 }
             }
         }
 
-        deserializer.deserialize_string(NumWorkersVisitor)
+        deserializer.deserialize_string(NumWorkersVisitor)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/timeout.rs.html b/src/actix_settings/settings/timeout.rs.html index 9a4c97f05..100e7f15d 100644 --- a/src/actix_settings/settings/timeout.rs.html +++ b/src/actix_settings/settings/timeout.rs.html @@ -98,65 +98,65 @@ 96 97 98 -
use std::fmt;
+
use std::fmt;
 
-use once_cell::sync::Lazy;
-use regex::Regex;
-use serde::de;
+use once_cell::sync::Lazy;
+use regex::Regex;
+use serde::de;
 
-use crate::{AsResult, Error, Parse};
+use crate::{AsResult, Error, Parse};
 
-/// A timeout duration in milliseconds or seconds.
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum Timeout {
-    /// The default timeout. Depends on context.
-    Default,
+/// A timeout duration in milliseconds or seconds.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum Timeout {
+    /// The default timeout. Depends on context.
+    Default,
 
-    /// Timeout in milliseconds.
-    Milliseconds(usize),
+    /// Timeout in milliseconds.
+    Milliseconds(usize),
 
-    /// Timeout in seconds.
-    Seconds(usize),
+    /// Timeout in seconds.
+    Seconds(usize),
 }
 
-impl Parse for Timeout {
-    fn parse(string: &str) -> AsResult<Self> {
-        pub static FMT: Lazy<Regex> = Lazy::new(|| {
-            Regex::new(r"^\d+ (milliseconds|seconds)$").expect("Failed to compile regex: FMT")
+impl Parse for Timeout {
+    fn parse(string: &str) -> AsResult<Self> {
+        pub static FMT: Lazy<Regex> = Lazy::new(|| {
+            Regex::new(r"^\d+ (milliseconds|seconds)$").expect("Failed to compile regex: FMT")
         });
 
-        pub static DIGITS: Lazy<Regex> =
-            Lazy::new(|| Regex::new(r"^\d+").expect("Failed to compile regex: DIGITS"));
+        pub static DIGITS: Lazy<Regex> =
+            Lazy::new(|| Regex::new(r"^\d+").expect("Failed to compile regex: DIGITS"));
 
-        pub static UNIT: Lazy<Regex> = Lazy::new(|| {
-            Regex::new(r"(milliseconds|seconds)$").expect("Failed to compile regex: UNIT")
+        pub static UNIT: Lazy<Regex> = Lazy::new(|| {
+            Regex::new(r"(milliseconds|seconds)$").expect("Failed to compile regex: UNIT")
         });
 
-        macro_rules! invalid_value {
-            ($got:expr) => {
-                Err(InvalidValue! {
-                    expected: "a string of the format \"N seconds\" or \"N milliseconds\" where N is an integer > 0",
-                    got: $got,
+        macro_rules! invalid_value {
+            ($got:expr) => {
+                Err(InvalidValue! {
+                    expected: "a string of the format \"N seconds\" or \"N milliseconds\" where N is an integer > 0",
+                    got: $got,
                 })
             }
         }
 
-        match string {
-            "default" => Ok(Timeout::Default),
+        match string {
+            "default" => Ok(Timeout::Default),
 
-            string if !FMT.is_match(string) => invalid_value!(string),
+            string if !FMT.is_match(string) => invalid_value!(string),
 
-            string => match (DIGITS.find(string), UNIT.find(string)) {
-                (None, _) | (_, None) => invalid_value!(string),
+            string => match (DIGITS.find(string), UNIT.find(string)) {
+                (None, _) | (_, None) => invalid_value!(string),
 
-                (Some(digits), Some(unit)) => {
-                    let digits = &string[digits.range()];
-                    let unit = &string[unit.range()];
+                (Some(digits), Some(unit)) => {
+                    let digits = &string[digits.range()];
+                    let unit = &string[unit.range()];
 
-                    match (digits.parse(), unit) {
-                        (Ok(n), "milliseconds") => Ok(Timeout::Milliseconds(n)),
-                        (Ok(n), "seconds") => Ok(Timeout::Seconds(n)),
-                        _ => invalid_value!(string),
+                    match (digits.parse(), unit) {
+                        (Ok(n), "milliseconds") => Ok(Timeout::Milliseconds(n)),
+                        (Ok(n), "seconds") => Ok(Timeout::Seconds(n)),
+                        _ => invalid_value!(string),
                     }
                 }
             },
@@ -164,37 +164,37 @@
     }
 }
 
-impl<'de> de::Deserialize<'de> for Timeout {
-    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
-    where
-        D: de::Deserializer<'de>,
+impl<'de> de::Deserialize<'de> for Timeout {
+    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+    where
+        D: de::Deserializer<'de>,
     {
-        struct TimeoutVisitor;
+        struct TimeoutVisitor;
 
-        impl<'de> de::Visitor<'de> for TimeoutVisitor {
-            type Value = Timeout;
+        impl<'de> de::Visitor<'de> for TimeoutVisitor {
+            type Value = Timeout;
 
-            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                let msg = "Either \"default\", \"disabled\", \"os\", or a string of the format \"N seconds\" where N is an integer > 0";
-                f.write_str(msg)
+            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                let msg = "Either \"default\", \"disabled\", \"os\", or a string of the format \"N seconds\" where N is an integer > 0";
+                f.write_str(msg)
             }
 
-            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
-            where
-                E: de::Error,
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+            where
+                E: de::Error,
             {
-                match Timeout::parse(value) {
-                    Ok(num_workers) => Ok(num_workers),
-                    Err(Error::InvalidValue { expected, got, .. }) => Err(
-                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
+                match Timeout::parse(value) {
+                    Ok(num_workers) => Ok(num_workers),
+                    Err(Error::InvalidValue { expected, got, .. }) => Err(
+                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
                     ),
                     Err(_) => unreachable!(),
                 }
             }
         }
 
-        deserializer.deserialize_string(TimeoutVisitor)
+        deserializer.deserialize_string(TimeoutVisitor)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_settings/settings/tls.rs.html b/src/actix_settings/settings/tls.rs.html index 3cde02929..783751da7 100644 --- a/src/actix_settings/settings/tls.rs.html +++ b/src/actix_settings/settings/tls.rs.html @@ -18,23 +18,23 @@ 16 17 18 -
use std::path::PathBuf;
+
use std::path::PathBuf;
 
-use serde::Deserialize;
+use serde::Deserialize;
 
-/// TLS (HTTPS) configuration.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
-#[serde(rename_all = "kebab-case")]
-#[doc(alias = "ssl", alias = "https")]
-pub struct Tls {
-    /// Tru if accepting TLS connections should be enabled.
-    pub enabled: bool,
+/// TLS (HTTPS) configuration.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+#[doc(alias = "ssl", alias = "https")]
+pub struct Tls {
+    /// Tru if accepting TLS connections should be enabled.
+    pub enabled: bool,
 
-    /// Path to certificate `.pem` file.
-    pub certificate: PathBuf,
+    /// Path to certificate `.pem` file.
+    pub certificate: PathBuf,
 
-    /// Path to private key `.pem` file.
-    pub private_key: PathBuf,
+    /// Path to private key `.pem` file.
+    pub private_key: PathBuf,
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/extractors/basic.rs.html b/src/actix_web_httpauth/extractors/basic.rs.html index c028cf98f..fd23fbf37 100644 --- a/src/actix_web_httpauth/extractors/basic.rs.html +++ b/src/actix_web_httpauth/extractors/basic.rs.html @@ -110,117 +110,117 @@ 110 111 112 -
//! Extractor for the "Basic" HTTP Authentication Scheme.
+
//! Extractor for the "Basic" HTTP Authentication Scheme.
 
-use std::borrow::Cow;
+use std::borrow::Cow;
 
-use actix_utils::future::{ready, Ready};
-use actix_web::{dev::Payload, http::header::Header, FromRequest, HttpRequest};
+use actix_utils::future::{ready, Ready};
+use actix_web::{dev::Payload, http::header::Header, FromRequest, HttpRequest};
 
-use super::{config::AuthExtractorConfig, errors::AuthenticationError};
-use crate::headers::{
-    authorization::{Authorization, Basic},
-    www_authenticate::basic::Basic as Challenge,
+use super::{config::AuthExtractorConfig, errors::AuthenticationError};
+use crate::headers::{
+    authorization::{Authorization, Basic},
+    www_authenticate::basic::Basic as Challenge,
 };
 
-/// [`BasicAuth`] extractor configuration used for [`WWW-Authenticate`] header later.
-///
-/// [`WWW-Authenticate`]: crate::headers::www_authenticate::WwwAuthenticate
-#[derive(Debug, Clone, Default)]
-pub struct Config(Challenge);
+/// [`BasicAuth`] extractor configuration used for [`WWW-Authenticate`] header later.
+///
+/// [`WWW-Authenticate`]: crate::headers::www_authenticate::WwwAuthenticate
+#[derive(Debug, Clone, Default)]
+pub struct Config(Challenge);
 
-impl Config {
-    /// Set challenge `realm` attribute.
-    ///
-    /// The "realm" attribute indicates the scope of protection in the manner described in HTTP/1.1
-    /// [RFC 2617 §1.2](https://tools.ietf.org/html/rfc2617#section-1.2).
-    pub fn realm<T>(mut self, value: T) -> Config
-    where
-        T: Into<Cow<'static, str>>,
+impl Config {
+    /// Set challenge `realm` attribute.
+    ///
+    /// The "realm" attribute indicates the scope of protection in the manner described in HTTP/1.1
+    /// [RFC 2617 §1.2](https://tools.ietf.org/html/rfc2617#section-1.2).
+    pub fn realm<T>(mut self, value: T) -> Config
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.0.realm = Some(value.into());
-        self
+        self.0.realm = Some(value.into());
+        self
+    }
+}
+
+impl AsRef<Challenge> for Config {
+    fn as_ref(&self) -> &Challenge {
+        &self.0
+    }
+}
+
+impl AuthExtractorConfig for Config {
+    type Inner = Challenge;
+
+    fn into_inner(self) -> Self::Inner {
+        self.0
+    }
+}
+
+/// Extractor for HTTP Basic auth.
+///
+/// # Examples
+/// ```
+/// use actix_web_httpauth::extractors::basic::BasicAuth;
+///
+/// async fn index(auth: BasicAuth) -> String {
+///     format!("Hello, {}!", auth.user_id())
+/// }
+/// ```
+///
+/// If authentication fails, this extractor fetches the [`Config`] instance from the [app data] in
+/// order to properly form the `WWW-Authenticate` response header.
+///
+/// # Examples
+/// ```
+/// use actix_web::{web, App};
+/// use actix_web_httpauth::extractors::basic::{self, BasicAuth};
+///
+/// async fn index(auth: BasicAuth) -> String {
+///     format!("Hello, {}!", auth.user_id())
+/// }
+///
+/// App::new()
+///     .app_data(basic::Config::default().realm("Restricted area"))
+///     .service(web::resource("/index.html").route(web::get().to(index)));
+/// ```
+///
+/// [app data]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.app_data
+#[derive(Debug, Clone)]
+pub struct BasicAuth(Basic);
+
+impl BasicAuth {
+    /// Returns client's user-ID.
+    pub fn user_id(&self) -> &str {
+        self.0.user_id()
+    }
+
+    /// Returns client's password.
+    pub fn password(&self) -> Option<&str> {
+        self.0.password()
     }
 }
 
-impl AsRef<Challenge> for Config {
-    fn as_ref(&self) -> &Challenge {
-        &self.0
-    }
-}
+impl FromRequest for BasicAuth {
+    type Future = Ready<Result<Self, Self::Error>>;
+    type Error = AuthenticationError<Challenge>;
 
-impl AuthExtractorConfig for Config {
-    type Inner = Challenge;
+    fn from_request(req: &HttpRequest, _: &mut Payload) -> <Self as FromRequest>::Future {
+        ready(
+            Authorization::<Basic>::parse(req)
+                .map(|auth| BasicAuth(auth.into_scheme()))
+                .map_err(|err| {
+                    log::debug!("`BasicAuth` extract error: {}", err);
 
-    fn into_inner(self) -> Self::Inner {
-        self.0
-    }
-}
+                    let challenge = req
+                        .app_data::<Config>()
+                        .map(|config| config.0.clone())
+                        .unwrap_or_default();
 
-/// Extractor for HTTP Basic auth.
-///
-/// # Examples
-/// ```
-/// use actix_web_httpauth::extractors::basic::BasicAuth;
-///
-/// async fn index(auth: BasicAuth) -> String {
-///     format!("Hello, {}!", auth.user_id())
-/// }
-/// ```
-///
-/// If authentication fails, this extractor fetches the [`Config`] instance from the [app data] in
-/// order to properly form the `WWW-Authenticate` response header.
-///
-/// # Examples
-/// ```
-/// use actix_web::{web, App};
-/// use actix_web_httpauth::extractors::basic::{self, BasicAuth};
-///
-/// async fn index(auth: BasicAuth) -> String {
-///     format!("Hello, {}!", auth.user_id())
-/// }
-///
-/// App::new()
-///     .app_data(basic::Config::default().realm("Restricted area"))
-///     .service(web::resource("/index.html").route(web::get().to(index)));
-/// ```
-///
-/// [app data]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.app_data
-#[derive(Debug, Clone)]
-pub struct BasicAuth(Basic);
-
-impl BasicAuth {
-    /// Returns client's user-ID.
-    pub fn user_id(&self) -> &str {
-        self.0.user_id()
-    }
-
-    /// Returns client's password.
-    pub fn password(&self) -> Option<&str> {
-        self.0.password()
-    }
-}
-
-impl FromRequest for BasicAuth {
-    type Future = Ready<Result<Self, Self::Error>>;
-    type Error = AuthenticationError<Challenge>;
-
-    fn from_request(req: &HttpRequest, _: &mut Payload) -> <Self as FromRequest>::Future {
-        ready(
-            Authorization::<Basic>::parse(req)
-                .map(|auth| BasicAuth(auth.into_scheme()))
-                .map_err(|err| {
-                    log::debug!("`BasicAuth` extract error: {}", err);
-
-                    let challenge = req
-                        .app_data::<Config>()
-                        .map(|config| config.0.clone())
-                        .unwrap_or_default();
-
-                    AuthenticationError::new(challenge)
+                    AuthenticationError::new(challenge)
                 }),
         )
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/extractors/bearer.rs.html b/src/actix_web_httpauth/extractors/bearer.rs.html index 77a32f465..26c43d461 100644 --- a/src/actix_web_httpauth/extractors/bearer.rs.html +++ b/src/actix_web_httpauth/extractors/bearer.rs.html @@ -142,149 +142,149 @@ 142 143 144 -
//! Extractor for the "Bearer" HTTP Authentication Scheme.
+
//! Extractor for the "Bearer" HTTP Authentication Scheme.
 
-use std::{borrow::Cow, default::Default};
+use std::{borrow::Cow, default::Default};
 
-use actix_utils::future::{ready, Ready};
-use actix_web::{dev::Payload, http::header::Header, FromRequest, HttpRequest};
+use actix_utils::future::{ready, Ready};
+use actix_web::{dev::Payload, http::header::Header, FromRequest, HttpRequest};
 
-use super::{config::AuthExtractorConfig, errors::AuthenticationError};
-pub use crate::headers::www_authenticate::bearer::Error;
-use crate::headers::{authorization, www_authenticate::bearer};
+use super::{config::AuthExtractorConfig, errors::AuthenticationError};
+pub use crate::headers::www_authenticate::bearer::Error;
+use crate::headers::{authorization, www_authenticate::bearer};
 
-/// [`BearerAuth`] extractor configuration.
-#[derive(Debug, Clone, Default)]
-pub struct Config(bearer::Bearer);
+/// [`BearerAuth`] extractor configuration.
+#[derive(Debug, Clone, Default)]
+pub struct Config(bearer::Bearer);
 
-impl Config {
-    /// Set challenge `scope` attribute.
-    ///
-    /// The `"scope"` attribute is a space-delimited list of case-sensitive
-    /// scope values indicating the required scope of the access token for
-    /// accessing the requested resource.
-    pub fn scope<T: Into<Cow<'static, str>>>(mut self, value: T) -> Config {
-        self.0.scope = Some(value.into());
-        self
-    }
+impl Config {
+    /// Set challenge `scope` attribute.
+    ///
+    /// The `"scope"` attribute is a space-delimited list of case-sensitive
+    /// scope values indicating the required scope of the access token for
+    /// accessing the requested resource.
+    pub fn scope<T: Into<Cow<'static, str>>>(mut self, value: T) -> Config {
+        self.0.scope = Some(value.into());
+        self
+    }
 
-    /// Set challenge `realm` attribute.
-    ///
-    /// The "realm" attribute indicates the scope of protection in the manner
-    /// described in HTTP/1.1 [RFC 2617](https://tools.ietf.org/html/rfc2617#section-1.2).
-    pub fn realm<T: Into<Cow<'static, str>>>(mut self, value: T) -> Config {
-        self.0.realm = Some(value.into());
-        self
+    /// Set challenge `realm` attribute.
+    ///
+    /// The "realm" attribute indicates the scope of protection in the manner
+    /// described in HTTP/1.1 [RFC 2617](https://tools.ietf.org/html/rfc2617#section-1.2).
+    pub fn realm<T: Into<Cow<'static, str>>>(mut self, value: T) -> Config {
+        self.0.realm = Some(value.into());
+        self
+    }
+}
+
+impl AsRef<bearer::Bearer> for Config {
+    fn as_ref(&self) -> &bearer::Bearer {
+        &self.0
+    }
+}
+
+impl AuthExtractorConfig for Config {
+    type Inner = bearer::Bearer;
+
+    fn into_inner(self) -> Self::Inner {
+        self.0
+    }
+}
+
+/// Extractor for HTTP Bearer auth
+///
+/// # Examples
+/// ```
+/// use actix_web_httpauth::extractors::bearer::BearerAuth;
+///
+/// async fn index(auth: BearerAuth) -> String {
+///     format!("Hello, user with token {}!", auth.token())
+/// }
+/// ```
+///
+/// If authentication fails, this extractor fetches the [`Config`] instance
+/// from the [app data] in order to properly form the `WWW-Authenticate`
+/// response header.
+///
+/// # Examples
+/// ```
+/// use actix_web::{web, App};
+/// use actix_web_httpauth::extractors::bearer::{self, BearerAuth};
+///
+/// async fn index(auth: BearerAuth) -> String {
+///     format!("Hello, {}!", auth.token())
+/// }
+///
+/// App::new()
+///     .app_data(
+///         bearer::Config::default()
+///             .realm("Restricted area")
+///             .scope("email photo"),
+///     )
+///     .service(web::resource("/index.html").route(web::get().to(index)));
+/// ```
+#[derive(Debug, Clone)]
+pub struct BearerAuth(authorization::Bearer);
+
+impl BearerAuth {
+    /// Returns bearer token provided by client.
+    pub fn token(&self) -> &str {
+        self.0.token()
     }
 }
 
-impl AsRef<bearer::Bearer> for Config {
-    fn as_ref(&self) -> &bearer::Bearer {
-        &self.0
-    }
-}
+impl FromRequest for BearerAuth {
+    type Future = Ready<Result<Self, Self::Error>>;
+    type Error = AuthenticationError<bearer::Bearer>;
 
-impl AuthExtractorConfig for Config {
-    type Inner = bearer::Bearer;
+    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> <Self as FromRequest>::Future {
+        ready(
+            authorization::Authorization::<authorization::Bearer>::parse(req)
+                .map(|auth| BearerAuth(auth.into_scheme()))
+                .map_err(|_| {
+                    let bearer = req
+                        .app_data::<Config>()
+                        .map(|config| config.0.clone())
+                        .unwrap_or_else(Default::default);
 
-    fn into_inner(self) -> Self::Inner {
-        self.0
-    }
-}
-
-/// Extractor for HTTP Bearer auth
-///
-/// # Examples
-/// ```
-/// use actix_web_httpauth::extractors::bearer::BearerAuth;
-///
-/// async fn index(auth: BearerAuth) -> String {
-///     format!("Hello, user with token {}!", auth.token())
-/// }
-/// ```
-///
-/// If authentication fails, this extractor fetches the [`Config`] instance
-/// from the [app data] in order to properly form the `WWW-Authenticate`
-/// response header.
-///
-/// # Examples
-/// ```
-/// use actix_web::{web, App};
-/// use actix_web_httpauth::extractors::bearer::{self, BearerAuth};
-///
-/// async fn index(auth: BearerAuth) -> String {
-///     format!("Hello, {}!", auth.token())
-/// }
-///
-/// App::new()
-///     .app_data(
-///         bearer::Config::default()
-///             .realm("Restricted area")
-///             .scope("email photo"),
-///     )
-///     .service(web::resource("/index.html").route(web::get().to(index)));
-/// ```
-#[derive(Debug, Clone)]
-pub struct BearerAuth(authorization::Bearer);
-
-impl BearerAuth {
-    /// Returns bearer token provided by client.
-    pub fn token(&self) -> &str {
-        self.0.token()
-    }
-}
-
-impl FromRequest for BearerAuth {
-    type Future = Ready<Result<Self, Self::Error>>;
-    type Error = AuthenticationError<bearer::Bearer>;
-
-    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> <Self as FromRequest>::Future {
-        ready(
-            authorization::Authorization::<authorization::Bearer>::parse(req)
-                .map(|auth| BearerAuth(auth.into_scheme()))
-                .map_err(|_| {
-                    let bearer = req
-                        .app_data::<Config>()
-                        .map(|config| config.0.clone())
-                        .unwrap_or_else(Default::default);
-
-                    AuthenticationError::new(bearer)
+                    AuthenticationError::new(bearer)
                 }),
         )
     }
 }
 
-/// Extended error customization for HTTP `Bearer` auth.
-impl AuthenticationError<bearer::Bearer> {
-    /// Attach `Error` to the current Authentication error.
-    ///
-    /// Error status code will be changed to the one provided by the `kind`
-    /// Error.
-    pub fn with_error(mut self, kind: Error) -> Self {
-        *self.status_code_mut() = kind.status_code();
-        self.challenge_mut().error = Some(kind);
-        self
-    }
+/// Extended error customization for HTTP `Bearer` auth.
+impl AuthenticationError<bearer::Bearer> {
+    /// Attach `Error` to the current Authentication error.
+    ///
+    /// Error status code will be changed to the one provided by the `kind`
+    /// Error.
+    pub fn with_error(mut self, kind: Error) -> Self {
+        *self.status_code_mut() = kind.status_code();
+        self.challenge_mut().error = Some(kind);
+        self
+    }
 
-    /// Attach error description to the current Authentication error.
-    pub fn with_error_description<T>(mut self, desc: T) -> Self
-    where
-        T: Into<Cow<'static, str>>,
+    /// Attach error description to the current Authentication error.
+    pub fn with_error_description<T>(mut self, desc: T) -> Self
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.challenge_mut().error_description = Some(desc.into());
-        self
-    }
+        self.challenge_mut().error_description = Some(desc.into());
+        self
+    }
 
-    /// Attach error URI to the current Authentication error.
-    ///
-    /// It is up to implementor to provide properly formed absolute URI.
-    pub fn with_error_uri<T>(mut self, uri: T) -> Self
-    where
-        T: Into<Cow<'static, str>>,
+    /// Attach error URI to the current Authentication error.
+    ///
+    /// It is up to implementor to provide properly formed absolute URI.
+    pub fn with_error_uri<T>(mut self, uri: T) -> Self
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.challenge_mut().error_uri = Some(uri.into());
-        self
-    }
+        self.challenge_mut().error_uri = Some(uri.into());
+        self
+    }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/extractors/config.rs.html b/src/actix_web_httpauth/extractors/config.rs.html index d3564567c..122638287 100644 --- a/src/actix_web_httpauth/extractors/config.rs.html +++ b/src/actix_web_httpauth/extractors/config.rs.html @@ -19,26 +19,26 @@ 19 20 21 -
use super::AuthenticationError;
-use crate::headers::www_authenticate::Challenge;
+
use super::AuthenticationError;
+use crate::headers::www_authenticate::Challenge;
 
-/// Trait implemented for types that provides configuration for the authentication
-/// [extractors](super::AuthExtractor).
-pub trait AuthExtractorConfig {
-    /// Associated challenge type.
-    type Inner: Challenge;
+/// Trait implemented for types that provides configuration for the authentication
+/// [extractors](super::AuthExtractor).
+pub trait AuthExtractorConfig {
+    /// Associated challenge type.
+    type Inner: Challenge;
 
-    /// Convert the config instance into a HTTP challenge.
-    fn into_inner(self) -> Self::Inner;
+    /// Convert the config instance into a HTTP challenge.
+    fn into_inner(self) -> Self::Inner;
 }
 
-impl<T> From<T> for AuthenticationError<<T as AuthExtractorConfig>::Inner>
-where
-    T: AuthExtractorConfig,
+impl<T> From<T> for AuthenticationError<<T as AuthExtractorConfig>::Inner>
+where
+    T: AuthExtractorConfig,
 {
-    fn from(config: T) -> Self {
-        AuthenticationError::new(config.into_inner())
+    fn from(config: T) -> Self {
+        AuthenticationError::new(config.into_inner())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/extractors/errors.rs.html b/src/actix_web_httpauth/extractors/errors.rs.html index ae2547942..40cd17f8a 100644 --- a/src/actix_web_httpauth/extractors/errors.rs.html +++ b/src/actix_web_httpauth/extractors/errors.rs.html @@ -77,84 +77,84 @@ 77 78 79 -
use std::{error::Error, fmt};
+
use std::{error::Error, fmt};
 
-use actix_web::{http::StatusCode, HttpResponse, ResponseError};
+use actix_web::{http::StatusCode, HttpResponse, ResponseError};
 
-use crate::headers::www_authenticate::{Challenge, WwwAuthenticate};
+use crate::headers::www_authenticate::{Challenge, WwwAuthenticate};
 
-/// Authentication error returned by authentication extractors.
-///
-/// Different extractors may extend `AuthenticationError` implementation in order to provide access
-/// inner challenge fields.
-#[derive(Debug)]
-pub struct AuthenticationError<C: Challenge> {
-    challenge: C,
-    status_code: StatusCode,
+/// Authentication error returned by authentication extractors.
+///
+/// Different extractors may extend `AuthenticationError` implementation in order to provide access
+/// inner challenge fields.
+#[derive(Debug)]
+pub struct AuthenticationError<C: Challenge> {
+    challenge: C,
+    status_code: StatusCode,
 }
 
-impl<C: Challenge> AuthenticationError<C> {
-    /// Creates new authentication error from the provided `challenge`.
-    ///
-    /// By default returned error will resolve into the `HTTP 401` status code.
-    pub fn new(challenge: C) -> AuthenticationError<C> {
-        AuthenticationError {
-            challenge,
-            status_code: StatusCode::UNAUTHORIZED,
+impl<C: Challenge> AuthenticationError<C> {
+    /// Creates new authentication error from the provided `challenge`.
+    ///
+    /// By default returned error will resolve into the `HTTP 401` status code.
+    pub fn new(challenge: C) -> AuthenticationError<C> {
+        AuthenticationError {
+            challenge,
+            status_code: StatusCode::UNAUTHORIZED,
         }
     }
 
-    /// Returns mutable reference to the inner challenge instance.
-    pub fn challenge_mut(&mut self) -> &mut C {
-        &mut self.challenge
+    /// Returns mutable reference to the inner challenge instance.
+    pub fn challenge_mut(&mut self) -> &mut C {
+        &mut self.challenge
     }
 
-    /// Returns mutable reference to the inner status code.
-    ///
-    /// Can be used to override returned status code, but by default this lib tries to stick to the
-    /// RFC, so it might be unreasonable.
-    pub fn status_code_mut(&mut self) -> &mut StatusCode {
-        &mut self.status_code
+    /// Returns mutable reference to the inner status code.
+    ///
+    /// Can be used to override returned status code, but by default this lib tries to stick to the
+    /// RFC, so it might be unreasonable.
+    pub fn status_code_mut(&mut self) -> &mut StatusCode {
+        &mut self.status_code
     }
 }
 
-impl<C: Challenge> fmt::Display for AuthenticationError<C> {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        fmt::Display::fmt(&self.status_code, f)
+impl<C: Challenge> fmt::Display for AuthenticationError<C> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt::Display::fmt(&self.status_code, f)
     }
 }
 
-impl<C: Challenge + 'static> Error for AuthenticationError<C> {}
+impl<C: Challenge + 'static> Error for AuthenticationError<C> {}
 
-impl<C: Challenge + 'static> ResponseError for AuthenticationError<C> {
-    fn status_code(&self) -> StatusCode {
-        self.status_code
+impl<C: Challenge + 'static> ResponseError for AuthenticationError<C> {
+    fn status_code(&self) -> StatusCode {
+        self.status_code
     }
 
-    fn error_response(&self) -> HttpResponse {
-        HttpResponse::build(self.status_code())
-            .insert_header(WwwAuthenticate(self.challenge.clone()))
-            .finish()
+    fn error_response(&self) -> HttpResponse {
+        HttpResponse::build(self.status_code())
+            .insert_header(WwwAuthenticate(self.challenge.clone()))
+            .finish()
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use actix_web::Error;
+#[cfg(test)]
+mod tests {
+    use actix_web::Error;
 
-    use super::*;
-    use crate::headers::www_authenticate::basic::Basic;
+    use super::*;
+    use crate::headers::www_authenticate::basic::Basic;
 
-    #[test]
-    fn test_status_code_is_preserved_across_error_conversions() {
-        let ae = AuthenticationError::new(Basic::default());
-        let expected = ae.status_code;
+    #[test]
+    fn test_status_code_is_preserved_across_error_conversions() {
+        let ae = AuthenticationError::new(Basic::default());
+        let expected = ae.status_code;
 
-        // Converting the AuthenticationError into a ResponseError should preserve the status code.
-        let err = Error::from(ae);
-        let res_err = err.as_response_error();
-        assert_eq!(expected, res_err.status_code());
+        // Converting the AuthenticationError into a ResponseError should preserve the status code.
+        let err = Error::from(ae);
+        let res_err = err.as_response_error();
+        assert_eq!(expected, res_err.status_code());
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/extractors/mod.rs.html b/src/actix_web_httpauth/extractors/mod.rs.html index 5ff40ec3c..c0d874172 100644 --- a/src/actix_web_httpauth/extractors/mod.rs.html +++ b/src/actix_web_httpauth/extractors/mod.rs.html @@ -7,14 +7,14 @@ 7 8 9 -
//! Type-safe authentication information extractors.
+
//! Type-safe authentication information extractors.
 
-pub mod basic;
-pub mod bearer;
-mod config;
-mod errors;
+pub mod basic;
+pub mod bearer;
+mod config;
+mod errors;
 
-pub use self::config::AuthExtractorConfig;
-pub use self::errors::AuthenticationError;
+pub use self::config::AuthExtractorConfig;
+pub use self::errors::AuthenticationError;
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/authorization/errors.rs.html b/src/actix_web_httpauth/headers/authorization/errors.rs.html index d957521cd..7dac84434 100644 --- a/src/actix_web_httpauth/headers/authorization/errors.rs.html +++ b/src/actix_web_httpauth/headers/authorization/errors.rs.html @@ -70,77 +70,77 @@ 70 71 72 -
use std::{convert::From, error::Error, fmt, str};
+
use std::{convert::From, error::Error, fmt, str};
 
-use actix_web::http::header;
+use actix_web::http::header;
 
-/// Possible errors while parsing `Authorization` header.
-///
-/// Should not be used directly unless you are implementing your own
-/// [authentication scheme](super::Scheme).
-#[derive(Debug)]
-pub enum ParseError {
-    /// Header value is malformed.
-    Invalid,
+/// Possible errors while parsing `Authorization` header.
+///
+/// Should not be used directly unless you are implementing your own
+/// [authentication scheme](super::Scheme).
+#[derive(Debug)]
+pub enum ParseError {
+    /// Header value is malformed.
+    Invalid,
 
-    /// Authentication scheme is missing.
-    MissingScheme,
+    /// Authentication scheme is missing.
+    MissingScheme,
 
-    /// Required authentication field is missing.
-    MissingField(&'static str),
+    /// Required authentication field is missing.
+    MissingField(&'static str),
 
-    /// Unable to convert header into the str.
-    ToStrError(header::ToStrError),
+    /// Unable to convert header into the str.
+    ToStrError(header::ToStrError),
 
-    /// Malformed base64 string.
-    Base64DecodeError(base64::DecodeError),
+    /// Malformed base64 string.
+    Base64DecodeError(base64::DecodeError),
 
-    /// Malformed UTF-8 string.
-    Utf8Error(str::Utf8Error),
+    /// Malformed UTF-8 string.
+    Utf8Error(str::Utf8Error),
 }
 
-impl fmt::Display for ParseError {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        match self {
-            ParseError::Invalid => f.write_str("Invalid header value"),
-            ParseError::MissingScheme => f.write_str("Missing authorization scheme"),
-            ParseError::MissingField(field) => write!(f, "Missing header field ({})", field),
-            ParseError::ToStrError(err) => fmt::Display::fmt(err, f),
-            ParseError::Base64DecodeError(err) => fmt::Display::fmt(err, f),
-            ParseError::Utf8Error(err) => fmt::Display::fmt(err, f),
+impl fmt::Display for ParseError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            ParseError::Invalid => f.write_str("Invalid header value"),
+            ParseError::MissingScheme => f.write_str("Missing authorization scheme"),
+            ParseError::MissingField(field) => write!(f, "Missing header field ({})", field),
+            ParseError::ToStrError(err) => fmt::Display::fmt(err, f),
+            ParseError::Base64DecodeError(err) => fmt::Display::fmt(err, f),
+            ParseError::Utf8Error(err) => fmt::Display::fmt(err, f),
         }
     }
 }
 
-impl Error for ParseError {
-    fn source(&self) -> Option<&(dyn Error + 'static)> {
-        match self {
-            ParseError::Invalid => None,
-            ParseError::MissingScheme => None,
-            ParseError::MissingField(_) => None,
-            ParseError::ToStrError(err) => Some(err),
-            ParseError::Base64DecodeError(err) => Some(err),
-            ParseError::Utf8Error(err) => Some(err),
+impl Error for ParseError {
+    fn source(&self) -> Option<&(dyn Error + 'static)> {
+        match self {
+            ParseError::Invalid => None,
+            ParseError::MissingScheme => None,
+            ParseError::MissingField(_) => None,
+            ParseError::ToStrError(err) => Some(err),
+            ParseError::Base64DecodeError(err) => Some(err),
+            ParseError::Utf8Error(err) => Some(err),
         }
     }
 }
 
-impl From<header::ToStrError> for ParseError {
-    fn from(err: header::ToStrError) -> Self {
-        ParseError::ToStrError(err)
+impl From<header::ToStrError> for ParseError {
+    fn from(err: header::ToStrError) -> Self {
+        ParseError::ToStrError(err)
     }
 }
 
-impl From<base64::DecodeError> for ParseError {
-    fn from(err: base64::DecodeError) -> Self {
-        ParseError::Base64DecodeError(err)
+impl From<base64::DecodeError> for ParseError {
+    fn from(err: base64::DecodeError) -> Self {
+        ParseError::Base64DecodeError(err)
     }
 }
 
-impl From<str::Utf8Error> for ParseError {
-    fn from(err: str::Utf8Error) -> Self {
-        ParseError::Utf8Error(err)
+impl From<str::Utf8Error> for ParseError {
+    fn from(err: str::Utf8Error) -> Self {
+        ParseError::Utf8Error(err)
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/authorization/header.rs.html b/src/actix_web_httpauth/headers/authorization/header.rs.html index 48d0fdef2..2795f639b 100644 --- a/src/actix_web_httpauth/headers/authorization/header.rs.html +++ b/src/actix_web_httpauth/headers/authorization/header.rs.html @@ -82,89 +82,89 @@ 82 83 84 -
use std::fmt;
+
use std::fmt;
 
-use actix_web::{
-    error::ParseError,
-    http::header::{Header, HeaderName, HeaderValue, TryIntoHeaderValue, AUTHORIZATION},
-    HttpMessage,
+use actix_web::{
+    error::ParseError,
+    http::header::{Header, HeaderName, HeaderValue, TryIntoHeaderValue, AUTHORIZATION},
+    HttpMessage,
 };
 
-use crate::headers::authorization::scheme::Scheme;
+use crate::headers::authorization::scheme::Scheme;
 
-/// `Authorization` header, defined in [RFC 7235](https://tools.ietf.org/html/rfc7235#section-4.2)
-///
-/// The "Authorization" header field allows a user agent to authenticate itself with an origin
-/// server—usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value
-/// consists of credentials containing the authentication information of the user agent for the
-/// realm of the resource being requested.
-///
-/// `Authorization` is generic over an [authentication scheme](Scheme).
-///
-/// # Examples
-/// ```
-/// # use actix_web::{HttpRequest, Result, http::header::Header};
-/// # use actix_web_httpauth::headers::authorization::{Authorization, Basic};
-/// fn handler(req: HttpRequest) -> Result<String> {
-///     let auth = Authorization::<Basic>::parse(&req)?;
-///
-///     Ok(format!("Hello, {}!", auth.as_ref().user_id()))
-/// }
-/// ```
-#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct Authorization<S: Scheme>(S);
+/// `Authorization` header, defined in [RFC 7235](https://tools.ietf.org/html/rfc7235#section-4.2)
+///
+/// The "Authorization" header field allows a user agent to authenticate itself with an origin
+/// server—usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value
+/// consists of credentials containing the authentication information of the user agent for the
+/// realm of the resource being requested.
+///
+/// `Authorization` is generic over an [authentication scheme](Scheme).
+///
+/// # Examples
+/// ```
+/// # use actix_web::{HttpRequest, Result, http::header::Header};
+/// # use actix_web_httpauth::headers::authorization::{Authorization, Basic};
+/// fn handler(req: HttpRequest) -> Result<String> {
+///     let auth = Authorization::<Basic>::parse(&req)?;
+///
+///     Ok(format!("Hello, {}!", auth.as_ref().user_id()))
+/// }
+/// ```
+#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Authorization<S: Scheme>(S);
 
-impl<S: Scheme> Authorization<S> {
-    /// Consumes `Authorization` header and returns inner [`Scheme`] implementation.
-    pub fn into_scheme(self) -> S {
-        self.0
+impl<S: Scheme> Authorization<S> {
+    /// Consumes `Authorization` header and returns inner [`Scheme`] implementation.
+    pub fn into_scheme(self) -> S {
+        self.0
+    }
+}
+
+impl<S: Scheme> From<S> for Authorization<S> {
+    fn from(scheme: S) -> Authorization<S> {
+        Authorization(scheme)
     }
 }
 
-impl<S: Scheme> From<S> for Authorization<S> {
-    fn from(scheme: S) -> Authorization<S> {
-        Authorization(scheme)
+impl<S: Scheme> AsRef<S> for Authorization<S> {
+    fn as_ref(&self) -> &S {
+        &self.0
+    }
+}
+
+impl<S: Scheme> AsMut<S> for Authorization<S> {
+    fn as_mut(&mut self) -> &mut S {
+        &mut self.0
+    }
+}
+
+impl<S: Scheme> fmt::Display for Authorization<S> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt::Display::fmt(&self.0, f)
     }
 }
 
-impl<S: Scheme> AsRef<S> for Authorization<S> {
-    fn as_ref(&self) -> &S {
-        &self.0
+impl<S: Scheme> Header for Authorization<S> {
+    #[inline]
+    fn name() -> HeaderName {
+        AUTHORIZATION
+    }
+
+    fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> {
+        let header = msg.headers().get(Self::name()).ok_or(ParseError::Header)?;
+        let scheme = S::parse(header).map_err(|_| ParseError::Header)?;
+
+        Ok(Authorization(scheme))
     }
 }
 
-impl<S: Scheme> AsMut<S> for Authorization<S> {
-    fn as_mut(&mut self) -> &mut S {
-        &mut self.0
-    }
-}
+impl<S: Scheme> TryIntoHeaderValue for Authorization<S> {
+    type Error = <S as TryIntoHeaderValue>::Error;
 
-impl<S: Scheme> fmt::Display for Authorization<S> {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        fmt::Display::fmt(&self.0, f)
-    }
-}
-
-impl<S: Scheme> Header for Authorization<S> {
-    #[inline]
-    fn name() -> HeaderName {
-        AUTHORIZATION
-    }
-
-    fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError> {
-        let header = msg.headers().get(Self::name()).ok_or(ParseError::Header)?;
-        let scheme = S::parse(header).map_err(|_| ParseError::Header)?;
-
-        Ok(Authorization(scheme))
-    }
-}
-
-impl<S: Scheme> TryIntoHeaderValue for Authorization<S> {
-    type Error = <S as TryIntoHeaderValue>::Error;
-
-    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
-        self.0.try_into_value()
+    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
+        self.0.try_into_value()
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/authorization/mod.rs.html b/src/actix_web_httpauth/headers/authorization/mod.rs.html index 06374114f..f4b0d497f 100644 --- a/src/actix_web_httpauth/headers/authorization/mod.rs.html +++ b/src/actix_web_httpauth/headers/authorization/mod.rs.html @@ -7,14 +7,14 @@ 7 8 9 -
//! `Authorization` header and various auth schemes.
+
//! `Authorization` header and various auth schemes.
 
-mod errors;
-mod header;
-mod scheme;
+mod errors;
+mod header;
+mod scheme;
 
-pub use self::errors::ParseError;
-pub use self::header::Authorization;
-pub use self::scheme::{basic::Basic, bearer::Bearer, Scheme};
+pub use self::errors::ParseError;
+pub use self::header::Authorization;
+pub use self::scheme::{basic::Basic, bearer::Bearer, Scheme};
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/authorization/scheme/basic.rs.html b/src/actix_web_httpauth/headers/authorization/scheme/basic.rs.html index a037eaff8..cf2630dc8 100644 --- a/src/actix_web_httpauth/headers/authorization/scheme/basic.rs.html +++ b/src/actix_web_httpauth/headers/authorization/scheme/basic.rs.html @@ -193,200 +193,200 @@ 193 194 195 -
use std::{borrow::Cow, fmt, str};
+
use std::{borrow::Cow, fmt, str};
 
-use actix_web::{
-    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
-    web::{BufMut, BytesMut},
+use actix_web::{
+    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
+    web::{BufMut, BytesMut},
 };
 
-use crate::headers::authorization::{errors::ParseError, Scheme};
+use crate::headers::authorization::{errors::ParseError, Scheme};
 
-/// Credentials for `Basic` authentication scheme, defined in [RFC 7617](https://tools.ietf.org/html/rfc7617)
-#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
-pub struct Basic {
-    user_id: Cow<'static, str>,
-    password: Option<Cow<'static, str>>,
+/// Credentials for `Basic` authentication scheme, defined in [RFC 7617](https://tools.ietf.org/html/rfc7617)
+#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Basic {
+    user_id: Cow<'static, str>,
+    password: Option<Cow<'static, str>>,
 }
 
-impl Basic {
-    /// Creates `Basic` credentials with provided `user_id` and optional
-    /// `password`.
-    ///
-    /// # Examples
-    /// ```
-    /// # use actix_web_httpauth::headers::authorization::Basic;
-    /// let credentials = Basic::new("Alladin", Some("open sesame"));
-    /// ```
-    pub fn new<U, P>(user_id: U, password: Option<P>) -> Basic
-    where
-        U: Into<Cow<'static, str>>,
-        P: Into<Cow<'static, str>>,
+impl Basic {
+    /// Creates `Basic` credentials with provided `user_id` and optional
+    /// `password`.
+    ///
+    /// # Examples
+    /// ```
+    /// # use actix_web_httpauth::headers::authorization::Basic;
+    /// let credentials = Basic::new("Alladin", Some("open sesame"));
+    /// ```
+    pub fn new<U, P>(user_id: U, password: Option<P>) -> Basic
+    where
+        U: Into<Cow<'static, str>>,
+        P: Into<Cow<'static, str>>,
     {
-        Basic {
-            user_id: user_id.into(),
-            password: password.map(Into::into),
+        Basic {
+            user_id: user_id.into(),
+            password: password.map(Into::into),
         }
     }
 
-    /// Returns client's user-ID.
-    pub fn user_id(&self) -> &str {
-        self.user_id.as_ref()
+    /// Returns client's user-ID.
+    pub fn user_id(&self) -> &str {
+        self.user_id.as_ref()
     }
 
-    /// Returns client's password if provided.
-    pub fn password(&self) -> Option<&str> {
-        self.password.as_deref()
+    /// Returns client's password if provided.
+    pub fn password(&self) -> Option<&str> {
+        self.password.as_deref()
     }
 }
 
-impl Scheme for Basic {
-    fn parse(header: &HeaderValue) -> Result<Self, ParseError> {
-        // "Basic *" length
-        if header.len() < 7 {
-            return Err(ParseError::Invalid);
+impl Scheme for Basic {
+    fn parse(header: &HeaderValue) -> Result<Self, ParseError> {
+        // "Basic *" length
+        if header.len() < 7 {
+            return Err(ParseError::Invalid);
         }
 
-        let mut parts = header.to_str()?.splitn(2, ' ');
-        match parts.next() {
-            Some(scheme) if scheme == "Basic" => (),
-            _ => return Err(ParseError::MissingScheme),
+        let mut parts = header.to_str()?.splitn(2, ' ');
+        match parts.next() {
+            Some(scheme) if scheme == "Basic" => (),
+            _ => return Err(ParseError::MissingScheme),
         }
 
-        let decoded = base64::decode(parts.next().ok_or(ParseError::Invalid)?)?;
-        let mut credentials = str::from_utf8(&decoded)?.splitn(2, ':');
+        let decoded = base64::decode(parts.next().ok_or(ParseError::Invalid)?)?;
+        let mut credentials = str::from_utf8(&decoded)?.splitn(2, ':');
 
-        let user_id = credentials
-            .next()
-            .ok_or(ParseError::MissingField("user_id"))
-            .map(|user_id| user_id.to_string().into())?;
+        let user_id = credentials
+            .next()
+            .ok_or(ParseError::MissingField("user_id"))
+            .map(|user_id| user_id.to_string().into())?;
 
-        let password = credentials
-            .next()
-            .ok_or(ParseError::MissingField("password"))
-            .map(|password| {
-                if password.is_empty() {
-                    None
-                } else {
-                    Some(password.to_string().into())
+        let password = credentials
+            .next()
+            .ok_or(ParseError::MissingField("password"))
+            .map(|password| {
+                if password.is_empty() {
+                    None
+                } else {
+                    Some(password.to_string().into())
                 }
             })?;
 
-        Ok(Basic { user_id, password })
+        Ok(Basic { user_id, password })
     }
 }
 
-impl fmt::Debug for Basic {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.write_fmt(format_args!("Basic {}:******", self.user_id))
+impl fmt::Debug for Basic {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_fmt(format_args!("Basic {}:******", self.user_id))
     }
 }
 
-impl fmt::Display for Basic {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.write_fmt(format_args!("Basic {}:******", self.user_id))
+impl fmt::Display for Basic {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_fmt(format_args!("Basic {}:******", self.user_id))
     }
 }
 
-impl TryIntoHeaderValue for Basic {
-    type Error = InvalidHeaderValue;
+impl TryIntoHeaderValue for Basic {
+    type Error = InvalidHeaderValue;
 
-    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
-        let mut credentials = BytesMut::with_capacity(
-            self.user_id.len()
-                + 1 // ':'
-                + self.password.as_ref().map_or(0, |pwd| pwd.len()),
+    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
+        let mut credentials = BytesMut::with_capacity(
+            self.user_id.len()
+                + 1 // ':'
+                + self.password.as_ref().map_or(0, |pwd| pwd.len()),
         );
 
-        credentials.extend_from_slice(self.user_id.as_bytes());
-        credentials.put_u8(b':');
-        if let Some(ref password) = self.password {
-            credentials.extend_from_slice(password.as_bytes());
+        credentials.extend_from_slice(self.user_id.as_bytes());
+        credentials.put_u8(b':');
+        if let Some(ref password) = self.password {
+            credentials.extend_from_slice(password.as_bytes());
         }
 
-        // TODO: It would be nice not to allocate new `String`  here but write
-        // directly to `value`
-        let encoded = base64::encode(&credentials);
-        let mut value = BytesMut::with_capacity(6 + encoded.len());
-        value.put(&b"Basic "[..]);
-        value.put(encoded.as_bytes());
+        // TODO: It would be nice not to allocate new `String`  here but write
+        // directly to `value`
+        let encoded = base64::encode(&credentials);
+        let mut value = BytesMut::with_capacity(6 + encoded.len());
+        value.put(&b"Basic "[..]);
+        value.put(encoded.as_bytes());
 
-        HeaderValue::from_maybe_shared(value.freeze())
+        HeaderValue::from_maybe_shared(value.freeze())
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn test_parse_header() {
-        let value = HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
-        let scheme = Basic::parse(&value);
+    #[test]
+    fn test_parse_header() {
+        let value = HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
+        let scheme = Basic::parse(&value);
 
-        assert!(scheme.is_ok());
-        let scheme = scheme.unwrap();
-        assert_eq!(scheme.user_id, "Aladdin");
-        assert_eq!(scheme.password, Some("open sesame".into()));
+        assert!(scheme.is_ok());
+        let scheme = scheme.unwrap();
+        assert_eq!(scheme.user_id, "Aladdin");
+        assert_eq!(scheme.password, Some("open sesame".into()));
     }
 
-    #[test]
-    fn test_empty_password() {
-        let value = HeaderValue::from_static("Basic QWxhZGRpbjo=");
-        let scheme = Basic::parse(&value);
+    #[test]
+    fn test_empty_password() {
+        let value = HeaderValue::from_static("Basic QWxhZGRpbjo=");
+        let scheme = Basic::parse(&value);
 
-        assert!(scheme.is_ok());
-        let scheme = scheme.unwrap();
-        assert_eq!(scheme.user_id, "Aladdin");
-        assert_eq!(scheme.password, None);
+        assert!(scheme.is_ok());
+        let scheme = scheme.unwrap();
+        assert_eq!(scheme.user_id, "Aladdin");
+        assert_eq!(scheme.password, None);
     }
 
-    #[test]
-    fn test_empty_header() {
-        let value = HeaderValue::from_static("");
-        let scheme = Basic::parse(&value);
+    #[test]
+    fn test_empty_header() {
+        let value = HeaderValue::from_static("");
+        let scheme = Basic::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_wrong_scheme() {
-        let value = HeaderValue::from_static("THOUSHALLNOTPASS please?");
-        let scheme = Basic::parse(&value);
+    #[test]
+    fn test_wrong_scheme() {
+        let value = HeaderValue::from_static("THOUSHALLNOTPASS please?");
+        let scheme = Basic::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_missing_credentials() {
-        let value = HeaderValue::from_static("Basic ");
-        let scheme = Basic::parse(&value);
+    #[test]
+    fn test_missing_credentials() {
+        let value = HeaderValue::from_static("Basic ");
+        let scheme = Basic::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_missing_credentials_colon() {
-        let value = HeaderValue::from_static("Basic QWxsYWRpbg==");
-        let scheme = Basic::parse(&value);
+    #[test]
+    fn test_missing_credentials_colon() {
+        let value = HeaderValue::from_static("Basic QWxsYWRpbg==");
+        let scheme = Basic::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_into_header_value() {
-        let basic = Basic {
-            user_id: "Aladdin".into(),
-            password: Some("open sesame".into()),
+    #[test]
+    fn test_into_header_value() {
+        let basic = Basic {
+            user_id: "Aladdin".into(),
+            password: Some("open sesame".into()),
         };
 
-        let result = basic.try_into_value();
-        assert!(result.is_ok());
+        let result = basic.try_into_value();
+        assert!(result.is_ok());
         assert_eq!(
-            result.unwrap(),
-            HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
+            result.unwrap(),
+            HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
         );
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/authorization/scheme/bearer.rs.html b/src/actix_web_httpauth/headers/authorization/scheme/bearer.rs.html index 74db483e6..162ae3214 100644 --- a/src/actix_web_httpauth/headers/authorization/scheme/bearer.rs.html +++ b/src/actix_web_httpauth/headers/authorization/scheme/bearer.rs.html @@ -136,143 +136,143 @@ 136 137 138 -
use std::{borrow::Cow, fmt};
+
use std::{borrow::Cow, fmt};
 
-use actix_web::{
-    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
-    web::{BufMut, BytesMut},
+use actix_web::{
+    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
+    web::{BufMut, BytesMut},
 };
 
-use crate::headers::authorization::{errors::ParseError, scheme::Scheme};
+use crate::headers::authorization::{errors::ParseError, scheme::Scheme};
 
-/// Credentials for `Bearer` authentication scheme, defined in [RFC 6750].
-///
-/// Should be used in combination with [`Authorization`](super::Authorization) header.
-///
-/// [RFC 6750]: https://tools.ietf.org/html/rfc6750
-#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
-pub struct Bearer {
-    token: Cow<'static, str>,
+/// Credentials for `Bearer` authentication scheme, defined in [RFC 6750].
+///
+/// Should be used in combination with [`Authorization`](super::Authorization) header.
+///
+/// [RFC 6750]: https://tools.ietf.org/html/rfc6750
+#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
+pub struct Bearer {
+    token: Cow<'static, str>,
 }
 
-impl Bearer {
-    /// Creates new `Bearer` credentials with the token provided.
-    ///
-    /// # Example
-    /// ```
-    /// # use actix_web_httpauth::headers::authorization::Bearer;
-    /// let credentials = Bearer::new("mF_9.B5f-4.1JqM");
-    /// ```
-    pub fn new<T>(token: T) -> Bearer
-    where
-        T: Into<Cow<'static, str>>,
+impl Bearer {
+    /// Creates new `Bearer` credentials with the token provided.
+    ///
+    /// # Example
+    /// ```
+    /// # use actix_web_httpauth::headers::authorization::Bearer;
+    /// let credentials = Bearer::new("mF_9.B5f-4.1JqM");
+    /// ```
+    pub fn new<T>(token: T) -> Bearer
+    where
+        T: Into<Cow<'static, str>>,
     {
-        Bearer {
-            token: token.into(),
+        Bearer {
+            token: token.into(),
         }
     }
 
-    /// Gets reference to the credentials token.
-    pub fn token(&self) -> &str {
-        self.token.as_ref()
+    /// Gets reference to the credentials token.
+    pub fn token(&self) -> &str {
+        self.token.as_ref()
     }
 }
 
-impl Scheme for Bearer {
-    fn parse(header: &HeaderValue) -> Result<Self, ParseError> {
-        // "Bearer *" length
-        if header.len() < 8 {
-            return Err(ParseError::Invalid);
+impl Scheme for Bearer {
+    fn parse(header: &HeaderValue) -> Result<Self, ParseError> {
+        // "Bearer *" length
+        if header.len() < 8 {
+            return Err(ParseError::Invalid);
         }
 
-        let mut parts = header.to_str()?.splitn(2, ' ');
+        let mut parts = header.to_str()?.splitn(2, ' ');
 
-        match parts.next() {
-            Some(scheme) if scheme == "Bearer" => {}
-            _ => return Err(ParseError::MissingScheme),
+        match parts.next() {
+            Some(scheme) if scheme == "Bearer" => {}
+            _ => return Err(ParseError::MissingScheme),
         }
 
-        let token = parts.next().ok_or(ParseError::Invalid)?;
+        let token = parts.next().ok_or(ParseError::Invalid)?;
 
-        Ok(Bearer {
-            token: token.to_string().into(),
+        Ok(Bearer {
+            token: token.to_string().into(),
         })
     }
 }
 
-impl fmt::Debug for Bearer {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.write_fmt(format_args!("Bearer ******"))
+impl fmt::Debug for Bearer {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_fmt(format_args!("Bearer ******"))
     }
 }
 
-impl fmt::Display for Bearer {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.write_fmt(format_args!("Bearer {}", self.token))
+impl fmt::Display for Bearer {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_fmt(format_args!("Bearer {}", self.token))
     }
 }
 
-impl TryIntoHeaderValue for Bearer {
-    type Error = InvalidHeaderValue;
+impl TryIntoHeaderValue for Bearer {
+    type Error = InvalidHeaderValue;
 
-    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
-        let mut buffer = BytesMut::with_capacity(7 + self.token.len());
-        buffer.put(&b"Bearer "[..]);
-        buffer.extend_from_slice(self.token.as_bytes());
+    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
+        let mut buffer = BytesMut::with_capacity(7 + self.token.len());
+        buffer.put(&b"Bearer "[..]);
+        buffer.extend_from_slice(self.token.as_bytes());
 
-        HeaderValue::from_maybe_shared(buffer.freeze())
+        HeaderValue::from_maybe_shared(buffer.freeze())
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn test_parse_header() {
-        let value = HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM");
-        let scheme = Bearer::parse(&value);
+    #[test]
+    fn test_parse_header() {
+        let value = HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM");
+        let scheme = Bearer::parse(&value);
 
-        assert!(scheme.is_ok());
-        let scheme = scheme.unwrap();
-        assert_eq!(scheme.token, "mF_9.B5f-4.1JqM");
+        assert!(scheme.is_ok());
+        let scheme = scheme.unwrap();
+        assert_eq!(scheme.token, "mF_9.B5f-4.1JqM");
     }
 
-    #[test]
-    fn test_empty_header() {
-        let value = HeaderValue::from_static("");
-        let scheme = Bearer::parse(&value);
+    #[test]
+    fn test_empty_header() {
+        let value = HeaderValue::from_static("");
+        let scheme = Bearer::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_wrong_scheme() {
-        let value = HeaderValue::from_static("OAuthToken foo");
-        let scheme = Bearer::parse(&value);
+    #[test]
+    fn test_wrong_scheme() {
+        let value = HeaderValue::from_static("OAuthToken foo");
+        let scheme = Bearer::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_missing_token() {
-        let value = HeaderValue::from_static("Bearer ");
-        let scheme = Bearer::parse(&value);
+    #[test]
+    fn test_missing_token() {
+        let value = HeaderValue::from_static("Bearer ");
+        let scheme = Bearer::parse(&value);
 
-        assert!(scheme.is_err());
+        assert!(scheme.is_err());
     }
 
-    #[test]
-    fn test_into_header_value() {
-        let bearer = Bearer::new("mF_9.B5f-4.1JqM");
+    #[test]
+    fn test_into_header_value() {
+        let bearer = Bearer::new("mF_9.B5f-4.1JqM");
 
-        let result = bearer.try_into_value();
-        assert!(result.is_ok());
+        let result = bearer.try_into_value();
+        assert!(result.is_ok());
         assert_eq!(
-            result.unwrap(),
-            HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM")
+            result.unwrap(),
+            HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM")
         );
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/authorization/scheme/mod.rs.html b/src/actix_web_httpauth/headers/authorization/scheme/mod.rs.html index 9685c1660..085919798 100644 --- a/src/actix_web_httpauth/headers/authorization/scheme/mod.rs.html +++ b/src/actix_web_httpauth/headers/authorization/scheme/mod.rs.html @@ -12,19 +12,19 @@ 12 13 14 -
use std::fmt::{Debug, Display};
+
use std::fmt::{Debug, Display};
 
-use actix_web::http::header::{HeaderValue, TryIntoHeaderValue};
+use actix_web::http::header::{HeaderValue, TryIntoHeaderValue};
 
-pub mod basic;
-pub mod bearer;
+pub mod basic;
+pub mod bearer;
 
-use crate::headers::authorization::errors::ParseError;
+use crate::headers::authorization::errors::ParseError;
 
-/// Authentication scheme for [`Authorization`](super::Authorization) header.
-pub trait Scheme: TryIntoHeaderValue + Debug + Display + Clone + Send + Sync {
-    /// Try to parse an authentication scheme from the `Authorization` header.
-    fn parse(header: &HeaderValue) -> Result<Self, ParseError>;
+/// Authentication scheme for [`Authorization`](super::Authorization) header.
+pub trait Scheme: TryIntoHeaderValue + Debug + Display + Clone + Send + Sync {
+    /// Try to parse an authentication scheme from the `Authorization` header.
+    fn parse(header: &HeaderValue) -> Result<Self, ParseError>;
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/mod.rs.html b/src/actix_web_httpauth/headers/mod.rs.html index d4b4bb84c..4d20df35f 100644 --- a/src/actix_web_httpauth/headers/mod.rs.html +++ b/src/actix_web_httpauth/headers/mod.rs.html @@ -2,9 +2,9 @@ 2 3 4 -
//! Typed HTTP headers.
+
//! Typed HTTP headers.
 
-pub mod authorization;
-pub mod www_authenticate;
+pub mod authorization;
+pub mod www_authenticate;
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/challenge/basic.rs.html b/src/actix_web_httpauth/headers/www_authenticate/challenge/basic.rs.html index bbcb3e3c1..db25a68e8 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/challenge/basic.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/challenge/basic.rs.html @@ -134,141 +134,141 @@ 134 135 136 -
//! Challenge for the "Basic" HTTP Authentication Scheme.
+
//! Challenge for the "Basic" HTTP Authentication Scheme.
 
-use std::{borrow::Cow, fmt, str};
+use std::{borrow::Cow, fmt, str};
 
-use actix_web::{
-    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
-    web::{BufMut, Bytes, BytesMut},
+use actix_web::{
+    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
+    web::{BufMut, Bytes, BytesMut},
 };
 
-use super::Challenge;
-use crate::utils;
+use super::Challenge;
+use crate::utils;
 
-/// Challenge for [`WWW-Authenticate`] header with HTTP Basic auth scheme,
-/// described in [RFC 7617](https://tools.ietf.org/html/rfc7617)
-///
-/// # Examples
-/// ```
-/// # use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
-/// use actix_web_httpauth::headers::www_authenticate::basic::Basic;
-/// use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
-///
-/// fn index(_req: HttpRequest) -> HttpResponse {
-///     let challenge = Basic::with_realm("Restricted area");
-///
-///     HttpResponse::Unauthorized()
-///         .insert_header(WwwAuthenticate(challenge))
-///         .finish()
-/// }
-/// ```
-///
-/// [`WWW-Authenticate`]: ../struct.WwwAuthenticate.html
-#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Clone)]
-pub struct Basic {
-    // "realm" parameter is optional now: https://tools.ietf.org/html/rfc7235#appendix-A
-    pub(crate) realm: Option<Cow<'static, str>>,
+/// Challenge for [`WWW-Authenticate`] header with HTTP Basic auth scheme,
+/// described in [RFC 7617](https://tools.ietf.org/html/rfc7617)
+///
+/// # Examples
+/// ```
+/// # use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
+/// use actix_web_httpauth::headers::www_authenticate::basic::Basic;
+/// use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
+///
+/// fn index(_req: HttpRequest) -> HttpResponse {
+///     let challenge = Basic::with_realm("Restricted area");
+///
+///     HttpResponse::Unauthorized()
+///         .insert_header(WwwAuthenticate(challenge))
+///         .finish()
+/// }
+/// ```
+///
+/// [`WWW-Authenticate`]: ../struct.WwwAuthenticate.html
+#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Clone)]
+pub struct Basic {
+    // "realm" parameter is optional now: https://tools.ietf.org/html/rfc7235#appendix-A
+    pub(crate) realm: Option<Cow<'static, str>>,
 }
 
-impl Basic {
-    /// Creates new `Basic` challenge with an empty `realm` field.
-    ///
-    /// # Examples
-    /// ```
-    /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic;
-    /// let challenge = Basic::new();
-    /// ```
-    pub fn new() -> Basic {
-        Default::default()
+impl Basic {
+    /// Creates new `Basic` challenge with an empty `realm` field.
+    ///
+    /// # Examples
+    /// ```
+    /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic;
+    /// let challenge = Basic::new();
+    /// ```
+    pub fn new() -> Basic {
+        Default::default()
     }
 
-    /// Creates new `Basic` challenge from the provided `realm` field value.
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic;
-    /// let challenge = Basic::with_realm("Restricted area");
-    /// ```
-    ///
-    /// ```
-    /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic;
-    /// let my_realm = "Earth realm".to_string();
-    /// let challenge = Basic::with_realm(my_realm);
-    /// ```
-    pub fn with_realm<T>(value: T) -> Basic
-    where
-        T: Into<Cow<'static, str>>,
+    /// Creates new `Basic` challenge from the provided `realm` field value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic;
+    /// let challenge = Basic::with_realm("Restricted area");
+    /// ```
+    ///
+    /// ```
+    /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic;
+    /// let my_realm = "Earth realm".to_string();
+    /// let challenge = Basic::with_realm(my_realm);
+    /// ```
+    pub fn with_realm<T>(value: T) -> Basic
+    where
+        T: Into<Cow<'static, str>>,
     {
-        Basic {
-            realm: Some(value.into()),
+        Basic {
+            realm: Some(value.into()),
         }
     }
 }
 
-#[doc(hidden)]
-impl Challenge for Basic {
-    fn to_bytes(&self) -> Bytes {
-        // 5 is for `"Basic"`, 9 is for `"realm=\"\""`
-        let length = 5 + self.realm.as_ref().map_or(0, |realm| realm.len() + 9);
-        let mut buffer = BytesMut::with_capacity(length);
-        buffer.put(&b"Basic"[..]);
-        if let Some(ref realm) = self.realm {
-            buffer.put(&b" realm=\""[..]);
-            utils::put_quoted(&mut buffer, realm);
-            buffer.put_u8(b'"');
+#[doc(hidden)]
+impl Challenge for Basic {
+    fn to_bytes(&self) -> Bytes {
+        // 5 is for `"Basic"`, 9 is for `"realm=\"\""`
+        let length = 5 + self.realm.as_ref().map_or(0, |realm| realm.len() + 9);
+        let mut buffer = BytesMut::with_capacity(length);
+        buffer.put(&b"Basic"[..]);
+        if let Some(ref realm) = self.realm {
+            buffer.put(&b" realm=\""[..]);
+            utils::put_quoted(&mut buffer, realm);
+            buffer.put_u8(b'"');
         }
 
-        buffer.freeze()
+        buffer.freeze()
     }
 }
 
-impl fmt::Display for Basic {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
-        let bytes = self.to_bytes();
-        let repr = str::from_utf8(&bytes)
-            // Should not happen since challenges are crafted manually
-            // from a `&'static str` or `String`
-            .map_err(|_| fmt::Error)?;
+impl fmt::Display for Basic {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+        let bytes = self.to_bytes();
+        let repr = str::from_utf8(&bytes)
+            // Should not happen since challenges are crafted manually
+            // from a `&'static str` or `String`
+            .map_err(|_| fmt::Error)?;
 
-        f.write_str(repr)
+        f.write_str(repr)
     }
 }
 
-impl TryIntoHeaderValue for Basic {
-    type Error = InvalidHeaderValue;
+impl TryIntoHeaderValue for Basic {
+    type Error = InvalidHeaderValue;
 
-    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
-        HeaderValue::from_maybe_shared(self.to_bytes())
+    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
+        HeaderValue::from_maybe_shared(self.to_bytes())
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn test_plain_into_header_value() {
-        let challenge = Basic { realm: None };
+    #[test]
+    fn test_plain_into_header_value() {
+        let challenge = Basic { realm: None };
 
-        let value = challenge.try_into_value();
-        assert!(value.is_ok());
-        let value = value.unwrap();
-        assert_eq!(value, "Basic");
+        let value = challenge.try_into_value();
+        assert!(value.is_ok());
+        let value = value.unwrap();
+        assert_eq!(value, "Basic");
     }
 
-    #[test]
-    fn test_with_realm_into_header_value() {
-        let challenge = Basic {
-            realm: Some("Restricted area".into()),
+    #[test]
+    fn test_with_realm_into_header_value() {
+        let challenge = Basic {
+            realm: Some("Restricted area".into()),
         };
 
-        let value = challenge.try_into_value();
-        assert!(value.is_ok());
-        let value = value.unwrap();
-        assert_eq!(value, "Basic realm=\"Restricted area\"");
+        let value = challenge.try_into_value();
+        assert!(value.is_ok());
+        let value = value.unwrap();
+        assert_eq!(value, "Basic realm=\"Restricted area\"");
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/builder.rs.html b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/builder.rs.html index 6dee44fdf..2aad2bead 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/builder.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/builder.rs.html @@ -69,76 +69,76 @@ 69 70 71 -
use std::borrow::Cow;
+
use std::borrow::Cow;
 
-use super::{Bearer, Error};
+use super::{Bearer, Error};
 
-/// Builder for the [`Bearer`] challenge.
-///
-/// It is up to implementor to fill all required fields, neither this `Builder` nor [`Bearer`]
-/// provide any validation.
-#[derive(Debug, Default)]
-pub struct BearerBuilder(Bearer);
+/// Builder for the [`Bearer`] challenge.
+///
+/// It is up to implementor to fill all required fields, neither this `Builder` nor [`Bearer`]
+/// provide any validation.
+#[derive(Debug, Default)]
+pub struct BearerBuilder(Bearer);
 
-impl BearerBuilder {
-    /// Provides the `scope` attribute, as defined in [RFC 6749 §3.3].
-    ///
-    /// [RFC 6749 §3.3]: https://tools.ietf.org/html/rfc6749#section-3.3
-    pub fn scope<T>(mut self, value: T) -> Self
-    where
-        T: Into<Cow<'static, str>>,
+impl BearerBuilder {
+    /// Provides the `scope` attribute, as defined in [RFC 6749 §3.3].
+    ///
+    /// [RFC 6749 §3.3]: https://tools.ietf.org/html/rfc6749#section-3.3
+    pub fn scope<T>(mut self, value: T) -> Self
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.0.scope = Some(value.into());
-        self
-    }
+        self.0.scope = Some(value.into());
+        self
+    }
 
-    /// Provides the `realm` attribute, as defined in [RFC 2617].
-    ///
-    /// [RFC 2617]: https://tools.ietf.org/html/rfc2617
-    pub fn realm<T>(mut self, value: T) -> Self
-    where
-        T: Into<Cow<'static, str>>,
+    /// Provides the `realm` attribute, as defined in [RFC 2617].
+    ///
+    /// [RFC 2617]: https://tools.ietf.org/html/rfc2617
+    pub fn realm<T>(mut self, value: T) -> Self
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.0.realm = Some(value.into());
-        self
-    }
+        self.0.realm = Some(value.into());
+        self
+    }
 
-    /// Provides the `error` attribute, as defined in [RFC 6750, Section 3.1].
-    ///
-    /// [RFC 6750 §3.1]: https://tools.ietf.org/html/rfc6750#section-3.1
-    pub fn error(mut self, value: Error) -> Self {
-        self.0.error = Some(value);
-        self
-    }
+    /// Provides the `error` attribute, as defined in [RFC 6750, Section 3.1].
+    ///
+    /// [RFC 6750 §3.1]: https://tools.ietf.org/html/rfc6750#section-3.1
+    pub fn error(mut self, value: Error) -> Self {
+        self.0.error = Some(value);
+        self
+    }
 
-    /// Provides the `error_description` attribute, as defined in [RFC 6750, Section 3].
-    ///
-    /// [RFC 6750 §3]: https://tools.ietf.org/html/rfc6750#section-3
-    pub fn error_description<T>(mut self, value: T) -> Self
-    where
-        T: Into<Cow<'static, str>>,
+    /// Provides the `error_description` attribute, as defined in [RFC 6750, Section 3].
+    ///
+    /// [RFC 6750 §3]: https://tools.ietf.org/html/rfc6750#section-3
+    pub fn error_description<T>(mut self, value: T) -> Self
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.0.error_description = Some(value.into());
-        self
-    }
+        self.0.error_description = Some(value.into());
+        self
+    }
 
-    /// Provides the `error_uri` attribute, as defined in [RFC 6750 §3].
-    ///
-    /// It is up to implementor to provide properly-formed absolute URI.
-    ///
-    /// [RFC 6750 §3](https://tools.ietf.org/html/rfc6750#section-3)
-    pub fn error_uri<T>(mut self, value: T) -> Self
-    where
-        T: Into<Cow<'static, str>>,
+    /// Provides the `error_uri` attribute, as defined in [RFC 6750 §3].
+    ///
+    /// It is up to implementor to provide properly-formed absolute URI.
+    ///
+    /// [RFC 6750 §3](https://tools.ietf.org/html/rfc6750#section-3)
+    pub fn error_uri<T>(mut self, value: T) -> Self
+    where
+        T: Into<Cow<'static, str>>,
     {
-        self.0.error_uri = Some(value.into());
-        self
-    }
+        self.0.error_uri = Some(value.into());
+        self
+    }
 
-    /// Consumes the builder and returns built `Bearer` instance.
-    pub fn finish(self) -> Bearer {
-        self.0
-    }
+    /// Consumes the builder and returns built `Bearer` instance.
+    pub fn finish(self) -> Bearer {
+        self.0
+    }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/challenge.rs.html b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/challenge.rs.html index 280197ccc..49ac5b198 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/challenge.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/challenge.rs.html @@ -140,147 +140,147 @@ 140 141 142 -
use std::{borrow::Cow, fmt, str};
+
use std::{borrow::Cow, fmt, str};
 
-use actix_web::{
-    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
-    web::{BufMut, Bytes, BytesMut},
+use actix_web::{
+    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
+    web::{BufMut, Bytes, BytesMut},
 };
 
-use super::super::Challenge;
-use super::{BearerBuilder, Error};
-use crate::utils;
+use super::super::Challenge;
+use super::{BearerBuilder, Error};
+use crate::utils;
 
-/// Challenge for [`WWW-Authenticate`] header with HTTP Bearer auth scheme, described in [RFC 6750].
-///
-/// # Examples
-/// ```
-/// # use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
-/// use actix_web_httpauth::headers::www_authenticate::bearer::{
-///     Bearer, Error,
-/// };
-/// use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
-///
-/// fn index(_req: HttpRequest) -> HttpResponse {
-///     let challenge = Bearer::build()
-///         .realm("example")
-///         .scope("openid profile email")
-///         .error(Error::InvalidToken)
-///         .error_description("The access token expired")
-///         .error_uri("http://example.org")
-///         .finish();
-///
-///     HttpResponse::Unauthorized()
-///         .insert_header(WwwAuthenticate(challenge))
-///         .finish()
-/// }
-/// ```
-///
-/// [`WWW-Authenticate`]: crate::headers::www_authenticate::WwwAuthenticate
-/// [RFC 6750]: https://tools.ietf.org/html/rfc6750#section-3
-#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct Bearer {
-    pub(crate) scope: Option<Cow<'static, str>>,
-    pub(crate) realm: Option<Cow<'static, str>>,
-    pub(crate) error: Option<Error>,
-    pub(crate) error_description: Option<Cow<'static, str>>,
-    pub(crate) error_uri: Option<Cow<'static, str>>,
+/// Challenge for [`WWW-Authenticate`] header with HTTP Bearer auth scheme, described in [RFC 6750].
+///
+/// # Examples
+/// ```
+/// # use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
+/// use actix_web_httpauth::headers::www_authenticate::bearer::{
+///     Bearer, Error,
+/// };
+/// use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate;
+///
+/// fn index(_req: HttpRequest) -> HttpResponse {
+///     let challenge = Bearer::build()
+///         .realm("example")
+///         .scope("openid profile email")
+///         .error(Error::InvalidToken)
+///         .error_description("The access token expired")
+///         .error_uri("http://example.org")
+///         .finish();
+///
+///     HttpResponse::Unauthorized()
+///         .insert_header(WwwAuthenticate(challenge))
+///         .finish()
+/// }
+/// ```
+///
+/// [`WWW-Authenticate`]: crate::headers::www_authenticate::WwwAuthenticate
+/// [RFC 6750]: https://tools.ietf.org/html/rfc6750#section-3
+#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Bearer {
+    pub(crate) scope: Option<Cow<'static, str>>,
+    pub(crate) realm: Option<Cow<'static, str>>,
+    pub(crate) error: Option<Error>,
+    pub(crate) error_description: Option<Cow<'static, str>>,
+    pub(crate) error_uri: Option<Cow<'static, str>>,
 }
 
-impl Bearer {
-    /// Creates the builder for `Bearer` challenge.
-    ///
-    /// # Examples
-    /// ```
-    /// # use actix_web_httpauth::headers::www_authenticate::bearer::{Bearer};
-    /// let challenge = Bearer::build()
-    ///     .realm("Restricted area")
-    ///     .scope("openid profile email")
-    ///     .finish();
-    /// ```
-    pub fn build() -> BearerBuilder {
-        BearerBuilder::default()
+impl Bearer {
+    /// Creates the builder for `Bearer` challenge.
+    ///
+    /// # Examples
+    /// ```
+    /// # use actix_web_httpauth::headers::www_authenticate::bearer::{Bearer};
+    /// let challenge = Bearer::build()
+    ///     .realm("Restricted area")
+    ///     .scope("openid profile email")
+    ///     .finish();
+    /// ```
+    pub fn build() -> BearerBuilder {
+        BearerBuilder::default()
     }
 }
 
-#[doc(hidden)]
-impl Challenge for Bearer {
-    fn to_bytes(&self) -> Bytes {
-        let desc_uri_required = self
-            .error_description
-            .as_ref()
-            .map_or(0, |desc| desc.len() + 20)
-            + self.error_uri.as_ref().map_or(0, |url| url.len() + 12);
+#[doc(hidden)]
+impl Challenge for Bearer {
+    fn to_bytes(&self) -> Bytes {
+        let desc_uri_required = self
+            .error_description
+            .as_ref()
+            .map_or(0, |desc| desc.len() + 20)
+            + self.error_uri.as_ref().map_or(0, |url| url.len() + 12);
 
-        let capacity = 6
-            + self.realm.as_ref().map_or(0, |realm| realm.len() + 9)
-            + self.scope.as_ref().map_or(0, |scope| scope.len() + 9)
-            + desc_uri_required;
+        let capacity = 6
+            + self.realm.as_ref().map_or(0, |realm| realm.len() + 9)
+            + self.scope.as_ref().map_or(0, |scope| scope.len() + 9)
+            + desc_uri_required;
 
-        let mut buffer = BytesMut::with_capacity(capacity);
-        buffer.put(&b"Bearer"[..]);
+        let mut buffer = BytesMut::with_capacity(capacity);
+        buffer.put(&b"Bearer"[..]);
 
-        if let Some(ref realm) = self.realm {
-            buffer.put(&b" realm=\""[..]);
-            utils::put_quoted(&mut buffer, realm);
-            buffer.put_u8(b'"');
+        if let Some(ref realm) = self.realm {
+            buffer.put(&b" realm=\""[..]);
+            utils::put_quoted(&mut buffer, realm);
+            buffer.put_u8(b'"');
         }
 
-        if let Some(ref scope) = self.scope {
-            buffer.put(&b" scope=\""[..]);
-            utils::put_quoted(&mut buffer, scope);
-            buffer.put_u8(b'"');
+        if let Some(ref scope) = self.scope {
+            buffer.put(&b" scope=\""[..]);
+            utils::put_quoted(&mut buffer, scope);
+            buffer.put_u8(b'"');
         }
 
-        if let Some(ref error) = self.error {
-            let error_repr = error.as_str();
-            let remaining = buffer.remaining_mut();
-            let required = desc_uri_required + error_repr.len() + 9; // 9 is for `" error=\"\""`
+        if let Some(ref error) = self.error {
+            let error_repr = error.as_str();
+            let remaining = buffer.remaining_mut();
+            let required = desc_uri_required + error_repr.len() + 9; // 9 is for `" error=\"\""`
 
-            if remaining < required {
-                buffer.reserve(required);
+            if remaining < required {
+                buffer.reserve(required);
             }
 
-            buffer.put(&b" error=\""[..]);
-            utils::put_quoted(&mut buffer, error_repr);
-            buffer.put_u8(b'"')
+            buffer.put(&b" error=\""[..]);
+            utils::put_quoted(&mut buffer, error_repr);
+            buffer.put_u8(b'"')
         }
 
-        if let Some(ref error_description) = self.error_description {
-            buffer.put(&b" error_description=\""[..]);
-            utils::put_quoted(&mut buffer, error_description);
-            buffer.put_u8(b'"');
+        if let Some(ref error_description) = self.error_description {
+            buffer.put(&b" error_description=\""[..]);
+            utils::put_quoted(&mut buffer, error_description);
+            buffer.put_u8(b'"');
         }
 
-        if let Some(ref error_uri) = self.error_uri {
-            buffer.put(&b" error_uri=\""[..]);
-            utils::put_quoted(&mut buffer, error_uri);
-            buffer.put_u8(b'"');
+        if let Some(ref error_uri) = self.error_uri {
+            buffer.put(&b" error_uri=\""[..]);
+            utils::put_quoted(&mut buffer, error_uri);
+            buffer.put_u8(b'"');
         }
 
-        buffer.freeze()
+        buffer.freeze()
     }
 }
 
-impl fmt::Display for Bearer {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
-        let bytes = self.to_bytes();
+impl fmt::Display for Bearer {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+        let bytes = self.to_bytes();
 
-        let repr = str::from_utf8(&bytes)
-            // Should not happen since challenges are crafted manually
-            // from `&'static str`'s and Strings
-            .map_err(|_| fmt::Error)?;
+        let repr = str::from_utf8(&bytes)
+            // Should not happen since challenges are crafted manually
+            // from `&'static str`'s and Strings
+            .map_err(|_| fmt::Error)?;
 
-        f.write_str(repr)
+        f.write_str(repr)
     }
 }
 
-impl TryIntoHeaderValue for Bearer {
-    type Error = InvalidHeaderValue;
+impl TryIntoHeaderValue for Bearer {
+    type Error = InvalidHeaderValue;
 
-    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
-        HeaderValue::from_maybe_shared(self.to_bytes())
+    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
+        HeaderValue::from_maybe_shared(self.to_bytes())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/errors.rs.html b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/errors.rs.html index 94e97631a..c3227d106 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/errors.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/errors.rs.html @@ -48,55 +48,55 @@ 48 49 50 -
use std::fmt;
+
use std::fmt;
 
-use actix_web::http::StatusCode;
+use actix_web::http::StatusCode;
 
-/// Bearer authorization error types, described in [RFC 6750].
-///
-/// [RFC 6750]: https://tools.ietf.org/html/rfc6750#section-3.1
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub enum Error {
-    /// The request is missing a required parameter, includes an unsupported parameter or parameter
-    /// value, repeats the same parameter, uses more than one method for including an access token,
-    /// or is otherwise malformed.
-    InvalidRequest,
+/// Bearer authorization error types, described in [RFC 6750].
+///
+/// [RFC 6750]: https://tools.ietf.org/html/rfc6750#section-3.1
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Error {
+    /// The request is missing a required parameter, includes an unsupported parameter or parameter
+    /// value, repeats the same parameter, uses more than one method for including an access token,
+    /// or is otherwise malformed.
+    InvalidRequest,
 
-    /// The access token provided is expired, revoked, malformed, or invalid for other reasons.
-    InvalidToken,
+    /// The access token provided is expired, revoked, malformed, or invalid for other reasons.
+    InvalidToken,
 
-    /// The request requires higher privileges than provided by the access token.
-    InsufficientScope,
+    /// The request requires higher privileges than provided by the access token.
+    InsufficientScope,
 }
 
-impl Error {
-    /// Returns [HTTP status code] suitable for current error type.
-    ///
-    /// [HTTP status code]: `actix_web::http::StatusCode`
-    #[allow(clippy::trivially_copy_pass_by_ref)]
-    pub fn status_code(&self) -> StatusCode {
-        match self {
-            Error::InvalidRequest => StatusCode::BAD_REQUEST,
-            Error::InvalidToken => StatusCode::UNAUTHORIZED,
-            Error::InsufficientScope => StatusCode::FORBIDDEN,
+impl Error {
+    /// Returns [HTTP status code] suitable for current error type.
+    ///
+    /// [HTTP status code]: `actix_web::http::StatusCode`
+    #[allow(clippy::trivially_copy_pass_by_ref)]
+    pub fn status_code(&self) -> StatusCode {
+        match self {
+            Error::InvalidRequest => StatusCode::BAD_REQUEST,
+            Error::InvalidToken => StatusCode::UNAUTHORIZED,
+            Error::InsufficientScope => StatusCode::FORBIDDEN,
         }
     }
 
-    #[doc(hidden)]
-    #[allow(clippy::trivially_copy_pass_by_ref)]
-    pub fn as_str(&self) -> &str {
-        match self {
-            Error::InvalidRequest => "invalid_request",
-            Error::InvalidToken => "invalid_token",
-            Error::InsufficientScope => "insufficient_scope",
+    #[doc(hidden)]
+    #[allow(clippy::trivially_copy_pass_by_ref)]
+    pub fn as_str(&self) -> &str {
+        match self {
+            Error::InvalidRequest => "invalid_request",
+            Error::InvalidToken => "invalid_token",
+            Error::InsufficientScope => "insufficient_scope",
         }
     }
 }
 
-impl fmt::Display for Error {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.write_str(self.as_str())
+impl fmt::Display for Error {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str(self.as_str())
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/mod.rs.html b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/mod.rs.html index d88236515..ec6e4dad5 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/mod.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/challenge/bearer/mod.rs.html @@ -25,32 +25,32 @@ 25 26 27 -
//! Challenge for the "Bearer" HTTP Authentication Scheme.
+
//! Challenge for the "Bearer" HTTP Authentication Scheme.
 
-mod builder;
-mod challenge;
-mod errors;
+mod builder;
+mod challenge;
+mod errors;
 
-pub use self::builder::BearerBuilder;
-pub use self::challenge::Bearer;
-pub use self::errors::Error;
+pub use self::builder::BearerBuilder;
+pub use self::challenge::Bearer;
+pub use self::errors::Error;
 
-#[cfg(test)]
-mod tests {
-    use super::*;
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-    #[test]
-    fn to_bytes() {
-        let b = Bearer::build()
-            .error(Error::InvalidToken)
-            .error_description("Subject 8740827c-2e0a-447b-9716-d73042e4039d not found")
-            .finish();
+    #[test]
+    fn to_bytes() {
+        let b = Bearer::build()
+            .error(Error::InvalidToken)
+            .error_description("Subject 8740827c-2e0a-447b-9716-d73042e4039d not found")
+            .finish();
 
         assert_eq!(
         "Bearer error=\"invalid_token\" error_description=\"Subject 8740827c-2e0a-447b-9716-d73042e4039d not found\"",
-        format!("{}", b)
+        format!("{}", b)
     );
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/challenge/mod.rs.html b/src/actix_web_httpauth/headers/www_authenticate/challenge/mod.rs.html index 2bac83c80..41bd667c3 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/challenge/mod.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/challenge/mod.rs.html @@ -10,17 +10,17 @@ 10 11 12 -
use std::fmt::{Debug, Display};
+
use std::fmt::{Debug, Display};
 
-use actix_web::{http::header::TryIntoHeaderValue, web::Bytes};
+use actix_web::{http::header::TryIntoHeaderValue, web::Bytes};
 
-pub mod basic;
-pub mod bearer;
+pub mod basic;
+pub mod bearer;
 
-/// Authentication challenge for `WWW-Authenticate` header.
-pub trait Challenge: TryIntoHeaderValue + Debug + Display + Clone + Send + Sync {
-    /// Converts the challenge into a bytes suitable for HTTP transmission.
-    fn to_bytes(&self) -> Bytes;
+/// Authentication challenge for `WWW-Authenticate` header.
+pub trait Challenge: TryIntoHeaderValue + Debug + Display + Clone + Send + Sync {
+    /// Converts the challenge into a bytes suitable for HTTP transmission.
+    fn to_bytes(&self) -> Bytes;
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/header.rs.html b/src/actix_web_httpauth/headers/www_authenticate/header.rs.html index 0f8991b15..e58a6ec8d 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/header.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/header.rs.html @@ -33,40 +33,40 @@ 33 34 35 -
use actix_web::{
-    error::ParseError,
-    http::header::{Header, HeaderName, HeaderValue, TryIntoHeaderValue, WWW_AUTHENTICATE},
-    HttpMessage,
+
use actix_web::{
+    error::ParseError,
+    http::header::{Header, HeaderName, HeaderValue, TryIntoHeaderValue, WWW_AUTHENTICATE},
+    HttpMessage,
 };
 
-use super::Challenge;
+use super::Challenge;
 
-/// `WWW-Authenticate` header, described in [RFC 7235].
-///
-/// This header is generic over the [`Challenge`] trait, see [`Basic`](super::basic::Basic) and
-/// [`Bearer`](super::bearer::Bearer) challenges for details.
-///
-/// [RFC 7235]: https://tools.ietf.org/html/rfc7235#section-4.1
-#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct WwwAuthenticate<C: Challenge>(pub C);
+/// `WWW-Authenticate` header, described in [RFC 7235].
+///
+/// This header is generic over the [`Challenge`] trait, see [`Basic`](super::basic::Basic) and
+/// [`Bearer`](super::bearer::Bearer) challenges for details.
+///
+/// [RFC 7235]: https://tools.ietf.org/html/rfc7235#section-4.1
+#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct WwwAuthenticate<C: Challenge>(pub C);
 
-impl<C: Challenge> Header for WwwAuthenticate<C> {
-    #[inline]
-    fn name() -> HeaderName {
-        WWW_AUTHENTICATE
+impl<C: Challenge> Header for WwwAuthenticate<C> {
+    #[inline]
+    fn name() -> HeaderName {
+        WWW_AUTHENTICATE
     }
 
-    fn parse<T: HttpMessage>(_msg: &T) -> Result<Self, ParseError> {
+    fn parse<T: HttpMessage>(_msg: &T) -> Result<Self, ParseError> {
         unimplemented!()
     }
 }
 
-impl<C: Challenge> TryIntoHeaderValue for WwwAuthenticate<C> {
-    type Error = <C as TryIntoHeaderValue>::Error;
+impl<C: Challenge> TryIntoHeaderValue for WwwAuthenticate<C> {
+    type Error = <C as TryIntoHeaderValue>::Error;
 
-    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
-        self.0.try_into_value()
+    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
+        self.0.try_into_value()
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/headers/www_authenticate/mod.rs.html b/src/actix_web_httpauth/headers/www_authenticate/mod.rs.html index 950ee8c11..ac641f52a 100644 --- a/src/actix_web_httpauth/headers/www_authenticate/mod.rs.html +++ b/src/actix_web_httpauth/headers/www_authenticate/mod.rs.html @@ -5,12 +5,12 @@ 5 6 7 -
//! `WWW-Authenticate` header and various auth challenges.
+
//! `WWW-Authenticate` header and various auth challenges.
 
-mod challenge;
-mod header;
+mod challenge;
+mod header;
 
-pub use self::challenge::{basic, bearer, Challenge};
-pub use self::header::WwwAuthenticate;
+pub use self::challenge::{basic, bearer, Challenge};
+pub use self::header::WwwAuthenticate;
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/lib.rs.html b/src/actix_web_httpauth/lib.rs.html index 2c2d59369..15c88c87f 100644 --- a/src/actix_web_httpauth/lib.rs.html +++ b/src/actix_web_httpauth/lib.rs.html @@ -22,29 +22,29 @@ 22 23 24 -
//! HTTP authentication schemes for [Actix Web](https://actix.rs).
-//!
-//! Provides:
-//! - Typed [Authorization] and [WWW-Authenticate] headers
-//! - [Extractors] for an [Authorization] header
-//! - [Middleware] for easier authorization checking
-//!
-//! ## Supported schemes
-//! - `Bearer` as defined in [RFC 6750](https://tools.ietf.org/html/rfc6750).
-//! - `Basic` as defined in [RFC 7617](https://tools.ietf.org/html/rfc7617).
-//!
-//! [Authorization]: `self::headers::authorization::Authorization`
-//! [WWW-Authenticate]: `self::headers::www_authenticate::WwwAuthenticate`
-//! [Extractors]: https://actix.rs/docs/extractors
-//! [Middleware]: self::middleware
+
//! HTTP authentication schemes for [Actix Web](https://actix.rs).
+//!
+//! Provides:
+//! - Typed [Authorization] and [WWW-Authenticate] headers
+//! - [Extractors] for an [Authorization] header
+//! - [Middleware] for easier authorization checking
+//!
+//! ## Supported schemes
+//! - `Bearer` as defined in [RFC 6750](https://tools.ietf.org/html/rfc6750).
+//! - `Basic` as defined in [RFC 7617](https://tools.ietf.org/html/rfc7617).
+//!
+//! [Authorization]: `self::headers::authorization::Authorization`
+//! [WWW-Authenticate]: `self::headers::www_authenticate::WwwAuthenticate`
+//! [Extractors]: https://actix.rs/docs/extractors
+//! [Middleware]: self::middleware
 
-#![forbid(unsafe_code)]
-#![deny(rust_2018_idioms, nonstandard_style)]
-#![warn(future_incompatible, missing_docs)]
+#![forbid(unsafe_code)]
+#![deny(rust_2018_idioms, nonstandard_style)]
+#![warn(future_incompatible, missing_docs)]
 
-pub mod extractors;
-pub mod headers;
-pub mod middleware;
-mod utils;
+pub mod extractors;
+pub mod headers;
+pub mod middleware;
+mod utils;
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/middleware.rs.html b/src/actix_web_httpauth/middleware.rs.html index abb7b201f..204865037 100644 --- a/src/actix_web_httpauth/middleware.rs.html +++ b/src/actix_web_httpauth/middleware.rs.html @@ -415,422 +415,422 @@ 415 416 417 -
//! HTTP Authentication middleware.
+
//! HTTP Authentication middleware.
 
-use std::{
-    future::Future,
-    marker::PhantomData,
-    pin::Pin,
-    rc::Rc,
-    sync::Arc,
-    task::{Context, Poll},
+use std::{
+    future::Future,
+    marker::PhantomData,
+    pin::Pin,
+    rc::Rc,
+    sync::Arc,
+    task::{Context, Poll},
 };
 
-use actix_web::{
-    body::{EitherBody, MessageBody},
-    dev::{Service, ServiceRequest, ServiceResponse, Transform},
-    Error, FromRequest,
+use actix_web::{
+    body::{EitherBody, MessageBody},
+    dev::{Service, ServiceRequest, ServiceResponse, Transform},
+    Error, FromRequest,
 };
-use futures_core::ready;
-use futures_util::future::{self, LocalBoxFuture, TryFutureExt as _};
+use futures_core::ready;
+use futures_util::future::{self, LocalBoxFuture, TryFutureExt as _};
 
-use crate::extractors::{basic, bearer};
+use crate::extractors::{basic, bearer};
 
-/// Middleware for checking HTTP authentication.
-///
-/// If there is no `Authorization` header in the request, this middleware returns an error
-/// immediately, without calling the `F` callback.
-///
-/// Otherwise, it will pass both the request and the parsed credentials into it. In case of
-/// successful validation `F` callback is required to return the `ServiceRequest` back.
-#[derive(Debug, Clone)]
-pub struct HttpAuthentication<T, F>
-where
-    T: FromRequest,
+/// Middleware for checking HTTP authentication.
+///
+/// If there is no `Authorization` header in the request, this middleware returns an error
+/// immediately, without calling the `F` callback.
+///
+/// Otherwise, it will pass both the request and the parsed credentials into it. In case of
+/// successful validation `F` callback is required to return the `ServiceRequest` back.
+#[derive(Debug, Clone)]
+pub struct HttpAuthentication<T, F>
+where
+    T: FromRequest,
 {
-    process_fn: Arc<F>,
-    _extractor: PhantomData<T>,
+    process_fn: Arc<F>,
+    _extractor: PhantomData<T>,
 }
 
-impl<T, F, O> HttpAuthentication<T, F>
-where
-    T: FromRequest,
-    F: Fn(ServiceRequest, T) -> O,
-    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>>,
+impl<T, F, O> HttpAuthentication<T, F>
+where
+    T: FromRequest,
+    F: Fn(ServiceRequest, T) -> O,
+    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>>,
 {
-    /// Construct `HttpAuthentication` middleware with the provided auth extractor `T` and
-    /// validation callback `F`.
-    pub fn with_fn(process_fn: F) -> HttpAuthentication<T, F> {
-        HttpAuthentication {
-            process_fn: Arc::new(process_fn),
-            _extractor: PhantomData,
+    /// Construct `HttpAuthentication` middleware with the provided auth extractor `T` and
+    /// validation callback `F`.
+    pub fn with_fn(process_fn: F) -> HttpAuthentication<T, F> {
+        HttpAuthentication {
+            process_fn: Arc::new(process_fn),
+            _extractor: PhantomData,
         }
     }
 }
 
-impl<F, O> HttpAuthentication<basic::BasicAuth, F>
-where
-    F: Fn(ServiceRequest, basic::BasicAuth) -> O,
-    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>>,
+impl<F, O> HttpAuthentication<basic::BasicAuth, F>
+where
+    F: Fn(ServiceRequest, basic::BasicAuth) -> O,
+    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>>,
 {
-    /// Construct `HttpAuthentication` middleware for the HTTP "Basic" authentication scheme.
-    ///
-    /// # Examples
-    /// ```
-    /// # use actix_web::{Error, dev::ServiceRequest};
-    /// # use actix_web_httpauth::{extractors::basic::BasicAuth, middleware::HttpAuthentication};
-    /// // In this example validator returns immediately, but since it is required to return
-    /// // anything that implements `IntoFuture` trait, it can be extended to query database or to
-    /// // do something else in a async manner.
-    /// async fn validator(
-    ///     req: ServiceRequest,
-    ///     credentials: BasicAuth,
-    /// ) -> Result<ServiceRequest, (Error, ServiceRequest)> {
-    ///     // All users are great and more than welcome!
-    ///     Ok(req)
-    /// }
-    ///
-    /// let middleware = HttpAuthentication::basic(validator);
-    /// ```
-    pub fn basic(process_fn: F) -> Self {
-        Self::with_fn(process_fn)
+    /// Construct `HttpAuthentication` middleware for the HTTP "Basic" authentication scheme.
+    ///
+    /// # Examples
+    /// ```
+    /// # use actix_web::{Error, dev::ServiceRequest};
+    /// # use actix_web_httpauth::{extractors::basic::BasicAuth, middleware::HttpAuthentication};
+    /// // In this example validator returns immediately, but since it is required to return
+    /// // anything that implements `IntoFuture` trait, it can be extended to query database or to
+    /// // do something else in a async manner.
+    /// async fn validator(
+    ///     req: ServiceRequest,
+    ///     credentials: BasicAuth,
+    /// ) -> Result<ServiceRequest, (Error, ServiceRequest)> {
+    ///     // All users are great and more than welcome!
+    ///     Ok(req)
+    /// }
+    ///
+    /// let middleware = HttpAuthentication::basic(validator);
+    /// ```
+    pub fn basic(process_fn: F) -> Self {
+        Self::with_fn(process_fn)
     }
 }
 
-impl<F, O> HttpAuthentication<bearer::BearerAuth, F>
-where
-    F: Fn(ServiceRequest, bearer::BearerAuth) -> O,
-    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>>,
+impl<F, O> HttpAuthentication<bearer::BearerAuth, F>
+where
+    F: Fn(ServiceRequest, bearer::BearerAuth) -> O,
+    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>>,
 {
-    /// Construct `HttpAuthentication` middleware for the HTTP "Bearer" authentication scheme.
-    ///
-    /// # Examples
-    /// ```
-    /// # use actix_web::{Error, dev::ServiceRequest};
-    /// # use actix_web_httpauth::{
-    /// #     extractors::{AuthenticationError, AuthExtractorConfig, bearer::{self, BearerAuth}},
-    /// #     middleware::HttpAuthentication,
-    /// # };
-    /// async fn validator(
-    ///     req: ServiceRequest,
-    ///     credentials: BearerAuth
-    /// ) -> Result<ServiceRequest, (Error, ServiceRequest)> {
-    ///     if credentials.token() == "mF_9.B5f-4.1JqM" {
-    ///         Ok(req)
-    ///     } else {
-    ///         let config = req.app_data::<bearer::Config>()
-    ///             .cloned()
-    ///             .unwrap_or_default()
-    ///             .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
-    ///
-    ///         Err((AuthenticationError::from(config).into(), req))
-    ///     }
-    /// }
-    ///
-    /// let middleware = HttpAuthentication::bearer(validator);
-    /// ```
-    pub fn bearer(process_fn: F) -> Self {
-        Self::with_fn(process_fn)
+    /// Construct `HttpAuthentication` middleware for the HTTP "Bearer" authentication scheme.
+    ///
+    /// # Examples
+    /// ```
+    /// # use actix_web::{Error, dev::ServiceRequest};
+    /// # use actix_web_httpauth::{
+    /// #     extractors::{AuthenticationError, AuthExtractorConfig, bearer::{self, BearerAuth}},
+    /// #     middleware::HttpAuthentication,
+    /// # };
+    /// async fn validator(
+    ///     req: ServiceRequest,
+    ///     credentials: BearerAuth
+    /// ) -> Result<ServiceRequest, (Error, ServiceRequest)> {
+    ///     if credentials.token() == "mF_9.B5f-4.1JqM" {
+    ///         Ok(req)
+    ///     } else {
+    ///         let config = req.app_data::<bearer::Config>()
+    ///             .cloned()
+    ///             .unwrap_or_default()
+    ///             .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
+    ///
+    ///         Err((AuthenticationError::from(config).into(), req))
+    ///     }
+    /// }
+    ///
+    /// let middleware = HttpAuthentication::bearer(validator);
+    /// ```
+    pub fn bearer(process_fn: F) -> Self {
+        Self::with_fn(process_fn)
     }
 }
 
-impl<S, B, T, F, O> Transform<S, ServiceRequest> for HttpAuthentication<T, F>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
-    S::Future: 'static,
-    F: Fn(ServiceRequest, T) -> O + 'static,
-    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>> + 'static,
-    T: FromRequest + 'static,
-    B: MessageBody + 'static,
+impl<S, B, T, F, O> Transform<S, ServiceRequest> for HttpAuthentication<T, F>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
+    S::Future: 'static,
+    F: Fn(ServiceRequest, T) -> O + 'static,
+    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>> + 'static,
+    T: FromRequest + 'static,
+    B: MessageBody + 'static,
 {
-    type Response = ServiceResponse<EitherBody<B>>;
-    type Error = Error;
-    type Transform = AuthenticationMiddleware<S, F, T>;
-    type InitError = ();
-    type Future = future::Ready<Result<Self::Transform, Self::InitError>>;
+    type Response = ServiceResponse<EitherBody<B>>;
+    type Error = Error;
+    type Transform = AuthenticationMiddleware<S, F, T>;
+    type InitError = ();
+    type Future = future::Ready<Result<Self::Transform, Self::InitError>>;
 
-    fn new_transform(&self, service: S) -> Self::Future {
-        future::ok(AuthenticationMiddleware {
-            service: Rc::new(service),
-            process_fn: self.process_fn.clone(),
-            _extractor: PhantomData,
+    fn new_transform(&self, service: S) -> Self::Future {
+        future::ok(AuthenticationMiddleware {
+            service: Rc::new(service),
+            process_fn: self.process_fn.clone(),
+            _extractor: PhantomData,
         })
     }
 }
 
-#[doc(hidden)]
-pub struct AuthenticationMiddleware<S, F, T>
-where
-    T: FromRequest,
+#[doc(hidden)]
+pub struct AuthenticationMiddleware<S, F, T>
+where
+    T: FromRequest,
 {
-    service: Rc<S>,
-    process_fn: Arc<F>,
-    _extractor: PhantomData<T>,
+    service: Rc<S>,
+    process_fn: Arc<F>,
+    _extractor: PhantomData<T>,
 }
 
-impl<S, B, F, T, O> Service<ServiceRequest> for AuthenticationMiddleware<S, F, T>
-where
-    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
-    S::Future: 'static,
-    F: Fn(ServiceRequest, T) -> O + 'static,
-    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>> + 'static,
-    T: FromRequest + 'static,
-    B: MessageBody + 'static,
+impl<S, B, F, T, O> Service<ServiceRequest> for AuthenticationMiddleware<S, F, T>
+where
+    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
+    S::Future: 'static,
+    F: Fn(ServiceRequest, T) -> O + 'static,
+    O: Future<Output = Result<ServiceRequest, (Error, ServiceRequest)>> + 'static,
+    T: FromRequest + 'static,
+    B: MessageBody + 'static,
 {
-    type Response = ServiceResponse<EitherBody<B>>;
-    type Error = S::Error;
-    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
+    type Response = ServiceResponse<EitherBody<B>>;
+    type Error = S::Error;
+    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
 
-    actix_web::dev::forward_ready!(service);
+    actix_web::dev::forward_ready!(service);
 
-    fn call(&self, req: ServiceRequest) -> Self::Future {
-        let process_fn = Arc::clone(&self.process_fn);
-        let service = Rc::clone(&self.service);
+    fn call(&self, req: ServiceRequest) -> Self::Future {
+        let process_fn = Arc::clone(&self.process_fn);
+        let service = Rc::clone(&self.service);
 
-        Box::pin(async move {
-            let (req, credentials) = match Extract::<T>::new(req).await {
-                Ok(req) => req,
-                Err((err, req)) => {
-                    return Ok(req.error_response(err).map_into_right_body());
+        Box::pin(async move {
+            let (req, credentials) = match Extract::<T>::new(req).await {
+                Ok(req) => req,
+                Err((err, req)) => {
+                    return Ok(req.error_response(err).map_into_right_body());
                 }
             };
 
-            let req = match process_fn(req, credentials).await {
-                Ok(req) => req,
-                Err((err, req)) => {
-                    return Ok(req.error_response(err).map_into_right_body());
+            let req = match process_fn(req, credentials).await {
+                Ok(req) => req,
+                Err((err, req)) => {
+                    return Ok(req.error_response(err).map_into_right_body());
                 }
             };
 
-            service.call(req).await.map(|res| res.map_into_left_body())
+            service.call(req).await.map(|res| res.map_into_left_body())
         })
     }
 }
 
-struct Extract<T> {
-    req: Option<ServiceRequest>,
-    fut: Option<LocalBoxFuture<'static, Result<T, Error>>>,
-    _extractor: PhantomData<fn() -> T>,
+struct Extract<T> {
+    req: Option<ServiceRequest>,
+    fut: Option<LocalBoxFuture<'static, Result<T, Error>>>,
+    _extractor: PhantomData<fn() -> T>,
 }
 
-impl<T> Extract<T> {
-    pub fn new(req: ServiceRequest) -> Self {
-        Extract {
-            req: Some(req),
-            fut: None,
-            _extractor: PhantomData,
+impl<T> Extract<T> {
+    pub fn new(req: ServiceRequest) -> Self {
+        Extract {
+            req: Some(req),
+            fut: None,
+            _extractor: PhantomData,
         }
     }
 }
 
-impl<T> Future for Extract<T>
-where
-    T: FromRequest,
-    T::Future: 'static,
-    T::Error: 'static,
+impl<T> Future for Extract<T>
+where
+    T: FromRequest,
+    T::Future: 'static,
+    T::Error: 'static,
 {
-    type Output = Result<(ServiceRequest, T), (Error, ServiceRequest)>;
+    type Output = Result<(ServiceRequest, T), (Error, ServiceRequest)>;
 
-    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
-        if self.fut.is_none() {
-            let req = self.req.as_mut().expect("Extract future was polled twice!");
-            let fut = req.extract::<T>().map_err(Into::into);
-            self.fut = Some(Box::pin(fut));
+    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
+        if self.fut.is_none() {
+            let req = self.req.as_mut().expect("Extract future was polled twice!");
+            let fut = req.extract::<T>().map_err(Into::into);
+            self.fut = Some(Box::pin(fut));
         }
 
-        let fut = self
-            .fut
-            .as_mut()
-            .expect("Extraction future should be initialized at this point");
+        let fut = self
+            .fut
+            .as_mut()
+            .expect("Extraction future should be initialized at this point");
 
-        let credentials = ready!(fut.as_mut().poll(ctx)).map_err(|err| {
+        let credentials = ready!(fut.as_mut().poll(ctx)).map_err(|err| {
             (
-                err,
-                // returning request allows a proper error response to be created
-                self.req.take().expect("Extract future was polled twice!"),
+                err,
+                // returning request allows a proper error response to be created
+                self.req.take().expect("Extract future was polled twice!"),
             )
         })?;
 
-        let req = self.req.take().expect("Extract future was polled twice!");
-        Poll::Ready(Ok((req, credentials)))
+        let req = self.req.take().expect("Extract future was polled twice!");
+        Poll::Ready(Ok((req, credentials)))
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use actix_service::into_service;
-    use actix_web::{
-        dev::Service,
-        error::{self, ErrorForbidden},
-        http::StatusCode,
-        test::TestRequest,
-        web, App, HttpResponse,
+#[cfg(test)]
+mod tests {
+    use actix_service::into_service;
+    use actix_web::{
+        dev::Service,
+        error::{self, ErrorForbidden},
+        http::StatusCode,
+        test::TestRequest,
+        web, App, HttpResponse,
     };
 
-    use super::*;
-    use crate::extractors::{basic::BasicAuth, bearer::BearerAuth};
+    use super::*;
+    use crate::extractors::{basic::BasicAuth, bearer::BearerAuth};
 
-    /// This is a test for https://github.com/actix/actix-extras/issues/10
-    #[actix_web::test]
-    async fn test_middleware_panic() {
-        let middleware = AuthenticationMiddleware {
-            service: Rc::new(into_service(|_: ServiceRequest| async move {
-                actix_web::rt::time::sleep(std::time::Duration::from_secs(1)).await;
-                Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
+    /// This is a test for https://github.com/actix/actix-extras/issues/10
+    #[actix_web::test]
+    async fn test_middleware_panic() {
+        let middleware = AuthenticationMiddleware {
+            service: Rc::new(into_service(|_: ServiceRequest| async move {
+                actix_web::rt::time::sleep(std::time::Duration::from_secs(1)).await;
+                Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
             })),
-            process_fn: Arc::new(|req, _: BearerAuth| async { Ok(req) }),
-            _extractor: PhantomData,
+            process_fn: Arc::new(|req, _: BearerAuth| async { Ok(req) }),
+            _extractor: PhantomData,
         };
 
-        let req = TestRequest::get()
-            .append_header(("Authorization", "Bearer 1"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .append_header(("Authorization", "Bearer 1"))
+            .to_srv_request();
 
-        let f = middleware.call(req).await;
+        let f = middleware.call(req).await;
 
-        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
+        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
 
-        assert!(f.is_err());
+        assert!(f.is_err());
     }
 
-    /// This is a test for https://github.com/actix/actix-extras/issues/10
-    #[actix_web::test]
-    async fn test_middleware_panic_several_orders() {
-        let middleware = AuthenticationMiddleware {
-            service: Rc::new(into_service(|_: ServiceRequest| async move {
-                actix_web::rt::time::sleep(std::time::Duration::from_secs(1)).await;
-                Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
+    /// This is a test for https://github.com/actix/actix-extras/issues/10
+    #[actix_web::test]
+    async fn test_middleware_panic_several_orders() {
+        let middleware = AuthenticationMiddleware {
+            service: Rc::new(into_service(|_: ServiceRequest| async move {
+                actix_web::rt::time::sleep(std::time::Duration::from_secs(1)).await;
+                Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
             })),
-            process_fn: Arc::new(|req, _: BearerAuth| async { Ok(req) }),
-            _extractor: PhantomData,
+            process_fn: Arc::new(|req, _: BearerAuth| async { Ok(req) }),
+            _extractor: PhantomData,
         };
 
-        let req = TestRequest::get()
-            .append_header(("Authorization", "Bearer 1"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .append_header(("Authorization", "Bearer 1"))
+            .to_srv_request();
 
-        let f1 = middleware.call(req).await;
+        let f1 = middleware.call(req).await;
 
-        let req = TestRequest::get()
-            .append_header(("Authorization", "Bearer 1"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .append_header(("Authorization", "Bearer 1"))
+            .to_srv_request();
 
-        let f2 = middleware.call(req).await;
+        let f2 = middleware.call(req).await;
 
-        let req = TestRequest::get()
-            .append_header(("Authorization", "Bearer 1"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .append_header(("Authorization", "Bearer 1"))
+            .to_srv_request();
 
-        let f3 = middleware.call(req).await;
+        let f3 = middleware.call(req).await;
 
-        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
+        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
 
-        assert!(f1.is_err());
-        assert!(f2.is_err());
-        assert!(f3.is_err());
+        assert!(f1.is_err());
+        assert!(f2.is_err());
+        assert!(f3.is_err());
     }
 
-    #[actix_web::test]
-    async fn test_middleware_opt_extractor() {
-        let middleware = AuthenticationMiddleware {
-            service: Rc::new(into_service(|req: ServiceRequest| async move {
-                Ok::<ServiceResponse, _>(req.into_response(HttpResponse::Ok().finish()))
+    #[actix_web::test]
+    async fn test_middleware_opt_extractor() {
+        let middleware = AuthenticationMiddleware {
+            service: Rc::new(into_service(|req: ServiceRequest| async move {
+                Ok::<ServiceResponse, _>(req.into_response(HttpResponse::Ok().finish()))
             })),
-            process_fn: Arc::new(|req, auth: Option<BearerAuth>| {
-                assert!(auth.is_none());
-                async { Ok(req) }
+            process_fn: Arc::new(|req, auth: Option<BearerAuth>| {
+                assert!(auth.is_none());
+                async { Ok(req) }
             }),
-            _extractor: PhantomData,
+            _extractor: PhantomData,
         };
 
-        let req = TestRequest::get()
-            .append_header(("Authorization996", "Bearer 1"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .append_header(("Authorization996", "Bearer 1"))
+            .to_srv_request();
 
-        let f = middleware.call(req).await;
+        let f = middleware.call(req).await;
 
-        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
+        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
 
-        assert!(f.is_ok());
+        assert!(f.is_ok());
     }
 
-    #[actix_web::test]
-    async fn test_middleware_res_extractor() {
-        let middleware = AuthenticationMiddleware {
-            service: Rc::new(into_service(|req: ServiceRequest| async move {
-                Ok::<ServiceResponse, _>(req.into_response(HttpResponse::Ok().finish()))
+    #[actix_web::test]
+    async fn test_middleware_res_extractor() {
+        let middleware = AuthenticationMiddleware {
+            service: Rc::new(into_service(|req: ServiceRequest| async move {
+                Ok::<ServiceResponse, _>(req.into_response(HttpResponse::Ok().finish()))
             })),
-            process_fn: Arc::new(
-                |req, auth: Result<BearerAuth, <BearerAuth as FromRequest>::Error>| {
-                    assert!(auth.is_err());
-                    async { Ok(req) }
+            process_fn: Arc::new(
+                |req, auth: Result<BearerAuth, <BearerAuth as FromRequest>::Error>| {
+                    assert!(auth.is_err());
+                    async { Ok(req) }
                 },
             ),
-            _extractor: PhantomData,
+            _extractor: PhantomData,
         };
 
-        let req = TestRequest::get()
-            .append_header(("Authorization", "BearerLOL"))
-            .to_srv_request();
+        let req = TestRequest::get()
+            .append_header(("Authorization", "BearerLOL"))
+            .to_srv_request();
 
-        let f = middleware.call(req).await;
+        let f = middleware.call(req).await;
 
-        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
+        let _res = futures_util::future::lazy(|cx| middleware.poll_ready(cx)).await;
 
-        assert!(f.is_ok());
+        assert!(f.is_ok());
     }
 
-    #[actix_web::test]
-    async fn test_middleware_works_with_app() {
-        async fn validator(
-            req: ServiceRequest,
-            _credentials: BasicAuth,
-        ) -> Result<ServiceRequest, (actix_web::Error, ServiceRequest)> {
-            Err((ErrorForbidden("You are not welcome!"), req))
+    #[actix_web::test]
+    async fn test_middleware_works_with_app() {
+        async fn validator(
+            req: ServiceRequest,
+            _credentials: BasicAuth,
+        ) -> Result<ServiceRequest, (actix_web::Error, ServiceRequest)> {
+            Err((ErrorForbidden("You are not welcome!"), req))
         }
-        let middleware = HttpAuthentication::basic(validator);
+        let middleware = HttpAuthentication::basic(validator);
 
-        let srv = actix_web::test::init_service(
-            App::new()
-                .wrap(middleware)
-                .route("/", web::get().to(HttpResponse::Ok)),
+        let srv = actix_web::test::init_service(
+            App::new()
+                .wrap(middleware)
+                .route("/", web::get().to(HttpResponse::Ok)),
         )
         .await;
 
-        let req = actix_web::test::TestRequest::with_uri("/")
-            .append_header(("Authorization", "Basic DontCare"))
-            .to_request();
+        let req = actix_web::test::TestRequest::with_uri("/")
+            .append_header(("Authorization", "Basic DontCare"))
+            .to_request();
 
-        let resp = srv.call(req).await.unwrap();
-        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+        let resp = srv.call(req).await.unwrap();
+        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
     }
 
-    #[actix_web::test]
-    async fn test_middleware_works_with_scope() {
-        async fn validator(
-            req: ServiceRequest,
-            _credentials: BasicAuth,
-        ) -> Result<ServiceRequest, (actix_web::Error, ServiceRequest)> {
-            Err((ErrorForbidden("You are not welcome!"), req))
+    #[actix_web::test]
+    async fn test_middleware_works_with_scope() {
+        async fn validator(
+            req: ServiceRequest,
+            _credentials: BasicAuth,
+        ) -> Result<ServiceRequest, (actix_web::Error, ServiceRequest)> {
+            Err((ErrorForbidden("You are not welcome!"), req))
         }
-        let middleware = actix_web::middleware::Compat::new(HttpAuthentication::basic(validator));
+        let middleware = actix_web::middleware::Compat::new(HttpAuthentication::basic(validator));
 
-        let srv = actix_web::test::init_service(
-            App::new().service(
-                web::scope("/")
-                    .wrap(middleware)
-                    .route("/", web::get().to(HttpResponse::Ok)),
+        let srv = actix_web::test::init_service(
+            App::new().service(
+                web::scope("/")
+                    .wrap(middleware)
+                    .route("/", web::get().to(HttpResponse::Ok)),
             ),
         )
         .await;
 
-        let req = actix_web::test::TestRequest::with_uri("/")
-            .append_header(("Authorization", "Basic DontCare"))
-            .to_request();
+        let req = actix_web::test::TestRequest::with_uri("/")
+            .append_header(("Authorization", "Basic DontCare"))
+            .to_request();
 
-        let resp = srv.call(req).await.unwrap();
-        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+        let resp = srv.call(req).await.unwrap();
+        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file diff --git a/src/actix_web_httpauth/utils.rs.html b/src/actix_web_httpauth/utils.rs.html index 59dcfd8fd..7e869d730 100644 --- a/src/actix_web_httpauth/utils.rs.html +++ b/src/actix_web_httpauth/utils.rs.html @@ -110,117 +110,117 @@ 110 111 112 -
use std::str;
+
use std::str;
 
-use actix_web::web::BytesMut;
+use actix_web::web::BytesMut;
 
-enum State {
-    YieldStr,
-    YieldQuote,
+enum State {
+    YieldStr,
+    YieldQuote,
 }
 
-struct Quoted<'a> {
-    inner: ::std::iter::Peekable<str::Split<'a, char>>,
-    state: State,
+struct Quoted<'a> {
+    inner: ::std::iter::Peekable<str::Split<'a, char>>,
+    state: State,
 }
 
-impl<'a> Quoted<'a> {
-    pub fn new(s: &'a str) -> Quoted<'_> {
-        Quoted {
-            inner: s.split('"').peekable(),
-            state: State::YieldStr,
+impl<'a> Quoted<'a> {
+    pub fn new(s: &'a str) -> Quoted<'_> {
+        Quoted {
+            inner: s.split('"').peekable(),
+            state: State::YieldStr,
         }
     }
 }
 
-impl<'a> Iterator for Quoted<'a> {
-    type Item = &'a str;
+impl<'a> Iterator for Quoted<'a> {
+    type Item = &'a str;
 
-    fn next(&mut self) -> Option<Self::Item> {
-        match self.state {
-            State::YieldStr => match self.inner.next() {
-                Some(val) => {
-                    self.state = State::YieldQuote;
-                    Some(val)
+    fn next(&mut self) -> Option<Self::Item> {
+        match self.state {
+            State::YieldStr => match self.inner.next() {
+                Some(val) => {
+                    self.state = State::YieldQuote;
+                    Some(val)
                 }
-                None => None,
+                None => None,
             },
 
-            State::YieldQuote => match self.inner.peek() {
+            State::YieldQuote => match self.inner.peek() {
                 Some(_) => {
-                    self.state = State::YieldStr;
+                    self.state = State::YieldStr;
                     Some("\\\"")
                 }
-                None => None,
+                None => None,
             },
         }
     }
 }
 
-/// Escapes the quotes in `val`.
-pub fn put_quoted(buf: &mut BytesMut, val: &str) {
-    for part in Quoted::new(val) {
-        buf.extend_from_slice(part.as_bytes());
+/// Escapes the quotes in `val`.
+pub fn put_quoted(buf: &mut BytesMut, val: &str) {
+    for part in Quoted::new(val) {
+        buf.extend_from_slice(part.as_bytes());
     }
 }
 
-#[cfg(test)]
-mod tests {
-    use std::str;
+#[cfg(test)]
+mod tests {
+    use std::str;
 
-    use actix_web::web::BytesMut;
+    use actix_web::web::BytesMut;
 
-    use super::put_quoted;
+    use super::put_quoted;
 
-    #[test]
-    fn test_quote_str() {
-        let input = "a \"quoted\" string";
-        let mut output = BytesMut::new();
-        put_quoted(&mut output, input);
-        let result = str::from_utf8(&output).unwrap();
+    #[test]
+    fn test_quote_str() {
+        let input = "a \"quoted\" string";
+        let mut output = BytesMut::new();
+        put_quoted(&mut output, input);
+        let result = str::from_utf8(&output).unwrap();
 
-        assert_eq!(result, "a \\\"quoted\\\" string");
+        assert_eq!(result, "a \\\"quoted\\\" string");
     }
 
-    #[test]
-    fn test_without_quotes() {
-        let input = "non-quoted string";
-        let mut output = BytesMut::new();
-        put_quoted(&mut output, input);
-        let result = str::from_utf8(&output).unwrap();
+    #[test]
+    fn test_without_quotes() {
+        let input = "non-quoted string";
+        let mut output = BytesMut::new();
+        put_quoted(&mut output, input);
+        let result = str::from_utf8(&output).unwrap();
 
-        assert_eq!(result, "non-quoted string");
+        assert_eq!(result, "non-quoted string");
     }
 
-    #[test]
-    fn test_starts_with_quote() {
-        let input = "\"first-quoted string";
-        let mut output = BytesMut::new();
-        put_quoted(&mut output, input);
-        let result = str::from_utf8(&output).unwrap();
+    #[test]
+    fn test_starts_with_quote() {
+        let input = "\"first-quoted string";
+        let mut output = BytesMut::new();
+        put_quoted(&mut output, input);
+        let result = str::from_utf8(&output).unwrap();
 
-        assert_eq!(result, "\\\"first-quoted string");
+        assert_eq!(result, "\\\"first-quoted string");
     }
 
-    #[test]
-    fn test_ends_with_quote() {
-        let input = "last-quoted string\"";
-        let mut output = BytesMut::new();
-        put_quoted(&mut output, input);
-        let result = str::from_utf8(&output).unwrap();
+    #[test]
+    fn test_ends_with_quote() {
+        let input = "last-quoted string\"";
+        let mut output = BytesMut::new();
+        put_quoted(&mut output, input);
+        let result = str::from_utf8(&output).unwrap();
 
-        assert_eq!(result, "last-quoted string\\\"");
+        assert_eq!(result, "last-quoted string\\\"");
     }
 
-    #[test]
-    fn test_double_quote() {
-        let input = "quote\"\"string";
-        let mut output = BytesMut::new();
-        put_quoted(&mut output, input);
-        let result = str::from_utf8(&output).unwrap();
+    #[test]
+    fn test_double_quote() {
+        let input = "quote\"\"string";
+        let mut output = BytesMut::new();
+        put_quoted(&mut output, input);
+        let result = str::from_utf8(&output).unwrap();
 
-        assert_eq!(result, "quote\\\"\\\"string");
+        assert_eq!(result, "quote\\\"\\\"string");
     }
 }
 
-
\ No newline at end of file +
\ No newline at end of file