CodeSampleX

Пример

http 1.4.0: http::Request

Проверенный пример — cargo http 1.4.0: http::Request. Контракт выполнен на rust 1 · linux alpine/x64 · docker и пройден: Request::new constructs a default…

sha256:0dd09768818f596e28a7fe9b4060f4541b580b7067b981c2e79d1dec94d56cea

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux · alpine · musl x64 cargo

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-16

Кейс

HOW
Цель
verify http::Request in pkg:cargo/http@1.4.0
Пакеты
Символы
  • http::Request
Создан
2026-11-16T23:27:38Z

Контракт

  1. Request::new constructs a default GET / HTTP/1.1 request with empty headers and the supplied body
  2. Request::builder and method-specific constructors (such as Request::get and Request::put) configure method, URI, HTTP version, headers, extensions, and body
  3. Mutable accessors (method_mut, uri_mut, version_mut, headers_mut, extensions_mut, body_mut) update request metadata and payload in place
  4. Request::map, into_parts, and Request::from_parts transform or replace the body type while preserving method, URI, headers, and typed extensions
  5. Invalid URI syntax or invalid header names cause Request::builder().body(...) to return Err(http::Error)

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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

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

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

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

[[package]]
name = "sample-http-request"
version = "0.1.0"
dependencies = [
 "http",
]
Cargo.toml
[package]
name = "sample-http-request"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
http = "=1.4.0"

[[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 http::Request in pkg:cargo/http@1.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/http@1.4.0
Demonstrate these symbols/APIs:
  - http::Request

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:2d81ea0264d176b60159000675ae5d8cb58510f12b236ab540e3056ae97462fc","contract":["Request::new constructs a default GET / HTTP/1.1 request with empty headers and the supplied body","Request::builder and method-specific constructors (such as Request::get and Request::put) configure method, URI, HTTP version, headers, extensions, and body","Mutable accessors (method_mut, uri_mut, version_mut, headers_mut, extensions_mut, body_mut) update request metadata and payload in place","Request::map, into_parts, and Request::from_parts transform or replace the body type while preserving method, URI, headers, and typed extensions","Invalid URI syntax or invalid header names cause Request::builder().body(...) to return Err(http::Error)"],"goal":"verify http::Request in pkg:cargo/http@1.4.0","kind":"HOW","packages":["pkg:cargo/http@1.4.0"],"schemaVersion":1,"symbols":["http::Request"]},"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/http@1.4.0"],"schemaVersion":1,"subject":"pkg:cargo/http@1.4.0","symbols":["http::Request"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify http::Request in pkg:cargo/http@1.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/http@1.4.0"
  ],
  "symbols": [
    "http::Request"
  ]
}
src/lib.rs
//! Minimal verification helpers for `http::Request` in `http` 1.4.0.

use http::header::{HeaderName, HeaderValue};
use http::{Method, Request, Result, Version};

/// Builds a typed `http::Request<T>` with explicit method, URI, HTTP version, and a single header.
pub fn build_typed_request<T>(
    method: Method,
    uri: &str,
    version: Version,
    header_name: HeaderName,
    header_value: HeaderValue,
    body: T,
) -> Result<Request<T>> {
    Request::builder()
        .method(method)
        .uri(uri)
        .version(version)
        .header(header_name, header_value)
        .body(body)
}

/// Transforms a `Request<Vec<u8>>` body into its byte length via `Request::map`.
pub fn map_body_to_len(req: Request<Vec<u8>>) -> Request<usize> {
    req.map(|bytes| bytes.len())
}
test/contract.rs
use http::header::{HeaderValue, ACCEPT, CONTENT_TYPE};
use http::{Method, Request, Uri, Version};
use sample_http_request::{build_typed_request, map_body_to_len};

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

