CodeSampleX

Ejemplo

axum-macros 0.5.1: FromRequestParts

Muestra verificada para cargo axum-macros 0.5.1: FromRequestParts. El contrato se ejecutó en rust 1 · linux alpine/x64 · docker y pasó.

sha256:a3d0daac144e72990541788ef8e90b1929493a65a549d3c26a9a881998466c80

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux · alpine · musl x64 cargo

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-17

Caso

HOW
Objetivo
verify FromRequestParts in pkg:cargo/axum-macros@0.5.1
Paquetes
Símbolos
  • FromRequestParts
Creado
2026-11-17T00:51:06Z

Contrato

  1. FromRequestParts derives axum::extract::FromRequestParts on named and tuple structs to extract fields without consuming the request body, inferring state from State<T> fields and defaulting Rejection to axum::response::Response
  2. Field-level #[from_request(via(...))] extracts inner values via wrapper extractors and supports Option<T> and Result<T, Rejection> for optional or fallible parts
  3. Container-level #[from_request(state(...), rejection(...))] binds extraction to a concrete state type and converts field rejections via From into a custom rejection type
  4. Container-level #[from_request(via(...))] extracts structs, single-field generic tuple structs, and enums as a whole via a wrapper extractor
  5. Deriving FromRequestParts on unit structs sets Rejection to std::convert::Infallible and succeeds for any Send + Sync state

Archivos

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
 "axum-core",
 "bytes",
 "futures-util",
 "http",
 "http-body",
 "http-body-util",
 "itoa",
 "matchit",
 "memchr",
 "mime",
 "percent-encoding",
 "pin-project-lite",
 "serde_core",
 "sync_wrapper",
 "tower",
 "tower-layer",
 "tower-service",
]

[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
 "bytes",
 "futures-core",
 "http",
 "http-body",
 "http-body-util",
 "mime",
 "pin-project-lite",
 "sync_wrapper",
 "tower-layer",
 "tower-service",
]

[[package]]
name = "axum-macros"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"
dependencies = [
 "proc-macro2",
 "quote",
 "syn 2.0.119",
]

