Skip to main content

aws_smithy_schema/
lib.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6/* Automatically managed default lints */
7#![cfg_attr(docsrs, feature(doc_cfg))]
8/* End of automatically managed default lints */
9#![forbid(unsafe_code)]
10#![warn(
11    missing_docs,
12    rustdoc::missing_crate_level_docs,
13    missing_debug_implementations,
14    rust_2018_idioms,
15    unreachable_pub
16)]
17
18//! Runtime schema types for Smithy shapes.
19//!
20//! This crate provides the core types for representing Smithy schemas at
21//! runtime, enabling protocol-agnostic serialization and deserialization.
22//! The two central types are [`Schema`] (a runtime descriptor of a Smithy
23//! shape) and [`ShapeId`] (a Smithy shape identifier). Both are parameterized
24//! over a lifetime `'a` that names the data their string fields and member
25//! references borrow from. An [`OperationSchema`] relates an operation's
26//! shape ID to its input, output, and error schemas.
27//!
28//! # API stability
29//!
30//! Items marked `#[doc(hidden)]` are not part of the public API. They exist for
31//! generated code and the `shape_id!` macro to call, and may change or disappear
32//! in any release.
33//!
34//! # Construction patterns
35//!
36//! ## `Schema<'static>` — the codegen-emitted form
37//!
38//! Generated SDK code emits every schema as a `static` of type
39//! `Schema<'static>`, built at compile time via `const fn` constructors and
40//! `with_*` setters. The Smithy prelude entries in this crate
41//! ([`prelude::STRING`], [`prelude::INTEGER`], etc.) follow the same pattern.
42//! Because the entire schema graph lives in the binary's data segment, there
43//! is no startup cost and no heap allocation on the hot serde path.
44//!
45//! ```
46//! use aws_smithy_schema::{shape_id, Schema, ShapeId, ShapeType};
47//!
48//! const SHAPE_ID: ShapeId<'static> = shape_id!("ns", "MyShape");
49//! static MY_SHAPE_SCHEMA: Schema<'static> = Schema::new(SHAPE_ID, ShapeType::String);
50//! assert_eq!(MY_SHAPE_SCHEMA.shape_id().as_str(), "ns#MyShape");
51//! ```
52//!
53//! Declare schemas as `static`s, not `const`s. A `const` is copied at every
54//! use, so each use gets its own empty [`extension`] cache, and the
55//! work cached on it is repeated.
56//!
57//! ## `Schema<'a>` — runtime construction
58//!
59//! Hand-written code may construct schemas at any lifetime; this is the path
60//! used by test fixtures and (in the future) by dynamic clients that load a
61//! Smithy model at runtime. Every value referenced by the schema must outlive
62//! the schema itself; the borrow checker enforces this. See
63//! [`Schema::new_struct`] for a worked example.
64//!
65//! Wire-format trait values follow the same rule and may borrow from storage
66//! the caller owns, such as an arena holding the parsed model text — with one
67//! exception. [`Schema::with_http_header`] requires `&'static str`, because the
68//! HTTP binder passes header names to an API that needs
69//! `Cow<'static, str>`. Use [`intern_header_name`] to obtain a suitable
70//! `&'static str` from a runtime string; it deduplicates, so the cost is
71//! bounded by the number of distinct header names in the model.
72//!
73//! # Trait maps and the `LazyLock` discipline
74//!
75//! The serde traits a schema cares about ([`@jsonName`][traits::JsonNameTrait],
76//! HTTP bindings, etc.) are stored as inline typed `Option` fields on the
77//! schema and accessed via direct field reads. Unknown or custom traits go
78//! through a fallback [`TraitMap`] reachable from [`Schema::with_traits`].
79//!
80//! [`Schema::with_traits`] accepts an `&'a std::sync::LazyLock<TraitMap>`, so
81//! the `LazyLock` must outlive any schema that references it. Codegen places
82//! both in statics (the `LazyLock` is `'static`, the schema is
83//! `Schema<'static>`); runtime-constructed schemas must arrange the lifetimes
84//! manually using standard borrow-check discipline.
85//!
86//! # Schema extensions
87//!
88//! Codecs and protocols often need data derived from a schema, such as a
89//! pre-encoded wire name or a member lookup table, that is the same on every
90//! request. [`Schema::extension`] computes such data once per schema and caches
91//! it on the schema, keyed by a [`SchemaExtensionKey`](extension::SchemaExtensionKey)
92//! that any crate can declare. Every schema carries the cache, whether it was
93//! generated, written by hand, or built from a model at runtime. See the
94//! [`extension`] module.
95//!
96//! Because of that cache, `Schema` has interior mutability and drop glue. The
97//! constructors and `with_*` setters remain `const fn`s, so schemas can still be
98//! initialized at compile time as `static`s, and a `const` can still refer to
99//! one (`const S: &Schema<'static> = &MY_STATIC;`). Two constant-evaluation
100//! patterns are not possible: a `const` item cannot call a method that reads a
101//! schema `static`, and a `const` or `static` cannot borrow a temporary
102//! `Schema` (`&Schema::new(..)`). Declare the schema as a `static` and borrow
103//! that instead.
104//!
105//! # Variance
106//!
107//! `Schema<'a>`, `ShapeId<'a>`, [`OperationSchema<'a>`], and the typed trait
108//! wrappers are covariant in `'a`. Covariance is what
109//! lets a `&'static Schema<'static>` (the codegen form) coerce implicitly
110//! into a `&Schema<'_>` argument at any call site, with no annotation needed
111//! at the call site. Compile-time assertion functions in this crate enforce
112//! covariance; if a future field change would break it, the build fails
113//! before any downstream code is affected.
114
115mod schema {
116    pub(crate) mod operation_schema;
117    pub(crate) mod payload_hint;
118    pub(crate) mod shape_id;
119    pub(crate) mod shape_type;
120    pub(crate) mod trait_map;
121    pub(crate) mod trait_type;
122    pub(crate) mod traits;
123
124    pub(crate) mod codec;
125    pub(crate) mod document;
126    pub(crate) mod error_envelope;
127    pub(crate) mod extension;
128    pub(crate) mod header_omit_settings;
129    pub(crate) mod http_protocol;
130    pub(crate) mod prelude;
131    pub(crate) mod protocol;
132    pub(crate) mod registry;
133    pub(crate) mod serde;
134}
135
136pub use schema::operation_schema::{OperationSchema, OperationSchemaBuilder};
137pub use schema::payload_hint::PayloadHint;
138pub use schema::shape_id::ShapeId;
139pub use schema::shape_type::ShapeType;
140pub use schema::trait_map::TraitMap;
141pub use schema::trait_type::Trait;
142pub use schema::trait_type::{AnnotationTrait, DocumentTrait, StringTrait};
143
144/// Interns a header name so it can be attached to a runtime-materialized schema.
145///
146/// [`Schema::with_http_header`] is the one trait setter that requires
147/// `&'static str` rather than `&'a str`, because the HTTP binder hands header
148/// names to `Headers::insert`, which needs a `Cow<'static, str>`. Every other
149/// wire-format trait can borrow from storage the caller owns — an arena holding
150/// the parsed model text, for instance — and be dropped freely.
151///
152/// This function bridges that gap: it takes a runtime string and returns a
153/// `&'static str` suitable for [`Schema::with_http_header`], keeping the
154/// binder's zero-allocation fast path intact
155/// (`HttpHeaderTrait::value_static` returns `Some` for interned names).
156///
157/// # This leaks, deliberately
158///
159/// The returned `&'static str` is never freed. Interning is deduplicated, so a
160/// given name leaks at most once no matter how many times it is interned; the
161/// total is bounded by the number of *distinct* header names passed in, not by
162/// the number of calls. Re-materializing the same model repeatedly does not
163/// grow memory. For reference, the whole of Amazon S3 uses 158 distinct header
164/// names, about 4.4 KiB once.
165///
166/// Prefer this over a hand-rolled `Box::leak`, which leaks on every call and so
167/// grows without bound when placed in a loop.
168///
169/// # When this is the wrong tool
170///
171/// Because the memory is never reclaimed, the bound is "every distinct header
172/// name this process has ever seen". That is fine for a client that loads its
173/// models at startup. It is *not* fine for a long-lived process that keeps
174/// ingesting new models, where the total grows without limit and cannot be
175/// reclaimed. Such callers should not intern; they need `@httpHeader` names
176/// borrowed from their own storage, which is an additive relaxation of
177/// [`Schema::with_http_header`] rather than something an interner can provide.
178///
179/// # Examples
180///
181/// ```
182/// use aws_smithy_schema::intern_header_name;
183///
184/// // A header name that only exists at runtime.
185/// let parsed = String::from("x-amz-request-id");
186/// let name: &'static str = intern_header_name(&parsed);
187/// assert_eq!(name, "x-amz-request-id");
188///
189/// // Interning the same name again returns the identical pointer, not a copy.
190/// assert!(std::ptr::eq(name, intern_header_name("x-amz-request-id")));
191/// ```
192pub fn intern_header_name(name: &str) -> &'static str {
193    static INTERNED: std::sync::LazyLock<
194        std::sync::Mutex<std::collections::HashSet<&'static str>>,
195    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
196
197    // The guarded section cannot panic, so a poisoned lock is not reachable in
198    // practice; recover rather than propagate a panic if it somehow happens.
199    let mut table = INTERNED
200        .lock()
201        .unwrap_or_else(std::sync::PoisonError::into_inner);
202
203    if let Some(&existing) = table.get(name) {
204        return existing;
205    }
206    let leaked: &'static str = Box::leak(name.to_owned().into_boxed_str());
207    table.insert(leaked);
208    leaked
209}
210
211/// Schemas for the Smithy prelude shapes (`smithy.api#String`,
212/// `smithy.api#Integer`, and so on).
213pub mod prelude {
214    pub use crate::schema::prelude::*;
215}
216
217/// Derived data that runtime components compute once per schema and cache on it.
218pub mod extension {
219    pub use crate::schema::extension::SchemaExtensionKey;
220}
221
222/// Shape serialization and deserialization traits and their error type.
223pub mod serde {
224    pub use crate::schema::serde::*;
225}
226
227/// Runtime representations of the Smithy serialization traits carried on a schema.
228pub mod traits {
229    pub use crate::schema::traits::*;
230}
231
232/// Format codecs that pair a shape serializer with a matching deserializer.
233pub mod codec {
234    pub use crate::schema::codec::*;
235}
236
237/// `Document` shape serde and the discriminated-document conversion extension.
238pub mod document {
239    pub use crate::schema::document::*;
240}
241
242/// Settings controlling which HTTP headers are omitted during serialization.
243pub mod header_omit_settings {
244    pub use crate::schema::header_omit_settings::*;
245}
246
247/// Client protocol abstraction for serializing requests and deserializing responses.
248pub mod protocol {
249    pub use crate::schema::protocol::*;
250}
251
252/// Shared helpers for parsing AWS protocol error envelopes (error-code
253/// sanitization and the awsQueryCompatible header), used by the JSON and CBOR
254/// codecs.
255pub mod error_envelope {
256    pub use crate::schema::error_envelope::*;
257}
258
259/// HTTP client-protocol building blocks: HTTP bindings and RPC payloads.
260pub mod http_protocol {
261    pub use crate::schema::http_protocol::*;
262}
263
264/// Runtime type and error registries for resolving shapes by `ShapeId`.
265pub mod registry {
266    pub use crate::schema::registry::*;
267}
268
269use schema::traits as trait_types;
270
271/// A member's position in its parent's member array, stored in one word.
272///
273/// `Option<usize>` would be the obvious type, but it is 16 bytes on a 64-bit target:
274/// the niche-free `usize` forces a separate discriminant word. Encoding absence as `0`
275/// and a present index as `index + 1` fits the same information in 8 bytes. That matters
276/// because [`Schema`] is instantiated once per shape *and* once per member, so thousands
277/// of times in a generated client, and the reclaimed word funds the response routing word
278/// without growing the struct.
279///
280/// The encoding is contained entirely within this type. [`Schema::member_index`] returns
281/// `Option<usize>` exactly as before, and the [`std::fmt::Debug`] impl below prints the decoded
282/// `Option` so `Schema`'s derived `Debug` output is unchanged.
283#[derive(Clone, Copy, PartialEq, Eq)]
284struct MemberIndex(usize);
285
286impl MemberIndex {
287    /// Not a member schema.
288    const NONE: Self = Self(0);
289
290    /// Encodes `index`.
291    ///
292    /// # Panics
293    ///
294    /// If `index == usize::MAX`, which would overflow the encoding. Generated schemas are
295    /// built in const context, so an out-of-range index is a compile-time error rather
296    /// than a runtime one. No real model comes close: the largest structure observed
297    /// across AWS models has 42 members.
298    const fn new(index: usize) -> Self {
299        assert!(
300            index != usize::MAX,
301            "member index must be less than usize::MAX"
302        );
303        Self(index + 1)
304    }
305
306    /// Decodes back to `Option<usize>`.
307    const fn get(self) -> Option<usize> {
308        match self.0 {
309            0 => None,
310            encoded => Some(encoded - 1),
311        }
312    }
313}
314
315impl std::fmt::Debug for MemberIndex {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        // Print the decoded value so the encoding never leaks into diagnostics and
318        // `Schema`'s derived `Debug` keeps its previous output.
319        self.get().fmt(f)
320    }
321}
322
323/// Bit layout of the response routing word derived by [`Schema::new_struct`].
324///
325/// The word answers, in one load, the two questions a protocol asks of a response
326/// structure: which members are bound to somewhere other than the body, and is there
327/// anything left for the body codec to read. Deriving it in const evaluation keeps the
328/// runtime off the O(all members) trait-checking path the previous implementation used.
329mod response_routing {
330    /// Member positions the mask can represent: bits `0..=61`.
331    pub(crate) const MASK_BITS: usize = 62;
332
333    /// Covers the representable member positions.
334    pub(crate) const MASK: u64 = (1u64 << MASK_BITS) - 1;
335
336    /// Bit 62: at least one member has no response binding, so on a response it belongs
337    /// to the protocol document body and the body codec must be invoked.
338    pub(crate) const HAS_BODY_MEMBERS: u64 = 1u64 << 62;
339
340    /// Bit 63: a response-bound member sits at a position the mask cannot represent.
341    /// Consumers MUST ignore [`MASK`] entirely when this is set and scan the member slice
342    /// instead; the mask is then incomplete, not merely approximate.
343    pub(crate) const NEEDS_SCAN: u64 = 1u64 << 63;
344}
345
346/// A Smithy schema — a lightweight runtime representation of a Smithy shape.
347///
348/// Contains the shape's ID, type, traits relevant to serialization, and
349/// references to member schemas (for aggregate types).
350///
351/// Schemas are constructed at compile time (via `const`) for generated code
352/// and prelude types. The Smithy type system is closed, so no extensibility
353/// via trait objects is needed.
354#[derive(Debug)]
355pub struct Schema<'a> {
356    id: ShapeId<'a>,
357    shape_type: ShapeType,
358    /// Member name if this is a member schema.
359    member_name: Option<&'a str>,
360    /// Member index for position-based lookup in generated code, encoded so it costs
361    /// one word instead of two. See [`MemberIndex`].
362    member_index: MemberIndex,
363    /// Response binding routing, derived in const evaluation by
364    /// [`new_struct`](Schema::new_struct). See [`response_routing`] for the bit layout
365    /// and the accessors below for how to read it.
366    ///
367    /// Zero for every non-struct schema, which reads as "no bound members, no body
368    /// members, mask exact". That is the conservative default: it fails the
369    /// body-only fast path's `HAS_BODY_MEMBERS` requirement, so such a schema routes
370    /// through the full composite rather than silently skipping work.
371    response_routing: u64,
372    /// Shape-type-specific member data.
373    members: SchemaMembers<'a>,
374
375    /// The pre-synthesis shape name for synthetic operation input/output
376    /// shapes.
377    ///
378    /// Smithy's `OperationNormalizer` rewrites every operation's input/output
379    /// to a synthetic shape named `OperationNameInput` / `OperationNameOutput`;
380    /// this field surfaces the name component of
381    /// `SyntheticInputTrait::originalId` / `SyntheticOutputTrait::originalId`,
382    /// which preserves the user-authored shape name. `None` for non-synthetic
383    /// shapes and for member schemas.
384    ///
385    /// Currently consumed by the REST XML codec to determine the body root
386    /// element name when no `@xmlName` overrides it. Distinct from `xml_name`,
387    /// which carries an `@xmlName` trait value. Other consumers (logging,
388    /// future protocols) may also read this field.
389    original_name: Option<&'a str>,
390
391    // -- Known serde trait fields (const-constructable) --
392    // IMPORTANT: These fields and their `with_*` setters must stay in sync with
393    // `knownTraitSetter` in `SchemaGenerator.kt`. If a new known trait is added
394    // here, a corresponding entry must be added in the codegen.
395    sensitive: Option<trait_types::SensitiveTrait>,
396    json_name: Option<trait_types::JsonNameTrait<'a>>,
397    timestamp_format: Option<trait_types::TimestampFormatTrait>,
398    xml_name: Option<trait_types::XmlNameTrait<'a>>,
399    xml_attribute: Option<trait_types::XmlAttributeTrait>,
400    xml_flattened: Option<trait_types::XmlFlattenedTrait>,
401    /// Marks an operation output struct whose XML wire format omits the
402    /// outer wrapper element (set by codegen for operations carrying the
403    /// AWS-customization `S3UnwrappedXmlOutputTrait`). Honored by the XML
404    /// codec; ignored by other codecs (so the schema remains protocol-neutral
405    /// — runtime protocol swap is unaffected).
406    xml_unwrapped_output: bool,
407    /// `true` (the default, conservative) means this struct has at least one
408    /// member that serializes to the request/response body — i.e., a member
409    /// without any HTTP binding trait, OR a member with `@httpPayload`
410    /// targeting a struct/union (which provides body framing through the codec).
411    ///
412    /// `false` (set by codegen via [`with_no_body_members`](Schema::with_no_body_members))
413    /// means every member is HTTP-bound (header / query / label / prefix-headers
414    /// / query-params, or scalar `@httpPayload` whose bytes go into the request
415    /// body raw). The HTTP binding protocol uses this to skip body codec
416    /// invocation entirely on the request side: no XML/JSON wrapper element
417    /// is opened, no `serialize_members` re-entry through the codec proxy
418    /// happens, and the body bytes are never collected (they'd be discarded
419    /// anyway). Saves ~15-20% on header-heavy SER cases like S3 PutObject.
420    has_body_members: bool,
421    /// Records whether an `@httpPayload` member supplies its own body framing,
422    /// so the HTTP binding protocol does not have to scan members to find out.
423    ///
424    /// Defaults to [`PayloadHint::Unknown`], which means "not recorded", the
425    /// runtime then derives the answer itself. See [`PayloadHint`] for why that
426    /// fallback is permanent rather than transitional.
427    payload_hint: PayloadHint,
428    xml_namespace: Option<trait_types::XmlNamespaceTrait<'a>>,
429    /// Deliberately pinned to `'static` while the other seven trait values
430    /// carry `'a`. `Headers::insert` takes `impl AsHeaderComponent`, whose
431    /// zero-allocation impl is for `&'static str`
432    /// (`aws-smithy-runtime-api`'s `MaybeStatic = Cow<'static, str>`), and the
433    /// HTTP binder receives member schemas through `ShapeSerializer` methods
434    /// whose `&Schema<'_>` lifetime is unrelated to the binder's.
435    ///
436    /// The field carries `'a` like every other trait, and the `'static`
437    /// requirement lives on the *constructor* instead:
438    /// [`with_http_header`](Schema::with_http_header) takes `&'static str`, and
439    /// `HttpHeaderTrait::value_static` recovers it for the binder. Keeping the
440    /// restriction at the constructor rather than in the type means relaxing it
441    /// later is additive rather than a breaking signature change, and it avoids
442    /// pinning `ClientProtocol::serialize_request` — which would force every
443    /// protocol to take a `'static` schema.
444    ///
445    /// So: runtime-materialized schemas currently set header names from
446    /// interned/leaked strings, while every other wire-format trait already
447    /// accepts an arbitrary lifetime.
448    http_header: Option<trait_types::HttpHeaderTrait<'a>>,
449    http_label: Option<trait_types::HttpLabelTrait>,
450    http_payload: Option<trait_types::HttpPayloadTrait>,
451    http_prefix_headers: Option<trait_types::HttpPrefixHeadersTrait<'a>>,
452    http_query: Option<trait_types::HttpQueryTrait<'a>>,
453    http_query_params: Option<trait_types::HttpQueryParamsTrait>,
454    http_response_code: Option<trait_types::HttpResponseCodeTrait>,
455    /// The `@http` trait — an operation-level trait included on the input schema
456    /// for convenience so the protocol serializer can construct the request URI.
457    http: Option<trait_types::HttpTrait<'a>>,
458    streaming: Option<trait_types::StreamingTrait>,
459    event_header: Option<trait_types::EventHeaderTrait>,
460    event_payload: Option<trait_types::EventPayloadTrait>,
461    host_label: Option<trait_types::HostLabelTrait>,
462    media_type: Option<trait_types::MediaTypeTrait<'a>>,
463
464    /// Fallback for unknown/custom traits. `None` in const contexts (no allocation).
465    traits: Option<&'a std::sync::LazyLock<TraitMap>>,
466
467    /// Cached derived data. See [`Schema::extension`].
468    extensions: schema::extension::ExtensionStorage,
469}
470
471/// Shape-type-specific member references.
472#[derive(Debug)]
473enum SchemaMembers<'a> {
474    /// No members (simple types).
475    None,
476    /// Structure or union members.
477    Struct { members: &'a [&'a Schema<'a>] },
478    /// List member schema.
479    List { member: &'a Schema<'a> },
480    /// Map key and value schemas.
481    Map {
482        key: &'a Schema<'a>,
483        value: &'a Schema<'a>,
484    },
485}
486
487// ---------- Variance assertions ----------
488//
489// `Schema<'a>`, `ShapeId<'a>`, `OperationSchema<'a>`, and the eight trait-value wrappers must remain
490// **covariant** in `'a`. Covariance
491// is what lets `&'static Schema<'static>` (the codegen-emitted form) coerce
492// implicitly into `&Schema<'_>` at call sites — without it, every call would
493// need an explicit lifetime annotation.
494//
495// Today all of them are covariant by construction: every field is of the form
496// `&'a T` or contains another covariant `'a`-parameterized type. There is no
497// `&'a mut T`, no `fn(&'a T)`, and no interior mutability tying `'a` invariantly.
498//
499// These assertion functions make the covariance requirement *load-bearing on
500// the build*. If a future field changes that property — e.g. someone adds a
501// `RefCell` holding a `&'a` reference, an `fn(&'a Self)` field, or a `*mut T`
502// with `'a` — the function bodies will fail to type-check and the build breaks
503// before any downstream code is affected.
504//
505// Compile-time only; zero runtime cost.
506
507#[allow(dead_code)]
508fn _assert_schema_covariant<'a, 'b: 'a>(s: &'b Schema<'b>) -> &'a Schema<'a> {
509    s
510}
511
512#[allow(dead_code)]
513fn _assert_shape_id_covariant<'a, 'b: 'a>(id: ShapeId<'b>) -> ShapeId<'a> {
514    id
515}
516
517#[allow(dead_code)]
518fn _assert_operation_schema_covariant<'a, 'b: 'a>(
519    operation: OperationSchema<'b>,
520) -> OperationSchema<'a> {
521    operation
522}
523
524// The eight trait-value wrappers carry `'a` too, and the same reasoning
525// applies: a codegen-emitted `JsonNameTrait<'static>` has to be usable
526// wherever a `JsonNameTrait<'_>` is expected. `HttpHeaderTrait` is included
527// even though its only public constructor takes `&'static str` — its private
528// `HeaderName<'a>` enum has a `Borrowed(&'a str)` arm, and this assertion is
529// what keeps that arm covariant if it ever becomes constructible.
530macro_rules! assert_wrapper_covariant {
531    ($fn_name:ident, $wrapper:ident) => {
532        #[allow(dead_code)]
533        fn $fn_name<'a, 'b: 'a>(t: trait_types::$wrapper<'b>) -> trait_types::$wrapper<'a> {
534            t
535        }
536    };
537}
538
539assert_wrapper_covariant!(_assert_json_name_covariant, JsonNameTrait);
540assert_wrapper_covariant!(_assert_xml_name_covariant, XmlNameTrait);
541assert_wrapper_covariant!(_assert_media_type_covariant, MediaTypeTrait);
542assert_wrapper_covariant!(_assert_http_query_covariant, HttpQueryTrait);
543assert_wrapper_covariant!(
544    _assert_http_prefix_headers_covariant,
545    HttpPrefixHeadersTrait
546);
547assert_wrapper_covariant!(_assert_http_header_covariant, HttpHeaderTrait);
548assert_wrapper_covariant!(_assert_xml_namespace_covariant, XmlNamespaceTrait);
549assert_wrapper_covariant!(_assert_http_covariant, HttpTrait);
550
551// Generated schemas are `static`s shared across threads, so `Schema` must stay
552// `Send + Sync`. Extension storage preserves both because cached values are
553// required to be `Send + Sync` themselves.
554const _: () = {
555    const fn assert_send_sync<T: Send + Sync>() {}
556    assert_send_sync::<Schema<'static>>();
557    assert_send_sync::<OperationSchema<'static>>();
558    assert_send_sync::<OperationSchemaBuilder<'static>>();
559};
560
561impl<'a> Schema<'a> {
562    /// Default values for all fields. Constructors start from this value and assign the
563    /// fields they set; see the `INVARIANT` comment on the trait setters for why they
564    /// do not use it with struct-update syntax.
565    ///
566    /// Implemented as a `const fn` rather than a `const` so it can be
567    /// parameterized over the schema lifetime — `const` items cannot
568    /// have lifetime parameters in stable Rust.
569    const fn empty_traits() -> Schema<'a> {
570        Schema {
571            id: ShapeId::<'a>::from_parts("", "", ""),
572            shape_type: ShapeType::Boolean,
573            member_name: None,
574            member_index: MemberIndex::NONE,
575            response_routing: 0,
576            members: SchemaMembers::None,
577            original_name: None,
578            sensitive: None,
579            json_name: None,
580            timestamp_format: None,
581            xml_name: None,
582            xml_attribute: None,
583            xml_flattened: None,
584            xml_unwrapped_output: false,
585            has_body_members: true,
586            payload_hint: PayloadHint::Unknown,
587            xml_namespace: None,
588            http_header: None,
589            http_label: None,
590            http_payload: None,
591            http_prefix_headers: None,
592            http_query: None,
593            http_query_params: None,
594            http_response_code: None,
595            http: None,
596            streaming: None,
597            event_header: None,
598            event_payload: None,
599            host_label: None,
600            media_type: None,
601            traits: None,
602            extensions: schema::extension::ExtensionStorage::new(),
603        }
604    }
605
606    /// Creates a schema for a simple type (no members).
607    pub const fn new(id: ShapeId<'a>, shape_type: ShapeType) -> Self {
608        let mut schema = Self::empty_traits();
609        schema.id = id;
610        schema.shape_type = shape_type;
611        schema
612    }
613
614    /// Creates a schema for a structure or union type.
615    ///
616    /// `id` and `members` are borrowed for `'a`, so both must outlive the
617    /// returned schema. For codegen-emitted schemas this is always `'static`
618    /// to `'static`. Hand-written runtime construction can use any lifetime
619    /// — typically the surrounding function body's:
620    ///
621    /// ```
622    /// use aws_smithy_schema::{Schema, ShapeId, ShapeType};
623    ///
624    /// let id = ShapeId::from_parts("ns#Foo", "ns", "Foo");
625    /// let member_x = Schema::new_member(
626    ///     ShapeId::from_parts("smithy.api#String", "smithy.api", "String"),
627    ///     ShapeType::String,
628    ///     "x",
629    ///     0,
630    /// );
631    /// let members: [&Schema<'_>; 1] = [&member_x];
632    /// let schema = Schema::new_struct(id, ShapeType::Structure, &members);
633    ///
634    /// assert_eq!(schema.shape_id().as_str(), "ns#Foo");
635    /// assert_eq!(schema.shape_type(), ShapeType::Structure);
636    /// ```
637    ///
638    /// `id`, `member_x`, `members`, and `schema` all share the surrounding
639    /// scope's lifetime; the borrow checker enforces that `members[0]`
640    /// outlives `schema`.
641    pub const fn new_struct(
642        id: ShapeId<'a>,
643        shape_type: ShapeType,
644        members: &'a [&'a Schema<'a>],
645    ) -> Self {
646        let mut schema = Self::empty_traits();
647        schema.id = id;
648        schema.shape_type = shape_type;
649        schema.response_routing = Self::derive_response_routing(members);
650        schema.members = SchemaMembers::Struct { members };
651        schema
652    }
653
654    /// Derives the response routing word from a structure's member slice.
655    ///
656    /// Runs in const evaluation, so generated schemas pay nothing at runtime and an
657    /// out-of-order member array is a compile error rather than a silently wrong mask.
658    ///
659    /// A member is *response-bound* when it carries `@httpHeader`,
660    /// `@httpPrefixHeaders`, `@httpResponseCode`, or `@httpPayload`. Every other member
661    /// — including one carrying only a request-side binding such as `@httpQuery` or
662    /// `@httpLabel` — belongs to the document body on a response, and so sets
663    /// [`response_routing::HAS_BODY_MEMBERS`] rather than a mask bit.
664    const fn derive_response_routing(members: &[&Schema<'a>]) -> u64 {
665        let mut word: u64 = 0;
666        let mut i = 0;
667        while i < members.len() {
668            let member = members[i];
669
670            // The mask encodes a member's identity as its position in this slice, so the
671            // two must agree. `member_schema_by_index` already depends on the same
672            // ordering; asserting here turns a silent mismatch into a build failure at
673            // the point the schema is declared.
674            let index = match member.member_index.get() {
675                Some(index) => index,
676                None => panic!("a struct member schema must carry a member index"),
677            };
678            assert!(
679                index == i,
680                "struct member schemas must be listed in member-index order, because the \
681                 response routing mask uses a member's array position as its index"
682            );
683
684            if member.has_http_response_binding() {
685                if i < response_routing::MASK_BITS {
686                    word |= 1u64 << i;
687                } else {
688                    // Out of mask range: the mask can no longer describe every bound
689                    // member, so consumers must scan. Earlier bits stay set but must be
690                    // ignored once this is flagged.
691                    word |= response_routing::NEEDS_SCAN;
692                }
693            } else {
694                word |= response_routing::HAS_BODY_MEMBERS;
695            }
696            i += 1;
697        }
698        word
699    }
700
701    /// Creates a schema for a list type.
702    pub const fn new_list(id: ShapeId<'a>, member: &'a Schema<'a>) -> Self {
703        let mut schema = Self::empty_traits();
704        schema.id = id;
705        schema.shape_type = ShapeType::List;
706        schema.members = SchemaMembers::List { member };
707        schema
708    }
709
710    /// Creates a schema for a map type.
711    pub const fn new_map(id: ShapeId<'a>, key: &'a Schema<'a>, value: &'a Schema<'a>) -> Self {
712        let mut schema = Self::empty_traits();
713        schema.id = id;
714        schema.shape_type = ShapeType::Map;
715        schema.members = SchemaMembers::Map { key, value };
716        schema
717    }
718
719    /// Creates a member schema wrapping a target schema.
720    pub const fn new_member(
721        id: ShapeId<'a>,
722        shape_type: ShapeType,
723        member_name: &'a str,
724        member_index: usize,
725    ) -> Self {
726        let mut schema = Self::empty_traits();
727        schema.id = id;
728        schema.shape_type = shape_type;
729        schema.member_name = Some(member_name);
730        schema.member_index = MemberIndex::new(member_index);
731        schema
732    }
733
734    /// Returns the Shape ID of this schema.
735    ///
736    /// The returned reference's outer lifetime is the receiver's; the
737    /// inner `ShapeId<'a>` carries the data's lifetime, which is
738    /// `'static` for codegen-emitted schemas (preserving the
739    /// `&'static str` accessor guarantees that downstream
740    /// optimizations rely on).
741    pub fn shape_id(&self) -> &ShapeId<'a> {
742        &self.id
743    }
744
745    /// Returns the shape type.
746    pub fn shape_type(&self) -> ShapeType {
747        self.shape_type
748    }
749
750    /// Returns the fallback trait map for unknown/custom traits.
751    pub fn traits(&self) -> Option<&TraitMap> {
752        self.traits.map(|lazy| &**lazy)
753    }
754
755    // -- Known trait accessors --
756
757    /// Returns the `@sensitive` trait if present.
758    pub fn sensitive(&self) -> Option<&trait_types::SensitiveTrait> {
759        self.sensitive.as_ref()
760    }
761
762    /// Returns the `@jsonName` value if present.
763    pub fn json_name(&self) -> Option<&trait_types::JsonNameTrait<'a>> {
764        self.json_name.as_ref()
765    }
766
767    /// Returns the `@timestampFormat` if present.
768    pub fn timestamp_format(&self) -> Option<&trait_types::TimestampFormatTrait> {
769        self.timestamp_format.as_ref()
770    }
771
772    /// Returns the `@xmlName` value if present.
773    pub fn xml_name(&self) -> Option<&trait_types::XmlNameTrait<'a>> {
774        self.xml_name.as_ref()
775    }
776
777    /// Returns the `@xmlNamespace` value if present.
778    pub fn xml_namespace(&self) -> Option<&trait_types::XmlNamespaceTrait<'a>> {
779        self.xml_namespace.as_ref()
780    }
781
782    /// Returns `true` if this member has the `@xmlAttribute` trait.
783    pub fn xml_attribute(&self) -> bool {
784        self.xml_attribute.is_some()
785    }
786
787    /// Returns `true` if this member has the `@xmlFlattened` trait.
788    pub fn xml_flattened(&self) -> bool {
789        self.xml_flattened.is_some()
790    }
791
792    /// Returns `true` if this struct's XML wire format omits the outer
793    /// wrapper element. See field doc for details.
794    pub fn xml_unwrapped_output(&self) -> bool {
795        self.xml_unwrapped_output
796    }
797
798    /// Returns `true` if this shape has the `@streaming` trait.
799    ///
800    /// In Smithy the trait is applied to a blob or union *shape*, never to a member, so
801    /// codegen propagates it from a member's target into the combined member schema. That
802    /// makes the distinction available here without model access: a protocol can tell a
803    /// streaming payload member — whose live body or event receiver is owned elsewhere —
804    /// from a buffered one it should read itself.
805    pub fn streaming(&self) -> bool {
806        self.streaming.is_some()
807    }
808
809    /// Returns `true` if this struct has at least one member that serializes
810    /// to the request/response body, `false` if every member is HTTP-bound.
811    pub fn has_body_members(&self) -> bool {
812        self.has_body_members
813    }
814
815    /// Returns the recorded [`PayloadHint`], or [`PayloadHint::Unknown`] if none
816    /// was recorded.
817    ///
818    /// Callers MUST handle `Unknown` by deriving the answer themselves; it is
819    /// the default for every hand-constructed schema and for schemas generated
820    /// before codegen began recording it.
821    pub fn payload_hint(&self) -> PayloadHint {
822        self.payload_hint
823    }
824
825    /// Returns `true` if this member schema has any HTTP response binding trait
826    /// (`@httpHeader`, `@httpResponseCode`, `@httpPrefixHeaders`, or `@httpPayload`).
827    pub const fn has_http_response_binding(&self) -> bool {
828        self.http_header.is_some()
829            || self.http_response_code.is_some()
830            || self.http_prefix_headers.is_some()
831            || self.http_payload.is_some()
832    }
833
834    /// Bit set of member positions that carry a response binding.
835    ///
836    /// Bit `i` corresponds to `members()[i]`, so a set bit can be turned into a member
837    /// schema with [`member_schema_by_index`](Schema::member_schema_by_index) in O(1) and
838    /// the whole set walked in O(bound members) rather than O(all members):
839    ///
840    /// ```ignore
841    /// let mut mask = schema.response_binding_mask();
842    /// while mask != 0 {
843    ///     let index = mask.trailing_zeros() as usize;
844    ///     mask &= mask - 1;
845    ///     let member = schema.member_schema_by_index(index).expect("mask derived from members");
846    /// }
847    /// ```
848    ///
849    /// Only meaningful when [`response_bindings_need_scan`](Schema::response_bindings_need_scan)
850    /// is `false`; otherwise it is incomplete and the member slice must be scanned.
851    pub(crate) const fn response_binding_mask(&self) -> u64 {
852        self.response_routing & response_routing::MASK
853    }
854
855    /// Returns `true` if at least one member belongs to the document body on a response,
856    /// meaning the body codec has something to read.
857    ///
858    /// `false` means every member is bound elsewhere in the message, so the body codec
859    /// can be skipped entirely.
860    pub(crate) const fn has_response_body_members(&self) -> bool {
861        self.response_routing & response_routing::HAS_BODY_MEMBERS != 0
862    }
863
864    /// Returns `true` if the binding mask cannot describe every response-bound member, so
865    /// callers must scan [`members`](Schema::members) and test
866    /// [`has_http_response_binding`](Schema::has_http_response_binding) instead.
867    ///
868    /// Only reachable for a structure with a response-bound member at position 62 or
869    /// later. The largest structure observed across AWS models has 42 members, so this is
870    /// a correctness fallback rather than a path real models take.
871    pub(crate) const fn response_bindings_need_scan(&self) -> bool {
872        self.response_routing & response_routing::NEEDS_SCAN != 0
873    }
874
875    /// Returns the `@httpHeader` value if present.
876    ///
877    /// Use [`HttpHeaderTrait::value_static`](trait_types::HttpHeaderTrait::value_static)
878    /// rather than `value()` when inserting into `Headers`, which needs a
879    /// `'static` name; see the field's comment for why.
880    pub fn http_header(&self) -> Option<&trait_types::HttpHeaderTrait<'a>> {
881        self.http_header.as_ref()
882    }
883
884    /// Returns the `@httpQuery` value if present.
885    pub fn http_query(&self) -> Option<&trait_types::HttpQueryTrait<'a>> {
886        self.http_query.as_ref()
887    }
888
889    /// Returns the `@httpLabel` trait if present.
890    pub fn http_label(&self) -> Option<&trait_types::HttpLabelTrait> {
891        self.http_label.as_ref()
892    }
893
894    /// Returns the `@httpPayload` trait if present.
895    pub fn http_payload(&self) -> Option<&trait_types::HttpPayloadTrait> {
896        self.http_payload.as_ref()
897    }
898
899    /// Returns the `@httpPrefixHeaders` value if present.
900    pub fn http_prefix_headers(&self) -> Option<&trait_types::HttpPrefixHeadersTrait<'a>> {
901        self.http_prefix_headers.as_ref()
902    }
903
904    /// Returns the `@mediaType` trait if present.
905    pub fn media_type(&self) -> Option<&trait_types::MediaTypeTrait<'a>> {
906        self.media_type.as_ref()
907    }
908
909    /// Returns the `@httpQueryParams` trait if present.
910    pub fn http_query_params(&self) -> Option<&trait_types::HttpQueryParamsTrait> {
911        self.http_query_params.as_ref()
912    }
913
914    /// Returns the `@httpResponseCode` trait if present.
915    pub fn http_response_code(&self) -> Option<&trait_types::HttpResponseCodeTrait> {
916        self.http_response_code.as_ref()
917    }
918
919    /// Returns the `@http` trait if present.
920    ///
921    /// This is an operation-level trait included on the input schema for
922    /// convenience so the protocol serializer can construct the request URI.
923    pub fn http(&self) -> Option<&trait_types::HttpTrait<'a>> {
924        self.http.as_ref()
925    }
926
927    /// Returns the `@eventHeader` trait if present.
928    pub fn event_header(&self) -> Option<&trait_types::EventHeaderTrait> {
929        self.event_header.as_ref()
930    }
931
932    /// Returns the `@eventPayload` trait if present.
933    pub fn event_payload(&self) -> Option<&trait_types::EventPayloadTrait> {
934        self.event_payload.as_ref()
935    }
936
937    // -- Const setters for builder-style construction in generated code --
938
939    /// Sets the original (pre-synthesis) shape name for synthetic operation
940    /// input/output shapes. See [`Schema::original_name`] for semantics.
941    pub const fn with_original_name(mut self, name: &'a str) -> Self {
942        self.original_name = Some(name);
943        self
944    }
945
946    /// Attaches key and value member schemas to a map member schema.
947    /// Used by the XML codec to resolve `<key>` and `<value>` element names.
948    pub const fn with_map_members(mut self, key: &'a Schema<'a>, value: &'a Schema<'a>) -> Self {
949        self.members = SchemaMembers::Map { key, value };
950        self
951    }
952
953    /// Sets the list member schema on a member schema that targets a list.
954    pub const fn with_list_member(mut self, member: &'a Schema<'a>) -> Self {
955        self.members = SchemaMembers::List { member };
956        self
957    }
958
959    /// Sets the `@sensitive` trait.
960    pub const fn with_sensitive(mut self) -> Self {
961        self.sensitive = Some(trait_types::SensitiveTrait);
962        self
963    }
964
965    // -- Trait-wrapper setters --
966    //
967    // The setters below construct typed trait wrappers (`JsonNameTrait`,
968    // `XmlNameTrait`, `HttpTrait`, etc.). All of them take `&'a str` — the
969    // schema's data lifetime — so a schema materialized at runtime can carry
970    // wire-format traits borrowed from storage the caller owns, such as an
971    // arena holding the parsed model text. Codegen-emitted schemas pass string
972    // literals, so for them `'a` is `'static` and nothing changes.
973    //
974    // `with_http_header` is the one exception and takes `&'static str`; see its
975    // own doc comment and the `http_header` field comment for why, and note the
976    // restriction is at the constructor rather than in the type, so relaxing it
977    // later is additive.
978    //
979    // INVARIANT — do not introduce a trait field that needs drop.
980    //
981    // Every `with_*` setter is a `const fn`, and assigning to a field drops the
982    // field's previous value. A `const fn` body cannot run destructors, so a
983    // trait field with drop glue makes *every* setter for it illegal in const
984    // context (E0493). That matters because generated schemas are
985    // const-initialized statics:
986    //
987    //     static FOO_SCHEMA: Schema<'static> =
988    //         Schema::new_member(..).with_http_header("x-amz-...");
989    //
990    // and a const initializer cannot allocate. So trait values are `&'a str`
991    // and must stay borrow-only: `Cow<'static, str>`, `String`, or any enum
992    // with an owning arm are all ruled out, however convenient they look. A
993    // borrowed-only enum is fine — `HttpHeaderTrait` uses one — because
994    // references have no drop glue.
995    //
996    // `Schema` as a whole does have drop glue, from its extension storage. That
997    // is why the `new_*` constructors start from `Self::empty_traits()` and
998    // assign fields one at a time: struct-update syntax
999    // (`..Self::empty_traits()`) would drop the unused remainder of the base
1000    // value, extension storage included, and fail with E0493. Setters are
1001    // unaffected because they only overwrite fields that have no drop glue and
1002    // then move `self` out whole.
1003    //
1004    // Keeping the fields borrow-only also preserves the niche optimization
1005    // that makes `Option<JsonNameTrait<'a>>` 16 bytes rather than 24, which at
1006    // SDK scale is thousands of schemas per crate.
1007
1008    /// Sets the `@jsonName` trait.
1009    pub const fn with_json_name(mut self, value: &'a str) -> Self {
1010        self.json_name = Some(trait_types::JsonNameTrait::new(value));
1011        self
1012    }
1013
1014    /// Sets the `@timestampFormat` trait.
1015    pub const fn with_timestamp_format(mut self, format: trait_types::TimestampFormat) -> Self {
1016        self.timestamp_format = Some(trait_types::TimestampFormatTrait::new(format));
1017        self
1018    }
1019
1020    /// Sets the `@xmlName` trait.
1021    pub const fn with_xml_name(mut self, value: &'a str) -> Self {
1022        self.xml_name = Some(trait_types::XmlNameTrait::new(value));
1023        self
1024    }
1025
1026    /// Sets the `@xmlAttribute` trait.
1027    pub const fn with_xml_attribute(mut self) -> Self {
1028        self.xml_attribute = Some(trait_types::XmlAttributeTrait);
1029        self
1030    }
1031
1032    /// Sets the `@xmlFlattened` trait.
1033    pub const fn with_xml_flattened(mut self) -> Self {
1034        self.xml_flattened = Some(trait_types::XmlFlattenedTrait);
1035        self
1036    }
1037
1038    /// Marks the struct as an unwrapped XML output. See field doc for details.
1039    pub const fn with_xml_unwrapped_output(mut self) -> Self {
1040        self.xml_unwrapped_output = true;
1041        self
1042    }
1043
1044    /// Marks this struct as having no body members — every member is HTTP-bound.
1045    /// See [`has_body_members`](Schema::has_body_members) for what this enables.
1046    pub const fn with_no_body_members(mut self) -> Self {
1047        self.has_body_members = false;
1048        self
1049    }
1050
1051    /// Records whether an `@httpPayload` member supplies its own body framing.
1052    ///
1053    /// Setting this lets the HTTP binding protocol skip a per-request scan of
1054    /// this schema's members. It is an optimization only: leaving it at
1055    /// [`PayloadHint::Unknown`] (the default) produces identical output. See
1056    /// [`PayloadHint`] for why.
1057    pub const fn with_payload_hint(mut self, hint: PayloadHint) -> Self {
1058        self.payload_hint = hint;
1059        self
1060    }
1061
1062    /// Sets the `@httpHeader` trait.
1063    ///
1064    /// Takes `&'static str`, unlike the other wire-format setters, so the
1065    /// binder's `Headers::insert` fast path stays allocation-free. A schema
1066    /// built at runtime must supply an interned or leaked header name.
1067    ///
1068    /// Relaxing this is additive: a `with_http_header_borrowed(&'a str)`
1069    /// companion can be added without changing this signature or the getter's.
1070    pub const fn with_http_header(mut self, value: &'static str) -> Self {
1071        self.http_header = Some(trait_types::HttpHeaderTrait::new(value));
1072        self
1073    }
1074
1075    /// Sets the `@httpLabel` trait.
1076    pub const fn with_http_label(mut self) -> Self {
1077        self.http_label = Some(trait_types::HttpLabelTrait);
1078        self
1079    }
1080
1081    /// Sets the `@httpPayload` trait.
1082    pub const fn with_http_payload(mut self) -> Self {
1083        self.http_payload = Some(trait_types::HttpPayloadTrait);
1084        self
1085    }
1086
1087    /// Sets the `@httpPrefixHeaders` trait.
1088    pub const fn with_http_prefix_headers(mut self, value: &'a str) -> Self {
1089        self.http_prefix_headers = Some(trait_types::HttpPrefixHeadersTrait::new(value));
1090        self
1091    }
1092
1093    /// Sets the `@httpQuery` trait.
1094    pub const fn with_http_query(mut self, value: &'a str) -> Self {
1095        self.http_query = Some(trait_types::HttpQueryTrait::new(value));
1096        self
1097    }
1098
1099    /// Sets the `@httpQueryParams` trait.
1100    pub const fn with_http_query_params(mut self) -> Self {
1101        self.http_query_params = Some(trait_types::HttpQueryParamsTrait);
1102        self
1103    }
1104
1105    /// Sets the `@httpResponseCode` trait.
1106    pub const fn with_http_response_code(mut self) -> Self {
1107        self.http_response_code = Some(trait_types::HttpResponseCodeTrait);
1108        self
1109    }
1110
1111    /// Sets the `@http` trait (operation-level, included on input schema for convenience).
1112    pub const fn with_http(mut self, http: trait_types::HttpTrait<'a>) -> Self {
1113        self.http = Some(http);
1114        self
1115    }
1116
1117    /// Sets the `@streaming` trait.
1118    pub const fn with_streaming(mut self) -> Self {
1119        self.streaming = Some(trait_types::StreamingTrait);
1120        self
1121    }
1122
1123    /// Sets the `@eventHeader` trait.
1124    pub const fn with_event_header(mut self) -> Self {
1125        self.event_header = Some(trait_types::EventHeaderTrait);
1126        self
1127    }
1128
1129    /// Sets the `@eventPayload` trait.
1130    pub const fn with_event_payload(mut self) -> Self {
1131        self.event_payload = Some(trait_types::EventPayloadTrait);
1132        self
1133    }
1134
1135    /// Sets the `@hostLabel` trait.
1136    pub const fn with_host_label(mut self) -> Self {
1137        self.host_label = Some(trait_types::HostLabelTrait);
1138        self
1139    }
1140
1141    /// Sets the `@mediaType` trait.
1142    pub const fn with_media_type(mut self, value: &'a str) -> Self {
1143        self.media_type = Some(trait_types::MediaTypeTrait::new(value));
1144        self
1145    }
1146
1147    /// Sets the `@xmlNamespace` trait.
1148    ///
1149    /// `uri` is the namespace URI; `prefix` optionally declares the
1150    /// `xmlns:prefix` form. Pass `None` for the default (unprefixed)
1151    /// `xmlns="uri"` declaration.
1152    pub const fn with_xml_namespace(mut self, uri: &'a str, prefix: Option<&'a str>) -> Self {
1153        self.xml_namespace = Some(trait_types::XmlNamespaceTrait::new(uri, prefix));
1154        self
1155    }
1156
1157    /// Sets the fallback trait map for unknown/custom traits.
1158    ///
1159    /// The schema must outlive the `LazyLock` it references. For codegen-emitted
1160    /// schemas this is always `'static` to `'static`. Runtime-built schemas
1161    /// must arrange the lifetimes via standard borrow-check discipline.
1162    pub const fn with_traits(mut self, traits: &'a std::sync::LazyLock<TraitMap>) -> Self {
1163        self.traits = Some(traits);
1164        self
1165    }
1166
1167    /// Returns the value of extension `key` for this schema, computing it on first use.
1168    ///
1169    /// The value is computed by the key's provider the first time this schema is asked
1170    /// for it, then cached for the life of the schema. Concurrent first calls compute it
1171    /// once. See the [`extension`] module.
1172    ///
1173    /// # Panics
1174    ///
1175    /// If called from inside an extension provider for a value that is not yet cached,
1176    /// and if the provider itself panics.
1177    #[inline]
1178    pub fn extension<T: Send + Sync + 'static>(
1179        &self,
1180        key: &'static extension::SchemaExtensionKey<T>,
1181    ) -> &T {
1182        self.extensions.get_or_compute(self, key)
1183    }
1184
1185    /// Returns the member name if this is a member schema.
1186    ///
1187    /// Returns `Option<&'a str>` (the schema's data lifetime, not the
1188    /// receiver's). For `Schema<'static>` (codegen-emitted) this is
1189    /// `Option<&'static str>` and callers can store the name in
1190    /// `Cow::Borrowed` or other `'static`-lifetime contexts without
1191    /// allocating, matching the underlying field type.
1192    pub fn member_name(&self) -> Option<&'a str> {
1193        self.member_name
1194    }
1195
1196    /// Returns the member index for member schemas.
1197    ///
1198    /// This is used internally by generated code for efficient member lookup.
1199    /// Consumer code should not rely on specific position values as they may change.
1200    pub fn member_index(&self) -> Option<usize> {
1201        self.member_index.get()
1202    }
1203
1204    /// Returns the original (pre-synthesis) shape name for synthetic operation
1205    /// input/output shapes.
1206    ///
1207    /// `None` for non-synthetic shapes. See the field documentation for full
1208    /// semantics.
1209    pub fn original_name(&self) -> Option<&str> {
1210        self.original_name
1211    }
1212
1213    /// Returns the member schema by name (for structures and unions).
1214    pub fn member_schema(&self, name: &str) -> Option<&Schema<'_>> {
1215        match &self.members {
1216            SchemaMembers::Struct { members } => members
1217                .iter()
1218                .find(|m| m.member_name == Some(name))
1219                .copied(),
1220            _ => None,
1221        }
1222    }
1223
1224    /// Returns the member name and schema by position index (for structures and unions).
1225    ///
1226    /// This is an optimization for generated code to avoid string lookups.
1227    /// Consumer code should not rely on specific position values as they may change.
1228    pub fn member_schema_by_index(&self, index: usize) -> Option<&Schema<'_>> {
1229        match &self.members {
1230            SchemaMembers::Struct { members } => members.get(index).copied(),
1231            _ => None,
1232        }
1233    }
1234
1235    /// Returns the member schemas (for structures and unions).
1236    pub fn members(&self) -> &[&Schema<'_>] {
1237        match &self.members {
1238            SchemaMembers::Struct { members } => members,
1239            _ => &[],
1240        }
1241    }
1242
1243    /// Returns the member schema for collections (list member or map value).
1244    pub fn member(&self) -> Option<&Schema<'_>> {
1245        match &self.members {
1246            SchemaMembers::List { member } => Some(member),
1247            SchemaMembers::Map { value, .. } => Some(value),
1248            _ => None,
1249        }
1250    }
1251
1252    /// Like [`member`](Self::member) but returns the `'a` (data-lifetime)
1253    /// borrow that codegen actually stores. Use this when the caller must
1254    /// hold a reference to a value/element member schema across nested
1255    /// callbacks without inheriting the parent `&self` borrow's lifetime.
1256    ///
1257    /// For `Schema<'static>` (codegen-emitted) this returns
1258    /// `Option<&'static Schema<'static>>`.
1259    pub fn member_borrowed(&self) -> Option<&'a Schema<'a>> {
1260        match &self.members {
1261            SchemaMembers::List { member } => Some(*member),
1262            SchemaMembers::Map { value, .. } => Some(*value),
1263            _ => None,
1264        }
1265    }
1266
1267    /// Returns the key schema for maps.
1268    pub fn key(&self) -> Option<&Schema<'_>> {
1269        match &self.members {
1270            SchemaMembers::Map { key, .. } => Some(key),
1271            _ => None,
1272        }
1273    }
1274
1275    /// Like [`key`](Self::key) but returns the `'a` (data-lifetime) borrow
1276    /// that codegen stores. See [`member_borrowed`](Self::member_borrowed).
1277    pub fn key_borrowed(&self) -> Option<&'a Schema<'a>> {
1278        match &self.members {
1279            SchemaMembers::Map { key, .. } => Some(*key),
1280            _ => None,
1281        }
1282    }
1283
1284    // -- convenience predicates --
1285
1286    /// Returns true if this is a member schema.
1287    pub fn is_member(&self) -> bool {
1288        self.shape_type.is_member()
1289    }
1290
1291    /// Returns true if this is a structure schema.
1292    pub fn is_structure(&self) -> bool {
1293        self.shape_type == ShapeType::Structure
1294    }
1295
1296    /// Returns true if this is a union schema.
1297    pub fn is_union(&self) -> bool {
1298        self.shape_type == ShapeType::Union
1299    }
1300
1301    /// Returns true if this is a list schema.
1302    pub fn is_list(&self) -> bool {
1303        self.shape_type == ShapeType::List
1304    }
1305
1306    /// Returns true if this is a map schema.
1307    pub fn is_map(&self) -> bool {
1308        self.shape_type == ShapeType::Map
1309    }
1310
1311    /// Returns true if this is a blob schema.
1312    pub fn is_blob(&self) -> bool {
1313        self.shape_type == ShapeType::Blob
1314    }
1315
1316    /// Returns true if this is a string schema.
1317    pub fn is_string(&self) -> bool {
1318        self.shape_type == ShapeType::String
1319    }
1320}
1321
1322#[cfg(test)]
1323mod test {
1324    use crate::{shape_id, MemberIndex, Schema, ShapeId, ShapeType, Trait, TraitMap};
1325
1326    // Simple test trait implementation
1327    #[derive(Debug)]
1328    struct TestTrait {
1329        id: crate::ShapeId<'static>,
1330        #[allow(dead_code)]
1331        value: String,
1332    }
1333
1334    impl Trait for TestTrait {
1335        fn trait_id(&self) -> &crate::ShapeId<'static> {
1336            &self.id
1337        }
1338
1339        fn as_any(&self) -> &dyn std::any::Any {
1340            self
1341        }
1342    }
1343
1344    #[test]
1345    fn test_shape_type_simple() {
1346        assert!(ShapeType::String.is_simple());
1347        assert!(ShapeType::Integer.is_simple());
1348        assert!(ShapeType::Boolean.is_simple());
1349        assert!(!ShapeType::Structure.is_simple());
1350        assert!(!ShapeType::List.is_simple());
1351    }
1352
1353    #[test]
1354    fn test_shape_type_aggregate() {
1355        assert!(ShapeType::Structure.is_aggregate());
1356        assert!(ShapeType::Union.is_aggregate());
1357        assert!(ShapeType::List.is_aggregate());
1358        assert!(ShapeType::Map.is_aggregate());
1359        assert!(!ShapeType::String.is_aggregate());
1360    }
1361
1362    #[test]
1363    fn test_shape_type_member() {
1364        assert!(ShapeType::Member.is_member());
1365        assert!(!ShapeType::String.is_member());
1366        assert!(!ShapeType::Structure.is_member());
1367    }
1368
1369    #[test]
1370    fn test_shape_id_parsing() {
1371        let id = shape_id!("smithy.api", "String");
1372        assert_eq!(id.namespace(), "smithy.api");
1373        assert_eq!(id.shape_name(), "String");
1374        assert_eq!(id.member_name(), None);
1375    }
1376
1377    #[test]
1378    fn test_shape_id_with_member() {
1379        let id = shape_id!("com.example", "MyStruct", "member");
1380        assert_eq!(id.namespace(), "com.example");
1381        assert_eq!(id.shape_name(), "MyStruct");
1382        assert_eq!(id.member_name(), Some("member"));
1383    }
1384
1385    #[test]
1386    fn test_trait_map() {
1387        let mut map = TraitMap::new();
1388        assert!(map.is_empty());
1389        assert_eq!(map.len(), 0);
1390
1391        let trait_id = shape_id!("smithy.api", "required");
1392        let test_trait = Box::new(TestTrait {
1393            id: trait_id.clone(),
1394            value: "test".to_string(),
1395        });
1396
1397        map.insert(test_trait);
1398        assert!(!map.is_empty());
1399        assert_eq!(map.len(), 1);
1400        assert!(map.contains(&trait_id));
1401
1402        let retrieved = map.get(&trait_id);
1403        assert!(retrieved.is_some());
1404    }
1405
1406    /// `TraitMap::get` and `contains` accept any `&ShapeId<'_>`.
1407    /// `get_fqn` / `contains_fqn` accept `&str`. All resolve against the
1408    /// `'static`-keyed table by fully qualified name.
1409    #[test]
1410    fn test_trait_map_cross_lifetime_lookup() {
1411        let mut map = TraitMap::new();
1412        let trait_id = shape_id!("smithy.api", "required");
1413        map.insert(Box::new(TestTrait {
1414            id: trait_id,
1415            value: "test".to_string(),
1416        }));
1417
1418        // `&str` lookup.
1419        assert!(map.contains_fqn("smithy.api#required"));
1420        assert!(map.get_fqn("smithy.api#required").is_some());
1421        assert!(!map.contains_fqn("smithy.api#missing"));
1422
1423        // Runtime-built ShapeId lookup.
1424        let owned_fqn = String::from("smithy.api#required");
1425        let owned_ns = String::from("smithy.api");
1426        let owned_name = String::from("required");
1427        let runtime_id: ShapeId<'_> = ShapeId::from_parts(&owned_fqn, &owned_ns, &owned_name);
1428        assert!(map.contains(&runtime_id));
1429        assert!(map.get(&runtime_id).is_some());
1430    }
1431
1432    #[test]
1433    fn test_schema_predicates() {
1434        let schema = Schema::new(shape_id!("com.example", "MyStruct"), ShapeType::Structure);
1435
1436        assert!(schema.is_structure());
1437        assert!(!schema.is_union());
1438        assert!(!schema.is_list());
1439        assert!(!schema.is_member());
1440    }
1441
1442    #[test]
1443    fn test_schema_basic() {
1444        let schema = Schema::new(shape_id!("smithy.api", "String"), ShapeType::String);
1445
1446        assert_eq!(schema.shape_id().as_str(), "smithy.api#String");
1447        assert_eq!(schema.shape_type(), ShapeType::String);
1448        assert!(schema.traits().is_none());
1449        assert!(schema.member_name().is_none());
1450        assert!(schema.member_schema("test").is_none());
1451        assert!(schema.member_schema_by_index(0).is_none());
1452    }
1453
1454    /// The gap this test exists to close: `shape_id.rs` already covers runtime
1455    /// `ShapeId`s, but nothing covered runtime *trait values*, so a `Schema`
1456    /// could be given the right shape and then not be given a wire format.
1457    ///
1458    /// Every string here is owned by a local `Vec<String>` — an arena the
1459    /// caller controls. Nothing is `'static` and nothing is leaked, which is
1460    /// the property that makes runtime-materialized schemas practical.
1461    #[test]
1462    fn runtime_trait_values_from_an_arena() {
1463        let arena: Vec<String> = vec![
1464            String::from("ns#Foo"),              // 0 fqn
1465            String::from("ns"),                  // 1 namespace
1466            String::from("Foo"),                 // 2 shape name
1467            String::from("fieldName"),           // 3 member name
1468            String::from("WireName"),            // 4 @jsonName
1469            String::from("wire-elem"),           // 5 @xmlName
1470            String::from("application/json"),    // 6 @mediaType
1471            String::from("qparam"),              // 7 @httpQuery
1472            String::from("http://ns.example/x"), // 8 @xmlNamespace uri
1473            String::from("px"),                  // 9 @xmlNamespace prefix
1474        ];
1475
1476        let member: Schema<'_> = Schema::new_member(
1477            ShapeId::from_parts(&arena[0], &arena[1], &arena[2]),
1478            ShapeType::String,
1479            &arena[3],
1480            0,
1481        )
1482        .with_json_name(&arena[4])
1483        .with_xml_name(&arena[5])
1484        .with_media_type(&arena[6])
1485        .with_http_query(&arena[7])
1486        .with_xml_namespace(&arena[8], Some(&arena[9]));
1487
1488        // Read every wire-format trait back off the runtime schema.
1489        assert_eq!(member.json_name().unwrap().value(), "WireName");
1490        assert_eq!(member.xml_name().unwrap().value(), "wire-elem");
1491        assert_eq!(member.media_type().unwrap().value(), "application/json");
1492        assert_eq!(member.http_query().unwrap().value(), "qparam");
1493        let ns = member.xml_namespace().unwrap();
1494        assert_eq!(ns.uri(), "http://ns.example/x");
1495        assert_eq!(ns.prefix(), Some("px"));
1496        assert_eq!(member.member_name(), Some("fieldName"));
1497
1498        // And it composes into a struct schema whose members are readable.
1499        let members = [&member];
1500        let schema = Schema::new_struct(
1501            ShapeId::from_parts(&arena[0], &arena[1], &arena[2]),
1502            ShapeType::Structure,
1503            &members,
1504        );
1505        assert_eq!(
1506            schema
1507                .member_schema("fieldName")
1508                .unwrap()
1509                .json_name()
1510                .unwrap()
1511                .value(),
1512            "WireName"
1513        );
1514    }
1515
1516    /// `@http` carries the method and URI, so without runtime support a
1517    /// dynamically-built operation has no request line at all.
1518    #[test]
1519    fn runtime_http_trait_from_an_arena() {
1520        let method = String::from("PATCH");
1521        let uri = String::from("/things/{id}");
1522
1523        let schema = Schema::new(shape_id!("ns", "Op"), ShapeType::Structure)
1524            .with_http(crate::traits::HttpTrait::new(&method, &uri, Some(204)));
1525
1526        let http = schema.http().unwrap();
1527        assert_eq!(http.method(), "PATCH");
1528        assert_eq!(http.uri(), "/things/{id}");
1529        assert_eq!(http.code(), 204);
1530    }
1531
1532    /// A trait value read off a `Schema<'static>` is still `&'static str`, so
1533    /// the relaxation costs codegen-emitted schemas nothing. This is a
1534    /// compile-time assertion: the annotation is the test.
1535    #[test]
1536    fn static_schema_still_yields_static_trait_values() {
1537        static S: Schema<'static> =
1538            Schema::new(shape_id!("ns", "Foo"), ShapeType::String).with_json_name("WireName");
1539
1540        let value: &'static str = S.json_name().unwrap().value();
1541        assert_eq!(value, "WireName");
1542    }
1543
1544    /// Interning is deduplicated: the same name yields the identical pointer,
1545    /// so a repeated call leaks nothing further. This is the property that
1546    /// makes `intern_header_name` safe where a bare `Box::leak` is not.
1547    #[test]
1548    fn intern_header_name_dedups_by_pointer() {
1549        let from_runtime = String::from("x-dedup-probe");
1550
1551        let a = crate::intern_header_name(&from_runtime);
1552        let b = crate::intern_header_name("x-dedup-probe");
1553        let c = crate::intern_header_name(&String::from("x-dedup-probe"));
1554
1555        assert_eq!(a, "x-dedup-probe");
1556        assert!(std::ptr::eq(a, b), "second intern must reuse the first");
1557        assert!(std::ptr::eq(a, c), "third intern must reuse the first");
1558
1559        // Distinct names are distinct allocations with correct contents.
1560        let other = crate::intern_header_name("x-dedup-other");
1561        assert!(!std::ptr::eq(a, other));
1562        assert_eq!(other, "x-dedup-other");
1563    }
1564
1565    /// The point of interning: a header name that only exists at runtime can be
1566    /// attached to a schema, and the binder still sees a `'static` name, so the
1567    /// zero-allocation insert path is preserved rather than falling back to an
1568    /// owned copy.
1569    #[test]
1570    fn interned_header_name_preserves_the_binder_fast_path() {
1571        let arena: Vec<String> = vec![String::from("memberName"), String::from("x-runtime-hdr")];
1572
1573        let member: Schema<'_> =
1574            Schema::new_member(shape_id!("ns", "Foo"), ShapeType::String, &arena[0], 0)
1575                .with_http_header(crate::intern_header_name(&arena[1]));
1576
1577        // `Some` is what the binder needs; `None` would force an allocation.
1578        assert_eq!(
1579            member.http_header().unwrap().value_static(),
1580            Some("x-runtime-hdr")
1581        );
1582        assert_eq!(member.http_header().unwrap().value(), "x-runtime-hdr");
1583    }
1584
1585    #[test]
1586    fn streaming_accessor_reflects_the_propagated_trait() {
1587        // Codegen propagates `@streaming` from a member's target (the trait's selector is
1588        // `:is(blob, union)`, so a member never carries it directly). This is the accessor
1589        // the protocol uses to tell a streaming payload member from a buffered one.
1590        //
1591        // These are `static`s rather than locals on purpose: that is the position codegen
1592        // emits them in, so this also pins `with_streaming` as const-evaluable when
1593        // chained after another setter.
1594        static BUFFERED: Schema<'static> = Schema::new_member(
1595            shape_id!("com.example", "Output", "body"),
1596            ShapeType::Blob,
1597            "body",
1598            0,
1599        );
1600        assert!(
1601            !BUFFERED.streaming(),
1602            "a member whose target is not streaming must report false"
1603        );
1604
1605        static STREAMING_BLOB: Schema<'static> = Schema::new_member(
1606            shape_id!("com.example", "Output", "body"),
1607            ShapeType::Blob,
1608            "body",
1609            0,
1610        )
1611        .with_streaming();
1612        assert!(STREAMING_BLOB.streaming());
1613
1614        // The union half of the selector: an event-stream member.
1615        static EVENT_STREAM: Schema<'static> = Schema::new_member(
1616            shape_id!("com.example", "Output", "events"),
1617            ShapeType::Union,
1618            "events",
1619            0,
1620        )
1621        .with_streaming();
1622        assert!(EVENT_STREAM.streaming());
1623
1624        // Exactly the chain generated for a streaming payload member. Independent of the
1625        // payload binding, so the payload branch can check both.
1626        static STREAMING_PAYLOAD: Schema<'static> = Schema::new_member(
1627            shape_id!("com.example", "Output", "body"),
1628            ShapeType::Blob,
1629            "body",
1630            0,
1631        )
1632        .with_http_payload()
1633        .with_streaming();
1634        assert!(STREAMING_PAYLOAD.streaming());
1635        assert!(STREAMING_PAYLOAD.http_payload().is_some());
1636
1637        static BUFFERED_PAYLOAD: Schema<'static> = Schema::new_member(
1638            shape_id!("com.example", "Output", "body"),
1639            ShapeType::Blob,
1640            "body",
1641            0,
1642        )
1643        .with_http_payload();
1644        assert!(!BUFFERED_PAYLOAD.streaming());
1645        assert!(BUFFERED_PAYLOAD.http_payload().is_some());
1646    }
1647
1648    /// The size of [`Schema`] is a deliberate budget, not an accident.
1649    ///
1650    /// A generated client instantiates one `Schema` per shape *and* per member, so
1651    /// thousands of them; every added word is multiplied by that count in both the
1652    /// binary and resident memory. The running budget on a 64-bit target:
1653    ///
1654    /// | state | bytes | change |
1655    /// | --- | --- | --- |
1656    /// | baseline | 336 | — |
1657    /// | `member_index` encoded in one word instead of `Option<usize>` | 328 | −8 |
1658    /// | response routing word added | 336 | +8 |
1659    /// | schema extension storage added | 352 | +16 |
1660    ///
1661    /// The routing word was deliberately funded by the `member_index` re-encoding, so
1662    /// response binding routing cost no net memory.
1663    ///
1664    /// If this assertion fails, a field was added or widened. That is not automatically
1665    /// wrong, but it needs to be a conscious decision with SDK-scale source and rlib
1666    /// measurement behind it — so update the number deliberately rather than reflexively.
1667    ///
1668    /// Gated to 64-bit because the layout differs on 32-bit targets.
1669    #[test]
1670    #[cfg(target_pointer_width = "64")]
1671    fn schema_size_stays_within_its_budget() {
1672        assert_eq!(
1673            std::mem::size_of::<Schema<'static>>(),
1674            352,
1675            "Schema changed size; see this test's documentation before updating the number"
1676        );
1677    }
1678
1679    #[test]
1680    fn member_index_encoding_round_trips() {
1681        assert_eq!(MemberIndex::NONE.get(), None);
1682        for index in [0usize, 1, 2, 41, 61, 62, 63, 1000, usize::MAX - 1] {
1683            assert_eq!(
1684                MemberIndex::new(index).get(),
1685                Some(index),
1686                "index {index} did not round-trip"
1687            );
1688        }
1689        // The reason for the encoding: one word instead of two.
1690        assert_eq!(
1691            std::mem::size_of::<MemberIndex>(),
1692            std::mem::size_of::<usize>()
1693        );
1694        assert!(std::mem::size_of::<MemberIndex>() < std::mem::size_of::<Option<usize>>());
1695    }
1696
1697    #[test]
1698    fn member_index_zero_is_distinct_from_absent() {
1699        // The encoding's whole risk is conflating index 0 with "not a member", since both
1700        // are naturally zero.
1701        assert_eq!(MemberIndex::new(0).get(), Some(0));
1702        assert_ne!(MemberIndex::new(0), MemberIndex::NONE);
1703
1704        let member = Schema::new_member(
1705            shape_id!("com.example", "S", "first"),
1706            ShapeType::String,
1707            "first",
1708            0,
1709        );
1710        assert_eq!(
1711            member.member_index(),
1712            Some(0),
1713            "the first member must report index 0, not absent"
1714        );
1715
1716        let non_member = Schema::new(shape_id!("com.example", "S"), ShapeType::Structure);
1717        assert_eq!(non_member.member_index(), None);
1718    }
1719
1720    #[test]
1721    #[should_panic(expected = "member index must be less than usize::MAX")]
1722    fn member_index_rejects_the_unrepresentable_index() {
1723        // `usize::MAX` would overflow `index + 1`. Generated schemas are const-evaluated,
1724        // so in practice this is a compile-time error; this covers the runtime path.
1725        let _ = MemberIndex::new(usize::MAX);
1726    }
1727
1728    #[test]
1729    fn debug_output_shows_the_decoded_member_index() {
1730        // The encoding must not leak into diagnostics. `Schema` derives `Debug`, so this
1731        // pins that the newtype's `Debug` prints the decoded `Option`.
1732        let member = Schema::new_member(
1733            shape_id!("com.example", "S", "third"),
1734            ShapeType::String,
1735            "third",
1736            2,
1737        );
1738        let rendered = format!("{member:?}");
1739        assert!(
1740            rendered.contains("member_index: Some(2)"),
1741            "expected the decoded index in Debug output, got: {rendered}"
1742        );
1743        assert!(
1744            !rendered.contains("member_index: Some(3)") && !rendered.contains("member_index: 3"),
1745            "the raw encoded value leaked into Debug output: {rendered}"
1746        );
1747
1748        let non_member = Schema::new(shape_id!("com.example", "S"), ShapeType::Structure);
1749        assert!(
1750            format!("{non_member:?}").contains("member_index: None"),
1751            "absent index should render as None"
1752        );
1753    }
1754
1755    /// Walks a routing mask the way the composite does, returning visited member indices.
1756    fn mask_indices(schema: &Schema<'_>) -> Vec<usize> {
1757        let mut mask = schema.response_binding_mask();
1758        let mut out = Vec::new();
1759        while mask != 0 {
1760            let index = mask.trailing_zeros() as usize;
1761            mask &= mask - 1;
1762            out.push(index);
1763        }
1764        out
1765    }
1766
1767    #[test]
1768    fn routing_word_marks_only_response_bound_members() {
1769        static HEADER: Schema<'static> =
1770            Schema::new_member(shape_id!("t", "O", "h"), ShapeType::String, "h", 0)
1771                .with_http_header("x-h");
1772        static BODY: Schema<'static> =
1773            Schema::new_member(shape_id!("t", "O", "b"), ShapeType::String, "b", 1);
1774        static STATUS: Schema<'static> =
1775            Schema::new_member(shape_id!("t", "O", "s"), ShapeType::Integer, "s", 2)
1776                .with_http_response_code();
1777        static PREFIX: Schema<'static> =
1778            Schema::new_member(shape_id!("t", "O", "p"), ShapeType::Map, "p", 3)
1779                .with_http_prefix_headers("x-meta-");
1780        static PAYLOAD: Schema<'static> =
1781            Schema::new_member(shape_id!("t", "O", "pay"), ShapeType::Blob, "pay", 4)
1782                .with_http_payload();
1783        static OUTPUT: Schema<'static> = Schema::new_struct(
1784            shape_id!("t", "O"),
1785            ShapeType::Structure,
1786            &[&HEADER, &BODY, &STATUS, &PREFIX, &PAYLOAD],
1787        );
1788
1789        // All four response binding kinds set a bit; the unbound member does not.
1790        assert_eq!(mask_indices(&OUTPUT), vec![0, 2, 3, 4]);
1791        assert!(OUTPUT.has_response_body_members());
1792        assert!(!OUTPUT.response_bindings_need_scan());
1793
1794        // The mask agrees with the per-member predicate it is derived from.
1795        for (i, member) in OUTPUT.members().iter().enumerate() {
1796            assert_eq!(
1797                OUTPUT.response_binding_mask() & (1u64 << i) != 0,
1798                member.has_http_response_binding(),
1799                "mask bit {i} disagrees with has_http_response_binding()"
1800            );
1801        }
1802    }
1803
1804    #[test]
1805    fn request_only_bindings_are_body_members_on_a_response() {
1806        // The distinction the design is explicit about: `@httpQuery` and `@httpLabel` bind
1807        // a member on the request, but on a response it belongs to the document body. So
1808        // they must NOT set a mask bit, and they MUST set the body bit.
1809        static QUERY: Schema<'static> =
1810            Schema::new_member(shape_id!("t", "O", "q"), ShapeType::String, "q", 0)
1811                .with_http_query("q");
1812        static LABEL: Schema<'static> =
1813            Schema::new_member(shape_id!("t", "O", "l"), ShapeType::String, "l", 1)
1814                .with_http_label();
1815        static OUTPUT: Schema<'static> =
1816            Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&QUERY, &LABEL]);
1817
1818        assert_eq!(
1819            mask_indices(&OUTPUT),
1820            Vec::<usize>::new(),
1821            "request-only bindings must not be treated as response-bound"
1822        );
1823        assert!(
1824            OUTPUT.has_response_body_members(),
1825            "request-only bound members are body members on a response"
1826        );
1827    }
1828
1829    #[test]
1830    fn a_fully_bound_structure_has_no_body_members() {
1831        // This is what lets the composite skip the body codec entirely.
1832        static H1: Schema<'static> =
1833            Schema::new_member(shape_id!("t", "O", "a"), ShapeType::String, "a", 0)
1834                .with_http_header("x-a");
1835        static H2: Schema<'static> =
1836            Schema::new_member(shape_id!("t", "O", "b"), ShapeType::String, "b", 1)
1837                .with_http_header("x-b");
1838        static OUTPUT: Schema<'static> =
1839            Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&H1, &H2]);
1840
1841        assert_eq!(mask_indices(&OUTPUT), vec![0, 1]);
1842        assert!(!OUTPUT.has_response_body_members());
1843        assert!(!OUTPUT.response_bindings_need_scan());
1844    }
1845
1846    #[test]
1847    fn an_empty_structure_routes_through_the_composite() {
1848        // Zero members: no bindings and no body members. The body bit being clear is what
1849        // keeps an empty output off the bare-codec fast path, so the body codec is never
1850        // invoked on it.
1851        static EMPTY: Schema<'static> =
1852            Schema::new_struct(shape_id!("t", "E"), ShapeType::Structure, &[]);
1853        assert_eq!(EMPTY.response_binding_mask(), 0);
1854        assert!(!EMPTY.has_response_body_members());
1855        assert!(!EMPTY.response_bindings_need_scan());
1856    }
1857
1858    #[test]
1859    fn a_body_only_structure_reports_exactly_that() {
1860        // The shape of the success fast path's precondition: exact, mask zero, body bit set.
1861        static M0: Schema<'static> =
1862            Schema::new_member(shape_id!("t", "O", "a"), ShapeType::String, "a", 0);
1863        static M1: Schema<'static> =
1864            Schema::new_member(shape_id!("t", "O", "b"), ShapeType::Integer, "b", 1);
1865        static OUTPUT: Schema<'static> =
1866            Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&M0, &M1]);
1867
1868        assert_eq!(OUTPUT.response_binding_mask(), 0);
1869        assert!(OUTPUT.has_response_body_members());
1870        assert!(!OUTPUT.response_bindings_need_scan());
1871    }
1872
1873    #[test]
1874    fn non_struct_schemas_default_to_the_conservative_word() {
1875        // Zero must read as "nothing bound, nothing in the body", which fails the fast
1876        // path's body-bit requirement and so routes through the composite.
1877        let scalar = Schema::new(shape_id!("t", "S"), ShapeType::String);
1878        assert_eq!(scalar.response_binding_mask(), 0);
1879        assert!(!scalar.has_response_body_members());
1880        assert!(!scalar.response_bindings_need_scan());
1881
1882        let member = Schema::new_member(shape_id!("t", "O", "m"), ShapeType::String, "m", 0);
1883        assert_eq!(member.response_binding_mask(), 0);
1884        assert!(!member.has_response_body_members());
1885    }
1886
1887    #[test]
1888    fn unions_get_a_routing_word_too() {
1889        // Codegen builds union schemas with `new_struct`, so the derivation must accept
1890        // `ShapeType::Union` and the invariant must hold for union members as well.
1891        static V0: Schema<'static> =
1892            Schema::new_member(shape_id!("t", "U", "a"), ShapeType::String, "a", 0);
1893        static V1: Schema<'static> =
1894            Schema::new_member(shape_id!("t", "U", "b"), ShapeType::String, "b", 1);
1895        static UNION: Schema<'static> =
1896            Schema::new_struct(shape_id!("t", "U"), ShapeType::Union, &[&V0, &V1]);
1897        assert_eq!(UNION.response_binding_mask(), 0);
1898        assert!(UNION.has_response_body_members());
1899    }
1900
1901    #[test]
1902    fn mask_and_scan_paths_agree_on_the_same_members() {
1903        // The design requires the exact-mask path and the scan fallback to produce
1904        // identical results. With a hand-built schema we can compare them directly.
1905        static H: Schema<'static> =
1906            Schema::new_member(shape_id!("t", "O", "h"), ShapeType::String, "h", 0)
1907                .with_http_header("x-h");
1908        static B: Schema<'static> =
1909            Schema::new_member(shape_id!("t", "O", "b"), ShapeType::String, "b", 1);
1910        static S: Schema<'static> =
1911            Schema::new_member(shape_id!("t", "O", "s"), ShapeType::Integer, "s", 2)
1912                .with_http_response_code();
1913        static OUTPUT: Schema<'static> =
1914            Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&H, &B, &S]);
1915
1916        let via_mask = mask_indices(&OUTPUT);
1917        let via_scan: Vec<usize> = OUTPUT
1918            .members()
1919            .iter()
1920            .enumerate()
1921            .filter(|(_, m)| m.has_http_response_binding())
1922            .map(|(i, _)| i)
1923            .collect();
1924        assert_eq!(via_mask, via_scan);
1925    }
1926
1927    #[test]
1928    fn mask_bits_resolve_to_member_schemas_in_o1() {
1929        // What makes the mask useful: a set bit is a direct index into the member slice.
1930        static H: Schema<'static> =
1931            Schema::new_member(shape_id!("t", "O", "h"), ShapeType::String, "h", 0)
1932                .with_http_header("x-wanted");
1933        static B: Schema<'static> =
1934            Schema::new_member(shape_id!("t", "O", "b"), ShapeType::String, "b", 1);
1935        static OUTPUT: Schema<'static> =
1936            Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&H, &B]);
1937
1938        let indices = mask_indices(&OUTPUT);
1939        assert_eq!(indices, vec![0]);
1940        let member = OUTPUT
1941            .member_schema_by_index(indices[0])
1942            .expect("a mask bit must resolve to a member");
1943        assert_eq!(member.member_name(), Some("h"));
1944        assert_eq!(member.http_header().map(|h| h.value()), Some("x-wanted"));
1945    }
1946
1947    /// Builds a structure schema at runtime with `count` members, marking those whose
1948    /// index is in `bound` with `@httpHeader`. Returns owned storage plus the schema.
1949    ///
1950    /// `new_struct` is a `const fn` but is equally callable at runtime, which is how these
1951    /// tests reach member counts that would be impractical to write out as statics.
1952    fn struct_with(count: usize, bound: &[usize]) -> (Vec<Schema<'static>>, Vec<&'static str>) {
1953        // Member names must outlive the schema, so leak them; this is a test.
1954        let names: Vec<&'static str> = (0..count)
1955            .map(|i| Box::leak(format!("m{i}").into_boxed_str()) as &'static str)
1956            .collect();
1957        let members: Vec<Schema<'static>> = (0..count)
1958            .map(|i| {
1959                let m = Schema::new_member(shape_id!("t", "Big"), ShapeType::String, names[i], i);
1960                if bound.contains(&i) {
1961                    m.with_http_header(names[i])
1962                } else {
1963                    m
1964                }
1965            })
1966            .collect();
1967        (members, names)
1968    }
1969
1970    #[test]
1971    fn a_bound_member_beyond_the_mask_forces_the_scan_fallback() {
1972        // 64 members, all response-bound: positions 62 and 63 cannot be represented, so
1973        // the mask is incomplete and consumers must scan.
1974        let count = 64;
1975        let all: Vec<usize> = (0..count).collect();
1976        let (members, _names) = struct_with(count, &all);
1977        let refs: Vec<&Schema<'static>> = members.iter().collect();
1978        let schema = Schema::new_struct(shape_id!("t", "Big"), ShapeType::Structure, &refs);
1979
1980        assert!(
1981            schema.response_bindings_need_scan(),
1982            "a bound member at position >= 62 must set the scan flag"
1983        );
1984        assert!(
1985            !schema.has_response_body_members(),
1986            "every member is bound, so there is nothing for the body codec"
1987        );
1988
1989        // The scan fallback must find every bound member, including the ones the mask
1990        // could not represent.
1991        let via_scan: Vec<usize> = schema
1992            .members()
1993            .iter()
1994            .enumerate()
1995            .filter(|(_, m)| m.has_http_response_binding())
1996            .map(|(i, _)| i)
1997            .collect();
1998        assert_eq!(via_scan, all, "the scan path must see all 64 bound members");
1999    }
2000
2001    #[test]
2002    fn a_structure_at_the_mask_boundary_stays_exact() {
2003        // Exactly 62 bound members is the largest representable case; it must NOT scan.
2004        let count = crate::response_routing::MASK_BITS;
2005        let all: Vec<usize> = (0..count).collect();
2006        let (members, _names) = struct_with(count, &all);
2007        let refs: Vec<&Schema<'static>> = members.iter().collect();
2008        let schema = Schema::new_struct(shape_id!("t", "Big"), ShapeType::Structure, &refs);
2009
2010        assert!(
2011            !schema.response_bindings_need_scan(),
2012            "62 members fit the mask exactly and must not trigger a scan"
2013        );
2014        assert_eq!(
2015            schema.response_binding_mask().count_ones() as usize,
2016            count,
2017            "every one of the 62 positions should be marked"
2018        );
2019        assert_eq!(mask_indices(&schema), all);
2020    }
2021
2022    #[test]
2023    fn many_members_stay_exact_when_the_bindings_are_within_range() {
2024        // More than 62 members is fine as long as no *bound* member sits out of range: the
2025        // mask still describes every binding, so the fast path is preserved.
2026        let (members, _names) = struct_with(70, &[0, 5, 61]);
2027        let refs: Vec<&Schema<'static>> = members.iter().collect();
2028        let schema = Schema::new_struct(shape_id!("t", "Big"), ShapeType::Structure, &refs);
2029
2030        assert!(!schema.response_bindings_need_scan());
2031        assert_eq!(mask_indices(&schema), vec![0, 5, 61]);
2032        assert!(schema.has_response_body_members());
2033    }
2034
2035    #[test]
2036    fn the_mask_handles_sparse_bindings() {
2037        // The §11.4 sparse layout: a few bound members among many body members.
2038        let (members, _names) = struct_with(50, &[3, 17, 42, 49]);
2039        let refs: Vec<&Schema<'static>> = members.iter().collect();
2040        let schema = Schema::new_struct(shape_id!("t", "Big"), ShapeType::Structure, &refs);
2041
2042        assert_eq!(mask_indices(&schema), vec![3, 17, 42, 49]);
2043        assert!(schema.has_response_body_members());
2044        // O(bound), not O(all): four iterations for a fifty-member structure.
2045        assert_eq!(schema.response_binding_mask().count_ones(), 4);
2046    }
2047
2048    #[test]
2049    #[should_panic(expected = "member-index order")]
2050    fn out_of_order_members_are_rejected() {
2051        // The mask treats a member's array position as its index, so a mismatch would
2052        // silently route the wrong member. In generated code this is a compile error
2053        // because the schema is const-evaluated; here it is a runtime panic.
2054        static A: Schema<'static> =
2055            Schema::new_member(shape_id!("t", "O", "a"), ShapeType::String, "a", 0);
2056        static B: Schema<'static> =
2057            Schema::new_member(shape_id!("t", "O", "b"), ShapeType::String, "b", 1);
2058        // Swapped: B (index 1) is at position 0.
2059        let _ = Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&B, &A]);
2060    }
2061
2062    #[test]
2063    #[should_panic(expected = "must carry a member index")]
2064    fn a_non_member_in_the_member_array_is_rejected() {
2065        // A schema with no member index cannot be positioned in the mask.
2066        static NOT_A_MEMBER: Schema<'static> = Schema::new(shape_id!("t", "X"), ShapeType::String);
2067        let _ = Schema::new_struct(shape_id!("t", "O"), ShapeType::Structure, &[&NOT_A_MEMBER]);
2068    }
2069}