fn main() {
    // 1. Request::new constructs a default GET / HTTP/1.1 request with empty headers and the given body
    let default_req: Request<&str> = Request::new("ping");
    assert_eq!(default_req.method(), Method::GET);
    assert_eq!(default_req.uri(), "/");
    assert_eq!(default_req.version(), Version::HTTP_11);
    assert!(default_req.headers().is_empty());
    assert_eq!(*default_req.body(), "ping");
    assert_eq!(default_req.into_body(), "ping");

    // 2. Request::builder and method-specific constructors configure method, URI, version, headers, extensions, and body
    let built = build_typed_request(
        Method::POST,
        "https://example.com/v1/items?limit=10",
        Version::HTTP_2,
        CONTENT_TYPE,
        HeaderValue::from_static("application/json"),
        b"{\"ok\":true}".to_vec(),
    )
    .expect("valid request should build");

    assert_eq!(built.method(), Method::POST);
    assert_eq!(built.uri().scheme_str(), Some("https"));
    assert_eq!(built.uri().host(), Some("example.com"));
    assert_eq!(built.uri().path(), "/v1/items");
    assert_eq!(built.uri().query(), Some("limit=10"));
    assert_eq!(built.version(), Version::HTTP_2);
    assert_eq!(
        built.headers().get(CONTENT_TYPE),
        Some(&HeaderValue::from_static("application/json"))
    );
    assert_eq!(built.body().as_slice(), b"{\"ok\":true}");

    let shortcut_get = Request::get("http://localhost:8080/health")
        .header(ACCEPT, "text/plain")
        .extension(TraceId(42))
        .body(())
        .expect("Request::get builder should succeed");
    assert_eq!(shortcut_get.method(), Method::GET);
    assert_eq!(shortcut_get.uri().path(), "/health");
    assert_eq!(
        shortcut_get.headers().get(ACCEPT),
        Some(&HeaderValue::from_static("text/plain"))
    );
    assert_eq!(shortcut_get.extensions().get::<TraceId>(), Some(&TraceId(42)));

    // 3. Mutable accessors update method, URI, version, headers, extensions, and body in place
    let mut mutable_req = Request::put("https://example.com/resource/1")
        .body(String::from("initial"))
        .expect("Request::put should build");
    *mutable_req.method_mut() = Method::PATCH;
    *mutable_req.uri_mut() = Uri::from_static("https://example.com/resource/2");
    *mutable_req.version_mut() = Version::HTTP_11;
    mutable_req
        .headers_mut()
        .insert("x-mode", HeaderValue::from_static("delta"));
    mutable_req.extensions_mut().insert(TraceId(99));
    mutable_req.body_mut().push_str("-updated");

    assert_eq!(mutable_req.method(), Method::PATCH);
    assert_eq!(mutable_req.uri().path(), "/resource/2");
    assert_eq!(
        mutable_req.headers().get("x-mode"),
        Some(&HeaderValue::from_static("delta"))
    );
    assert_eq!(mutable_req.extensions().get::<TraceId>(), Some(&TraceId(99)));
    assert_eq!(mutable_req.body(), "initial-updated");

    // 4. into_parts, from_parts, and map transform the body type while preserving metadata and extensions
    let mapped_len = map_body_to_len(built);
    assert_eq!(mapped_len.method(), Method::POST);
    assert_eq!(mapped_len.uri().path(), "/v1/items");
    assert_eq!(*mapped_len.body(), 11usize);

    let (mut parts, old_body) = mutable_req.into_parts();
    assert_eq!(old_body, "initial-updated");
    assert_eq!(parts.method, Method::PATCH);
    parts.method = Method::DELETE;
    let rebuilt: Request<Option<u32>> = Request::from_parts(parts, Some(7));
    assert_eq!(rebuilt.method(), Method::DELETE);
    assert_eq!(rebuilt.uri().path(), "/resource/2");
    assert_eq!(rebuilt.extensions().get::<TraceId>(), Some(&TraceId(99)));
    assert_eq!(*rebuilt.body(), Some(7));

    // 5. Invalid URIs or invalid header names make Request::builder().body(...) return Err(http::Error)
    let bad_uri = Request::builder().uri("http://example.com/has space").body(());
    assert!(bad_uri.is_err());

    let bad_header = Request::builder()
        .uri("https://example.com/ok")
        .header("bad\nheader", "value")
        .body(());
    assert!(bad_header.is_err());
}

Исходный сидер

аноним