[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"

[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"

[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"

[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
 "futures-core",
 "futures-task",
 "pin-project-lite",
 "slab",
]

[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
 "bytes",
 "itoa",
]

[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
 "bytes",
 "http",
]

[[package]]
name = "http-body-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
dependencies = [
 "bytes",
 "futures-core",
 "http",
 "http-body",
 "pin-project-lite",
]

[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"

[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"

[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"

[[package]]
name = "mime"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"

[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"

[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "sample-axum-macros-from-request-parts"
version = "1.0.0"
dependencies = [
 "axum",
 "axum-macros",
]

[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
 "serde_derive",
]

[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
 "proc-macro2",
 "quote",
 "syn 3.0.10",
]

[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"

[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"

[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
 "futures-core",
 "futures-util",
 "pin-project-lite",
 "sync_wrapper",
 "tower-layer",
 "tower-service",
]

[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"

[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"

[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
Cargo.toml
[package]
name = "sample-axum-macros-from-request-parts"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
axum-macros = "=0.5.1"
axum = { version = "=0.8.9", default-features = false }

[[bin]]
name = "contract"
path = "test/contract.rs"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify FromRequestParts in pkg:cargo/axum-macros@0.5.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/axum-macros@0.5.1
Demonstrate these symbols/APIs:
  - FromRequestParts

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:a4e548fabf1b0c58f6598c44574114f55955de883c6066f069901751236dc453","contract":["FromRequestParts derives axum::extract::FromRequestParts on named and tuple structs to extract fields without consuming the request body, inferring state from State\u003cT\u003e fields and defaulting Rejection to axum::response::Response","Field-level #[from_request(via(...))] extracts inner values via wrapper extractors and supports Option\u003cT\u003e and Result\u003cT, Rejection\u003e for optional or fallible parts","Container-level #[from_request(state(...), rejection(...))] binds extraction to a concrete state type and converts field rejections via From into a custom rejection type","Container-level #[from_request(via(...))] extracts structs, single-field generic tuple structs, and enums as a whole via a wrapper extractor","Deriving FromRequestParts on unit structs sets Rejection to std::convert::Infallible and succeeds for any Send + Sync state"],"goal":"verify FromRequestParts in pkg:cargo/axum-macros@0.5.1","kind":"HOW","packages":["pkg:cargo/axum-macros@0.5.1"],"schemaVersion":1,"symbols":["FromRequestParts"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/axum-macros@0.5.1"],"schemaVersion":1,"subject":"pkg:cargo/axum-macros@0.5.1","symbols":["FromRequestParts"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify FromRequestParts in pkg:cargo/axum-macros@0.5.1",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/axum-macros@0.5.1"
  ],
  "symbols": [
    "FromRequestParts"
  ]
}
src/lib.rs
//! Clean-room verification sample for FromRequestParts in axum-macros.

pub use axum_macros::FromRequestParts;
test/contract.rs
use std::convert::Infallible;
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};

use axum::extract::rejection::ExtensionRejection;
use axum::extract::{Extension, FromRequestParts, State};
use axum::http::request::Parts;
use axum::http::{HeaderMap, Method, Request, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum_macros::FromRequestParts;

struct NoopWake;

impl Wake for NoopWake {
    fn wake(self: Arc<Self>) {}
}

fn block_on<F: Future>(fut: F) -> F::Output {
    let waker = Waker::from(Arc::new(NoopWake));
    let mut cx = Context::from_waker(&waker);
    let mut fut = pin!(fut);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(val) => return val,
            Poll::Pending => std::thread::yield_now(),
        }
    }
}

// 1. Named and tuple structs extracting fields individually with inferred State<AppConfig>
#[derive(Clone, Debug, PartialEq, Eq)]
struct AppConfig {
    label: &'static str,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct CorrelationId(u64);

#[derive(FromRequestParts, Debug)]
struct RequestSummary {
    method: Method,
    uri: Uri,
    headers: HeaderMap,
    config: State<AppConfig>,
    correlation: Extension<CorrelationId>,
}

#[derive(FromRequestParts, Debug, PartialEq, Eq)]
struct MethodAndUri(Method, Uri);

// 2. Field-level #[from_request(via(...))] with required, Option, and Result fields
#[derive(Clone, Debug, PartialEq, Eq)]
struct ScopeName(&'static str);

#[derive(Clone, Debug, PartialEq, Eq)]
struct VerboseFlag(bool);

#[derive(Clone, Debug, PartialEq, Eq)]
struct SequenceNum(u32);

#[derive(FromRequestParts, Debug)]
struct ScopedParts {
    #[from_request(via(Extension))]
    scope: ScopeName,
    #[from_request(via(Extension))]
    verbose: Option<VerboseFlag>,
    #[from_request(via(Extension))]
    sequence: Result<SequenceNum, ExtensionRejection>,
}

// 3. Container-level #[from_request(state(...), rejection(...))]
#[derive(Clone)]
struct ModeState {
    expected_mode: &'static str,
}

#[derive(Debug, PartialEq, Eq)]
struct CheckedMode(String);

#[derive(Debug, PartialEq, Eq)]
enum ModeRejection {
    MissingHeader,
    UnsupportedMode,
    MissingExtension(String),
}

impl From<Infallible> for ModeRejection {
    fn from(never: Infallible) -> Self {
        match never {}
    }
}

impl From<ExtensionRejection> for ModeRejection {
    fn from(rej: ExtensionRejection) -> Self {
        ModeRejection::MissingExtension(rej.body_text())
    }
}

impl IntoResponse for ModeRejection {
    fn into_response(self) -> Response {
        match self {
            ModeRejection::MissingHeader | ModeRejection::UnsupportedMode => {
                (StatusCode::BAD_REQUEST, "invalid mode").into_response()
            }
            ModeRejection::MissingExtension(msg) => {
                (StatusCode::INTERNAL_SERVER_ERROR, msg).into_response()
            }
        }
    }
}

impl FromRequestParts<ModeState> for CheckedMode {
    type Rejection = ModeRejection;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &ModeState,
    ) -> Result<Self, Self::Rejection> {
        let raw = parts
            .headers
            .get("x-mode")
            .and_then(|v| v.to_str().ok())
            .ok_or(ModeRejection::MissingHeader)?;
        if raw == state.expected_mode {
            Ok(CheckedMode(raw.to_owned()))
        } else {
            Err(ModeRejection::UnsupportedMode)
        }
    }
}

#[derive(FromRequestParts, Debug, PartialEq, Eq)]
#[from_request(state(ModeState), rejection(ModeRejection))]
struct ValidatedModeParts {
    method: Method,
    mode: CheckedMode,
    #[from_request(via(Extension))]
    scope: ScopeName,
}

// 4. Container-level #[from_request(via(...))] on structs, generic tuple structs, and enums
#[derive(Clone, Debug, PartialEq, Eq, FromRequestParts)]
#[from_request(via(Extension))]
struct WholeSettings {
    region: &'static str,
    max_items: u16,
}

#[derive(Clone, Debug, PartialEq, Eq, FromRequestParts)]
#[from_request(via(Extension), rejection(ModeRejection))]
struct WrappedExt<T>(T);

#[derive(Clone, Debug, PartialEq, Eq, FromRequestParts)]
#[from_request(via(Extension))]
enum AccessTier {
    Standard,
    Elevated,
}

// 5. Unit struct derives infallible FromRequestParts<S>
#[derive(Debug, PartialEq, Eq, FromRequestParts)]
struct UnitParts;

fn main() {
    // 1. Named and tuple structs + State inference + preserving request body + default Response rejection
    let app_cfg = AppConfig { label: "v1" };
    let req = Request::builder()
        .method(Method::POST)
        .uri("http://example.com/items?limit=10")
        .header("x-client", "cli")
        .extension(CorrelationId(9001))
        .body("untouched-payload")
        .unwrap();
    let (mut parts, body) = req.into_parts();

    let summary = block_on(RequestSummary::from_request_parts(&mut parts, &app_cfg)).unwrap();
    assert_eq!(summary.method, Method::POST);
    assert_eq!(summary.uri.path(), "/items");
    assert_eq!(summary.uri.query(), Some("limit=10"));
    assert_eq!(summary.headers.get("x-client").unwrap(), "cli");
    assert_eq!(summary.config.0, app_cfg);
    assert_eq!(summary.correlation.0, CorrelationId(9001));

    let pair = block_on(MethodAndUri::from_request_parts(&mut parts, &())).unwrap();
    assert_eq!(pair.0, Method::POST);
    assert_eq!(pair.1.path(), "/items");

    let rebuilt = Request::from_parts(parts, body);
    assert_eq!(*rebuilt.body(), "untouched-payload");

    let (mut missing_parts, _) = Request::builder()
        .uri("http://example.com/items")
        .body(())
        .unwrap()
        .into_parts();
    let missing_err: Response =
        block_on(RequestSummary::from_request_parts(&mut missing_parts, &app_cfg)).unwrap_err();
    assert_eq!(missing_err.status(), StatusCode::INTERNAL_SERVER_ERROR);

    // 2. Field-level #[from_request(via(...))] with required, Option, and Result
    let (mut scoped_parts, _) = Request::builder()
        .uri("http://example.com/scoped")
        .extension(ScopeName("catalog"))
        .extension(VerboseFlag(true))
        .extension(SequenceNum(42))
        .body(())
        .unwrap()
        .into_parts();
    let extracted_full = block_on(ScopedParts::from_request_parts(&mut scoped_parts, &())).unwrap();
    assert_eq!(extracted_full.scope, ScopeName("catalog"));
    assert_eq!(extracted_full.verbose, Some(VerboseFlag(true)));
    assert_eq!(extracted_full.sequence.unwrap(), SequenceNum(42));

    let (mut partial_parts, _) = Request::builder()
        .uri("http://example.com/scoped")
        .extension(ScopeName("inventory"))
        .body(())
        .unwrap()
        .into_parts();
    let extracted_partial =
        block_on(ScopedParts::from_request_parts(&mut partial_parts, &())).unwrap();
    assert_eq!(extracted_partial.scope, ScopeName("inventory"));
    assert_eq!(extracted_partial.verbose, None);
    assert!(extracted_partial.sequence.is_err());

    // 3. Container-level state(...) and rejection(...)
    let mode_state = ModeState {
        expected_mode: "strict",
    };
    let (mut ok_mode_parts, _) = Request::builder()
        .method(Method::GET)
        .uri("http://example.com/check")
        .header("x-mode", "strict")
        .extension(ScopeName("orders"))
        .body(())
        .unwrap()
        .into_parts();
    let validated =
        block_on(ValidatedModeParts::from_request_parts(&mut ok_mode_parts, &mode_state)).unwrap();
    assert_eq!(
        validated,
        ValidatedModeParts {
            method: Method::GET,
            mode: CheckedMode("strict".to_owned()),
            scope: ScopeName("orders"),
        }
    );

    let (mut no_hdr_parts, _) = Request::builder()
        .uri("http://example.com/check")
        .extension(ScopeName("orders"))
        .body(())
        .unwrap()
        .into_parts();
    assert_eq!(
        block_on(ValidatedModeParts::from_request_parts(&mut no_hdr_parts, &mode_state)),
        Err(ModeRejection::MissingHeader)
    );

    let (mut bad_mode_parts, _) = Request::builder()
        .uri("http://example.com/check")
        .header("x-mode", "relaxed")
        .extension(ScopeName("orders"))
        .body(())
        .unwrap()
        .into_parts();
    assert_eq!(
        block_on(ValidatedModeParts::from_request_parts(&mut bad_mode_parts, &mode_state)),
        Err(ModeRejection::UnsupportedMode)
    );

    let (mut no_ext_parts, _) = Request::builder()
        .uri("http://example.com/check")
        .header("x-mode", "strict")
        .body(())
        .unwrap()
        .into_parts();
    assert!(matches!(
        block_on(ValidatedModeParts::from_request_parts(&mut no_ext_parts, &mode_state)),
        Err(ModeRejection::MissingExtension(_))
    ));

    // 4. Container-level #[from_request(via(...))] on struct, generic tuple struct, and enum
    let (mut via_parts, _) = Request::builder()
        .uri("http://example.com/via")
        .extension(WholeSettings {
            region: "eu-central",
            max_items: 250,
        })
        .extension(SequenceNum(77))
        .extension(AccessTier::Elevated)
        .body(())
        .unwrap()
        .into_parts();

    let settings = block_on(WholeSettings::from_request_parts(&mut via_parts, &())).unwrap();
    assert_eq!(
        settings,
        WholeSettings {
            region: "eu-central",
            max_items: 250,
        }
    );

    let wrapped: WrappedExt<SequenceNum> =
        block_on(WrappedExt::<SequenceNum>::from_request_parts(&mut via_parts, &())).unwrap();
    assert_eq!(wrapped, WrappedExt(SequenceNum(77)));

    let tier = block_on(AccessTier::from_request_parts(&mut via_parts, &())).unwrap();
    assert_eq!(tier, AccessTier::Elevated);

    let (mut empty_via_parts, _) = Request::builder()
        .uri("http://example.com/via")
        .body(())
        .unwrap()
        .into_parts();
    assert!(matches!(
        block_on(WrappedExt::<SequenceNum>::from_request_parts(&mut empty_via_parts, &())),
        Err(ModeRejection::MissingExtension(_))
    ));
    let _ = AccessTier::Standard;

    // 5. Unit struct infallible extraction
    let unit_res: Result<UnitParts, Infallible> =
        block_on(UnitParts::from_request_parts(&mut empty_via_parts, &()));
    assert_eq!(unit_res, Ok(UnitParts));
}

Seeder de origen

anónimo