[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6994SZVJ06VW84X5GJCC2K5":3,"skill-same:01M6994SZVJ06VW84X5GJCC2K5":95},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":17,"ownerHtmlUrl":45,"ownerBlogUrl":46,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6994SZVJ06VW84X5GJCC2K5","unsafe-rust-review","Rust 不安全代码安全注释审查","Write and review unsafe Rust `# Safety` documentation and safety comments (e.g., `\u002F\u002F safety:` or `\u002F\u002F\u002F safety:` in any capitalization) as proof obligations grounded in the Rust Reference, standard library documentation, trusted opted-in dependency contracts, and explicit project invariants.","撰写和审查不安全 Rust 的 `# Safety` 文档与安全注释（例如任意大小写形式的 `\u002F\u002F safety:` 或 `\u002F\u002F\u002F safety:`），将其作为证明义务，并以 Rust 参考手册、标准库文档、显式选择加入的可信依赖契约以及明确的项目不变量为依据。","google\u002Frust-skills","google","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1342004?v=4","01M698VYEFDM0VJBZDYYJ2T83S","Google","01M6994Q063NRNDZA4BZD0E9GN",73,"Apache-2.0",null,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSNPHVX9Y1H3B2ZX3V06RF","Rust 开发","SCENARIO","使用场景",[31,32,33,34],"review","rust","unsafe rust","unsafe rust review","2026-11-10 10:12:30",false,"---\nname: unsafe-rust-review\ndescription: Write and review unsafe Rust `# Safety` documentation and safety comments (e.g., `\u002F\u002F safety:` or `\u002F\u002F\u002F safety:` in any capitalization) as proof obligations grounded in the Rust Reference, standard library documentation, trusted opted-in dependency contracts, and explicit project invariants.\n---\n\n# Unsafe Rust Safety Documentation and Commenting Skill\n\n## Mission\n\nAct as an extremely strict unsafe Rust author and reviewer. Treat every `#\nSafety` section as an English-language theorem or lemma, and every safety\ncomment (e.g., `\u002F\u002F safety:` or `\u002F\u002F\u002F safety:` in any capitalization) as an\nEnglish-language proof.\n\nThe goal is not reassuring prose. The goal is logic bulletproof-ness. A reviewer\nshould be able to mechanically translate the prose into proof obligations and\ncheck each obligation against authoritative Rust axioms, documented dependency\ncontracts, project-local invariants, type-system facts, and local code facts.\n\nThe governing standard is:\n\n> Every unsafe boundary creates proof obligations, and every unsafe operation\n> must locally prove that those obligations are discharged.\n\nAn `unsafe fn` or `unsafe trait` states extra conditions that callers or\nimplementers must satisfy. An `unsafe {}` block, `unsafe impl`, or unsafe\nattribute use is the code author’s assertion that the relevant conditions have\nbeen satisfied at that exact program point.\n\nUnsafe documentation and comments must therefore be written in the style of\nformal proof:\n\n-   Define the proposition being proved.\n-   Enumerate all required assumptions.\n-   Classify each assumption by source.\n-   Show that the assumptions imply the required unsafe contract.\n-   State the postconditions and state transitions caused by the unsafe\n    operation.\n-   Reject every implicit, circular, stale, unverifiable, or folklore premise.\n\n## Conventions\n\nEvery section carries a stable `` `[area.slug]` `` ID after its heading. Cite\nsections by ID, never by number or title: numbers shift when a list grows, and\ntitles get reworded. Areas: `model`, `evidence`, `fact`, `conv`\n(conventions), `doc` (`# Safety` criteria), `comment` (comment criteria), `auth`\n(authoring guidance), `topics`, `axiom`, `rej` (reject patterns), `dep`\n(dependency rules), `ref` (reference creation), `hazard` (high-risk hazard\nchecklists).\n\n## Activation criteria\n\nUse this skill whenever authoring or reviewing Rust code that contains, exposes,\nwraps, depends on, or reasons about any unsafe surface, including:\n\n-   `unsafe fn`\n-   `unsafe trait`\n-   unsafe trait methods\n-   `unsafe impl`\n-   `unsafe extern` blocks or functions\n-   unsafe attributes such as `no_mangle`, `export_name`, `link_section`, or\n    `naked`\n-   `unsafe {}` blocks\n-   raw pointer dereferences\n-   calls to unsafe functions\n-   accesses to union fields\n-   accesses to mutable statics or extern statics\n-   inline assembly\n-   FFI boundaries\n-   `target_feature`-sensitive code\n-   manual allocation, deallocation, ownership reconstruction, or layout\n    manipulation\n-   manual initialization or drop management\n-   pin projection or pinned destruction logic\n-   unsafe abstractions over safe callback, trait, iterator, comparator, or\n    closure inputs\n-   safe API surfaces that can establish, expose, or break unsafe invariants,\n    including public fields, constructors, safe methods, safe trait methods, and\n    macro-generated APIs\n-   macro-generated or build-generated unsafe code or safe API surfaces\n-   feature-gated, cfg-gated, target-specific, allocator-specific,\n    SIMD-specific, or debug\u002Frelease-specific unsafe code paths\n\nUse the strictest reasonable interpretation of all requirements. When style or\nreview advice conflicts, choose the more demanding rule unless it conflicts with\nthe Rust Reference or standard library documentation.\n\nIn review, findings come from `[fact.classify]`, `doc.*`, `comment.*`, `rej.*`,\n`dep.*`, `ref.*`, and `hazard.*`. The remaining sections define the model and the\nconventions proofs cite, and `auth.*` says how to write well; a departure from\n`auth.*` is not a finding.\n\n## Core model `[model]`\n\n### Safety documentation is a theorem `[model.theorem]`\n\nA `# Safety` section on an unsafe API states a theorem of the following shape:\n\n```text\nIf the caller or implementer satisfies preconditions P1 ... Pn,\nthen invoking or implementing this unsafe API preserves Rust soundness.\n```\n\nThe documentation must say exactly who is responsible for the preconditions and\nhow long each precondition must hold.\n\n### Safety comments are proofs `[model.proof]`\n\nA safety comment (which may use `\u002F\u002F SAFETY:`, `\u002F\u002F safety:`, `\u002F\u002F Safety:`, or\ntheir doc comment equivalents like `\u002F\u002F\u002F safety:`) immediately adjacent to an\nunsafe operation proves a theorem of the following shape:\n\n```text\nThe unsafe operation O requires obligations Q1 ... Qn.\nAt this program point, facts F1 ... Fm hold.\nFacts F1 ... Fm imply Q1 ... Qn.\nTherefore O's unsafe contract is discharged.\nAfter O, state changes S1 ... Sk hold.\n```\n\nThe proof must be local enough that a maintainer can audit it without searching\nthrough the entire program, except for explicitly named project-local\ninvariants, dependency contracts, upstream `# Safety` preconditions, and the\nguarantees documented by the crate-controlled or trusted-dependency functions it\ncalls or installs (an unsafe fn's `# Safety` postconditions, or a safe fn's `#\nSafety-usable invariant`; never the docs of caller-provided code).\n\n### Soundness target `[model.soundness]`\n\nUnsafe code is sound only if safe Rust code using the abstraction cannot trigger\nundefined behavior without crossing an unsafe contract. The abstraction may have\nlogic bugs, panic, leak memory, or produce incorrect values, but it must not\nallow safe callers to cause UB merely by using safe APIs in type-correct but\nadversarial ways.\n\n## Authority and evidence hierarchy `[evidence]`\n\nUse this hierarchy when writing or reviewing safety documentation.\n\n### 1. Core Rust axioms `[evidence.axioms]`\n\nThe only core axioms for Rust language and standard-library semantics are:\n\n1.  The Rust Reference.\n2.  The Rust standard library documentation.\n\nAll claims about undefined behavior, validity, aliasing, layout, references,\npointer arithmetic, initialization, drop, standard-library unsafe contracts, and\nstandard-library safe API semantics must bottom out in these sources.\n\nDo not use folklore as an axiom. Do not rely on current compiler behavior, LLVM\nbehavior, Miri behavior, blog posts, examples, or \"how Rust usually works\"\nunless the fact is entailed by the Rust Reference or standard library\ndocumentation.\n\n### 2. Trusted opted-in dependency contracts `[evidence.deps]`\n\nIt is acceptable to assume that safe dependencies intentionally selected by the\ncode author work as documented.\n\nFor example, if this crate intentionally depends on a library or uses a\nstandard-library safe API, the safety proof may assume that the dependency's\nsafe APIs perform their documented safe behavior. In particular, it is\nacceptable to rely on a dependency function such as `Vec::sort` actually\nperforming the sorting operation documented by the standard library, subject to\nthat API's own documented assumptions and inputs.\n\nThis rule is a trust-boundary rule, not a Rust-language axiom:\n\n-   Treat non-std dependency behavior as a `DEPENDENCY LEMMA`, not as a core\n    Rust axiom.\n-   Prefer pinned versions and exact documentation links when relying on non-std\n    dependency semantics.\n-   Do not let dependency documentation invent Rust layout, aliasing, validity,\n    provenance, or UB rules that are not supported by the Reference or std docs.\n-   Do not use a dependency lemma to discharge an unsafe contract unless the\n    dependency API actually guarantees the needed fact.\n-   Do not silently rely on a dependency's undocumented behavior.\n-   If the dependency API is unsafe, discharge its unsafe contract exactly like\n    any other unsafe API.\n\n### 3. Caller-provided safe code is not trusted for semantic correctness `[evidence.caller-code]`\n\nThe \"safe dependencies work as documented\" assumption does not apply to\ncaller-provided safe code.\n\nCaller-provided safe code includes, without limitation:\n\n-   safe function arguments\n-   closures\n-   callbacks\n-   function pointers supplied by the caller\n-   iterator implementations supplied by the caller\n-   safe trait implementations supplied by the caller\n-   implementations of `Ord`, `Eq`, `Hash`, `Iterator`, `ExactSizeIterator`,\n    `Drop`, `Deref`, `Borrow`, `AsRef`, `Default`, `Clone`, or other safe traits\n-   values whose behavior is mediated by caller-controlled interior mutability\n-   safe methods reachable through generic type parameters\n-   safe code transitively invoked by a dependency through caller-supplied\n    callbacks or trait methods\n\nModel caller-provided safe code as adversarial but type-correct. It may:\n\n-   panic at any point where panicking is possible;\n-   fail to terminate;\n-   return arbitrary values permitted by its type signature;\n-   violate safe trait laws such as ordering, equality, hashing, length hints,\n    or clone consistency;\n-   mutate reachable state through `Cell`, `RefCell`, atomics, locks,\n    `UnsafeCell`, global state, or reentrant calls;\n-   call back into this crate;\n-   observe intermediate states that are exposed to it;\n-   drop values at inconvenient times;\n-   use safe APIs in unexpected order;\n-   exploit every behavior allowed by safe Rust and the public API surface.\n\nDo not assume caller-provided safe code \"works as documented\" for memory-safety\nproofs. Safe trait documentation may describe logic contracts, but unsafe code\nmust not rely on a safe trait law for memory safety unless one of the following\nis true:\n\n1.  the trait is unsafe and the needed law is part of its `# Safety` contract;\n2.  the property is checked dynamically before unsafe reliance;\n3.  every possible implementation that can reach the unsafe code is\n    crate-controlled or comes from a trusted opted-in dependency, and\n    downstream\u002Fcaller code cannot add a new implementation that violates the\n    law;\n4.  the trait is sealed, and sealing is airtight: downstream crates cannot name,\n    implement, forge, or indirectly satisfy the sealing condition, including\n    through blanket impls, public fields, public constructors, macros, or\n    re-exported marker types;\n5.  the type system enforces the property independently of caller honesty.\n\nAn unsafe API may explicitly place a caller obligation on the behavior of an\notherwise safe implementation. In that case, do not assume the safe trait law\nfor arbitrary caller-provided implementations; instead, quote the unsafe API's\nprecondition and prove that every concrete implementation reachable in this\ncall satisfies it through crate control, a trusted dependency contract, sealing,\ntype-system enforcement, or direct inspection. `Pin::new_unchecked` is a key\nexample: its caller must establish the required behavior of the concrete\npointer type's `Deref`, `DerefMut`, and `Drop` implementations. (See also\n`[conv.safety-usable]`.)\n\nA sealed-trait proof must be mechanical, not aspirational. Documentation saying\n\"do not implement this trait\" is not sealing. A public supertrait, public marker\ntype, public token constructor, public blanket impl, re-exported sealing\nmechanism, or downstream-invoked macro may reopen the implementation set. If\ndownstream safe code can choose, generate, or influence an implementation that\nviolates the law, the implementation is caller-provided for proof purposes.\n\nWhen relying on a trusted dependency's safe trait implementation, rely on a\nconcrete implementation for a concrete type or a documented closed\nimplementation set. Do not generalize from \"this dependency implements the trait\ncorrectly for its types\" to \"an arbitrary caller-provided `T: Trait` satisfies\nthe law.\"\n\nThe abstraction must remain memory-safe even if caller-provided safe code is\nsemantically wrong. Violating safe trait laws may be a logic error by the\ncaller, but it must not become UB caused by this unsafe abstraction.\n\n#### Example: sorting\n\nIt is acceptable to rely on the standard library's `Vec::sort` implementation to\nperform the documented sort operation. It is not acceptable to assume that a\ncaller-provided `Ord` implementation defines a total order for memory-safety\npurposes. If memory safety depends on the vector being sorted according to a\ntrustworthy relation, then either the relation must be trusted, made unsafe,\ncontrolled by this crate, or checked after sorting.\n\n#### Example: iterator length\n\nIt is not acceptable to rely on a caller-provided safe `Iterator::size_hint` or\n`ExactSizeIterator::len` claim for memory safety unless the relevant trait\ncontract is unsafe or the value is checked. A lying safe iterator must not let\nyour unsafe code write out of bounds, read uninitialized memory, set an\nincorrect length, or double-drop elements.\n\n#### Example: callbacks\n\nIt is not acceptable to assume a caller-provided callback will not panic,\nreenter, mutate global state, mutate aliased state through interior mutability,\nor violate documented semantic promises. If unsafe code temporarily breaks an\ninvariant, do not call caller-provided safe code until the invariant has been\nrestored or a guard ensures restoration during unwinding.\n\n### 4. Advisory sources `[evidence.advisory]`\n\nThe following sources are explanatory or advisory unless their claims are also\nentailed by the Reference, std docs, a trusted dependency contract, or an\nexplicit project invariant:\n\n-   Rust API Guidelines\n-   Rust standard-library developer guide\n-   Clippy documentation\n-   Rust Edition Guide\n-   RFCs\n-   The Rust Book\n-   The Rustonomicon (some chapters lag current Reference semantics, e.g.\n    `unwinding.html` vs `ffi.html#ffi-and-unwinding`)\n-   Unsafe Code Guidelines material (except where specifically adopted by this\n    skill, such as\n    [UCG#414 on shallow reference validity](#uninitialized-memory-behind-references-ucg414))\n-   blog posts\n-   academic papers\n-   issue discussions\n-   forum posts\n-   Miri documentation\n-   sanitizer documentation\n\nUse these sources to improve rigor and style, but do not treat them as final\nauthority for UB, layout, aliasing, validity, or provenance.\n\n### 5. Project-local lemmas and invariants `[evidence.project]`\n\nProject-local invariants may be used as proof premises only if they are\nexplicitly documented and maintained by all constructors, mutators, destructors,\ntrait impls, FFI entry points, and panic paths.\n\nAcceptable project-local premises include:\n\n-   module invariants;\n-   type invariants;\n-   representation invariants;\n-   ownership invariants;\n-   initialization invariants;\n-   aliasing invariants;\n-   pinning invariants;\n-   FFI invariants;\n-   synchronization invariants;\n-   previously documented safety contracts.\n\nProject-local invariants are not self-proving. Every unsafe proof that cites one\nmust name it precisely, and review must verify that the invariant is established\nand preserved everywhere.\n\n### 6. Local facts `[evidence.local]`\n\nLocal facts include facts visible at the program point:\n\n-   branch conditions;\n-   runtime checks;\n-   values copied into locals;\n-   ownership state;\n-   initialization state;\n-   lifetime relationships;\n-   borrow relationships;\n-   arithmetic facts;\n-   control-flow facts;\n-   no-intervening-mutation facts;\n-   no-callback\u002Fno-reentrancy facts;\n-   exact type facts enforced by the compiler.\n\nLocal facts are valid only if still true at the unsafe operation. If a fact was\nchecked earlier, the safety comment must explain why it has not been invalidated\nby mutation, reallocation, aliasing, callbacks, panics, drops, or interior\nmutability.\n\n## Mandatory fact classification `[fact.classify]`\n\nEvery proof-sensitive sentence must be classifiable as one of:\n\n-   `AXIOM`: Rust Reference or standard library documentation.\n-   `DEPENDENCY LEMMA`: documented behavior of an intentionally selected safe\n    dependency.\n-   `PRECONDITION`: documented in a relevant `# Safety` section.\n-   `INVARIANT`: documented project-local invariant.\n-   `LOCAL FACT`: visible checked condition or control-flow fact.\n-   `TYPE FACT`: guaranteed by Rust's type system or by a documented type.\n-   `POSTCONDITION`: state established by a preceding operation whose contract\n    has already been proved, or a guarantee a callee documents (in its `#\n    Safety` section or under `# Safety-usable invariant`) whose preconditions\n    this proof discharges.\n\nReject any unclassified fact.\n\nA rigorous proof does not have to mechanically label every sentence with these\nwords, but the classification must be obvious. If a reviewer asks \"where does\nthis fact come from?\", the answer must be immediate and precise.\n\n## Core distinction: documentation vs comments `[conv]`\n\n### Safety documentation `[conv.docs]`\n\nSafety documentation belongs on unsafe APIs and unsafe extension points. It\nstates the theorem that callers or implementers must satisfy.\n\nExamples:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that ...\npub unsafe fn f(...) -> ...\n```\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F Implementors must ensure that ...\npub unsafe trait T { ... }\n```\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that this function is called only when ...\nunsafe extern \"C\" fn callback(...) { ... }\n```\n\n### Safety comments `[conv.comments]`\n\nSafety comments belong next to concrete unsafe operations. They prove that the\nexact operation is valid at the exact program point.\n\nFor unsafe attributes, use a safety comment to justify the whole-program,\nlinkage, ABI, symbol, section, or target-feature obligation being asserted.\n\n#### Comment Formatting `[conv.format]`\n\n*   **Canonical spelling:** Generate `\u002F\u002F SAFETY:` immediately before an unsafe\n    operation or `unsafe impl`. This form is recognized by Clippy's\n    `undocumented_unsafe_blocks` lint.\n*   **Review significance:** Capitalization or punctuation differences (such as\n    `\u002F\u002F Safety`, `\u002F\u002F\u002F safety`, or `\u002F\u002F safety:`) do not change the semantic\n    adequacy of a safety proof. When a project enables a lint that rejects the\n    local spelling, mention the canonical form as a brief tooling note; do not\n    report it as a soundness defect or let it dominate the review.\n*   **Doc Comments**: Safety comments can be regular comments (e.g., `\u002F\u002F\n    safety`) or doc comments (e.g., `\u002F\u002F\u002F safety`).\n*   **Safety Comments on `unsafe impl`**: A doc comment or regular comment\n    placed directly on an `unsafe impl` is a completely acceptable and valid\n    safety comment.\n*   **Public API Documentation**: Use `\u002F\u002F\u002F # Safety` for the caller or\n    implementer contract on public unsafe functions and traits.\n\nExample:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Operation: `core::slice::from_raw_parts(ptr, len)`.\n\u002F\u002F Required contract: `ptr` must be non-null, properly aligned, valid for reads\n\u002F\u002F of `len * size_of::\u003CT>()` bytes, refer to one allocation, and point to `len`\n\u002F\u002F initialized `T` values. The memory must not be mutated by any alias for `'a`\n\u002F\u002F except through nested `UnsafeCell`.\n\u002F\u002F Evidence:\n\u002F\u002F - By this function's `# Safety` precondition, the caller provides a live\n\u002F\u002F   allocation containing `len` initialized `T` values starting at `ptr`.\n\u002F\u002F - The same precondition requires `ptr` to be non-null and aligned for `T`.\n\u002F\u002F - `len` was checked above so that `len * size_of::\u003CT>() \u003C= isize::MAX`, and\n\u002F\u002F   no intervening code mutates `len` or `ptr`.\n\u002F\u002F - By `# Safety` precondition, the caller guarantees that for the full returned\n\u002F\u002F   lifetime `'a`, no access path—including pre-existing raw pointers, aliases,\n\u002F\u002F   callbacks, reentrant code, foreign code, or concurrent agents—will mutate the\n\u002F\u002F   range except within nested `UnsafeCell` values.\n\u002F\u002F - Between accepting that precondition and constructing the slice, this function\n\u002F\u002F   invokes no unknown code and performs no state transition that can invalidate it.\n\u002F\u002F Therefore all obligations of `from_raw_parts` are discharged.\nlet s = unsafe { core::slice::from_raw_parts(ptr, len) };\n```\n\nExample for unsafe attributes:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F This `export_name` is globally unique in the final linked artifact, and no\n\u002F\u002F other object defines an incompatible symbol with this name.\n#[unsafe(export_name = \"my_custom_symbol\")]\n```\n\nThe comment must not merely restate \"caller guarantees this.\" It must show that\nthe caller's documented obligation, plus local facts and invariants, logically\nimplies the callee's documented safety contract.\n\n### Nested `unsafe fn` `[conv.nested-fn]`\n\nFor an `unsafe fn` declared inside another function body, the `# Safety`\nsection is optional. Whether to write one is a judgment call for the author and\nreviewers: a nested fn with a simple contract usually does without, one with a\ncomplex contract usually should have it.\n\nThe nested fn's proof obligations must still be discharged: every use of it (a\ncall or an FFI\u002Fcallback registration) is an `unsafe` operation whose\n`\u002F\u002F SAFETY:` comment must establish the nested fn's preconditions, and `unsafe`\nblocks inside its body still need their own `\u002F\u002F SAFETY:` comments. Every other\n`unsafe fn` must document its preconditions under `# Safety`.\n\n### Field invariants `[conv.field-invariant]`\n\nIf a struct has private fields whose values are constrained by invariants that\nare necessary for the correctness of unsafe code inside the struct, those\ninvariants must be documented on the fields.\n\nThe comment must start with `\u002F\u002F Safety invariant:`.\n\n```rust\nstruct Foo {\n    \u002F\u002F Safety invariant: `ptr` is non-null and points to a valid `Bar`.\n    ptr: *mut Bar,\n}\n```\n\nAdditionally, any safe code that mutates these fields must maintain the\ninvariant, and any such mutation should be documented with a comment explaining\nhow the invariant is maintained.\n\n### Safety-usable invariants on safe helpers `[conv.safety-usable]`\n\nSometimes, safe helper functions exist to establish or verify invariants. While\nthese are safe to call, unsafe code may rely on their correctness for soundness.\nIn this case, the helper function should document this contract under a `\u002F\u002F\u002F #\nSafety-usable invariant` heading.\n\n```rust\nimpl Foo {\n    \u002F\u002F\u002F # Safety-usable invariant\n    \u002F\u002F\u002F\n    \u002F\u002F\u002F This function guarantees that the returned index is valid for `self.buffer`.\n    fn find_index(&self) -> usize { ... }\n}\n```\n\nThe unsafe code that relies on this helper must then document this in its `\u002F\u002F\nSAFETY:` comment:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F ...\n\u002F\u002F - Relies on the safety-usable invariant of `find_index` to ensure that\n\u002F\u002F   the index is in bounds.\n```\n\n\n### Anti-Gullibility Verification (Claim-vs-Code Decomposition) `[conv.anti-gullibility]`\n\nTreat every `\u002F\u002F SAFETY:` comment or `# Safety` doc section as an unverified\nhypothesis that must be proven by executable code or caller contracts. Before\naccepting any existing or newly added `\u002F\u002F SAFETY:` or `# Safety` comment,\ndecompose it into:\n\n1.  **Required Preconditions**: The exact obligations required by the callee's\n    `# Safety` contract or Rust Reference rules (for raw pointer dereference,\n    `Send`\u002F`Sync`, pointer provenance, lifetime transmutation, uninitialized\n    memory, or allocator layout).\n2.  **Author's Stated Justification**: What the comment claims holds at this\n    program point.\n3.  **Syntactic\u002FLocal Proof Check**: What the surrounding types, trait bounds,\n    dominating runtime checks (`assert!`, `if len \u003C ...`, `.get()`,\n    `.checked_mul()`), synchronization primitives, and lifetimes actually\n    guarantee in code.\n\nFollow a two-pass verification order: first derive the required preconditions\nand check whether the surrounding code enforces them (ignoring the comment\nprose); only then check whether the `\u002F\u002F SAFETY:` comment accurately states that\nproof. An explanatory comment without an enforcement mechanism in types, bounds,\ncaller `# Safety` contracts, or control flow is an **unproven safety claim**,\nnot a valid discharge of the obligation. In particular, if an `unsafe` block\nsits inside a **safe `fn`** and its `\u002F\u002F SAFETY:` comment asserts a property of a\ncaller-supplied argument that is not checked in code, the function is unsound.\n\n### Closed Proof Kernel Grouping (Deduplication) `[conv.dedup]`\n\nWhen multiple `unsafe` operations within the same function or module fail due to\nthe exact same missing precondition or broken invariant (a single shared proof\nkernel), group them into a single finding anchored at the root site rather than\nemitting duplicate findings for each downstream operation.\n\n## Criteria for `# Safety` documentation `[doc]`\n\nA `# Safety` section must satisfy all criteria in this section.\n\n### 1. Name the responsible party `[doc.party]`\n\nState whether the obligations are on the caller, implementer, linker, host\nenvironment, foreign code, whole program, or some combination.\n\nUse this for unsafe functions:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure ...\n```\n\nUse this for unsafe traits:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F Implementors must ensure ...\n```\n\nDo not use vague subjects such as \"it must be ensured.\" Say who must ensure it.\n\n### 2. Be complete enough to imply soundness `[doc.complete]`\n\nThe contract must include every precondition needed to prevent UB through this\nAPI. A proof reviewer should be able to derive the safety of every internal\nunsafe operation from:\n\n-   the `# Safety` section;\n-   local code facts;\n-   documented dependency lemmas;\n-   documented project-local invariants;\n-   documented callee guarantees (`# Safety` postconditions, `# Safety-usable\n    invariant`s);\n-   Reference and std axioms.\n\nDo not write:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F The pointer must be valid.\n```\n\nWrite the exact validity required:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that `ptr` is non-null, properly aligned for `T`,\n\u002F\u002F\u002F points to `len` consecutive initialized `T` values, is valid for reads of\n\u002F\u002F\u002F `len * size_of::\u003CT>()` bytes, and that the entire range lies within a\n\u002F\u002F\u002F single live allocation.\n```\n\nPointer validity is operation-specific. A pointer is not simply \"valid\" in the\nabstract. It may be valid for one kind of access, one byte range, one lifetime,\nor one aliasing mode, but invalid for another.\n\n### 3. Specify temporal scope `[doc.temporal]`\n\nEvery obligation must say when it must hold.\n\nExamples:\n\n```rust\n\u002F\u002F\u002F The memory must remain valid for reads for the entire lifetime `'a` of the\n\u002F\u002F\u002F returned slice.\n```\n\n```rust\n\u002F\u002F\u002F For the duration in which the returned `&mut T` is relied upon, the pointee\n\u002F\u002F\u002F must not be accessed through any pointer or reference whose access is not\n\u002F\u002F\u002F permitted by the applicable mutable-reference rules. `UnsafeCell` does not\n\u002F\u002F\u002F relax the uniqueness guarantee of `&mut`; it only permits mutation of its\n\u002F\u002F\u002F contents through shared references.\n```\n\n```rust\n\u002F\u002F\u002F For `!Unpin` data, the pointee must remain pinned in memory (never moved,\n\u002F\u002F\u002F deallocated, or repurposed without dropping) until its destructor completes.\n\u002F\u002F\u002F Dropping a temporary `Pin\u003C&mut T>` wrapper does not release this obligation.\n```\n\n```rust\n\u002F\u002F\u002F For this unsafe async function, `ptr` must remain valid until the returned\n\u002F\u002F\u002F future is dropped or completes.\n```\n\nDo not say only \"during the call\" unless the obligation truly ends before the\nfunction returns. Returned references, futures, iterators, guards, trait\nobjects, raw handles, and pinned values often extend obligations beyond the\ninitial call.\n\n### 4. Specify byte ranges, allocation identity, alignment, and initialization `[doc.ranges]`\n\nFor pointer, slice, buffer, allocation, and FFI APIs, the contract must state\nevery relevant low-level condition:\n\n-   read validity vs write validity;\n-   exact byte count;\n-   exact element count;\n-   alignment for the accessed type;\n-   non-nullness;\n-   initialization state;\n-   Rust value validity for type `T`;\n-   allocation liveness;\n-   whether the entire range lies in one allocation;\n-   provenance or allocation origin when relevant;\n-   aliasing and exclusivity;\n-   mutation permissions;\n-   arithmetic constraints;\n-   maximum size constraints such as `isize::MAX`;\n-   no address-space wraparound;\n-   deallocation layout, allocator identity, and capacity when reconstructing\n    ownership.\n\nExample:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that:\n\u002F\u002F\u002F\n\u002F\u002F\u002F 1. `ptr` is non-null and aligned for `T` (e.g. `NonNull::dangling()` for ZSTs or zero capacity).\n\u002F\u002F\u002F 2. If `size_of::\u003CT>() != 0 && cap != 0`, `ptr` was allocated by the global allocator\n\u002F\u002F\u002F    with layout `Layout::array::\u003CT>(cap).unwrap()`, and `cap` is the allocation capacity.\n\u002F\u002F\u002F 3. The first `len` elements are initialized valid `T` values.\n\u002F\u002F\u002F 4. `len \u003C= cap`.\n\u002F\u002F\u002F 5. `cap * size_of::\u003CT>() \u003C= isize::MAX as usize`.\n\u002F\u002F\u002F 6. No other owner will read, write, drop, or deallocate the allocation after\n\u002F\u002F\u002F    this function takes ownership.\n```\n\n### 5. Distinguish validity, initialization, and aliasing `[doc.validity-init-aliasing]`\n\nThese are separate proof obligations.\n\nA pointer can be:\n\n-   non-null but dangling;\n-   live but misaligned;\n-   aligned but not initialized;\n-   initialized but invalid for type `T`;\n-   valid for reads but not writes;\n-   valid for writes but not reads of initialized `T`;\n-   valid for one byte range but not another;\n-   valid at one time but invalid after reallocation or deallocation;\n-   valid for raw access but not valid for creating a reference;\n-   non-aliasing at one point but aliased after a callback or reentrant call.\n\nNever collapse these into \"valid pointer.\" State each property explicitly when\nrelevant.\n\n### 6. Do not rely on folklore facts `[doc.folklore]`\n\nReject any proof sentence whose source is \"everyone knows Rust works this way.\"\n\nExamples of facts that must be grounded in Reference or std docs:\n\n| Claimed fact                         | Required source               |\n| ------------------------------------ | ----------------------------- |\n| `bool` has only two valid values     | Rust Reference validity rules |\n| a reference must be non-null,        | Rust Reference validity rules |\n: aligned, and non-dangling            :                               :\n| zero-length slices still need        | `slice::from_raw_parts` \u002F     |\n: non-null aligned pointers            : `from_raw_parts_mut` docs     :\n| `ptr::read` creates a bitwise copy   | `ptr::read` docs              |\n: and can cause double-use issues for  :                               :\n: non-`Copy` values                    :                               :\n| `ptr::write` does not drop the old   | `ptr::write` docs             |\n: value                                :                               :\n| unaligned packed-field raw pointer   | `ptr::read_unaligned` docs    |\n: creation must avoid an intermediate  :                               :\n: reference                            :                               :\n| `transmute` requires both source and | `mem::transmute` docs         |\n: result to be valid at their types    :                               :\n| `Vec::from_raw_parts` requires matching | `Vec` docs                    |\n: allocator layout\u002Fcapacity when `cap > 0`:                               :\n: and `size_of::\u003CT>() > 0`; otherwise     :                               :\n: non-null aligned pointer & `len \u003C= cap` :                               :\n| raw pointer arithmetic has           | primitive pointer docs        |\n: same-allocation and `isize`          :                               :\n: constraints                          :                               :\n\nThe safety proof should cite or paraphrase exact contracts rather than importing\ninformal knowledge.\n\n### 7. Do not impose hidden safety obligations on safe callers `[doc.hidden-obligations]`\n\nA safe function must not require the caller to uphold unchecked memory-safety\npreconditions. If such preconditions are required, the function should be\n`unsafe` or the function should validate the preconditions dynamically.\n\nPublic safe API surfaces include more than `pub fn`. Public fields,\nconstructors, safe methods, safe trait methods, and macro-generated APIs all\ncount as safe API surfaces. Treat all of the following as surfaces that safe\ncaller code may use adversarially:\n\n-   public fields;\n-   public constructors and builder methods;\n-   public safe methods and inherent impls;\n-   safe trait methods and safe trait impl surfaces;\n-   public macros and proc macros;\n-   macro-generated APIs;\n-   re-exported APIs;\n-   safe callbacks, closures, comparators, allocators, and trait methods\n    accepted by public APIs;\n-   public types whose auto traits, blanket impls, `Deref`, `Drop`, or interior\n    mutability can affect unsafe invariants.\n\nA public field is a safe mutator. A public constructor is a safe\ninvariant-establishing boundary. A macro-generated safe function is still a safe\nfunction. If any such surface lets safe caller code create a value or state that\nlater makes internal unsafe code unsound, the abstraction is unsound unless the\ncondition is dynamically checked, made impossible by the type system, or moved\nbehind an unsafe contract.\n\nBad:\n\n```rust\n\u002F\u002F\u002F Caller must pass a pointer valid for reads of `len` elements.\npub fn from_ptr\u003CT>(ptr: *const T, len: usize) -> &'static [T] {\n    unsafe { core::slice::from_raw_parts(ptr, len) }\n}\n```\n\nThe caller can call this safe function with an invalid pointer. That would let\nsafe code trigger UB. The function is unsound.\n\nUse a different heading for internal invariants of safe types:\n\n```rust\n\u002F\u002F\u002F # Invariants\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ptr` is either null or points to an allocation created by `Box\u003CT>`.\n```\n\nDo not write a `# Safety` section for a safe API to shift unchecked\nmemory-safety obligations onto a safe caller.\n\nThis rule applies to private helper functions as well. Do not rely on module\nprivacy to hide memory-safety preconditions on a safe function. If a private\nhelper function must only be called under certain conditions to prevent UB, mark\nit `unsafe` and document those conditions under `# Safety` (optional for a\nnested `unsafe fn`, `[conv.nested-fn]`). Do not make it safe\nand rely on \"internal module invariants\" without an explicit safety contract, as\nfuture changes to the module might violate those invariants.\n\n**Exception for FFI-exported functions (`extern \"C\"`):** The rule against safe\nfunctions imposing unchecked preconditions applies to **safe Rust callers**.\nEvery call from C or C++ is already outside Rust's type-system guarantees on the\nforeign side. A `pub extern \"C\" fn` (or Crubit\u002FUniFFI export) that accepts\nreferences or `Option\u003C&T>` \u002F `Option\u003C&mut T>` (e.g., so `cbindgen` emits `T*`\nwhile Rust gets automatic null checking via niche optimization) does **not**\nneed to be marked `unsafe extern \"C\" fn` if safe Rust callers cannot cause UB\nthrough its signature:\n\n-   If a `pub extern \"C\" fn` takes `Option\u003C&T>` or `Option\u003C&mut T>`, safe Rust\n    callers are already forced by the compiler to pass valid, aligned,\n    non-aliasing references. Satisfying alignment, dereferenceability, and\n    non-aliasing on the C\u002FC++ side is the foreign caller's responsibility. Do\n    not flag such a function for lacking `unsafe` or demand raw pointers `*mut\n    T` instead of `Option\u003C&mut T>`.\n-   By contrast, if a `pub extern \"C\" fn` accepts raw pointers (`*const T` or\n    `*mut T`) and dereferences them internally without validating them, it\n    **must** be marked `unsafe extern \"C\" fn` (with `# Safety` documentation),\n    because otherwise *safe Rust* code could call it with a dangling or invalid\n    pointer and trigger UB.\n-   For C\u002FC++ out-parameters passed as `&mut T` or `Option\u003C&mut T>` (which C\u002FC++\n    callers commonly pass pointing to uninitialized stack memory), apply the\n    [Uninitialized memory behind references (`UCG#414`)](#uninitialized-memory-behind-references-ucg414)\n    rules below.\n\n### 8. Do not strengthen contracts you do not own `[doc.no-strengthen]`\n\nFor unsafe functions inside traits, the implementation cannot arbitrarily\nrequire stricter preconditions than the trait method's contract allows. A caller\nwho satisfies the trait-defined contract must be able to call the implementation\nsoundly.\n\nBad pattern:\n\n```rust\nunsafe trait Trait {\n    \u002F\u002F\u002F # Safety\n    \u002F\u002F\u002F Caller must pass any non-null pointer.\n    unsafe fn f(ptr: *const u8);\n}\n\nstruct Impl;\n\nunsafe impl Trait for Impl {\n    \u002F\u002F\u002F # Safety\n    \u002F\u002F\u002F Caller must pass a pointer to at least 16 initialized bytes.\n    unsafe fn f(ptr: *const u8) {\n        \u002F\u002F implementation relies on stronger condition\n    }\n}\n```\n\nThe implementation has silently strengthened the trait contract. Unsafe code\nusing the trait may call according to the trait contract, not the\nimplementation's private contract. This is unsound unless the trait contract\npermits the strengthening.\n\n### 9. Separate semantic preconditions from memory-safety preconditions `[doc.semantic-vs-memory]`\n\nA function may have ordinary semantic requirements, but memory-safety\nrequirements belong in `# Safety` only if violation can lead to UB.\n\nFor safe APIs, semantic preconditions must be handled safely:\n\n-   return `Result`;\n-   panic;\n-   clamp;\n-   ignore;\n-   validate;\n-   document as a logic error that cannot cause UB.\n\nFor unsafe APIs, the `# Safety` section must contain all unchecked memory-safety\npreconditions. Do not hide memory-safety preconditions in prose under `#\nPanics`, `# Errors`, examples, type names, module docs, or comments elsewhere.\n\n### 10. Include postconditions when unsafe callers may rely on them `[doc.postconditions]`\n\nA `# Safety` section should usually state not only what the caller must\nguarantee, but also what the function guarantees in return when those\npreconditions hold.\n\nExamples:\n\n```rust\n\u002F\u002F\u002F If these preconditions hold, the returned slice contains exactly the `len`\n\u002F\u002F\u002F initialized `T` values starting at `ptr`, and no safe operation on the slice\n\u002F\u002F\u002F can mutate the memory except through `UnsafeCell`.\n```\n\n```rust\n\u002F\u002F\u002F If these preconditions hold, this function takes exclusive ownership of the\n\u002F\u002F\u002F allocation and will deallocate it exactly once using the original layout.\n```\n\nPostconditions are especially important for unsafe traits and unsafe\nconstructors whose results are later used by safe code or other unsafe proofs.\n\n### 11. Do not rely on the absence of an impl `[doc.absent-impl]`\n\nAn `unsafe impl`'s obligation must be discharged with facts that remain true\nunder program extension: new crates, new types, new impls. The impl set of a\nsafe trait is open and extendable by safe code, and the absence of a trait\nimplementation on a type is not such a fact.\n\nThe suspect pattern:\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F If a type implements both `UnsafeTr` and `SafeTr`, `SafeTr` must behave\n\u002F\u002F\u002F a certain way.\nunsafe trait UnsafeTr {}\n```\n\nThis conditions an unsafe obligation on the behavior of a safe trait.\nWhichever impl completes the pair `UnsafeTr + SafeTr` last decides soundness,\nand the `SafeTr` half can be completed in safe code. Classify as follows.\n\nBad:\n\n1.  The unsafe trait is dyn-compatible. Downstream safe code may write:\n\n    ```rust\n    trait Sub: UnsafeTr {}\n    impl SafeTr for dyn Sub { \u002F\u002F impl that behaves incorrectly }\n    ```\n    `dyn Sub: UnsafeTr` holds via the built-in supertrait impl; no `unsafe`\n    appears downstream. Reject the contract as designed unless the defining\n    crate owns a blanket `impl\u003CT: UnsafeTr + ?Sized> SafeTr for T` (making\n    every such downstream impl a coherence error), or the unsafe trait is\n    non-dyn-compatible *by construction* — an explicit dyn-incompatible\n    supertrait or other property that would be a semver-breaking-change\n    to remove. A bare marker trait is dyn-compatible by default.\n\n2.  A blanket `unsafe impl` over a `#[fundamental]` constructor:\n\n    ```rust\n    unsafe impl\u003CT: UnsafeTr> UnsafeTr for Box\u003CT> {}\n    ```\n\n    No party can discharge this. A downstream crate owning `Local` may\n    soundly write `unsafe impl UnsafeTr for Local` (vacuous: `Local` has no\n    `SafeTr` impl) and then, because `Box` is fundamental, legally write\n    `impl SafeTr for Box\u003CLocal>` in safe code. `Box\u003CLocal>: UnsafeTr +\n    SafeTr` now violates a contract that no single impl broke. Reject\n    fundamental blankets under a conditional cross-trait contract unless the\n    defining crate owns the matching safe-trait blanket for the same coverage\n    (`impl\u003CT: UnsafeTr> SafeTr for Box\u003CT>`).\n\nIffy (accept, with an explicit label):\n\n3.  Coherence-based negative reasoning about a concrete local type:\n\n    ```rust\n    \u002F\u002F dyn-incompatible; same safety requirements.\n    unsafe trait UnsafeTr: Sized {}\n\n    \u002F\u002F SAFETY: `ExampleStruct` has no `SafeTr` impl in this crate, and\n    \u002F\u002F the orphan rule prevents any other crate from adding one, so the\n    \u002F\u002F conditional obligation is vacuous.\n    unsafe impl UnsafeTr for ExampleStruct {}\n    ```\n\n    Sound today, but only because current coherence rules forbid the downstream\n    impl. The orphan rule exists to make enforcing coherence easier, but it is\n    not a stated soundness guarantee, and active proposals would weaken it.\n    Accept only when cases 1 and 2 are absent (non-dyn-compatible unsafe trait,\n    no fundamental blankets) and the premise is flagged as orphan-rule-reliant\n    so it can be found and re-audited if coherence rules change. Flag as fragile\n    and prefer a restructuring below.\n\nGood:\n\n-   Move the constrained behavior into the unsafe trait itself, so each\n    `unsafe impl` carries the obligation directly (such as by making `SafeTr`\n    a supertrait, or tying the constrained behaviour to an unsafe marker\n    trait which is a subtrait of both).\n-   Validate dynamically before unsafe reliance (check the returned value,\n    then use the checked value).\n-   Have the defining crate own the safe trait's impl for the entire\n    `T: UnsafeTr + ?Sized` coverage, closing the impl set by coherence.\n-   Seal the safe trait, with sealing airtight per the sealing rule.\n\n## Criteria for safety comments `[comment]`\n\nA safety comment (e.g., using `\u002F\u002F safety:`, `\u002F\u002F SAFETY:`, or doc comment\nequivalents like `\u002F\u002F\u002F safety:`) must answer all five questions in this section,\nplus any specialized rule that applies to the operation, such as reference\ncreation, FFI, global state, or target-feature-sensitive execution.\n\n### 1. What exact unsafe operation is being justified? `[comment.operation]`\n\nBad:\n\n```rust\n\u002F\u002F SAFETY: This is safe.\nunsafe { ptr.add(i).read() }\n```\n\nGood:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Justifies both:\n\u002F\u002F 1. `ptr.add(i)`\n\u002F\u002F 2. `.read()` from the resulting pointer\nunsafe { ptr.add(i).read() }\n```\n\nStricter rule: prefer one unsafe operation per unsafe block. If a block contains\nmultiple unsafe operations, the comment must itemize and prove each one\nseparately.\n\n### 2. What contract is being discharged? `[comment.contract]`\n\nThe comment must name the contract source and the relevant obligations.\n\nExample:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr::read`: `src` must be valid for reads, properly aligned,\n\u002F\u002F and point to an initialized `T`.\nlet value = unsafe { src.read() };\n```\n\nFor raw pointer arithmetic:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr.add`: the offset in bytes must fit in `isize`; if the\n\u002F\u002F offset is non-zero, the original pointer must be derived from an allocation,\n\u002F\u002F and the entire range from the original pointer to the result must remain in\n\u002F\u002F bounds of that allocation without address-space wraparound.\nlet p = unsafe { ptr.add(i) };\n```\n\nDo not merely say \"bounds checked above\" unless the callee contract is only a\nbounds obligation. Most pointer operations have allocation, alignment,\ninitialization, provenance, aliasing, and size obligations too.\n\n### 3. Which premises prove the contract? `[comment.premises]`\n\nEvery premise must be classified as one of:\n\n-   Rust Reference or std axiom;\n-   documented dependency lemma;\n-   caller precondition from this function's `# Safety` section;\n-   implementer precondition from an unsafe trait's `# Safety` section;\n-   documented type invariant;\n-   documented module invariant;\n-   runtime check;\n-   control-flow fact;\n-   type-system fact;\n-   postcondition from a previous proved operation, or documented by a callee\n    under its `# Safety` or `# Safety-usable invariant`.\n\nBad:\n\n```rust\n\u002F\u002F SAFETY: `i` is in bounds.\nlet x = unsafe { slice.get_unchecked(i) };\n```\n\nGood:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `get_unchecked`: `i \u003C slice.len()`.\n\u002F\u002F Evidence: this branch is reached only after `if i \u003C slice.len()` succeeds.\n\u002F\u002F `slice` is immutably borrowed and no intervening code can change its length.\n\u002F\u002F Therefore `i` is a valid element index for `slice` at this call.\nlet x = unsafe { slice.get_unchecked(i) };\n```\n\n### 4. Why do the premises still hold at this program point? `[comment.still-hold]`\n\nThe proof must account for intervening code.\n\nBad:\n\n```rust\n\u002F\u002F SAFETY: We checked the length above.\nunsafe { v.set_len(len) }\n```\n\nGood:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `Vec::set_len`: `len \u003C= capacity`, and the first `len`\n\u002F\u002F elements must be initialized.\n\u002F\u002F Evidence:\n\u002F\u002F - `len \u003C= v.capacity()` was checked above.\n\u002F\u002F - Since that check, no code has mutated, reallocated, or moved `v`.\n\u002F\u002F - The loop initialized exactly indices `0..len` using `MaybeUninit::write`;\n\u002F\u002F   the loop counter is local and cannot be changed by external code.\n\u002F\u002F Therefore the new length exposes only initialized elements and does not exceed\n\u002F\u002F capacity.\nunsafe { v.set_len(len) }\n```\n\nMany comments fail because they cite a fact that was true earlier but may have\nbeen invalidated by mutation, reallocation, aliasing, callbacks, drops, panics,\nor interior mutability.\n\n### 5. What state changes after the unsafe operation? `[comment.state-change]`\n\nUnsafe comments must document postconditions when the operation changes\nownership, initialization, aliasing, lifetime, pinning, or drop obligations.\n\nExample for `ptr::read`:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr::read`: `src` is valid for reads, properly aligned, and\n\u002F\u002F points to an initialized `T`.\n\u002F\u002F Evidence: ...\n\u002F\u002F Postcondition: the value at `src` has been bitwise-copied out. Because `T`\n\u002F\u002F may be non-`Copy`, this code must not later treat the original location as an\n\u002F\u002F initialized owned `T` unless it is overwritten without first being dropped.\nlet value = unsafe { src.read() };\n```\n\nPostconditions are mandatory for operations such as:\n\n-   `ptr::read`\n-   `ptr::write`\n-   `ptr::copy` \u002F `copy_nonoverlapping`\n-   `MaybeUninit::assume_init`\n-   `Vec::set_len`\n-   `Vec::from_raw_parts`\n-   `Box::from_raw`\n-   `slice::from_raw_parts`\n-   `mem::transmute`\n-   `ManuallyDrop` operations\n-   raw allocation or deallocation\n-   FFI calls that transfer ownership\n-   pin projection\n-   partially initialized arrays or buffers\n\n## Authoring guidance `[auth]`\n\nThis section says how to write safety text well. Reviewers do not flag\ndepartures from it; they flag a missing or false proposition.\n\n### Procedure for writing a safety comment `[auth.procedure]`\n\nWhen adding a `\u002F\u002F SAFETY:` comment, follow this step-by-step procedure:\n\n1.  **Identify the unsafe operations**: Locate all `unsafe` blocks, `unsafe fn`\n    calls, `unsafe impl`s, or unsafe attributes.\n2.  **Determine the safety contracts**: Look up the exact safety contracts for\n    each operation in the Rust Reference or standard library documentation. Do\n    not guess.\n3.  **Audit the surrounding code**: Trace the inputs, lifetime bounds, and state\n    transitions of the surrounding code to ensure they satisfy the safety\n    contracts.\n4.  **Write the proof**: Write the `\u002F\u002F SAFETY:` comment, explaining step-by-step\n    how the contracts are met using the classified premises (Axioms,\n    Preconditions, Invariants, Local Facts).\n5.  **Verify**: Re-read the code and the proof to ensure there are no logical\n    gaps.\n\n### State only the property `[auth.property-only]`\n\nA `Safety invariant:` comment or a `# Safety` section states propositions.\nKeep the following out of it:\n\n-   **Origin.** Do not specify which constructor or operation first\n    established the property.\n-   **Maintainers.** Do not list the sites that currently uphold the invariant.\n    Each operation that might break the invariant (e.g., a write) must show\n    how it maintains the invariant.\n-   **Dependents.** Do not list the sites that rely on the invariant. Each\n    user of the invariant cites it in its `\u002F\u002F SAFETY:` comment.\n-   **Rationale.** Do not justify a clause inside it. Rationale belongs in\n    implementation comments separate from the proposition.\n\nBad (specifies the origin, lists maintainers and dependents):\n\n```rust\nstruct Node {\n    \u002F\u002F Safety invariant: `buf` is null or was allocated by `self.alloc()`, the\n    \u002F\u002F allocator `Node::new_in()` installed. `push_text()` allocates through\n    \u002F\u002F `self.alloc()`; `set_literal()` allocates through the parser's allocator,\n    \u002F\u002F which is the same one; `set_info()` copies a buffer that came from any\n    \u002F\u002F other allocator. `Drop` and `set_literal()` free the previous `buf`\n    \u002F\u002F through `self.dealloc()`.\n    buf: *mut u8,\n}\n```\n\nGood:\n\n```rust\nstruct Node {\n    \u002F\u002F Safety invariant: `buf` is null or was allocated by `self.alloc()` with\n    \u002F\u002F `Layout::array::\u003Cu8>(self.cap)`.\n    buf: *mut u8,\n}\n```\n\nNote that \"allocated by `self.alloc()` with this layout\" in this case is a part\nof the property, not a mere cross-reference to an origin.\n\nThis rule also applies to a `# Safety` section. Bad (origin, rationale):\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ptr` must be null or allocated by `new_in()` through `self.alloc()`,\n\u002F\u002F\u002F because `Drop` frees it through `self.dealloc()`. Pointers from\n\u002F\u002F\u002F `self.take_buf()` qualify.\npub unsafe fn set_buf(&mut self, ptr: *mut u8, cap: usize)\n```\n\nGood:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ptr` must be null or allocated by `self.alloc` with\n\u002F\u002F\u002F `Layout::array::\u003Cu8>(cap)`. `self` takes ownership of the allocation.\npub unsafe fn set_buf(&mut self, ptr: *mut u8, cap: usize)\n```\n\nNote that \"`self` takes ownership of the allocation\" is a postcondition the\ncaller must know (`[doc.postconditions]`), not a statement about dependents.\n\n### Cite a contract; do not copy it `[auth.cite-contract]`\n\nWhen a function's `# Safety` requires an argument to satisfy another contract (a\ntype invariant, a function's postcondition, a callback's contract), link that\ncontract:\n\n```rust\n\u002F\u002F\u002F - `callback`: `None`, or a function meeting the [`CallbackTy`] `# Safety`\n\u002F\u002F\u002F   contract.\n```\n\nDo not paste the contract's text: copies drift, and an intra-doc link lets\nrustdoc catch a rename.\n\nThis rule only applies to a `# Safety` section that delegates part of its\ncontract to another documented contract. It does not apply to `\u002F\u002F SAFETY:`\nproofs: a proof still enumerates the callee's obligations and discharges them\none by one (`[comment.contract]`).\n\n## Required proof topics checklist `[topics]`\n\nFor every unsafe site, check whether each topic is relevant. If relevant, the\nproof must address it explicitly.\n\n| Topic               | What the proof must establish                          |\n| ------------------- | ------------------------------------------------------ |\n| UB scope            | Safe code cannot trigger UB through this abstraction   |\n:                     : without crossing an unsafe contract.                   :\n| Operation identity  | The exact unsafe operation or unsafe contract being    |\n:                     : discharged is named.                                   :\n| Pointer validity    | Operation-specific validity: read\u002Fwrite, byte range,   |\n:                     : liveness, provenance\u002Fallocation, alignment.            :\n| Nullness            | Whether null is permitted; references and slices often |\n:                     : require non-null even for zero-size or zero-length     :\n:                     : cases when docs say so.                                :\n| Alignment           | Alignment for the accessed type, not merely            |\n:                     : byte-addressability.                                   :\n| Initialization      | Memory contains initialized values where the operation |\n:                     : reads, drops, or exposes initialized values (for       :\n:                     : uninitialized memory behind references, see            :\n:                     : [UCG#414](#uninitialized-memory-behind-references-ucg414)). :\n| Type validity       | Values satisfy Rust validity invariants, such as valid |\n:                     : discriminants, valid references, valid `bool`, valid   :\n:                     : `char`, valid `NonZero*`, and valid enum tags.         :\n| Aliasing            | Shared\u002Fmutable reference rules, exclusivity,           |\n:                     : `UnsafeCell`, raw pointer interleavings, and no        :\n:                     : invalid reference creation.                            :\n| Reference creation  | Every produced reference or reference-like owner is    |\n:                     : valid at creation; narrow creation is preferred but    :\n:                     : not sufficient.                                        :\n| Mutability          | No mutation through immutable\u002Fshared references except |\n:                     : through `UnsafeCell`; no mutation of immutable bytes.  :\n| Allocation identity | Whole range lies in one allocation when required;      |\n:                     : allocator, layout, capacity, and alignment match when  :\n:                     : reconstructing ownership.                              :\n| Pointer arithmetic  | Same-allocation range, `isize` fit, no wraparound, no  |\n:                     : out-of-bounds projection when the API requires         :\n:                     : in-bounds.                                             :\n| Temporal scope      | Each obligation states what event ends it. Do not infer |\n:                     : that dropping a temporary reference, guard, iterator,  :\n:                     : future, or `Pin\u003CPtr>` ends obligations attached to the :\n:                     : underlying allocation, pointee, or async operation.    :\n| Ownership           | Exactly one owner is responsible for                   |\n:                     : drop\u002Fdeallocation; ownership transfers are explicit.   :\n| Drop \u002F destructor   | No double drop, use-after-move, or drop of              |\n: elision             : uninitialized storage. Safety must not depend on a     :\n:                     : destructor running: safe code may use `mem::forget`,   :\n:                     : leak a guard or proxy, or form reference cycles. A     :\n:                     : leak may be acceptable; later safe access to invalid   :\n:                     : state is not.                                          :\n| Panic \u002F unwind      | Treat every call to caller-controlled safe code as a   |\n:                     : potential panic and reentrancy point. At each such     :\n:                     : point, invariants are either fully restored or         :\n:                     : protected so unwinding can leak but cannot expose UB,  :\n:                     : double-drop, or invalid state.                         :\n| FFI\u002FABI             | Correct ABI, FFI-safe representations, valid foreign   |\n:                     : contracts, unwind behavior, ownership transfer,        :\n:                     : retention behavior, callbacks, global state, and       :\n:                     : target-platform assumptions. A Rust panic reaching a   :\n:                     : non-`-unwind` ABI boundary (e.g. `extern \"C\"`) safely  :\n:                     : aborts after running local Rust destructors rather     :\n:                     : than unwinding across FFI; cross-boundary unwinding is :\n:                     : UB only when a panic exits an `-unwind` ABI (e.g.      :\n:                     : `extern \"C-unwind\"`) into a foreign frame that cannot  :\n:                     : handle it, or when a foreign exception enters Rust     :\n:                     : across a non-`-unwind` ABI or into `catch_unwind`.     :\n| Global state        | Global or process-wide state is assumed                |\n:                     : concurrent\u002Freentrant unless synchronization or an      :\n:                     : explicit out-of-band guarantee proves otherwise.       :\n| Configuration       | Every supported                                        |\n: matrix              : cfg\u002Ffeature\u002Ftarget\u002FSIMD\u002Fallocator\u002Fdebug\u002Fgenerated-code :\n:                     : combination in scope is sound.                         :\n| Concurrency         | No data races; atomics, locks, or other                |\n:                     : synchronization justify shared mutation.               :\n| Memory ordering \u002F   | When atomics publish data or transfer ownership        |\n: happens-before      : between threads, identify the precise synchronization  :\n:                     : edge (e.g. Release store synchronizes-with Acquire     :\n:                     : load), the data it orders, and why the chosen          :\n:                     : orderings establish the needed happens-before          :\n:                     : relationship.                                          :\n| Mixed-size \u002F        | When atomic and non-atomic accesses, or differently    |\n: overlapping atomics : sized atomic accesses, may refer to overlapping bytes,  :\n:                     : prove the access pattern is permitted by the           :\n:                     : documented memory model. Do not infer safety merely    :\n:                     : from each individual operation being atomic.           :\n| Mutex poisoning     | Mutex and RwLock poisoning is advisory. If memory      |\n:                     : safety depends on a lock-protected invariant, prove    :\n:                     : the invariant is restored or inaccessible after a      :\n:                     : panic without assuming poisoning always occurs or is   :\n:                     : always checked.                                        :\n| Generic wrapper     | For a type that logically borrows, owns, or may drop   |\n: semantics           : data not represented by ordinary Rust fields, verify   :\n:                     : that its inferred variance, `PhantomData` markers, and :\n:                     : drop-check behavior match the real lifetime and        :\n:                     : ownership contract.                                    :\n| Reentrancy          | Caller-provided callbacks or trait methods cannot      |\n:                     : observe or exploit broken intermediate invariants.     :\n| Safe trait laws     | Unsafe code does not rely on caller-provided safe      |\n:                     : trait implementations being semantically correct.      :\n| Dependency trust    | Any reliance on safe dependency semantics is           |\n:                     : deliberate, documented when proof-relevant, and does   :\n:                     : not extend to caller-supplied code.                    :\n| Traits              | Unsafe trait implementer obligations are satisfied and |\n:                     : not silently strengthened.                             :\n| Pinning             | Identify the pointee and the event that ends its        |\n:                     : pinning guarantee—commonly destruction of the          :\n:                     : pointee. Dropping a temporary `Pin\u003C&mut T>` handle     :\n:                     : alone does not make the pointee movable. Projection    :\n:                     : and pinned-drop rules remain satisfied for the full    :\n:                     : required duration.                                     :\n| Layout\u002Frepr         | Any layout assumption is guaranteed by `repr`,         |\n:                     : Reference, or std docs, not compiler accident.         :\n| Nested layout \u002F     | A direct representation guarantee for `A` and `B` does  |\n: niches              : not automatically imply that `Outer\u003CA>` and `Outer\u003CB>` :\n:                     : have the same layout, ABI, niches, or transmutability. :\n:                     : Prove the enclosing representation from its own `repr` :\n:                     : and documented guarantees. In particular, account for  :\n:                     : niche suppression by `UnsafeCell`.                     :\n| Padding \u002F object    | When code reads, compares, hashes, serializes,          |\n: representation      : transmutes, or attempts to preserve a value's raw      :\n:                     : bytes, prove that every observed byte is permitted to  :\n:                     : be read and that no claim depends on padding being     :\n:                     : initialized or preserved unless an authoritative       :\n:                     : contract guarantees it.                                :\n| Niche\u002Fvalidity      | Non-null\u002Faligned\u002Freference validity assumptions are    |\n: optimizations       : respected even when data length is zero.               :\n| Integer arithmetic  | Size computations are checked for overflow and         |\n:                     : documented as mathematical-integer facts where APIs    :\n:                     : require that.                                          :\n| Interior mutability | `UnsafeCell`, `Cell`, `RefCell`, atomics, locks, and   |\n:                     : global state are accounted for.                        :\n\n### Copy Function-Pointer Statics `[topics.func-ptr]`\n\nCalling a `Copy` method (such as `.expect(...)` or `.unwrap()`) on a `static\nmut` holding `Option\u003Cunsafe fn(...)>` (or reading the function pointer by value)\ncopies the function pointer by value and does **not** create a long-lived shared\nreference (`static_mut_refs` UB) across the subsequent indirect call, provided\nno concurrent mutation races with the read.\n\n## Core axiom lookup discipline `[axiom]`\n\nWhen a proof relies on a Rust fact, trace it to the relevant Reference or std\ndocumentation.\n\n### Undefined behavior and validity `[axiom.ub]`\n\nUse the Rust Reference for:\n\n-   the list of behavior considered undefined;\n-   the fact that the UB list is not necessarily exhaustive;\n-   dangling or misaligned place access;\n-   breaking pointer aliasing rules;\n-   mutating immutable bytes;\n-   producing invalid values;\n-   validity requirements for primitive types;\n-   validity requirements for references and `Box`;\n-   validity requirements for arrays, tuples, structs, and enums;\n-   layout facts guaranteed by `repr` attributes.\n\nExample proof phrasing:\n\n```rust\n\u002F\u002F AXIOM: The Reference requires a `bool` value to be either `0` or `1`.\n\u002F\u002F Evidence: `b` was produced by comparing two integers, not by reading raw\n\u002F\u002F bytes as `bool`. Therefore `b` is a valid `bool`.\n```\n\n### Standard-library unsafe contracts `[axiom.std]`\n\nUse the std docs for exact contracts of standard-library unsafe APIs. Do not\napproximate.\n\nCommon APIs that require exact contract extraction:\n\n-   `core::slice::from_raw_parts`\n-   `core::slice::from_raw_parts_mut`\n-   raw pointer `read`, `write`, `copy`, `copy_nonoverlapping`\n-   raw pointer `add`, `sub`, `offset`, `offset_from`\n-   `core::ptr::read_unaligned`\n-   `core::mem::transmute`\n-   `MaybeUninit::assume_init`\n-   `Vec::set_len`\n-   `Vec::from_raw_parts`\n-   `Box::from_raw`\n-   `CString::from_raw`\n-   `Arc::from_raw`\n-   `Rc::from_raw`\n-   allocator APIs\n-   `Pin::new_unchecked`\n-   `Pin::map_unchecked` and related projection APIs\n-   `NonNull::new_unchecked`\n-   `str::from_utf8_unchecked`\n-   unchecked indexing APIs\n-   SIMD and target-feature APIs\n\nFor each such call, copy the contract into proof obligations and discharge them\none by one.\n\n## Reject patterns `[rej]`\n\nThe following patterns should fail review.\n\n### 1. \"Pointer is valid\" `[rej.pointer-valid]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: `ptr` is valid.\nunsafe { ptr.read() }\n```\n\nRequire:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr::read`: `ptr` must be properly aligned, valid for reads of\n\u002F\u002F `size_of::\u003CT>()` bytes, and point to an initialized `T`.\n\u002F\u002F Evidence:\n\u002F\u002F - ...\n```\n\nFor slices or ranges, require the full range:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F `ptr` is non-null, aligned for `T`, valid for reads of\n\u002F\u002F `len * size_of::\u003CT>()` bytes, points to `len` initialized `T`s, and the full\n\u002F\u002F range lies in one live allocation.\n```\n\n### 2. \"Caller guarantees it\" `[rej.caller-guarantees]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: The caller guarantees this.\nunsafe { callee(ptr, len) }\n```\n\nRequire:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `callee`: requires P, Q, and R.\n\u002F\u002F By this function's `# Safety` contract, the caller guarantees P and Q.\n\u002F\u002F Local check `len \u003C= cap` plus invariant I imply R.\n\u002F\u002F No intervening code can invalidate P, Q, or R.\n\u002F\u002F Therefore all obligations of `callee` are satisfied.\nunsafe { callee(ptr, len) }\n```\n\n### 3. \"Miri passes\" `[rej.miri-passes]`\n\nReject as proof:\n\n```rust\n\u002F\u002F SAFETY: Miri passes.\nunsafe { ... }\n```\n\nMiri, fuzzing, sanitizers, tests, model checking, and examples are bug-finding\nor confidence-building tools. They are not axioms and do not replace a proof.\n\nAcceptable use:\n\n```rust\n\u002F\u002F Not a proof premise: Miri tests cover this path. The proof is above.\n```\n\nA test provides evidence only if it would actually fail if UB is present. For\nexample, a test that builds a reference from a dangling pointer but never loads\nthrough it does execute UB, but would likely pass under ASan nevertheless.\n\n### 4. \"Zero length means null is fine\" `[rej.zero-len-null]`\n\nReject for slice references:\n\n```rust\n\u002F\u002F SAFETY: `len == 0`, so null is okay.\nlet s = unsafe { core::slice::from_raw_parts(core::ptr::null(), 0) };\n```\n\nThe standard-library slice constructors require non-null aligned pointers even\nfor zero-length slices and ZSTs. Use a proper dangling-but-non-null aligned\npointer where the API permits it.\n\n### 5. Packed field address through intermediate reference `[rej.packed-ref]`\n\nReject:\n\n```rust\nlet p = &packed.field as *const Field;\nlet value = unsafe { p.read_unaligned() };\n```\n\nCreating the intermediate reference to a packed field may itself violate\nalignment requirements. Use raw address-of syntax when forming a raw pointer for\nunaligned access:\n\n```rust\nlet p = &raw const packed.field;\nlet value = unsafe { p.read_unaligned() };\n```\n\n### 6. \"Transmute because same size\" `[rej.transmute-size]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: Same size.\nlet b: B = unsafe { core::mem::transmute::\u003CA, B>(a) };\n```\n\nRequire proof that:\n\n-   source and destination have the same size;\n-   the source value is valid at type `A`;\n-   the resulting bits are valid at type `B`;\n-   alignment and layout assumptions are documented;\n-   pointer\u002Finteger provenance assumptions are valid;\n-   ownership and drop obligations are not duplicated or lost;\n-   there is no safer conversion.\n\n`transmute` is a last-resort operation. Same size is necessary but not\nsufficient.\n\n#### Non-Compositionality of Niches and Outer Layouts\n\nNever assume that layout equivalence of inner types composes to outer types: -\nAlthough `UnsafeCell\u003CT>` and `MaybeUninit\u003CT>` have identical size and alignment\nto `T`, wrapping `T` inside them inhibits or changes niche optimizations for\nenclosing types. - For example, `Option\u003Ccore::ptr::NonNull\u003Cu8>>` is 8 bytes due\nto null-pointer niche optimization, whereas\n`Option\u003Ccore::cell::UnsafeCell\u003Ccore::ptr::NonNull\u003Cu8>>>` or\n`Option\u003Ccore::mem::MaybeUninit\u003Ccore::ptr::NonNull\u003Cu8>>>` may be 16 bytes. -\nTransmuting between `Outer\u003CT>` and `Outer\u003CUnsafeCell\u003CT>>` or\n`Outer\u003CMaybeUninit\u003CT>>` is unsound unless the layout of the entire outer type is\nexplicitly proved.\n\n#### Padding and Raw Byte Access\n\nWhen code reads, compares, hashes, serializes, or transmutes raw struct bytes: -\nPadding bytes are uninitialized by default and not preserved across typed\nmoves\u002Fcopies. - Reading or hashing `size_of::\u003CT>()` raw bytes behind `&T` is\ninvalid whenever `T` contains uninitialized padding. - Fieldwise operations\nshould be preferred over whole-object raw byte operations.\n\n### 7. \"Vec owns this pointer\" `[rej.vec-owns]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: This came from a Vec.\nlet v = unsafe { Vec::from_raw_parts(ptr, len, cap) };\n```\n\nRequire proof of:\n\n-   **When `size_of::\u003CT>() != 0 && cap != 0`**:\n    -   original allocator identity;\n    -   exact allocation layout (`Layout::array::\u003CT>(cap)`);\n    -   alignment equality, not merely compatibility;\n    -   capacity from the original allocation;\n    -   allocation size constraints (`cap * size_of::\u003CT>() \u003C= isize::MAX as\n        usize`);\n-   **When `size_of::\u003CT>() == 0 || cap == 0`**:\n    -   `ptr` is non-null and suitably aligned for `T` (e.g.\n        `NonNull::dangling()`);\n    -   no heap allocation required;\n-   **In all cases**:\n    -   `len \u003C= cap`;\n    -   first `len` elements initialized;\n    -   ownership transfer;\n    -   no other owner will use or deallocate the allocation;\n    -   no double-drop or use-after-free path.\n\n#### Sequencing Ownership Transfer\n\nPrefer a consuming standard-library or project API such as `into_raw` or\n`into_raw_parts` that ends the old ownership state while yielding the raw\ncomponents.\n\nWhen manual extraction is unavoidable, disable the old owner's automatic `Drop`\n(e.g. using `std::mem::ManuallyDrop`) before constructing any replacement owner.\nAfter the replacement owner exists, do not read, move, pass, forget, or\notherwise use the invalidated old value. Audit every possible panic and\nearly-return point: failure may leak, but must not create two destructors for\nthe same resource or permit access through an invalid owner.\n\n### 8. Safe trait law relied on for memory safety `[rej.trait-law]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: `iter.len()` tells us exactly how many elements will be yielded.\nunsafe {\n    write_items_without_capacity_checks(iter, dst, iter.len());\n}\n```\n\nA caller-provided safe trait implementation may lie unless the property is\nenforced by an unsafe trait contract, trusted dependency implementation, dynamic\nvalidation, or the type system.\n\nRequire:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F This proof does not rely on caller-provided `ExactSizeIterator::len` for\n\u002F\u002F memory safety. Capacity is checked before every write, and `set_len` is called\n\u002F\u002F only for the number of elements actually initialized.\n```\n\n### 9. Callback cannot panic or reenter `[rej.no-panic]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: The callback just fills the buffer.\ncallback(&mut tmp);\nunsafe { tmp.set_len(n) }\n```\n\nA caller-provided safe callback may panic, reenter, or mutate reachable state\nthrough safe mechanisms. If invariants are temporarily broken, use guards or\navoid callbacks until invariants are restored.\n\n### 10. Dependency trust confused with caller trust `[rej.dep-vs-caller]`\n\nReject:\n\n```rust\nv.sort_by(caller_comparator);\n\u002F\u002F SAFETY: `Vec::sort_by` sorts the vector, so binary search invariants hold.\nunsafe { rely_on_sortedness_for_memory_safety(&v) }\n```\n\n`Vec::sort_by` may be trusted as a std dependency, but the caller-provided\ncomparator is not trusted for memory-safety-relevant semantic correctness. If\nsortedness is memory-safety-critical, validate it or require an unsafe contract.\n\n### 11. Proof by reading another function's body `[rej.other-body]`\n\nReject proofs that refer to the implementation (body) of another function\n(including a caller, a callee, or a callback being passed around).\n\nException: closures and `fn` items nested inside the function under review are\nlocal code, and the proof may rely on their bodies (`[conv.nested-fn]`).\nStating the fact on the nested item is still preferred.\n\nRequire facts about other functions to be established in their documentation\ncomments. Unsafe functions state their postconditions in the `# Safety` section.\nSafe functions use the `# Safety-usable invariant` section. Proofs cite these\nfacts.\n\nGiven:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `callback` must be `None` or a function that, when called with a `ctx` that\n\u002F\u002F\u002F points to a live `Ctx` and that nothing else accesses for the duration of\n\u002F\u002F\u002F the call, returns null or an unlinked node allocated through `ctx`'s\n\u002F\u002F\u002F allocator. The parser takes ownership of the returned node.\npub unsafe fn register_callback(\n    reg: &mut Registry,\n    callback: Option\u003Cunsafe extern \"C\" fn(*mut Ctx) -> *mut Node>,\n);\n```\n\nReject:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ctx` must point to a live `Ctx` that nothing else accesses for the\n\u002F\u002F\u002F duration of the call.\npub unsafe extern \"C\" fn my_callback(ctx: *mut Ctx) -> *mut Node { ... }\n\n\u002F\u002F SAFETY: The implementation of `my_callback` meets `register_callback`'s\n\u002F\u002F contract: it returns null or an unlinked node allocated through `ctx`'s\n\u002F\u002F allocator.\nunsafe { register_callback(reg, Some(my_callback)) };\n```\n\nAccept:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ctx` must point to a live `Ctx` that nothing else accesses for the\n\u002F\u002F\u002F duration of the call.\n\u002F\u002F\u002F\n\u002F\u002F\u002F If these preconditions hold, returns null or an unlinked node allocated\n\u002F\u002F\u002F through `ctx`'s allocator.\npub unsafe extern \"C\" fn my_callback(ctx: *mut Ctx) -> *mut Node { ... }\n\n\u002F\u002F SAFETY: `my_callback`'s `# Safety` preconditions are those\n\u002F\u002F `register_callback`'s contract guarantees its caller provides, and its\n\u002F\u002F postcondition is what that contract requires of the return value.\nunsafe { register_callback(reg, Some(my_callback)) };\n```\n\n## Safe dependency and caller-provided code review rules `[dep]`\n\n### Rule A: Intentionally selected safe dependencies may be trusted as documented `[dep.selected]`\n\nWhen this crate intentionally uses a safe dependency API, the proof may assume\nthe API behaves as documented.\n\nExamples:\n\n```rust\nlet mut v = vec![3, 1, 2];\nv.sort();\n\u002F\u002F A proof may assume the standard library sort implementation performs its\n\u002F\u002F documented operation, subject to the behavior of the `Ord` implementation.\n```\n\n```rust\nlet n = trusted_dependency::parse_header(bytes)?;\n\u002F\u002F A proof may rely on `parse_header` returning the documented result if this\n\u002F\u002F crate has intentionally chosen and audited\u002Ftrusted that dependency contract.\n```\n\nHowever, this is a project trust assumption. It should be explicit when\nproof-relevant and should be version-aware for third-party dependencies.\n\n### Rule B: Caller-provided safe code is adversarial `[dep.caller-adversarial]`\n\nDo not rely on caller-provided safe code for memory-safety-relevant semantics.\n\nExamples of invalid assumptions:\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Ord` is a total order.\nT: Ord\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Iterator::size_hint` is accurate.\niter.size_hint()\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Hash` is consistent with `Eq`.\nT: Hash + Eq\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Clone` returns an equivalent value.\nx.clone()\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided callback will not panic.\nf()\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Drop` has no side effects.\ndrop(x)\n```\n\n### Rule C: Safe trait laws are not safety contracts `[dep.trait-laws]`\n\nA safe trait's documentation may impose semantic laws, but violating those laws\nmust not cause UB in your unsafe abstraction. If unsafe code must rely on a law,\nmake the trait unsafe, use an existing unsafe trait with the required contract,\nvalidate dynamically, or constrain implementations to trusted types.\n\n#### Sealed-trait reliance must be airtight `[dep.sealed]`\n\nA sealed safe trait may be treated as trusted only if the proof establishes that\nall implementations are controlled by this crate or by a trusted opted-in\ndependency. \"This trait is sealed\" is itself a proof obligation, not a\nconclusion.\n\nFor a sealed-trait argument to discharge a memory-safety obligation, prove all\nof the following:\n\n-   downstream crates cannot implement the trait directly;\n-   downstream crates cannot implement the trait indirectly through a public\n    supertrait, blanket impl, associated type escape hatch, marker type,\n    macro-generated impl hook, feature-gated impl hook, re-exported private\n    token, or type alias;\n-   downstream safe code cannot construct, name, clone, deserialize, or\n    otherwise obtain any sealing token through any safe public surface;\n-   public fields, public constructors, re-exports, macros, proc macros, or\n    generated code cannot create values that claim the sealed invariant without\n    going through reviewed constructors;\n-   every cfg and feature combination preserves sealing;\n-   every existing implementation that can reach the unsafe code is reviewed and\n    maintains the required invariant;\n-   future implementations are forced through the same unsafe-code review gate,\n    for example by being inside the crate or inside a reviewed trusted\n    dependency;\n-   future semver-compatible implementation additions, feature additions, or\n    macro expansion changes cannot silently admit dishonest downstream behavior\n    without forcing re-audit;\n-   the semantic law being relied on is documented as an invariant of the sealed\n    trait, even if the trait itself is safe;\n-   the proof does not rely on caller-controlled generic parameters inside the\n    implementation unless those parameters are constrained by an unsafe\n    contract, dynamic checks, type-system facts, or trusted dependency\n    implementations.\n\nDo not require an abstraction to remain sound after downstream unsafe code\nforges an invalid token with `transmute` or otherwise violates an unsafe\ncontract. A project may separately review robustness against hostile unsafe\nclients or corrupted FFI input, but that is not part of the ordinary safe-client\nsealing proof.\n\nIf sealing is not airtight, treat the implementation as caller-provided safe\ncode. Then the law is not a valid memory-safety premise unless it is dynamically\nchecked, moved into an unsafe trait contract, or avoided entirely.\n\nA private trait is not automatically sealed for review purposes. Check macro\nexpansion, feature gates, visibility boundaries, re-exports, blanket impls, and\ndownstream extension points before relying on private or sealed status. A safe\ntrait method with a default body is still caller-influenced if downstream code\ncan implement the trait, override methods, choose associated types\u002Fconstants, or\nprovide values that the default method uses to establish a\nmemory-safety-relevant fact.\n\n### Rule D: Dependencies invoking caller code inherit caller-code distrust `[dep.transitive]`\n\nIf a trusted dependency calls a caller-provided closure, comparator, allocator,\ntrait method, or callback, the dependency's trust does not make that\ncaller-provided code trustworthy.\n\nProofs must separate:\n\n```text\nTrusted: dependency implementation follows its documented behavior.\nUntrusted: caller-provided callback or trait implementation may behave arbitrarily within its safe type signature.\n```\n\n### Rule E: Safe code may be safe but still hostile to invariants `[dep.hostile]`\n\nSafe caller-provided code cannot be assumed to preserve your undocumented\ninvariants. It may observe or mutate through any safe capability you give it.\nTherefore:\n\n-   Do not expose uninitialized or partially initialized storage to caller code\n    as initialized `T`, `&T`, `&mut T`, `[T]`, or any other type whose validity\n    requires initialization. Typed exposure as `MaybeUninit\u003CT>` (e.g.\n    `Vec::spare_capacity_mut`) may be sound when the API keeps initialized\n    length\u002Fownership metadata accurate and does not let safe caller actions\n    cause uninitialized storage to be read, dropped, or otherwise treated as\n    `T`.\n-   Do not call callbacks while `Vec::len` is inconsistent with initialized\n    elements.\n-   Do not hold invalid references across calls to unknown code.\n-   Do not assume locks, refcells, or globals remain unchanged across unknown\n    calls.\n-   Do not assume unknown `Drop` implementations are inert.\n-   Do not assume unknown trait methods are deterministic.\n\n## Reference creation is the unsafe operation `[ref.creation]`\n\nCreating a Rust reference-like value from raw parts is itself a safety\nassertion. The operation being justified is not merely the later load, store,\nslice access, or method call. The proof must establish that the reference-like\nvalue is valid at the exact moment it is created.\n\nThis applies to creating or reconstructing:\n\n-   `&T`;\n-   `&mut T`;\n-   `&[T]`;\n-   `&mut [T]`;\n-   `&str`;\n-   `&CStr`;\n-   `Box\u003CT>`;\n-   `Pin\u003C&mut T>` or `Pin\u003CBox\u003CT>>`;\n-   trait-object references;\n-   any other value whose type carries Rust reference, ownership, aliasing,\n    lifetime, or validity guarantees.\n\nThe proof for reference creation must establish every relevant obligation at\ncreation time:\n\n-   non-nullness where the reference-like type requires it;\n-   alignment for the referenced type;\n-   all pointed-to bytes are in live allocations for the full referenced extent;\n-   initialization and Rust value validity for the referenced type (or, if\n    temporarily pointing to uninitialized memory without reading or dropping it,\n    explicit documentation per\n    [Uninitialized memory behind references (`UCG#414`)](#uninitialized-memory-behind-references-ucg414));\n-   correct metadata for slices and trait objects;\n-   no violation of shared-reference immutability rules;\n-   no violation of mutable-reference exclusivity rules;\n-   the referenced value outlives the produced lifetime;\n-   the resulting reference does not overstate the real ownership, pinning,\n    lifetime, or mutation permissions.\n\nPrefer the narrowest reference possible, created as late as possible, and held\nfor the shortest possible lifetime. Do not create a broad `&mut [T]` merely to\naccess one element. Do not create a reference if raw pointer operations can\nexpress the actual invariant more honestly.\n\nNarrowness is only an auditing discipline. A narrow reference must still be\nvalid at the point of creation. A one-element `&mut T` is unsound if another\nlive reference aliases that element. A zero-length slice reference may still\nneed a non-null aligned pointer if the constructor's documented contract\nrequires it. A short-lived reference to misaligned, dangling, or aliased memory\nis still UB.\n\nDo not accept a proof that says only \"the reference is as narrow as possible.\"\nThat proves at most that the author reduced the size of the assertion. It does\nnot prove that the assertion is true. The proof must still establish each\nvalidity, aliasing, lifetime, and metadata obligation at creation time.\n\n### Uninitialized memory behind references (`UCG#414`) `[ref.uninit]` {#uninitialized-memory-behind-references-ucg414}\n\nPer\n[Rust Unsafe Code Guidelines Issue #414](https:\u002F\u002Fgithub.com\u002Frust-lang\u002Funsafe-code-guidelines\u002Fissues\u002F414)\n(and the\n[Rust Reference on undefined behavior](https:\u002F\u002Fdoc.rust-lang.org\u002Freference\u002Fbehavior-considered-undefined.html)),\nthe validity invariant of a reference (`&T`, `&mut T`, `&[T]`, `&mut [T]`) is\nshallow: it does **not** depend on the initialized contents of the pointed-to\nmemory. Merely constructing a reference or slice reference to uninitialized\nmemory is **not** immediate UB, provided the pointer is non-null, properly\naligned, dereferenceable for the full extent of `T`, and obeys Rust's aliasing\nrules.\n\nHowever, having references temporarily point to uninitialized memory is still\nrisky. When reviewing or authoring code involving uninitialized memory, apply\nthe following distinctions strictly:\n\n1.  **Actual Soundness Violations (Undefined Behavior)**:\n    -   **Uninitialized stack\u002Fby-value `T` or reads**: Producing an\n        uninitialized value `T` by value (e.g., an uninitialized stack variable,\n        `MaybeUninit::assume_init()`, `ptr::read`, `mem::transmute`, or reading\n        through `*r` before initialization) is immediate UB for any type `T`\n        whose validity invariant requires initialized bytes (such as integers,\n        floats, `bool`, `char`, references, `Box`, enums, or structs containing\n        them).\n    -   **Overwriting uninitialized `&mut T` when `T` has drop glue**: Assigning\n        `*r = val` through `r: &mut T` evaluates the place `*r` and drops the\n        existing value in place before writing `val`. If `*r` is uninitialized\n        and `T` has drop glue (`core::mem::needs_drop::\u003CT>()`), `*r = val` drops\n        uninitialized memory, which is immediate UB. Overwriting `*r = val` on\n        uninitialized memory is sound **only** when `T` is `Copy` or trivially\n        has no drop glue; otherwise, `ptr::write` or `MaybeUninit` is required.\n    -   **Exposing uninitialized references to code that assumes\n        initialization**: Returning or passing `&T`, `&mut T`, `&[T]`, or `&mut\n        [T]` pointing to uninitialized memory across a safe public API boundary,\n        to untrusted callbacks, or to internal code that is not documented as\n        accepting uninitialized references is unsound, because ordinary Rust\n        code is entitled to read from `&T`\u002F`&[T]`\u002F`&mut T` or assign to `&mut T`\n        (running drop glue). Passing or returning an uninitialized reference to\n        an `unsafe` function or internal helper is only sound when that boundary\n        explicitly documents that the reference may be uninitialized so the Rust\n        code handling it knows not to read or drop it (e.g., using `ptr::write`\n        or only assigning when `T` has no drop glue).\n2.  **Sound Reference Creation to Uninitialized Memory (Documentation\n    Obligation)**:\n    -   If `&T`, `&mut T`, `&[T]`, or `&mut [T]` is created pointing to\n        uninitialized memory and is **not** used unsafely (i.e., it is never\n        read before initialization, never assigned via `*r = val` when `T` has\n        drop glue, and never passed to code that assumes initialization), the\n        code is **sound**.\n    -   **Review classification**: Treat undocumented creation or passing of a\n        reference or slice to uninitialized memory as **Incomplete Safety\n        Documentation** (the same severity and category as a missing or\n        incomplete safety comment, **not** a soundness bug).\n    -   **Required documentation**: Require that the code document *somehow* (in\n        a `\u002F\u002F SAFETY:` comment or function\u002Fhelper comment) that the reference\n        may point to uninitialized memory and how it is handled safely (e.g.,\n        that it is only written to via `ptr::write` or `*r = val` on a\n        `Copy`\u002Fno-drop-glue type, and never read before initialization). The\n        comment does **not** need to explicitly cite\n        [UCG#414](https:\u002F\u002Fgithub.com\u002Frust-lang\u002Funsafe-code-guidelines\u002Fissues\u002F414)\n        (though reviewers may reference UCG#414 when explaining why this pattern\n        is sound). Recommend `MaybeUninit\u003CT>` or raw pointers (`*mut T` \u002F\n        `ptr::write`) as preferred alternatives where practical, but **accept\n        the code as sound** once the uninitialized state is documented.\n3.  **FFI Out-Parameters (`&mut T` \u002F `Option\u003C&mut T>`)**:\n    -   C and C++ callers routinely pass pointers to uninitialized stack\n        variables as out-parameters (e.g., `size_t out; ffi_fn(&out);`), and\n        header generators like `cbindgen` map `Option\u003C&mut T>` to `T*` while\n        failing to unwrap `MaybeUninit\u003CT>`.\n    -   Accept `pub extern \"C\" fn` (and internal FFI helpers) that take `&mut T`\n        or `Option\u003C&mut T>` for C\u002FC++ out-parameters when `T` is `Copy` (or has\n        no drop glue) and the implementation only writes to `*out` (or\n        initializes it via `ptr::write`) without reading or dropping it first.\n        Because Rust code handling `*out` must know that the value may be\n        uninitialized so it can handle it properly (e.g., using `ptr::write` or\n        avoiding reads\u002Fdrops), this should be documented *somehow* (e.g., in the\n        function\u002Fhelper doc comment or an enclosing comment, without needing a\n        `UCG#414` citation); if completely undocumented, flag it as **Incomplete\n        Safety Documentation** (not a soundness bug).\n\n`UnsafeCell` is not a general aliasing eraser. It permits interior mutation\nthrough shared references only for a pointed-to `UnsafeCell` value itself. A\nshared reference `&T` where `T` contains `UnsafeCell` allows mutating the cell\ncontents safely (e.g. via `Cell::set`), but creating `&mut T` while a shared\n`&T` exists is still undefined behavior, even if no code reads or writes the\n`UnsafeCell`. Similarly, mutating a shared reference value directly without\ngoing through `UnsafeCell` is UB.\n\n## High-Risk Hazard Checklists `[hazard]`\n\nReviewers must explicitly audit the following high-risk Rust soundness hazards:\n\n1.  **`unsafe impl Send` \u002F `unsafe impl Sync` vs. Thread-Affinity & Unsynchronized Shared Mutation `[hazard.send-sync]`**:\n    `Send` allows moving a value to *another* OS thread; `Sync` (`&T: Send`)\n    allows concurrent access from *multiple* OS threads. A comment claiming\n    \"only used on one thread\" or \"wrapped in thread-local storage by callers\"\n    does **not** make a publicly or module-accessible wrapper type safely `Send`\n    or `Sync` unless the type's API prevents cross-thread transfer or\n    unsynchronized interior mutation (`*mut T`, `UnsafeCell`, raw FFI handles).\n2.  **Safe Public\u002FModule Functions Wrapping `unsafe` Operations `[hazard.safe-fn-wrap]`**:\n    Any safe `fn` (without the `unsafe` keyword) that converts raw pointers,\n    offsets, or indices into references\u002Fslices (`slice::from_raw_parts`,\n    `&*ptr`, `ptr.add`, `offset_from`, `get_unchecked`) or passes\n    caller-controlled pointers\u002Flengths to FFI without validating bounds,\n    alignment, non-nullness, and lifetime tying is **unsound** (it must either\n    validate all preconditions at runtime or be marked `unsafe fn` with a\n    `# Safety` section).\n3.  **Lifetime & Mutability Upgrade Scrutiny (`&self` -> `&mut T` \u002F `'a` -> `'static`) `[hazard.lifetime-mut]`**:\n    Upgrading `&self` to `&mut T` (via raw pointer casts or `UnsafeCell` without\n    a runtime borrow flag, `Mutex`, or `&mut self` witness) or extending a\n    lifetime `'a` to `'static` (e.g. for async tasks, threads, or callbacks)\n    without guaranteeing the pointee outlives all possible uses is immediate\n    aliasing or use-after-free UB.\n4.  **Cross-Allocation Pointer Arithmetic & Provenance `[hazard.provenance]`**:\n    `ptr::offset_from`, `ptr::add`, and `slice::from_raw_parts` require both\n    pointers (or the start and end of the range) to be derived from the **same\n    allocation** (`allocated object`). Computing offsets between arbitrary slice\n    references or separate heap allocations is immediate UB in Rust even if only\n    used as a diagnostic offset. Paired ownership\u002Fallocation APIs (`into_raw*`\n    and `from_raw*`, `alloc` and `dealloc`) must also preserve allocation\n    identity, layout, and drop symmetry across empty (`is_empty()`) and ZST\n    (`size_of::\u003CT>() == 0`) branches.\n5.  **Pre-Check Against Callee\u002FTrait Encapsulation Before Flagging `[hazard.encapsulation]`**:\n    Before flagging a caller of an `unsafe` helper or macro, inspect the\n    definition of the helper or trait in the same module\u002Fcrate to check whether\n    preconditions (such as alignment, `size_of::\u003CT>()` bounds, or `repr(C)`) are\n    already enforced by `const` assertions, trait bounds (e.g., `FromBytes`,\n    `IntoBytes`, `Immutable`), or constructor invariants.\n\n### Four-Item Edge-Domain Checklist `[hazard.edge-domain]`\n\nExplicitly substitute these four boundary cases into every `unsafe` expression\nbefore concluding it is sound:\n\n1.  **Zero-Sized Types & Zero Lengths (`size_of::\u003CT>() == 0`, `len == 0`)**:\n    Does `Box::into_raw` or `Vec::as_ptr` yield `NonNull::dangling()` when\n    `size_of::\u003CT>() == 0` or `cap == 0` (violating \"allocated by `A`\" invariants\n    when `len > 0` on `[(); N]` or dropping the allocator early)? Does `len == 0`\n    get passed to foreign functions that compute `len - 1` or dereference\n    `ptr[0]`?\n2.  **Allocator Alignment & Signed\u002FUnsigned Casts (`0 \u003C size \u003C align`, `c_int \u003C 0`, `usize -> u32`)**:\n    When implementing `Allocator` or `GlobalAlloc` over C\n    `malloc`\u002F`calloc`\u002F`realloc`, can `0 \u003C layout.size() \u003C layout.align()` return\n    an under-aligned pointer? Can a signed integer (`c_int`, `isize`, `i32`) be\n    negative before `as usize`, or can `usize` truncate when cast to `u32`\u002F`i32`?\n    Are all signed\u002Funsigned type tags handled without panicking across\n    non-unwind FFI boundaries?\n3.  **Pointer Stride & Final-Iteration Stepping (`i == n - 1`)**:\n    Does `.add(stride)` or `.offset(stride)` on the **final loop iteration**\n    step more than one byte past the end of the allocation (which is immediate\n    UB even if not dereferenced)?\n4.  **`core::mem::forget` & Drop-Based Lifetime Guards**:\n    Does a safe API pass a non-`'static` borrow or pointer (`'a`) to a\n    background thread, FFI callback, or hardware\u002FDMA table and rely on `Drop` to\n    stop access before `'a` ends (or implement `Deref` on a static wrapper\n    without requiring `'static`)? Because `core::mem::forget` is safe, relying\n    on `Drop` for soundness of borrowed lifetimes is unsound.\n\n","# Unsafe Rust Safety Documentation and Commenting Skill\n\n## Mission\n\nAct as an extremely strict unsafe Rust author and reviewer. Treat every `#\nSafety` section as an English-language theorem or lemma, and every safety\ncomment (e.g., `\u002F\u002F safety:` or `\u002F\u002F\u002F safety:` in any capitalization) as an\nEnglish-language proof.\n\nThe goal is not reassuring prose. The goal is logic bulletproof-ness. A reviewer\nshould be able to mechanically translate the prose into proof obligations and\ncheck each obligation against authoritative Rust axioms, documented dependency\ncontracts, project-local invariants, type-system facts, and local code facts.\n\nThe governing standard is:\n\n> Every unsafe boundary creates proof obligations, and every unsafe operation\n> must locally prove that those obligations are discharged.\n\nAn `unsafe fn` or `unsafe trait` states extra conditions that callers or\nimplementers must satisfy. An `unsafe {}` block, `unsafe impl`, or unsafe\nattribute use is the code author’s assertion that the relevant conditions have\nbeen satisfied at that exact program point.\n\nUnsafe documentation and comments must therefore be written in the style of\nformal proof:\n\n-   Define the proposition being proved.\n-   Enumerate all required assumptions.\n-   Classify each assumption by source.\n-   Show that the assumptions imply the required unsafe contract.\n-   State the postconditions and state transitions caused by the unsafe\n    operation.\n-   Reject every implicit, circular, stale, unverifiable, or folklore premise.\n\n## Conventions\n\nEvery section carries a stable `` `[area.slug]` `` ID after its heading. Cite\nsections by ID, never by number or title: numbers shift when a list grows, and\ntitles get reworded. Areas: `model`, `evidence`, `fact`, `conv`\n(conventions), `doc` (`# Safety` criteria), `comment` (comment criteria), `auth`\n(authoring guidance), `topics`, `axiom`, `rej` (reject patterns), `dep`\n(dependency rules), `ref` (reference creation), `hazard` (high-risk hazard\nchecklists).\n\n## Activation criteria\n\nUse this skill whenever authoring or reviewing Rust code that contains, exposes,\nwraps, depends on, or reasons about any unsafe surface, including:\n\n-   `unsafe fn`\n-   `unsafe trait`\n-   unsafe trait methods\n-   `unsafe impl`\n-   `unsafe extern` blocks or functions\n-   unsafe attributes such as `no_mangle`, `export_name`, `link_section`, or\n    `naked`\n-   `unsafe {}` blocks\n-   raw pointer dereferences\n-   calls to unsafe functions\n-   accesses to union fields\n-   accesses to mutable statics or extern statics\n-   inline assembly\n-   FFI boundaries\n-   `target_feature`-sensitive code\n-   manual allocation, deallocation, ownership reconstruction, or layout\n    manipulation\n-   manual initialization or drop management\n-   pin projection or pinned destruction logic\n-   unsafe abstractions over safe callback, trait, iterator, comparator, or\n    closure inputs\n-   safe API surfaces that can establish, expose, or break unsafe invariants,\n    including public fields, constructors, safe methods, safe trait methods, and\n    macro-generated APIs\n-   macro-generated or build-generated unsafe code or safe API surfaces\n-   feature-gated, cfg-gated, target-specific, allocator-specific,\n    SIMD-specific, or debug\u002Frelease-specific unsafe code paths\n\nUse the strictest reasonable interpretation of all requirements. When style or\nreview advice conflicts, choose the more demanding rule unless it conflicts with\nthe Rust Reference or standard library documentation.\n\nIn review, findings come from `[fact.classify]`, `doc.*`, `comment.*`, `rej.*`,\n`dep.*`, `ref.*`, and `hazard.*`. The remaining sections define the model and the\nconventions proofs cite, and `auth.*` says how to write well; a departure from\n`auth.*` is not a finding.\n\n## Core model `[model]`\n\n### Safety documentation is a theorem `[model.theorem]`\n\nA `# Safety` section on an unsafe API states a theorem of the following shape:\n\n```text\nIf the caller or implementer satisfies preconditions P1 ... Pn,\nthen invoking or implementing this unsafe API preserves Rust soundness.\n```\n\nThe documentation must say exactly who is responsible for the preconditions and\nhow long each precondition must hold.\n\n### Safety comments are proofs `[model.proof]`\n\nA safety comment (which may use `\u002F\u002F SAFETY:`, `\u002F\u002F safety:`, `\u002F\u002F Safety:`, or\ntheir doc comment equivalents like `\u002F\u002F\u002F safety:`) immediately adjacent to an\nunsafe operation proves a theorem of the following shape:\n\n```text\nThe unsafe operation O requires obligations Q1 ... Qn.\nAt this program point, facts F1 ... Fm hold.\nFacts F1 ... Fm imply Q1 ... Qn.\nTherefore O's unsafe contract is discharged.\nAfter O, state changes S1 ... Sk hold.\n```\n\nThe proof must be local enough that a maintainer can audit it without searching\nthrough the entire program, except for explicitly named project-local\ninvariants, dependency contracts, upstream `# Safety` preconditions, and the\nguarantees documented by the crate-controlled or trusted-dependency functions it\ncalls or installs (an unsafe fn's `# Safety` postconditions, or a safe fn's `#\nSafety-usable invariant`; never the docs of caller-provided code).\n\n### Soundness target `[model.soundness]`\n\nUnsafe code is sound only if safe Rust code using the abstraction cannot trigger\nundefined behavior without crossing an unsafe contract. The abstraction may have\nlogic bugs, panic, leak memory, or produce incorrect values, but it must not\nallow safe callers to cause UB merely by using safe APIs in type-correct but\nadversarial ways.\n\n## Authority and evidence hierarchy `[evidence]`\n\nUse this hierarchy when writing or reviewing safety documentation.\n\n### 1. Core Rust axioms `[evidence.axioms]`\n\nThe only core axioms for Rust language and standard-library semantics are:\n\n1.  The Rust Reference.\n2.  The Rust standard library documentation.\n\nAll claims about undefined behavior, validity, aliasing, layout, references,\npointer arithmetic, initialization, drop, standard-library unsafe contracts, and\nstandard-library safe API semantics must bottom out in these sources.\n\nDo not use folklore as an axiom. Do not rely on current compiler behavior, LLVM\nbehavior, Miri behavior, blog posts, examples, or \"how Rust usually works\"\nunless the fact is entailed by the Rust Reference or standard library\ndocumentation.\n\n### 2. Trusted opted-in dependency contracts `[evidence.deps]`\n\nIt is acceptable to assume that safe dependencies intentionally selected by the\ncode author work as documented.\n\nFor example, if this crate intentionally depends on a library or uses a\nstandard-library safe API, the safety proof may assume that the dependency's\nsafe APIs perform their documented safe behavior. In particular, it is\nacceptable to rely on a dependency function such as `Vec::sort` actually\nperforming the sorting operation documented by the standard library, subject to\nthat API's own documented assumptions and inputs.\n\nThis rule is a trust-boundary rule, not a Rust-language axiom:\n\n-   Treat non-std dependency behavior as a `DEPENDENCY LEMMA`, not as a core\n    Rust axiom.\n-   Prefer pinned versions and exact documentation links when relying on non-std\n    dependency semantics.\n-   Do not let dependency documentation invent Rust layout, aliasing, validity,\n    provenance, or UB rules that are not supported by the Reference or std docs.\n-   Do not use a dependency lemma to discharge an unsafe contract unless the\n    dependency API actually guarantees the needed fact.\n-   Do not silently rely on a dependency's undocumented behavior.\n-   If the dependency API is unsafe, discharge its unsafe contract exactly like\n    any other unsafe API.\n\n### 3. Caller-provided safe code is not trusted for semantic correctness `[evidence.caller-code]`\n\nThe \"safe dependencies work as documented\" assumption does not apply to\ncaller-provided safe code.\n\nCaller-provided safe code includes, without limitation:\n\n-   safe function arguments\n-   closures\n-   callbacks\n-   function pointers supplied by the caller\n-   iterator implementations supplied by the caller\n-   safe trait implementations supplied by the caller\n-   implementations of `Ord`, `Eq`, `Hash`, `Iterator`, `ExactSizeIterator`,\n    `Drop`, `Deref`, `Borrow`, `AsRef`, `Default`, `Clone`, or other safe traits\n-   values whose behavior is mediated by caller-controlled interior mutability\n-   safe methods reachable through generic type parameters\n-   safe code transitively invoked by a dependency through caller-supplied\n    callbacks or trait methods\n\nModel caller-provided safe code as adversarial but type-correct. It may:\n\n-   panic at any point where panicking is possible;\n-   fail to terminate;\n-   return arbitrary values permitted by its type signature;\n-   violate safe trait laws such as ordering, equality, hashing, length hints,\n    or clone consistency;\n-   mutate reachable state through `Cell`, `RefCell`, atomics, locks,\n    `UnsafeCell`, global state, or reentrant calls;\n-   call back into this crate;\n-   observe intermediate states that are exposed to it;\n-   drop values at inconvenient times;\n-   use safe APIs in unexpected order;\n-   exploit every behavior allowed by safe Rust and the public API surface.\n\nDo not assume caller-provided safe code \"works as documented\" for memory-safety\nproofs. Safe trait documentation may describe logic contracts, but unsafe code\nmust not rely on a safe trait law for memory safety unless one of the following\nis true:\n\n1.  the trait is unsafe and the needed law is part of its `# Safety` contract;\n2.  the property is checked dynamically before unsafe reliance;\n3.  every possible implementation that can reach the unsafe code is\n    crate-controlled or comes from a trusted opted-in dependency, and\n    downstream\u002Fcaller code cannot add a new implementation that violates the\n    law;\n4.  the trait is sealed, and sealing is airtight: downstream crates cannot name,\n    implement, forge, or indirectly satisfy the sealing condition, including\n    through blanket impls, public fields, public constructors, macros, or\n    re-exported marker types;\n5.  the type system enforces the property independently of caller honesty.\n\nAn unsafe API may explicitly place a caller obligation on the behavior of an\notherwise safe implementation. In that case, do not assume the safe trait law\nfor arbitrary caller-provided implementations; instead, quote the unsafe API's\nprecondition and prove that every concrete implementation reachable in this\ncall satisfies it through crate control, a trusted dependency contract, sealing,\ntype-system enforcement, or direct inspection. `Pin::new_unchecked` is a key\nexample: its caller must establish the required behavior of the concrete\npointer type's `Deref`, `DerefMut`, and `Drop` implementations. (See also\n`[conv.safety-usable]`.)\n\nA sealed-trait proof must be mechanical, not aspirational. Documentation saying\n\"do not implement this trait\" is not sealing. A public supertrait, public marker\ntype, public token constructor, public blanket impl, re-exported sealing\nmechanism, or downstream-invoked macro may reopen the implementation set. If\ndownstream safe code can choose, generate, or influence an implementation that\nviolates the law, the implementation is caller-provided for proof purposes.\n\nWhen relying on a trusted dependency's safe trait implementation, rely on a\nconcrete implementation for a concrete type or a documented closed\nimplementation set. Do not generalize from \"this dependency implements the trait\ncorrectly for its types\" to \"an arbitrary caller-provided `T: Trait` satisfies\nthe law.\"\n\nThe abstraction must remain memory-safe even if caller-provided safe code is\nsemantically wrong. Violating safe trait laws may be a logic error by the\ncaller, but it must not become UB caused by this unsafe abstraction.\n\n#### Example: sorting\n\nIt is acceptable to rely on the standard library's `Vec::sort` implementation to\nperform the documented sort operation. It is not acceptable to assume that a\ncaller-provided `Ord` implementation defines a total order for memory-safety\npurposes. If memory safety depends on the vector being sorted according to a\ntrustworthy relation, then either the relation must be trusted, made unsafe,\ncontrolled by this crate, or checked after sorting.\n\n#### Example: iterator length\n\nIt is not acceptable to rely on a caller-provided safe `Iterator::size_hint` or\n`ExactSizeIterator::len` claim for memory safety unless the relevant trait\ncontract is unsafe or the value is checked. A lying safe iterator must not let\nyour unsafe code write out of bounds, read uninitialized memory, set an\nincorrect length, or double-drop elements.\n\n#### Example: callbacks\n\nIt is not acceptable to assume a caller-provided callback will not panic,\nreenter, mutate global state, mutate aliased state through interior mutability,\nor violate documented semantic promises. If unsafe code temporarily breaks an\ninvariant, do not call caller-provided safe code until the invariant has been\nrestored or a guard ensures restoration during unwinding.\n\n### 4. Advisory sources `[evidence.advisory]`\n\nThe following sources are explanatory or advisory unless their claims are also\nentailed by the Reference, std docs, a trusted dependency contract, or an\nexplicit project invariant:\n\n-   Rust API Guidelines\n-   Rust standard-library developer guide\n-   Clippy documentation\n-   Rust Edition Guide\n-   RFCs\n-   The Rust Book\n-   The Rustonomicon (some chapters lag current Reference semantics, e.g.\n    `unwinding.html` vs `ffi.html#ffi-and-unwinding`)\n-   Unsafe Code Guidelines material (except where specifically adopted by this\n    skill, such as\n    [UCG#414 on shallow reference validity](#uninitialized-memory-behind-references-ucg414))\n-   blog posts\n-   academic papers\n-   issue discussions\n-   forum posts\n-   Miri documentation\n-   sanitizer documentation\n\nUse these sources to improve rigor and style, but do not treat them as final\nauthority for UB, layout, aliasing, validity, or provenance.\n\n### 5. Project-local lemmas and invariants `[evidence.project]`\n\nProject-local invariants may be used as proof premises only if they are\nexplicitly documented and maintained by all constructors, mutators, destructors,\ntrait impls, FFI entry points, and panic paths.\n\nAcceptable project-local premises include:\n\n-   module invariants;\n-   type invariants;\n-   representation invariants;\n-   ownership invariants;\n-   initialization invariants;\n-   aliasing invariants;\n-   pinning invariants;\n-   FFI invariants;\n-   synchronization invariants;\n-   previously documented safety contracts.\n\nProject-local invariants are not self-proving. Every unsafe proof that cites one\nmust name it precisely, and review must verify that the invariant is established\nand preserved everywhere.\n\n### 6. Local facts `[evidence.local]`\n\nLocal facts include facts visible at the program point:\n\n-   branch conditions;\n-   runtime checks;\n-   values copied into locals;\n-   ownership state;\n-   initialization state;\n-   lifetime relationships;\n-   borrow relationships;\n-   arithmetic facts;\n-   control-flow facts;\n-   no-intervening-mutation facts;\n-   no-callback\u002Fno-reentrancy facts;\n-   exact type facts enforced by the compiler.\n\nLocal facts are valid only if still true at the unsafe operation. If a fact was\nchecked earlier, the safety comment must explain why it has not been invalidated\nby mutation, reallocation, aliasing, callbacks, panics, drops, or interior\nmutability.\n\n## Mandatory fact classification `[fact.classify]`\n\nEvery proof-sensitive sentence must be classifiable as one of:\n\n-   `AXIOM`: Rust Reference or standard library documentation.\n-   `DEPENDENCY LEMMA`: documented behavior of an intentionally selected safe\n    dependency.\n-   `PRECONDITION`: documented in a relevant `# Safety` section.\n-   `INVARIANT`: documented project-local invariant.\n-   `LOCAL FACT`: visible checked condition or control-flow fact.\n-   `TYPE FACT`: guaranteed by Rust's type system or by a documented type.\n-   `POSTCONDITION`: state established by a preceding operation whose contract\n    has already been proved, or a guarantee a callee documents (in its `#\n    Safety` section or under `# Safety-usable invariant`) whose preconditions\n    this proof discharges.\n\nReject any unclassified fact.\n\nA rigorous proof does not have to mechanically label every sentence with these\nwords, but the classification must be obvious. If a reviewer asks \"where does\nthis fact come from?\", the answer must be immediate and precise.\n\n## Core distinction: documentation vs comments `[conv]`\n\n### Safety documentation `[conv.docs]`\n\nSafety documentation belongs on unsafe APIs and unsafe extension points. It\nstates the theorem that callers or implementers must satisfy.\n\nExamples:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that ...\npub unsafe fn f(...) -> ...\n```\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F Implementors must ensure that ...\npub unsafe trait T { ... }\n```\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that this function is called only when ...\nunsafe extern \"C\" fn callback(...) { ... }\n```\n\n### Safety comments `[conv.comments]`\n\nSafety comments belong next to concrete unsafe operations. They prove that the\nexact operation is valid at the exact program point.\n\nFor unsafe attributes, use a safety comment to justify the whole-program,\nlinkage, ABI, symbol, section, or target-feature obligation being asserted.\n\n#### Comment Formatting `[conv.format]`\n\n*   **Canonical spelling:** Generate `\u002F\u002F SAFETY:` immediately before an unsafe\n    operation or `unsafe impl`. This form is recognized by Clippy's\n    `undocumented_unsafe_blocks` lint.\n*   **Review significance:** Capitalization or punctuation differences (such as\n    `\u002F\u002F Safety`, `\u002F\u002F\u002F safety`, or `\u002F\u002F safety:`) do not change the semantic\n    adequacy of a safety proof. When a project enables a lint that rejects the\n    local spelling, mention the canonical form as a brief tooling note; do not\n    report it as a soundness defect or let it dominate the review.\n*   **Doc Comments**: Safety comments can be regular comments (e.g., `\u002F\u002F\n    safety`) or doc comments (e.g., `\u002F\u002F\u002F safety`).\n*   **Safety Comments on `unsafe impl`**: A doc comment or regular comment\n    placed directly on an `unsafe impl` is a completely acceptable and valid\n    safety comment.\n*   **Public API Documentation**: Use `\u002F\u002F\u002F # Safety` for the caller or\n    implementer contract on public unsafe functions and traits.\n\nExample:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Operation: `core::slice::from_raw_parts(ptr, len)`.\n\u002F\u002F Required contract: `ptr` must be non-null, properly aligned, valid for reads\n\u002F\u002F of `len * size_of::\u003CT>()` bytes, refer to one allocation, and point to `len`\n\u002F\u002F initialized `T` values. The memory must not be mutated by any alias for `'a`\n\u002F\u002F except through nested `UnsafeCell`.\n\u002F\u002F Evidence:\n\u002F\u002F - By this function's `# Safety` precondition, the caller provides a live\n\u002F\u002F   allocation containing `len` initialized `T` values starting at `ptr`.\n\u002F\u002F - The same precondition requires `ptr` to be non-null and aligned for `T`.\n\u002F\u002F - `len` was checked above so that `len * size_of::\u003CT>() \u003C= isize::MAX`, and\n\u002F\u002F   no intervening code mutates `len` or `ptr`.\n\u002F\u002F - By `# Safety` precondition, the caller guarantees that for the full returned\n\u002F\u002F   lifetime `'a`, no access path—including pre-existing raw pointers, aliases,\n\u002F\u002F   callbacks, reentrant code, foreign code, or concurrent agents—will mutate the\n\u002F\u002F   range except within nested `UnsafeCell` values.\n\u002F\u002F - Between accepting that precondition and constructing the slice, this function\n\u002F\u002F   invokes no unknown code and performs no state transition that can invalidate it.\n\u002F\u002F Therefore all obligations of `from_raw_parts` are discharged.\nlet s = unsafe { core::slice::from_raw_parts(ptr, len) };\n```\n\nExample for unsafe attributes:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F This `export_name` is globally unique in the final linked artifact, and no\n\u002F\u002F other object defines an incompatible symbol with this name.\n#[unsafe(export_name = \"my_custom_symbol\")]\n```\n\nThe comment must not merely restate \"caller guarantees this.\" It must show that\nthe caller's documented obligation, plus local facts and invariants, logically\nimplies the callee's documented safety contract.\n\n### Nested `unsafe fn` `[conv.nested-fn]`\n\nFor an `unsafe fn` declared inside another function body, the `# Safety`\nsection is optional. Whether to write one is a judgment call for the author and\nreviewers: a nested fn with a simple contract usually does without, one with a\ncomplex contract usually should have it.\n\nThe nested fn's proof obligations must still be discharged: every use of it (a\ncall or an FFI\u002Fcallback registration) is an `unsafe` operation whose\n`\u002F\u002F SAFETY:` comment must establish the nested fn's preconditions, and `unsafe`\nblocks inside its body still need their own `\u002F\u002F SAFETY:` comments. Every other\n`unsafe fn` must document its preconditions under `# Safety`.\n\n### Field invariants `[conv.field-invariant]`\n\nIf a struct has private fields whose values are constrained by invariants that\nare necessary for the correctness of unsafe code inside the struct, those\ninvariants must be documented on the fields.\n\nThe comment must start with `\u002F\u002F Safety invariant:`.\n\n```rust\nstruct Foo {\n    \u002F\u002F Safety invariant: `ptr` is non-null and points to a valid `Bar`.\n    ptr: *mut Bar,\n}\n```\n\nAdditionally, any safe code that mutates these fields must maintain the\ninvariant, and any such mutation should be documented with a comment explaining\nhow the invariant is maintained.\n\n### Safety-usable invariants on safe helpers `[conv.safety-usable]`\n\nSometimes, safe helper functions exist to establish or verify invariants. While\nthese are safe to call, unsafe code may rely on their correctness for soundness.\nIn this case, the helper function should document this contract under a `\u002F\u002F\u002F #\nSafety-usable invariant` heading.\n\n```rust\nimpl Foo {\n    \u002F\u002F\u002F # Safety-usable invariant\n    \u002F\u002F\u002F\n    \u002F\u002F\u002F This function guarantees that the returned index is valid for `self.buffer`.\n    fn find_index(&self) -> usize { ... }\n}\n```\n\nThe unsafe code that relies on this helper must then document this in its `\u002F\u002F\nSAFETY:` comment:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F ...\n\u002F\u002F - Relies on the safety-usable invariant of `find_index` to ensure that\n\u002F\u002F   the index is in bounds.\n```\n\n\n### Anti-Gullibility Verification (Claim-vs-Code Decomposition) `[conv.anti-gullibility]`\n\nTreat every `\u002F\u002F SAFETY:` comment or `# Safety` doc section as an unverified\nhypothesis that must be proven by executable code or caller contracts. Before\naccepting any existing or newly added `\u002F\u002F SAFETY:` or `# Safety` comment,\ndecompose it into:\n\n1.  **Required Preconditions**: The exact obligations required by the callee's\n    `# Safety` contract or Rust Reference rules (for raw pointer dereference,\n    `Send`\u002F`Sync`, pointer provenance, lifetime transmutation, uninitialized\n    memory, or allocator layout).\n2.  **Author's Stated Justification**: What the comment claims holds at this\n    program point.\n3.  **Syntactic\u002FLocal Proof Check**: What the surrounding types, trait bounds,\n    dominating runtime checks (`assert!`, `if len \u003C ...`, `.get()`,\n    `.checked_mul()`), synchronization primitives, and lifetimes actually\n    guarantee in code.\n\nFollow a two-pass verification order: first derive the required preconditions\nand check whether the surrounding code enforces them (ignoring the comment\nprose); only then check whether the `\u002F\u002F SAFETY:` comment accurately states that\nproof. An explanatory comment without an enforcement mechanism in types, bounds,\ncaller `# Safety` contracts, or control flow is an **unproven safety claim**,\nnot a valid discharge of the obligation. In particular, if an `unsafe` block\nsits inside a **safe `fn`** and its `\u002F\u002F SAFETY:` comment asserts a property of a\ncaller-supplied argument that is not checked in code, the function is unsound.\n\n### Closed Proof Kernel Grouping (Deduplication) `[conv.dedup]`\n\nWhen multiple `unsafe` operations within the same function or module fail due to\nthe exact same missing precondition or broken invariant (a single shared proof\nkernel), group them into a single finding anchored at the root site rather than\nemitting duplicate findings for each downstream operation.\n\n## Criteria for `# Safety` documentation `[doc]`\n\nA `# Safety` section must satisfy all criteria in this section.\n\n### 1. Name the responsible party `[doc.party]`\n\nState whether the obligations are on the caller, implementer, linker, host\nenvironment, foreign code, whole program, or some combination.\n\nUse this for unsafe functions:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure ...\n```\n\nUse this for unsafe traits:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F Implementors must ensure ...\n```\n\nDo not use vague subjects such as \"it must be ensured.\" Say who must ensure it.\n\n### 2. Be complete enough to imply soundness `[doc.complete]`\n\nThe contract must include every precondition needed to prevent UB through this\nAPI. A proof reviewer should be able to derive the safety of every internal\nunsafe operation from:\n\n-   the `# Safety` section;\n-   local code facts;\n-   documented dependency lemmas;\n-   documented project-local invariants;\n-   documented callee guarantees (`# Safety` postconditions, `# Safety-usable\n    invariant`s);\n-   Reference and std axioms.\n\nDo not write:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F The pointer must be valid.\n```\n\nWrite the exact validity required:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that `ptr` is non-null, properly aligned for `T`,\n\u002F\u002F\u002F points to `len` consecutive initialized `T` values, is valid for reads of\n\u002F\u002F\u002F `len * size_of::\u003CT>()` bytes, and that the entire range lies within a\n\u002F\u002F\u002F single live allocation.\n```\n\nPointer validity is operation-specific. A pointer is not simply \"valid\" in the\nabstract. It may be valid for one kind of access, one byte range, one lifetime,\nor one aliasing mode, but invalid for another.\n\n### 3. Specify temporal scope `[doc.temporal]`\n\nEvery obligation must say when it must hold.\n\nExamples:\n\n```rust\n\u002F\u002F\u002F The memory must remain valid for reads for the entire lifetime `'a` of the\n\u002F\u002F\u002F returned slice.\n```\n\n```rust\n\u002F\u002F\u002F For the duration in which the returned `&mut T` is relied upon, the pointee\n\u002F\u002F\u002F must not be accessed through any pointer or reference whose access is not\n\u002F\u002F\u002F permitted by the applicable mutable-reference rules. `UnsafeCell` does not\n\u002F\u002F\u002F relax the uniqueness guarantee of `&mut`; it only permits mutation of its\n\u002F\u002F\u002F contents through shared references.\n```\n\n```rust\n\u002F\u002F\u002F For `!Unpin` data, the pointee must remain pinned in memory (never moved,\n\u002F\u002F\u002F deallocated, or repurposed without dropping) until its destructor completes.\n\u002F\u002F\u002F Dropping a temporary `Pin\u003C&mut T>` wrapper does not release this obligation.\n```\n\n```rust\n\u002F\u002F\u002F For this unsafe async function, `ptr` must remain valid until the returned\n\u002F\u002F\u002F future is dropped or completes.\n```\n\nDo not say only \"during the call\" unless the obligation truly ends before the\nfunction returns. Returned references, futures, iterators, guards, trait\nobjects, raw handles, and pinned values often extend obligations beyond the\ninitial call.\n\n### 4. Specify byte ranges, allocation identity, alignment, and initialization `[doc.ranges]`\n\nFor pointer, slice, buffer, allocation, and FFI APIs, the contract must state\nevery relevant low-level condition:\n\n-   read validity vs write validity;\n-   exact byte count;\n-   exact element count;\n-   alignment for the accessed type;\n-   non-nullness;\n-   initialization state;\n-   Rust value validity for type `T`;\n-   allocation liveness;\n-   whether the entire range lies in one allocation;\n-   provenance or allocation origin when relevant;\n-   aliasing and exclusivity;\n-   mutation permissions;\n-   arithmetic constraints;\n-   maximum size constraints such as `isize::MAX`;\n-   no address-space wraparound;\n-   deallocation layout, allocator identity, and capacity when reconstructing\n    ownership.\n\nExample:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F The caller must ensure that:\n\u002F\u002F\u002F\n\u002F\u002F\u002F 1. `ptr` is non-null and aligned for `T` (e.g. `NonNull::dangling()` for ZSTs or zero capacity).\n\u002F\u002F\u002F 2. If `size_of::\u003CT>() != 0 && cap != 0`, `ptr` was allocated by the global allocator\n\u002F\u002F\u002F    with layout `Layout::array::\u003CT>(cap).unwrap()`, and `cap` is the allocation capacity.\n\u002F\u002F\u002F 3. The first `len` elements are initialized valid `T` values.\n\u002F\u002F\u002F 4. `len \u003C= cap`.\n\u002F\u002F\u002F 5. `cap * size_of::\u003CT>() \u003C= isize::MAX as usize`.\n\u002F\u002F\u002F 6. No other owner will read, write, drop, or deallocate the allocation after\n\u002F\u002F\u002F    this function takes ownership.\n```\n\n### 5. Distinguish validity, initialization, and aliasing `[doc.validity-init-aliasing]`\n\nThese are separate proof obligations.\n\nA pointer can be:\n\n-   non-null but dangling;\n-   live but misaligned;\n-   aligned but not initialized;\n-   initialized but invalid for type `T`;\n-   valid for reads but not writes;\n-   valid for writes but not reads of initialized `T`;\n-   valid for one byte range but not another;\n-   valid at one time but invalid after reallocation or deallocation;\n-   valid for raw access but not valid for creating a reference;\n-   non-aliasing at one point but aliased after a callback or reentrant call.\n\nNever collapse these into \"valid pointer.\" State each property explicitly when\nrelevant.\n\n### 6. Do not rely on folklore facts `[doc.folklore]`\n\nReject any proof sentence whose source is \"everyone knows Rust works this way.\"\n\nExamples of facts that must be grounded in Reference or std docs:\n\n| Claimed fact                         | Required source               |\n| ------------------------------------ | ----------------------------- |\n| `bool` has only two valid values     | Rust Reference validity rules |\n| a reference must be non-null,        | Rust Reference validity rules |\n: aligned, and non-dangling            :                               :\n| zero-length slices still need        | `slice::from_raw_parts` \u002F     |\n: non-null aligned pointers            : `from_raw_parts_mut` docs     :\n| `ptr::read` creates a bitwise copy   | `ptr::read` docs              |\n: and can cause double-use issues for  :                               :\n: non-`Copy` values                    :                               :\n| `ptr::write` does not drop the old   | `ptr::write` docs             |\n: value                                :                               :\n| unaligned packed-field raw pointer   | `ptr::read_unaligned` docs    |\n: creation must avoid an intermediate  :                               :\n: reference                            :                               :\n| `transmute` requires both source and | `mem::transmute` docs         |\n: result to be valid at their types    :                               :\n| `Vec::from_raw_parts` requires matching | `Vec` docs                    |\n: allocator layout\u002Fcapacity when `cap > 0`:                               :\n: and `size_of::\u003CT>() > 0`; otherwise     :                               :\n: non-null aligned pointer & `len \u003C= cap` :                               :\n| raw pointer arithmetic has           | primitive pointer docs        |\n: same-allocation and `isize`          :                               :\n: constraints                          :                               :\n\nThe safety proof should cite or paraphrase exact contracts rather than importing\ninformal knowledge.\n\n### 7. Do not impose hidden safety obligations on safe callers `[doc.hidden-obligations]`\n\nA safe function must not require the caller to uphold unchecked memory-safety\npreconditions. If such preconditions are required, the function should be\n`unsafe` or the function should validate the preconditions dynamically.\n\nPublic safe API surfaces include more than `pub fn`. Public fields,\nconstructors, safe methods, safe trait methods, and macro-generated APIs all\ncount as safe API surfaces. Treat all of the following as surfaces that safe\ncaller code may use adversarially:\n\n-   public fields;\n-   public constructors and builder methods;\n-   public safe methods and inherent impls;\n-   safe trait methods and safe trait impl surfaces;\n-   public macros and proc macros;\n-   macro-generated APIs;\n-   re-exported APIs;\n-   safe callbacks, closures, comparators, allocators, and trait methods\n    accepted by public APIs;\n-   public types whose auto traits, blanket impls, `Deref`, `Drop`, or interior\n    mutability can affect unsafe invariants.\n\nA public field is a safe mutator. A public constructor is a safe\ninvariant-establishing boundary. A macro-generated safe function is still a safe\nfunction. If any such surface lets safe caller code create a value or state that\nlater makes internal unsafe code unsound, the abstraction is unsound unless the\ncondition is dynamically checked, made impossible by the type system, or moved\nbehind an unsafe contract.\n\nBad:\n\n```rust\n\u002F\u002F\u002F Caller must pass a pointer valid for reads of `len` elements.\npub fn from_ptr\u003CT>(ptr: *const T, len: usize) -> &'static [T] {\n    unsafe { core::slice::from_raw_parts(ptr, len) }\n}\n```\n\nThe caller can call this safe function with an invalid pointer. That would let\nsafe code trigger UB. The function is unsound.\n\nUse a different heading for internal invariants of safe types:\n\n```rust\n\u002F\u002F\u002F # Invariants\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ptr` is either null or points to an allocation created by `Box\u003CT>`.\n```\n\nDo not write a `# Safety` section for a safe API to shift unchecked\nmemory-safety obligations onto a safe caller.\n\nThis rule applies to private helper functions as well. Do not rely on module\nprivacy to hide memory-safety preconditions on a safe function. If a private\nhelper function must only be called under certain conditions to prevent UB, mark\nit `unsafe` and document those conditions under `# Safety` (optional for a\nnested `unsafe fn`, `[conv.nested-fn]`). Do not make it safe\nand rely on \"internal module invariants\" without an explicit safety contract, as\nfuture changes to the module might violate those invariants.\n\n**Exception for FFI-exported functions (`extern \"C\"`):** The rule against safe\nfunctions imposing unchecked preconditions applies to **safe Rust callers**.\nEvery call from C or C++ is already outside Rust's type-system guarantees on the\nforeign side. A `pub extern \"C\" fn` (or Crubit\u002FUniFFI export) that accepts\nreferences or `Option\u003C&T>` \u002F `Option\u003C&mut T>` (e.g., so `cbindgen` emits `T*`\nwhile Rust gets automatic null checking via niche optimization) does **not**\nneed to be marked `unsafe extern \"C\" fn` if safe Rust callers cannot cause UB\nthrough its signature:\n\n-   If a `pub extern \"C\" fn` takes `Option\u003C&T>` or `Option\u003C&mut T>`, safe Rust\n    callers are already forced by the compiler to pass valid, aligned,\n    non-aliasing references. Satisfying alignment, dereferenceability, and\n    non-aliasing on the C\u002FC++ side is the foreign caller's responsibility. Do\n    not flag such a function for lacking `unsafe` or demand raw pointers `*mut\n    T` instead of `Option\u003C&mut T>`.\n-   By contrast, if a `pub extern \"C\" fn` accepts raw pointers (`*const T` or\n    `*mut T`) and dereferences them internally without validating them, it\n    **must** be marked `unsafe extern \"C\" fn` (with `# Safety` documentation),\n    because otherwise *safe Rust* code could call it with a dangling or invalid\n    pointer and trigger UB.\n-   For C\u002FC++ out-parameters passed as `&mut T` or `Option\u003C&mut T>` (which C\u002FC++\n    callers commonly pass pointing to uninitialized stack memory), apply the\n    [Uninitialized memory behind references (`UCG#414`)](#uninitialized-memory-behind-references-ucg414)\n    rules below.\n\n### 8. Do not strengthen contracts you do not own `[doc.no-strengthen]`\n\nFor unsafe functions inside traits, the implementation cannot arbitrarily\nrequire stricter preconditions than the trait method's contract allows. A caller\nwho satisfies the trait-defined contract must be able to call the implementation\nsoundly.\n\nBad pattern:\n\n```rust\nunsafe trait Trait {\n    \u002F\u002F\u002F # Safety\n    \u002F\u002F\u002F Caller must pass any non-null pointer.\n    unsafe fn f(ptr: *const u8);\n}\n\nstruct Impl;\n\nunsafe impl Trait for Impl {\n    \u002F\u002F\u002F # Safety\n    \u002F\u002F\u002F Caller must pass a pointer to at least 16 initialized bytes.\n    unsafe fn f(ptr: *const u8) {\n        \u002F\u002F implementation relies on stronger condition\n    }\n}\n```\n\nThe implementation has silently strengthened the trait contract. Unsafe code\nusing the trait may call according to the trait contract, not the\nimplementation's private contract. This is unsound unless the trait contract\npermits the strengthening.\n\n### 9. Separate semantic preconditions from memory-safety preconditions `[doc.semantic-vs-memory]`\n\nA function may have ordinary semantic requirements, but memory-safety\nrequirements belong in `# Safety` only if violation can lead to UB.\n\nFor safe APIs, semantic preconditions must be handled safely:\n\n-   return `Result`;\n-   panic;\n-   clamp;\n-   ignore;\n-   validate;\n-   document as a logic error that cannot cause UB.\n\nFor unsafe APIs, the `# Safety` section must contain all unchecked memory-safety\npreconditions. Do not hide memory-safety preconditions in prose under `#\nPanics`, `# Errors`, examples, type names, module docs, or comments elsewhere.\n\n### 10. Include postconditions when unsafe callers may rely on them `[doc.postconditions]`\n\nA `# Safety` section should usually state not only what the caller must\nguarantee, but also what the function guarantees in return when those\npreconditions hold.\n\nExamples:\n\n```rust\n\u002F\u002F\u002F If these preconditions hold, the returned slice contains exactly the `len`\n\u002F\u002F\u002F initialized `T` values starting at `ptr`, and no safe operation on the slice\n\u002F\u002F\u002F can mutate the memory except through `UnsafeCell`.\n```\n\n```rust\n\u002F\u002F\u002F If these preconditions hold, this function takes exclusive ownership of the\n\u002F\u002F\u002F allocation and will deallocate it exactly once using the original layout.\n```\n\nPostconditions are especially important for unsafe traits and unsafe\nconstructors whose results are later used by safe code or other unsafe proofs.\n\n### 11. Do not rely on the absence of an impl `[doc.absent-impl]`\n\nAn `unsafe impl`'s obligation must be discharged with facts that remain true\nunder program extension: new crates, new types, new impls. The impl set of a\nsafe trait is open and extendable by safe code, and the absence of a trait\nimplementation on a type is not such a fact.\n\nThe suspect pattern:\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F If a type implements both `UnsafeTr` and `SafeTr`, `SafeTr` must behave\n\u002F\u002F\u002F a certain way.\nunsafe trait UnsafeTr {}\n```\n\nThis conditions an unsafe obligation on the behavior of a safe trait.\nWhichever impl completes the pair `UnsafeTr + SafeTr` last decides soundness,\nand the `SafeTr` half can be completed in safe code. Classify as follows.\n\nBad:\n\n1.  The unsafe trait is dyn-compatible. Downstream safe code may write:\n\n    ```rust\n    trait Sub: UnsafeTr {}\n    impl SafeTr for dyn Sub { \u002F\u002F impl that behaves incorrectly }\n    ```\n    `dyn Sub: UnsafeTr` holds via the built-in supertrait impl; no `unsafe`\n    appears downstream. Reject the contract as designed unless the defining\n    crate owns a blanket `impl\u003CT: UnsafeTr + ?Sized> SafeTr for T` (making\n    every such downstream impl a coherence error), or the unsafe trait is\n    non-dyn-compatible *by construction* — an explicit dyn-incompatible\n    supertrait or other property that would be a semver-breaking-change\n    to remove. A bare marker trait is dyn-compatible by default.\n\n2.  A blanket `unsafe impl` over a `#[fundamental]` constructor:\n\n    ```rust\n    unsafe impl\u003CT: UnsafeTr> UnsafeTr for Box\u003CT> {}\n    ```\n\n    No party can discharge this. A downstream crate owning `Local` may\n    soundly write `unsafe impl UnsafeTr for Local` (vacuous: `Local` has no\n    `SafeTr` impl) and then, because `Box` is fundamental, legally write\n    `impl SafeTr for Box\u003CLocal>` in safe code. `Box\u003CLocal>: UnsafeTr +\n    SafeTr` now violates a contract that no single impl broke. Reject\n    fundamental blankets under a conditional cross-trait contract unless the\n    defining crate owns the matching safe-trait blanket for the same coverage\n    (`impl\u003CT: UnsafeTr> SafeTr for Box\u003CT>`).\n\nIffy (accept, with an explicit label):\n\n3.  Coherence-based negative reasoning about a concrete local type:\n\n    ```rust\n    \u002F\u002F dyn-incompatible; same safety requirements.\n    unsafe trait UnsafeTr: Sized {}\n\n    \u002F\u002F SAFETY: `ExampleStruct` has no `SafeTr` impl in this crate, and\n    \u002F\u002F the orphan rule prevents any other crate from adding one, so the\n    \u002F\u002F conditional obligation is vacuous.\n    unsafe impl UnsafeTr for ExampleStruct {}\n    ```\n\n    Sound today, but only because current coherence rules forbid the downstream\n    impl. The orphan rule exists to make enforcing coherence easier, but it is\n    not a stated soundness guarantee, and active proposals would weaken it.\n    Accept only when cases 1 and 2 are absent (non-dyn-compatible unsafe trait,\n    no fundamental blankets) and the premise is flagged as orphan-rule-reliant\n    so it can be found and re-audited if coherence rules change. Flag as fragile\n    and prefer a restructuring below.\n\nGood:\n\n-   Move the constrained behavior into the unsafe trait itself, so each\n    `unsafe impl` carries the obligation directly (such as by making `SafeTr`\n    a supertrait, or tying the constrained behaviour to an unsafe marker\n    trait which is a subtrait of both).\n-   Validate dynamically before unsafe reliance (check the returned value,\n    then use the checked value).\n-   Have the defining crate own the safe trait's impl for the entire\n    `T: UnsafeTr + ?Sized` coverage, closing the impl set by coherence.\n-   Seal the safe trait, with sealing airtight per the sealing rule.\n\n## Criteria for safety comments `[comment]`\n\nA safety comment (e.g., using `\u002F\u002F safety:`, `\u002F\u002F SAFETY:`, or doc comment\nequivalents like `\u002F\u002F\u002F safety:`) must answer all five questions in this section,\nplus any specialized rule that applies to the operation, such as reference\ncreation, FFI, global state, or target-feature-sensitive execution.\n\n### 1. What exact unsafe operation is being justified? `[comment.operation]`\n\nBad:\n\n```rust\n\u002F\u002F SAFETY: This is safe.\nunsafe { ptr.add(i).read() }\n```\n\nGood:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Justifies both:\n\u002F\u002F 1. `ptr.add(i)`\n\u002F\u002F 2. `.read()` from the resulting pointer\nunsafe { ptr.add(i).read() }\n```\n\nStricter rule: prefer one unsafe operation per unsafe block. If a block contains\nmultiple unsafe operations, the comment must itemize and prove each one\nseparately.\n\n### 2. What contract is being discharged? `[comment.contract]`\n\nThe comment must name the contract source and the relevant obligations.\n\nExample:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr::read`: `src` must be valid for reads, properly aligned,\n\u002F\u002F and point to an initialized `T`.\nlet value = unsafe { src.read() };\n```\n\nFor raw pointer arithmetic:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr.add`: the offset in bytes must fit in `isize`; if the\n\u002F\u002F offset is non-zero, the original pointer must be derived from an allocation,\n\u002F\u002F and the entire range from the original pointer to the result must remain in\n\u002F\u002F bounds of that allocation without address-space wraparound.\nlet p = unsafe { ptr.add(i) };\n```\n\nDo not merely say \"bounds checked above\" unless the callee contract is only a\nbounds obligation. Most pointer operations have allocation, alignment,\ninitialization, provenance, aliasing, and size obligations too.\n\n### 3. Which premises prove the contract? `[comment.premises]`\n\nEvery premise must be classified as one of:\n\n-   Rust Reference or std axiom;\n-   documented dependency lemma;\n-   caller precondition from this function's `# Safety` section;\n-   implementer precondition from an unsafe trait's `# Safety` section;\n-   documented type invariant;\n-   documented module invariant;\n-   runtime check;\n-   control-flow fact;\n-   type-system fact;\n-   postcondition from a previous proved operation, or documented by a callee\n    under its `# Safety` or `# Safety-usable invariant`.\n\nBad:\n\n```rust\n\u002F\u002F SAFETY: `i` is in bounds.\nlet x = unsafe { slice.get_unchecked(i) };\n```\n\nGood:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `get_unchecked`: `i \u003C slice.len()`.\n\u002F\u002F Evidence: this branch is reached only after `if i \u003C slice.len()` succeeds.\n\u002F\u002F `slice` is immutably borrowed and no intervening code can change its length.\n\u002F\u002F Therefore `i` is a valid element index for `slice` at this call.\nlet x = unsafe { slice.get_unchecked(i) };\n```\n\n### 4. Why do the premises still hold at this program point? `[comment.still-hold]`\n\nThe proof must account for intervening code.\n\nBad:\n\n```rust\n\u002F\u002F SAFETY: We checked the length above.\nunsafe { v.set_len(len) }\n```\n\nGood:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `Vec::set_len`: `len \u003C= capacity`, and the first `len`\n\u002F\u002F elements must be initialized.\n\u002F\u002F Evidence:\n\u002F\u002F - `len \u003C= v.capacity()` was checked above.\n\u002F\u002F - Since that check, no code has mutated, reallocated, or moved `v`.\n\u002F\u002F - The loop initialized exactly indices `0..len` using `MaybeUninit::write`;\n\u002F\u002F   the loop counter is local and cannot be changed by external code.\n\u002F\u002F Therefore the new length exposes only initialized elements and does not exceed\n\u002F\u002F capacity.\nunsafe { v.set_len(len) }\n```\n\nMany comments fail because they cite a fact that was true earlier but may have\nbeen invalidated by mutation, reallocation, aliasing, callbacks, drops, panics,\nor interior mutability.\n\n### 5. What state changes after the unsafe operation? `[comment.state-change]`\n\nUnsafe comments must document postconditions when the operation changes\nownership, initialization, aliasing, lifetime, pinning, or drop obligations.\n\nExample for `ptr::read`:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr::read`: `src` is valid for reads, properly aligned, and\n\u002F\u002F points to an initialized `T`.\n\u002F\u002F Evidence: ...\n\u002F\u002F Postcondition: the value at `src` has been bitwise-copied out. Because `T`\n\u002F\u002F may be non-`Copy`, this code must not later treat the original location as an\n\u002F\u002F initialized owned `T` unless it is overwritten without first being dropped.\nlet value = unsafe { src.read() };\n```\n\nPostconditions are mandatory for operations such as:\n\n-   `ptr::read`\n-   `ptr::write`\n-   `ptr::copy` \u002F `copy_nonoverlapping`\n-   `MaybeUninit::assume_init`\n-   `Vec::set_len`\n-   `Vec::from_raw_parts`\n-   `Box::from_raw`\n-   `slice::from_raw_parts`\n-   `mem::transmute`\n-   `ManuallyDrop` operations\n-   raw allocation or deallocation\n-   FFI calls that transfer ownership\n-   pin projection\n-   partially initialized arrays or buffers\n\n## Authoring guidance `[auth]`\n\nThis section says how to write safety text well. Reviewers do not flag\ndepartures from it; they flag a missing or false proposition.\n\n### Procedure for writing a safety comment `[auth.procedure]`\n\nWhen adding a `\u002F\u002F SAFETY:` comment, follow this step-by-step procedure:\n\n1.  **Identify the unsafe operations**: Locate all `unsafe` blocks, `unsafe fn`\n    calls, `unsafe impl`s, or unsafe attributes.\n2.  **Determine the safety contracts**: Look up the exact safety contracts for\n    each operation in the Rust Reference or standard library documentation. Do\n    not guess.\n3.  **Audit the surrounding code**: Trace the inputs, lifetime bounds, and state\n    transitions of the surrounding code to ensure they satisfy the safety\n    contracts.\n4.  **Write the proof**: Write the `\u002F\u002F SAFETY:` comment, explaining step-by-step\n    how the contracts are met using the classified premises (Axioms,\n    Preconditions, Invariants, Local Facts).\n5.  **Verify**: Re-read the code and the proof to ensure there are no logical\n    gaps.\n\n### State only the property `[auth.property-only]`\n\nA `Safety invariant:` comment or a `# Safety` section states propositions.\nKeep the following out of it:\n\n-   **Origin.** Do not specify which constructor or operation first\n    established the property.\n-   **Maintainers.** Do not list the sites that currently uphold the invariant.\n    Each operation that might break the invariant (e.g., a write) must show\n    how it maintains the invariant.\n-   **Dependents.** Do not list the sites that rely on the invariant. Each\n    user of the invariant cites it in its `\u002F\u002F SAFETY:` comment.\n-   **Rationale.** Do not justify a clause inside it. Rationale belongs in\n    implementation comments separate from the proposition.\n\nBad (specifies the origin, lists maintainers and dependents):\n\n```rust\nstruct Node {\n    \u002F\u002F Safety invariant: `buf` is null or was allocated by `self.alloc()`, the\n    \u002F\u002F allocator `Node::new_in()` installed. `push_text()` allocates through\n    \u002F\u002F `self.alloc()`; `set_literal()` allocates through the parser's allocator,\n    \u002F\u002F which is the same one; `set_info()` copies a buffer that came from any\n    \u002F\u002F other allocator. `Drop` and `set_literal()` free the previous `buf`\n    \u002F\u002F through `self.dealloc()`.\n    buf: *mut u8,\n}\n```\n\nGood:\n\n```rust\nstruct Node {\n    \u002F\u002F Safety invariant: `buf` is null or was allocated by `self.alloc()` with\n    \u002F\u002F `Layout::array::\u003Cu8>(self.cap)`.\n    buf: *mut u8,\n}\n```\n\nNote that \"allocated by `self.alloc()` with this layout\" in this case is a part\nof the property, not a mere cross-reference to an origin.\n\nThis rule also applies to a `# Safety` section. Bad (origin, rationale):\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ptr` must be null or allocated by `new_in()` through `self.alloc()`,\n\u002F\u002F\u002F because `Drop` frees it through `self.dealloc()`. Pointers from\n\u002F\u002F\u002F `self.take_buf()` qualify.\npub unsafe fn set_buf(&mut self, ptr: *mut u8, cap: usize)\n```\n\nGood:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ptr` must be null or allocated by `self.alloc` with\n\u002F\u002F\u002F `Layout::array::\u003Cu8>(cap)`. `self` takes ownership of the allocation.\npub unsafe fn set_buf(&mut self, ptr: *mut u8, cap: usize)\n```\n\nNote that \"`self` takes ownership of the allocation\" is a postcondition the\ncaller must know (`[doc.postconditions]`), not a statement about dependents.\n\n### Cite a contract; do not copy it `[auth.cite-contract]`\n\nWhen a function's `# Safety` requires an argument to satisfy another contract (a\ntype invariant, a function's postcondition, a callback's contract), link that\ncontract:\n\n```rust\n\u002F\u002F\u002F - `callback`: `None`, or a function meeting the [`CallbackTy`] `# Safety`\n\u002F\u002F\u002F   contract.\n```\n\nDo not paste the contract's text: copies drift, and an intra-doc link lets\nrustdoc catch a rename.\n\nThis rule only applies to a `# Safety` section that delegates part of its\ncontract to another documented contract. It does not apply to `\u002F\u002F SAFETY:`\nproofs: a proof still enumerates the callee's obligations and discharges them\none by one (`[comment.contract]`).\n\n## Required proof topics checklist `[topics]`\n\nFor every unsafe site, check whether each topic is relevant. If relevant, the\nproof must address it explicitly.\n\n| Topic               | What the proof must establish                          |\n| ------------------- | ------------------------------------------------------ |\n| UB scope            | Safe code cannot trigger UB through this abstraction   |\n:                     : without crossing an unsafe contract.                   :\n| Operation identity  | The exact unsafe operation or unsafe contract being    |\n:                     : discharged is named.                                   :\n| Pointer validity    | Operation-specific validity: read\u002Fwrite, byte range,   |\n:                     : liveness, provenance\u002Fallocation, alignment.            :\n| Nullness            | Whether null is permitted; references and slices often |\n:                     : require non-null even for zero-size or zero-length     :\n:                     : cases when docs say so.                                :\n| Alignment           | Alignment for the accessed type, not merely            |\n:                     : byte-addressability.                                   :\n| Initialization      | Memory contains initialized values where the operation |\n:                     : reads, drops, or exposes initialized values (for       :\n:                     : uninitialized memory behind references, see            :\n:                     : [UCG#414](#uninitialized-memory-behind-references-ucg414)). :\n| Type validity       | Values satisfy Rust validity invariants, such as valid |\n:                     : discriminants, valid references, valid `bool`, valid   :\n:                     : `char`, valid `NonZero*`, and valid enum tags.         :\n| Aliasing            | Shared\u002Fmutable reference rules, exclusivity,           |\n:                     : `UnsafeCell`, raw pointer interleavings, and no        :\n:                     : invalid reference creation.                            :\n| Reference creation  | Every produced reference or reference-like owner is    |\n:                     : valid at creation; narrow creation is preferred but    :\n:                     : not sufficient.                                        :\n| Mutability          | No mutation through immutable\u002Fshared references except |\n:                     : through `UnsafeCell`; no mutation of immutable bytes.  :\n| Allocation identity | Whole range lies in one allocation when required;      |\n:                     : allocator, layout, capacity, and alignment match when  :\n:                     : reconstructing ownership.                              :\n| Pointer arithmetic  | Same-allocation range, `isize` fit, no wraparound, no  |\n:                     : out-of-bounds projection when the API requires         :\n:                     : in-bounds.                                             :\n| Temporal scope      | Each obligation states what event ends it. Do not infer |\n:                     : that dropping a temporary reference, guard, iterator,  :\n:                     : future, or `Pin\u003CPtr>` ends obligations attached to the :\n:                     : underlying allocation, pointee, or async operation.    :\n| Ownership           | Exactly one owner is responsible for                   |\n:                     : drop\u002Fdeallocation; ownership transfers are explicit.   :\n| Drop \u002F destructor   | No double drop, use-after-move, or drop of              |\n: elision             : uninitialized storage. Safety must not depend on a     :\n:                     : destructor running: safe code may use `mem::forget`,   :\n:                     : leak a guard or proxy, or form reference cycles. A     :\n:                     : leak may be acceptable; later safe access to invalid   :\n:                     : state is not.                                          :\n| Panic \u002F unwind      | Treat every call to caller-controlled safe code as a   |\n:                     : potential panic and reentrancy point. At each such     :\n:                     : point, invariants are either fully restored or         :\n:                     : protected so unwinding can leak but cannot expose UB,  :\n:                     : double-drop, or invalid state.                         :\n| FFI\u002FABI             | Correct ABI, FFI-safe representations, valid foreign   |\n:                     : contracts, unwind behavior, ownership transfer,        :\n:                     : retention behavior, callbacks, global state, and       :\n:                     : target-platform assumptions. A Rust panic reaching a   :\n:                     : non-`-unwind` ABI boundary (e.g. `extern \"C\"`) safely  :\n:                     : aborts after running local Rust destructors rather     :\n:                     : than unwinding across FFI; cross-boundary unwinding is :\n:                     : UB only when a panic exits an `-unwind` ABI (e.g.      :\n:                     : `extern \"C-unwind\"`) into a foreign frame that cannot  :\n:                     : handle it, or when a foreign exception enters Rust     :\n:                     : across a non-`-unwind` ABI or into `catch_unwind`.     :\n| Global state        | Global or process-wide state is assumed                |\n:                     : concurrent\u002Freentrant unless synchronization or an      :\n:                     : explicit out-of-band guarantee proves otherwise.       :\n| Configuration       | Every supported                                        |\n: matrix              : cfg\u002Ffeature\u002Ftarget\u002FSIMD\u002Fallocator\u002Fdebug\u002Fgenerated-code :\n:                     : combination in scope is sound.                         :\n| Concurrency         | No data races; atomics, locks, or other                |\n:                     : synchronization justify shared mutation.               :\n| Memory ordering \u002F   | When atomics publish data or transfer ownership        |\n: happens-before      : between threads, identify the precise synchronization  :\n:                     : edge (e.g. Release store synchronizes-with Acquire     :\n:                     : load), the data it orders, and why the chosen          :\n:                     : orderings establish the needed happens-before          :\n:                     : relationship.                                          :\n| Mixed-size \u002F        | When atomic and non-atomic accesses, or differently    |\n: overlapping atomics : sized atomic accesses, may refer to overlapping bytes,  :\n:                     : prove the access pattern is permitted by the           :\n:                     : documented memory model. Do not infer safety merely    :\n:                     : from each individual operation being atomic.           :\n| Mutex poisoning     | Mutex and RwLock poisoning is advisory. If memory      |\n:                     : safety depends on a lock-protected invariant, prove    :\n:                     : the invariant is restored or inaccessible after a      :\n:                     : panic without assuming poisoning always occurs or is   :\n:                     : always checked.                                        :\n| Generic wrapper     | For a type that logically borrows, owns, or may drop   |\n: semantics           : data not represented by ordinary Rust fields, verify   :\n:                     : that its inferred variance, `PhantomData` markers, and :\n:                     : drop-check behavior match the real lifetime and        :\n:                     : ownership contract.                                    :\n| Reentrancy          | Caller-provided callbacks or trait methods cannot      |\n:                     : observe or exploit broken intermediate invariants.     :\n| Safe trait laws     | Unsafe code does not rely on caller-provided safe      |\n:                     : trait implementations being semantically correct.      :\n| Dependency trust    | Any reliance on safe dependency semantics is           |\n:                     : deliberate, documented when proof-relevant, and does   :\n:                     : not extend to caller-supplied code.                    :\n| Traits              | Unsafe trait implementer obligations are satisfied and |\n:                     : not silently strengthened.                             :\n| Pinning             | Identify the pointee and the event that ends its        |\n:                     : pinning guarantee—commonly destruction of the          :\n:                     : pointee. Dropping a temporary `Pin\u003C&mut T>` handle     :\n:                     : alone does not make the pointee movable. Projection    :\n:                     : and pinned-drop rules remain satisfied for the full    :\n:                     : required duration.                                     :\n| Layout\u002Frepr         | Any layout assumption is guaranteed by `repr`,         |\n:                     : Reference, or std docs, not compiler accident.         :\n| Nested layout \u002F     | A direct representation guarantee for `A` and `B` does  |\n: niches              : not automatically imply that `Outer\u003CA>` and `Outer\u003CB>` :\n:                     : have the same layout, ABI, niches, or transmutability. :\n:                     : Prove the enclosing representation from its own `repr` :\n:                     : and documented guarantees. In particular, account for  :\n:                     : niche suppression by `UnsafeCell`.                     :\n| Padding \u002F object    | When code reads, compares, hashes, serializes,          |\n: representation      : transmutes, or attempts to preserve a value's raw      :\n:                     : bytes, prove that every observed byte is permitted to  :\n:                     : be read and that no claim depends on padding being     :\n:                     : initialized or preserved unless an authoritative       :\n:                     : contract guarantees it.                                :\n| Niche\u002Fvalidity      | Non-null\u002Faligned\u002Freference validity assumptions are    |\n: optimizations       : respected even when data length is zero.               :\n| Integer arithmetic  | Size computations are checked for overflow and         |\n:                     : documented as mathematical-integer facts where APIs    :\n:                     : require that.                                          :\n| Interior mutability | `UnsafeCell`, `Cell`, `RefCell`, atomics, locks, and   |\n:                     : global state are accounted for.                        :\n\n### Copy Function-Pointer Statics `[topics.func-ptr]`\n\nCalling a `Copy` method (such as `.expect(...)` or `.unwrap()`) on a `static\nmut` holding `Option\u003Cunsafe fn(...)>` (or reading the function pointer by value)\ncopies the function pointer by value and does **not** create a long-lived shared\nreference (`static_mut_refs` UB) across the subsequent indirect call, provided\nno concurrent mutation races with the read.\n\n## Core axiom lookup discipline `[axiom]`\n\nWhen a proof relies on a Rust fact, trace it to the relevant Reference or std\ndocumentation.\n\n### Undefined behavior and validity `[axiom.ub]`\n\nUse the Rust Reference for:\n\n-   the list of behavior considered undefined;\n-   the fact that the UB list is not necessarily exhaustive;\n-   dangling or misaligned place access;\n-   breaking pointer aliasing rules;\n-   mutating immutable bytes;\n-   producing invalid values;\n-   validity requirements for primitive types;\n-   validity requirements for references and `Box`;\n-   validity requirements for arrays, tuples, structs, and enums;\n-   layout facts guaranteed by `repr` attributes.\n\nExample proof phrasing:\n\n```rust\n\u002F\u002F AXIOM: The Reference requires a `bool` value to be either `0` or `1`.\n\u002F\u002F Evidence: `b` was produced by comparing two integers, not by reading raw\n\u002F\u002F bytes as `bool`. Therefore `b` is a valid `bool`.\n```\n\n### Standard-library unsafe contracts `[axiom.std]`\n\nUse the std docs for exact contracts of standard-library unsafe APIs. Do not\napproximate.\n\nCommon APIs that require exact contract extraction:\n\n-   `core::slice::from_raw_parts`\n-   `core::slice::from_raw_parts_mut`\n-   raw pointer `read`, `write`, `copy`, `copy_nonoverlapping`\n-   raw pointer `add`, `sub`, `offset`, `offset_from`\n-   `core::ptr::read_unaligned`\n-   `core::mem::transmute`\n-   `MaybeUninit::assume_init`\n-   `Vec::set_len`\n-   `Vec::from_raw_parts`\n-   `Box::from_raw`\n-   `CString::from_raw`\n-   `Arc::from_raw`\n-   `Rc::from_raw`\n-   allocator APIs\n-   `Pin::new_unchecked`\n-   `Pin::map_unchecked` and related projection APIs\n-   `NonNull::new_unchecked`\n-   `str::from_utf8_unchecked`\n-   unchecked indexing APIs\n-   SIMD and target-feature APIs\n\nFor each such call, copy the contract into proof obligations and discharge them\none by one.\n\n## Reject patterns `[rej]`\n\nThe following patterns should fail review.\n\n### 1. \"Pointer is valid\" `[rej.pointer-valid]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: `ptr` is valid.\nunsafe { ptr.read() }\n```\n\nRequire:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `ptr::read`: `ptr` must be properly aligned, valid for reads of\n\u002F\u002F `size_of::\u003CT>()` bytes, and point to an initialized `T`.\n\u002F\u002F Evidence:\n\u002F\u002F - ...\n```\n\nFor slices or ranges, require the full range:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F `ptr` is non-null, aligned for `T`, valid for reads of\n\u002F\u002F `len * size_of::\u003CT>()` bytes, points to `len` initialized `T`s, and the full\n\u002F\u002F range lies in one live allocation.\n```\n\n### 2. \"Caller guarantees it\" `[rej.caller-guarantees]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: The caller guarantees this.\nunsafe { callee(ptr, len) }\n```\n\nRequire:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F Contract from `callee`: requires P, Q, and R.\n\u002F\u002F By this function's `# Safety` contract, the caller guarantees P and Q.\n\u002F\u002F Local check `len \u003C= cap` plus invariant I imply R.\n\u002F\u002F No intervening code can invalidate P, Q, or R.\n\u002F\u002F Therefore all obligations of `callee` are satisfied.\nunsafe { callee(ptr, len) }\n```\n\n### 3. \"Miri passes\" `[rej.miri-passes]`\n\nReject as proof:\n\n```rust\n\u002F\u002F SAFETY: Miri passes.\nunsafe { ... }\n```\n\nMiri, fuzzing, sanitizers, tests, model checking, and examples are bug-finding\nor confidence-building tools. They are not axioms and do not replace a proof.\n\nAcceptable use:\n\n```rust\n\u002F\u002F Not a proof premise: Miri tests cover this path. The proof is above.\n```\n\nA test provides evidence only if it would actually fail if UB is present. For\nexample, a test that builds a reference from a dangling pointer but never loads\nthrough it does execute UB, but would likely pass under ASan nevertheless.\n\n### 4. \"Zero length means null is fine\" `[rej.zero-len-null]`\n\nReject for slice references:\n\n```rust\n\u002F\u002F SAFETY: `len == 0`, so null is okay.\nlet s = unsafe { core::slice::from_raw_parts(core::ptr::null(), 0) };\n```\n\nThe standard-library slice constructors require non-null aligned pointers even\nfor zero-length slices and ZSTs. Use a proper dangling-but-non-null aligned\npointer where the API permits it.\n\n### 5. Packed field address through intermediate reference `[rej.packed-ref]`\n\nReject:\n\n```rust\nlet p = &packed.field as *const Field;\nlet value = unsafe { p.read_unaligned() };\n```\n\nCreating the intermediate reference to a packed field may itself violate\nalignment requirements. Use raw address-of syntax when forming a raw pointer for\nunaligned access:\n\n```rust\nlet p = &raw const packed.field;\nlet value = unsafe { p.read_unaligned() };\n```\n\n### 6. \"Transmute because same size\" `[rej.transmute-size]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: Same size.\nlet b: B = unsafe { core::mem::transmute::\u003CA, B>(a) };\n```\n\nRequire proof that:\n\n-   source and destination have the same size;\n-   the source value is valid at type `A`;\n-   the resulting bits are valid at type `B`;\n-   alignment and layout assumptions are documented;\n-   pointer\u002Finteger provenance assumptions are valid;\n-   ownership and drop obligations are not duplicated or lost;\n-   there is no safer conversion.\n\n`transmute` is a last-resort operation. Same size is necessary but not\nsufficient.\n\n#### Non-Compositionality of Niches and Outer Layouts\n\nNever assume that layout equivalence of inner types composes to outer types: -\nAlthough `UnsafeCell\u003CT>` and `MaybeUninit\u003CT>` have identical size and alignment\nto `T`, wrapping `T` inside them inhibits or changes niche optimizations for\nenclosing types. - For example, `Option\u003Ccore::ptr::NonNull\u003Cu8>>` is 8 bytes due\nto null-pointer niche optimization, whereas\n`Option\u003Ccore::cell::UnsafeCell\u003Ccore::ptr::NonNull\u003Cu8>>>` or\n`Option\u003Ccore::mem::MaybeUninit\u003Ccore::ptr::NonNull\u003Cu8>>>` may be 16 bytes. -\nTransmuting between `Outer\u003CT>` and `Outer\u003CUnsafeCell\u003CT>>` or\n`Outer\u003CMaybeUninit\u003CT>>` is unsound unless the layout of the entire outer type is\nexplicitly proved.\n\n#### Padding and Raw Byte Access\n\nWhen code reads, compares, hashes, serializes, or transmutes raw struct bytes: -\nPadding bytes are uninitialized by default and not preserved across typed\nmoves\u002Fcopies. - Reading or hashing `size_of::\u003CT>()` raw bytes behind `&T` is\ninvalid whenever `T` contains uninitialized padding. - Fieldwise operations\nshould be preferred over whole-object raw byte operations.\n\n### 7. \"Vec owns this pointer\" `[rej.vec-owns]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: This came from a Vec.\nlet v = unsafe { Vec::from_raw_parts(ptr, len, cap) };\n```\n\nRequire proof of:\n\n-   **When `size_of::\u003CT>() != 0 && cap != 0`**:\n    -   original allocator identity;\n    -   exact allocation layout (`Layout::array::\u003CT>(cap)`);\n    -   alignment equality, not merely compatibility;\n    -   capacity from the original allocation;\n    -   allocation size constraints (`cap * size_of::\u003CT>() \u003C= isize::MAX as\n        usize`);\n-   **When `size_of::\u003CT>() == 0 || cap == 0`**:\n    -   `ptr` is non-null and suitably aligned for `T` (e.g.\n        `NonNull::dangling()`);\n    -   no heap allocation required;\n-   **In all cases**:\n    -   `len \u003C= cap`;\n    -   first `len` elements initialized;\n    -   ownership transfer;\n    -   no other owner will use or deallocate the allocation;\n    -   no double-drop or use-after-free path.\n\n#### Sequencing Ownership Transfer\n\nPrefer a consuming standard-library or project API such as `into_raw` or\n`into_raw_parts` that ends the old ownership state while yielding the raw\ncomponents.\n\nWhen manual extraction is unavoidable, disable the old owner's automatic `Drop`\n(e.g. using `std::mem::ManuallyDrop`) before constructing any replacement owner.\nAfter the replacement owner exists, do not read, move, pass, forget, or\notherwise use the invalidated old value. Audit every possible panic and\nearly-return point: failure may leak, but must not create two destructors for\nthe same resource or permit access through an invalid owner.\n\n### 8. Safe trait law relied on for memory safety `[rej.trait-law]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: `iter.len()` tells us exactly how many elements will be yielded.\nunsafe {\n    write_items_without_capacity_checks(iter, dst, iter.len());\n}\n```\n\nA caller-provided safe trait implementation may lie unless the property is\nenforced by an unsafe trait contract, trusted dependency implementation, dynamic\nvalidation, or the type system.\n\nRequire:\n\n```rust\n\u002F\u002F SAFETY:\n\u002F\u002F This proof does not rely on caller-provided `ExactSizeIterator::len` for\n\u002F\u002F memory safety. Capacity is checked before every write, and `set_len` is called\n\u002F\u002F only for the number of elements actually initialized.\n```\n\n### 9. Callback cannot panic or reenter `[rej.no-panic]`\n\nReject:\n\n```rust\n\u002F\u002F SAFETY: The callback just fills the buffer.\ncallback(&mut tmp);\nunsafe { tmp.set_len(n) }\n```\n\nA caller-provided safe callback may panic, reenter, or mutate reachable state\nthrough safe mechanisms. If invariants are temporarily broken, use guards or\navoid callbacks until invariants are restored.\n\n### 10. Dependency trust confused with caller trust `[rej.dep-vs-caller]`\n\nReject:\n\n```rust\nv.sort_by(caller_comparator);\n\u002F\u002F SAFETY: `Vec::sort_by` sorts the vector, so binary search invariants hold.\nunsafe { rely_on_sortedness_for_memory_safety(&v) }\n```\n\n`Vec::sort_by` may be trusted as a std dependency, but the caller-provided\ncomparator is not trusted for memory-safety-relevant semantic correctness. If\nsortedness is memory-safety-critical, validate it or require an unsafe contract.\n\n### 11. Proof by reading another function's body `[rej.other-body]`\n\nReject proofs that refer to the implementation (body) of another function\n(including a caller, a callee, or a callback being passed around).\n\nException: closures and `fn` items nested inside the function under review are\nlocal code, and the proof may rely on their bodies (`[conv.nested-fn]`).\nStating the fact on the nested item is still preferred.\n\nRequire facts about other functions to be established in their documentation\ncomments. Unsafe functions state their postconditions in the `# Safety` section.\nSafe functions use the `# Safety-usable invariant` section. Proofs cite these\nfacts.\n\nGiven:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `callback` must be `None` or a function that, when called with a `ctx` that\n\u002F\u002F\u002F points to a live `Ctx` and that nothing else accesses for the duration of\n\u002F\u002F\u002F the call, returns null or an unlinked node allocated through `ctx`'s\n\u002F\u002F\u002F allocator. The parser takes ownership of the returned node.\npub unsafe fn register_callback(\n    reg: &mut Registry,\n    callback: Option\u003Cunsafe extern \"C\" fn(*mut Ctx) -> *mut Node>,\n);\n```\n\nReject:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ctx` must point to a live `Ctx` that nothing else accesses for the\n\u002F\u002F\u002F duration of the call.\npub unsafe extern \"C\" fn my_callback(ctx: *mut Ctx) -> *mut Node { ... }\n\n\u002F\u002F SAFETY: The implementation of `my_callback` meets `register_callback`'s\n\u002F\u002F contract: it returns null or an unlinked node allocated through `ctx`'s\n\u002F\u002F allocator.\nunsafe { register_callback(reg, Some(my_callback)) };\n```\n\nAccept:\n\n```rust\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F\n\u002F\u002F\u002F `ctx` must point to a live `Ctx` that nothing else accesses for the\n\u002F\u002F\u002F duration of the call.\n\u002F\u002F\u002F\n\u002F\u002F\u002F If these preconditions hold, returns null or an unlinked node allocated\n\u002F\u002F\u002F through `ctx`'s allocator.\npub unsafe extern \"C\" fn my_callback(ctx: *mut Ctx) -> *mut Node { ... }\n\n\u002F\u002F SAFETY: `my_callback`'s `# Safety` preconditions are those\n\u002F\u002F `register_callback`'s contract guarantees its caller provides, and its\n\u002F\u002F postcondition is what that contract requires of the return value.\nunsafe { register_callback(reg, Some(my_callback)) };\n```\n\n## Safe dependency and caller-provided code review rules `[dep]`\n\n### Rule A: Intentionally selected safe dependencies may be trusted as documented `[dep.selected]`\n\nWhen this crate intentionally uses a safe dependency API, the proof may assume\nthe API behaves as documented.\n\nExamples:\n\n```rust\nlet mut v = vec![3, 1, 2];\nv.sort();\n\u002F\u002F A proof may assume the standard library sort implementation performs its\n\u002F\u002F documented operation, subject to the behavior of the `Ord` implementation.\n```\n\n```rust\nlet n = trusted_dependency::parse_header(bytes)?;\n\u002F\u002F A proof may rely on `parse_header` returning the documented result if this\n\u002F\u002F crate has intentionally chosen and audited\u002Ftrusted that dependency contract.\n```\n\nHowever, this is a project trust assumption. It should be explicit when\nproof-relevant and should be version-aware for third-party dependencies.\n\n### Rule B: Caller-provided safe code is adversarial `[dep.caller-adversarial]`\n\nDo not rely on caller-provided safe code for memory-safety-relevant semantics.\n\nExamples of invalid assumptions:\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Ord` is a total order.\nT: Ord\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Iterator::size_hint` is accurate.\niter.size_hint()\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Hash` is consistent with `Eq`.\nT: Hash + Eq\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Clone` returns an equivalent value.\nx.clone()\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided callback will not panic.\nf()\n```\n\n```rust\n\u002F\u002F Invalid for safety: caller-provided `Drop` has no side effects.\ndrop(x)\n```\n\n### Rule C: Safe trait laws are not safety contracts `[dep.trait-laws]`\n\nA safe trait's documentation may impose semantic laws, but violating those laws\nmust not cause UB in your unsafe abstraction. If unsafe code must rely on a law,\nmake the trait unsafe, use an existing unsafe trait with the required contract,\nvalidate dynamically, or constrain implementations to trusted types.\n\n#### Sealed-trait reliance must be airtight `[dep.sealed]`\n\nA sealed safe trait may be treated as trusted only if the proof establishes that\nall implementations are controlled by this crate or by a trusted opted-in\ndependency. \"This trait is sealed\" is itself a proof obligation, not a\nconclusion.\n\nFor a sealed-trait argument to discharge a memory-safety obligation, prove all\nof the following:\n\n-   downstream crates cannot implement the trait directly;\n-   downstream crates cannot implement the trait indirectly through a public\n    supertrait, blanket impl, associated type escape hatch, marker type,\n    macro-generated impl hook, feature-gated impl hook, re-exported private\n    token, or type alias;\n-   downstream safe code cannot construct, name, clone, deserialize, or\n    otherwise obtain any sealing token through any safe public surface;\n-   public fields, public constructors, re-exports, macros, proc macros, or\n    generated code cannot create values that claim the sealed invariant without\n    going through reviewed constructors;\n-   every cfg and feature combination preserves sealing;\n-   every existing implementation that can reach the unsafe code is reviewed and\n    maintains the required invariant;\n-   future implementations are forced through the same unsafe-code review gate,\n    for example by being inside the crate or inside a reviewed trusted\n    dependency;\n-   future semver-compatible implementation additions, feature additions, or\n    macro expansion changes cannot silently admit dishonest downstream behavior\n    without forcing re-audit;\n-   the semantic law being relied on is documented as an invariant of the sealed\n    trait, even if the trait itself is safe;\n-   the proof does not rely on caller-controlled generic parameters inside the\n    implementation unless those parameters are constrained by an unsafe\n    contract, dynamic checks, type-system facts, or trusted dependency\n    implementations.\n\nDo not require an abstraction to remain sound after downstream unsafe code\nforges an invalid token with `transmute` or otherwise violates an unsafe\ncontract. A project may separately review robustness against hostile unsafe\nclients or corrupted FFI input, but that is not part of the ordinary safe-client\nsealing proof.\n\nIf sealing is not airtight, treat the implementation as caller-provided safe\ncode. Then the law is not a valid memory-safety premise unless it is dynamically\nchecked, moved into an unsafe trait contract, or avoided entirely.\n\nA private trait is not automatically sealed for review purposes. Check macro\nexpansion, feature gates, visibility boundaries, re-exports, blanket impls, and\ndownstream extension points before relying on private or sealed status. A safe\ntrait method with a default body is still caller-influenced if downstream code\ncan implement the trait, override methods, choose associated types\u002Fconstants, or\nprovide values that the default method uses to establish a\nmemory-safety-relevant fact.\n\n### Rule D: Dependencies invoking caller code inherit caller-code distrust `[dep.transitive]`\n\nIf a trusted dependency calls a caller-provided closure, comparator, allocator,\ntrait method, or callback, the dependency's trust does not make that\ncaller-provided code trustworthy.\n\nProofs must separate:\n\n```text\nTrusted: dependency implementation follows its documented behavior.\nUntrusted: caller-provided callback or trait implementation may behave arbitrarily within its safe type signature.\n```\n\n### Rule E: Safe code may be safe but still hostile to invariants `[dep.hostile]`\n\nSafe caller-provided code cannot be assumed to preserve your undocumented\ninvariants. It may observe or mutate through any safe capability you give it.\nTherefore:\n\n-   Do not expose uninitialized or partially initialized storage to caller code\n    as initialized `T`, `&T`, `&mut T`, `[T]`, or any other type whose validity\n    requires initialization. Typed exposure as `MaybeUninit\u003CT>` (e.g.\n    `Vec::spare_capacity_mut`) may be sound when the API keeps initialized\n    length\u002Fownership metadata accurate and does not let safe caller actions\n    cause uninitialized storage to be read, dropped, or otherwise treated as\n    `T`.\n-   Do not call callbacks while `Vec::len` is inconsistent with initialized\n    elements.\n-   Do not hold invalid references across calls to unknown code.\n-   Do not assume locks, refcells, or globals remain unchanged across unknown\n    calls.\n-   Do not assume unknown `Drop` implementations are inert.\n-   Do not assume unknown trait methods are deterministic.\n\n## Reference creation is the unsafe operation `[ref.creation]`\n\nCreating a Rust reference-like value from raw parts is itself a safety\nassertion. The operation being justified is not merely the later load, store,\nslice access, or method call. The proof must establish that the reference-like\nvalue is valid at the exact moment it is created.\n\nThis applies to creating or reconstructing:\n\n-   `&T`;\n-   `&mut T`;\n-   `&[T]`;\n-   `&mut [T]`;\n-   `&str`;\n-   `&CStr`;\n-   `Box\u003CT>`;\n-   `Pin\u003C&mut T>` or `Pin\u003CBox\u003CT>>`;\n-   trait-object references;\n-   any other value whose type carries Rust reference, ownership, aliasing,\n    lifetime, or validity guarantees.\n\nThe proof for reference creation must establish every relevant obligation at\ncreation time:\n\n-   non-nullness where the reference-like type requires it;\n-   alignment for the referenced type;\n-   all pointed-to bytes are in live allocations for the full referenced extent;\n-   initialization and Rust value validity for the referenced type (or, if\n    temporarily pointing to uninitialized memory without reading or dropping it,\n    explicit documentation per\n    [Uninitialized memory behind references (`UCG#414`)](#uninitialized-memory-behind-references-ucg414));\n-   correct metadata for slices and trait objects;\n-   no violation of shared-reference immutability rules;\n-   no violation of mutable-reference exclusivity rules;\n-   the referenced value outlives the produced lifetime;\n-   the resulting reference does not overstate the real ownership, pinning,\n    lifetime, or mutation permissions.\n\nPrefer the narrowest reference possible, created as late as possible, and held\nfor the shortest possible lifetime. Do not create a broad `&mut [T]` merely to\naccess one element. Do not create a reference if raw pointer operations can\nexpress the actual invariant more honestly.\n\nNarrowness is only an auditing discipline. A narrow reference must still be\nvalid at the point of creation. A one-element `&mut T` is unsound if another\nlive reference aliases that element. A zero-length slice reference may still\nneed a non-null aligned pointer if the constructor's documented contract\nrequires it. A short-lived reference to misaligned, dangling, or aliased memory\nis still UB.\n\nDo not accept a proof that says only \"the reference is as narrow as possible.\"\nThat proves at most that the author reduced the size of the assertion. It does\nnot prove that the assertion is true. The proof must still establish each\nvalidity, aliasing, lifetime, and metadata obligation at creation time.\n\n### Uninitialized memory behind references (`UCG#414`) `[ref.uninit]` {#uninitialized-memory-behind-references-ucg414}\n\nPer\n[Rust Unsafe Code Guidelines Issue #414](https:\u002F\u002Fgithub.com\u002Frust-lang\u002Funsafe-code-guidelines\u002Fissues\u002F414)\n(and the\n[Rust Reference on undefined behavior](https:\u002F\u002Fdoc.rust-lang.org\u002Freference\u002Fbehavior-considered-undefined.html)),\nthe validity invariant of a reference (`&T`, `&mut T`, `&[T]`, `&mut [T]`) is\nshallow: it does **not** depend on the initialized contents of the pointed-to\nmemory. Merely constructing a reference or slice reference to uninitialized\nmemory is **not** immediate UB, provided the pointer is non-null, properly\naligned, dereferenceable for the full extent of `T`, and obeys Rust's aliasing\nrules.\n\nHowever, having references temporarily point to uninitialized memory is still\nrisky. When reviewing or authoring code involving uninitialized memory, apply\nthe following distinctions strictly:\n\n1.  **Actual Soundness Violations (Undefined Behavior)**:\n    -   **Uninitialized stack\u002Fby-value `T` or reads**: Producing an\n        uninitialized value `T` by value (e.g., an uninitialized stack variable,\n        `MaybeUninit::assume_init()`, `ptr::read`, `mem::transmute`, or reading\n        through `*r` before initialization) is immediate UB for any type `T`\n        whose validity invariant requires initialized bytes (such as integers,\n        floats, `bool`, `char`, references, `Box`, enums, or structs containing\n        them).\n    -   **Overwriting uninitialized `&mut T` when `T` has drop glue**: Assigning\n        `*r = val` through `r: &mut T` evaluates the place `*r` and drops the\n        existing value in place before writing `val`. If `*r` is uninitialized\n        and `T` has drop glue (`core::mem::needs_drop::\u003CT>()`), `*r = val` drops\n        uninitialized memory, which is immediate UB. Overwriting `*r = val` on\n        uninitialized memory is sound **only** when `T` is `Copy` or trivially\n        has no drop glue; otherwise, `ptr::write` or `MaybeUninit` is required.\n    -   **Exposing uninitialized references to code that assumes\n        initialization**: Returning or passing `&T`, `&mut T`, `&[T]`, or `&mut\n        [T]` pointing to uninitialized memory across a safe public API boundary,\n        to untrusted callbacks, or to internal code that is not documented as\n        accepting uninitialized references is unsound, because ordinary Rust\n        code is entitled to read from `&T`\u002F`&[T]`\u002F`&mut T` or assign to `&mut T`\n        (running drop glue). Passing or returning an uninitialized reference to\n        an `unsafe` function or internal helper is only sound when that boundary\n        explicitly documents that the reference may be uninitialized so the Rust\n        code handling it knows not to read or drop it (e.g., using `ptr::write`\n        or only assigning when `T` has no drop glue).\n2.  **Sound Reference Creation to Uninitialized Memory (Documentation\n    Obligation)**:\n    -   If `&T`, `&mut T`, `&[T]`, or `&mut [T]` is created pointing to\n        uninitialized memory and is **not** used unsafely (i.e., it is never\n        read before initialization, never assigned via `*r = val` when `T` has\n        drop glue, and never passed to code that assumes initialization), the\n        code is **sound**.\n    -   **Review classification**: Treat undocumented creation or passing of a\n        reference or slice to uninitialized memory as **Incomplete Safety\n        Documentation** (the same severity and category as a missing or\n        incomplete safety comment, **not** a soundness bug).\n    -   **Required documentation**: Require that the code document *somehow* (in\n        a `\u002F\u002F SAFETY:` comment or function\u002Fhelper comment) that the reference\n        may point to uninitialized memory and how it is handled safely (e.g.,\n        that it is only written to via `ptr::write` or `*r = val` on a\n        `Copy`\u002Fno-drop-glue type, and never read before initialization). The\n        comment does **not** need to explicitly cite\n        [UCG#414](https:\u002F\u002Fgithub.com\u002Frust-lang\u002Funsafe-code-guidelines\u002Fissues\u002F414)\n        (though reviewers may reference UCG#414 when explaining why this pattern\n        is sound). Recommend `MaybeUninit\u003CT>` or raw pointers (`*mut T` \u002F\n        `ptr::write`) as preferred alternatives where practical, but **accept\n        the code as sound** once the uninitialized state is documented.\n3.  **FFI Out-Parameters (`&mut T` \u002F `Option\u003C&mut T>`)**:\n    -   C and C++ callers routinely pass pointers to uninitialized stack\n        variables as out-parameters (e.g., `size_t out; ffi_fn(&out);`), and\n        header generators like `cbindgen` map `Option\u003C&mut T>` to `T*` while\n        failing to unwrap `MaybeUninit\u003CT>`.\n    -   Accept `pub extern \"C\" fn` (and internal FFI helpers) that take `&mut T`\n        or `Option\u003C&mut T>` for C\u002FC++ out-parameters when `T` is `Copy` (or has\n        no drop glue) and the implementation only writes to `*out` (or\n        initializes it via `ptr::write`) without reading or dropping it first.\n        Because Rust code handling `*out` must know that the value may be\n        uninitialized so it can handle it properly (e.g., using `ptr::write` or\n        avoiding reads\u002Fdrops), this should be documented *somehow* (e.g., in the\n        function\u002Fhelper doc comment or an enclosing comment, without needing a\n        `UCG#414` citation); if completely undocumented, flag it as **Incomplete\n        Safety Documentation** (not a soundness bug).\n\n`UnsafeCell` is not a general aliasing eraser. It permits interior mutation\nthrough shared references only for a pointed-to `UnsafeCell` value itself. A\nshared reference `&T` where `T` contains `UnsafeCell` allows mutating the cell\ncontents safely (e.g. via `Cell::set`), but creating `&mut T` while a shared\n`&T` exists is still undefined behavior, even if no code reads or writes the\n`UnsafeCell`. Similarly, mutating a shared reference value directly without\ngoing through `UnsafeCell` is UB.\n\n## High-Risk Hazard Checklists `[hazard]`\n\nReviewers must explicitly audit the following high-risk Rust soundness hazards:\n\n1.  **`unsafe impl Send` \u002F `unsafe impl Sync` vs. Thread-Affinity & Unsynchronized Shared Mutation `[hazard.send-sync]`**:\n    `Send` allows moving a value to *another* OS thread; `Sync` (`&T: Send`)\n    allows concurrent access from *multiple* OS threads. A comment claiming\n    \"only used on one thread\" or \"wrapped in thread-local storage by callers\"\n    does **not** make a publicly or module-accessible wrapper type safely `Send`\n    or `Sync` unless the type's API prevents cross-thread transfer or\n    unsynchronized interior mutation (`*mut T`, `UnsafeCell`, raw FFI handles).\n2.  **Safe Public\u002FModule Functions Wrapping `unsafe` Operations `[hazard.safe-fn-wrap]`**:\n    Any safe `fn` (without the `unsafe` keyword) that converts raw pointers,\n    offsets, or indices into references\u002Fslices (`slice::from_raw_parts`,\n    `&*ptr`, `ptr.add`, `offset_from`, `get_unchecked`) or passes\n    caller-controlled pointers\u002Flengths to FFI without validating bounds,\n    alignment, non-nullness, and lifetime tying is **unsound** (it must either\n    validate all preconditions at runtime or be marked `unsafe fn` with a\n    `# Safety` section).\n3.  **Lifetime & Mutability Upgrade Scrutiny (`&self` -> `&mut T` \u002F `'a` -> `'static`) `[hazard.lifetime-mut]`**:\n    Upgrading `&self` to `&mut T` (via raw pointer casts or `UnsafeCell` without\n    a runtime borrow flag, `Mutex`, or `&mut self` witness) or extending a\n    lifetime `'a` to `'static` (e.g. for async tasks, threads, or callbacks)\n    without guaranteeing the pointee outlives all possible uses is immediate\n    aliasing or use-after-free UB.\n4.  **Cross-Allocation Pointer Arithmetic & Provenance `[hazard.provenance]`**:\n    `ptr::offset_from`, `ptr::add`, and `slice::from_raw_parts` require both\n    pointers (or the start and end of the range) to be derived from the **same\n    allocation** (`allocated object`). Computing offsets between arbitrary slice\n    references or separate heap allocations is immediate UB in Rust even if only\n    used as a diagnostic offset. Paired ownership\u002Fallocation APIs (`into_raw*`\n    and `from_raw*`, `alloc` and `dealloc`) must also preserve allocation\n    identity, layout, and drop symmetry across empty (`is_empty()`) and ZST\n    (`size_of::\u003CT>() == 0`) branches.\n5.  **Pre-Check Against Callee\u002FTrait Encapsulation Before Flagging `[hazard.encapsulation]`**:\n    Before flagging a caller of an `unsafe` helper or macro, inspect the\n    definition of the helper or trait in the same module\u002Fcrate to check whether\n    preconditions (such as alignment, `size_of::\u003CT>()` bounds, or `repr(C)`) are\n    already enforced by `const` assertions, trait bounds (e.g., `FromBytes`,\n    `IntoBytes`, `Immutable`), or constructor invariants.\n\n### Four-Item Edge-Domain Checklist `[hazard.edge-domain]`\n\nExplicitly substitute these four boundary cases into every `unsafe` expression\nbefore concluding it is sound:\n\n1.  **Zero-Sized Types & Zero Lengths (`size_of::\u003CT>() == 0`, `len == 0`)**:\n    Does `Box::into_raw` or `Vec::as_ptr` yield `NonNull::dangling()` when\n    `size_of::\u003CT>() == 0` or `cap == 0` (violating \"allocated by `A`\" invariants\n    when `len > 0` on `[(); N]` or dropping the allocator early)? Does `len == 0`\n    get passed to foreign functions that compute `len - 1` or dereference\n    `ptr[0]`?\n2.  **Allocator Alignment & Signed\u002FUnsigned Casts (`0 \u003C size \u003C align`, `c_int \u003C 0`, `usize -> u32`)**:\n    When implementing `Allocator` or `GlobalAlloc` over C\n    `malloc`\u002F`calloc`\u002F`realloc`, can `0 \u003C layout.size() \u003C layout.align()` return\n    an under-aligned pointer? Can a signed integer (`c_int`, `isize`, `i32`) be\n    negative before `as usize`, or can `usize` truncate when cast to `u32`\u002F`i32`?\n    Are all signed\u002Funsigned type tags handled without panicking across\n    non-unwind FFI boundaries?\n3.  **Pointer Stride & Final-Iteration Stepping (`i == n - 1`)**:\n    Does `.add(stride)` or `.offset(stride)` on the **final loop iteration**\n    step more than one byte past the end of the allocation (which is immediate\n    UB even if not dereferenced)?\n4.  **`core::mem::forget` & Drop-Based Lifetime Guards**:\n    Does a safe API pass a non-`'static` borrow or pointer (`'a`) to a\n    background thread, FFI callback, or hardware\u002FDMA table and rely on `Drop` to\n    stop access before `'a` ends (or implement `Deref` on a static wrapper\n    without requiring `'static`)? Because `core::mem::forget` is safe, relying\n    on `Drop` for soundness of borrowed lifetimes is unsound.\n\n",{"name":5,"description":7},"main","34b87c594bf7386290a1e3698d5b8e06b6b9edd7","unsafe_rust_review",8,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills","https:\u002F\u002Fgithub.com\u002Fgoogle","https:\u002F\u002Fopensource.google\u002F","Google ❤️ Open Source","2026-10-28 08:29:24",{"source":9,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add google\u002Frust-skills --skill unsafe-rust-review",{"tool":55,"command":56},"bunx","bunx skills add google\u002Frust-skills --skill unsafe-rust-review",{"tool":58,"command":59},"pnpm","pnpm dlx skills add google\u002Frust-skills --skill unsafe-rust-review","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002FSKILL.md",true,[63,69,73,79,83,87,91],{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":68},"EVAL.yml","REFERENCE","参考文档",3888,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002FEVAL.yml",{"path":70,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":71,"sourceHtmlUrl":72},"README.md",1262,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002FREADME.md",{"path":74,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":77,"sourceHtmlUrl":78},"testcases\u002Ftest1.rs","SCRIPT","脚本",866,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002Ftestcases\u002Ftest1.rs",{"path":80,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":81,"sourceHtmlUrl":82},"testcases\u002Ftest2.rs",748,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002Ftestcases\u002Ftest2.rs",{"path":84,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":85,"sourceHtmlUrl":86},"testcases\u002Ftest3.rs",684,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002Ftestcases\u002Ftest3.rs",{"path":88,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":89,"sourceHtmlUrl":90},"testcases\u002Ftest4.rs",1881,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002Ftestcases\u002Ftest4.rs",{"path":92,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":93,"sourceHtmlUrl":94},"testcases\u002Ftest5.rs",1721,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review\u002Ftestcases\u002Ftest5.rs",[96,107,117,125,133,140],{"skillNo":97,"name":98,"nameZh":99,"description":100,"descriptionZh":101,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":102,"categories":103,"keywords":106,"publishedAt":35},"01M6996CWZ1D0A267DVXYS6AD3","unsafe-rust","Unsafe Rust 代码编写与审计","Author, document, review, audit, or redesign unsafe Rust with proof-grade rigor. Use for unsafe blocks and functions, unsafe traits and impls, raw pointers, FFI, inline assembly, intrinsics, layout or validity reasoning, concurrency and atomics, SIMD and target features, allocators, invariant-bearing fields, safety comments or `# Safety` documentation, soundness reviews, TCB audits, generated unsafe code, changes to safety or behavioral contracts, and proof-oriented redesign of unsafe abstractions.","以证明级别的严谨性编写、文档化、审查、审计或重新设计 unsafe Rust 代码。适用于 unsafe 块与函数、unsafe trait 及其实现、裸指针、FFI、内联汇编、intrinsics（内部函数）、内存布局或有效性推理、并发与原子操作、SIMD 与目标特性、分配器、承载不变量的字段、安全注释或 `# Safety` 文档、可靠性（soundness）审查、TCB（可信计算基）审计、生成的 unsafe 代码、安全性或行为契约的变更，以及以证明为导向的 unsafe 抽象重构。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review_experimental\u002Fevals\u002Funsafe-rust\u002Ffrozen-packages\u002Fd97b9ace50109216614fbb7c975ac9c97508bfa928381d247869699593a2bcdd\u002FSKILL.md",[104,105],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[33,32,31],{"skillNo":108,"name":98,"nameZh":109,"description":110,"descriptionZh":111,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":112,"categories":113,"keywords":116,"publishedAt":35},"01M6996AY793ZYDM664FGXV2A5","Unsafe Rust 编写与审计","Author, document, review, or audit unsafe Rust with proof-grade rigor. Use for unsafe blocks and functions, unsafe traits and impls, raw pointers, FFI, inline assembly, intrinsics, layout or validity reasoning, concurrency and atomics, SIMD and target features, allocators, invariant-bearing fields, safety comments or `# Safety` documentation, soundness reviews, TCB audits, generated unsafe code, and changes to safety or behavioral contracts.","以证明级的严谨性编写、记录、审查或审计 unsafe Rust。适用于 unsafe 块与函数、unsafe trait 及其 impl、裸指针、FFI、内联汇编、intrinsics（内部函数）、布局或有效性推理、并发与原子操作、SIMD 与目标特性、分配器、承载不变量的字段、安全注释或 `# Safety` 文档、可靠性（soundness）审查、TCB 审计、生成的 unsafe 代码，以及安全性或行为契约的变更。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review_experimental\u002Fevals\u002Funsafe-rust\u002Ffrozen-packages\u002F7ae4d42abd086720ed97bf1ef8b22f66b1d0ed33a0a5834b17eebfdc245c4d52\u002FSKILL.md",[114,115],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[33,32,31],{"skillNo":118,"name":98,"nameZh":109,"description":100,"descriptionZh":119,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":120,"categories":121,"keywords":124,"publishedAt":35},"01M69968MPGB3Y7R7Q36TNE4K7","以证明级的严谨性编写、记录、审查、审计或重新设计 unsafe Rust。适用于 unsafe 块与函数、unsafe trait 及其 impl、裸指针、FFI、内联汇编、intrinsics（内部函数）、布局或有效性推理、并发与原子操作、SIMD 与目标特性、分配器、承载不变量的字段、安全注释或 `# Safety` 文档、可靠性（soundness）审查、TCB 审计、生成的 unsafe 代码、安全性或行为契约的变更，以及面向证明的 unsafe 抽象重新设计。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review_experimental\u002Fevals\u002Funsafe-rust\u002Ffrozen-packages\u002F6d7e197e431b82eb81dbe7eefc79fde811e0e238435d38c69460cc068e631abb\u002FSKILL.md",[122,123],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[33,32,31],{"skillNo":126,"name":98,"nameZh":99,"description":100,"descriptionZh":127,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":128,"categories":129,"keywords":132,"publishedAt":35},"01M69966CDRPGH59Y5K89HFC3A","以证明级的严谨度编写、记录、评审、审计或重构不安全（unsafe）Rust 代码。适用于 unsafe 代码块与函数、unsafe trait 及其实现、裸指针、FFI、内联汇编、内建函数（intrinsics）、内存布局与有效性推理、并发与原子操作、SIMD 与目标特性、分配器、承载不变量的字段、安全注释或 `# Safety` 文档、健全性（soundness）评审、TCB（可信计算基）审计、生成的 unsafe 代码、安全或行为契约的变更，以及面向证明的 unsafe 抽象重构。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review_experimental\u002Fevals\u002Funsafe-rust\u002Ffrozen-packages\u002F668f70202c7bc8f23f7f894fb784a9629fd292c7f6fe69ede815b0e4c10137bf\u002FSKILL.md",[130,131],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[33,32,31],{"skillNo":134,"name":98,"nameZh":99,"description":100,"descriptionZh":127,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":135,"categories":136,"keywords":139,"publishedAt":35},"01M699648E197V2VZSB9A6MDQH","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review_experimental\u002Fevals\u002Funsafe-rust\u002Ffrozen-packages\u002F40b4171cc9daf7e51ba032aef52157a85a49c4c12cea8696deadb948e0867897\u002FSKILL.md",[137,138],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[33,32,31],{"skillNo":141,"name":98,"nameZh":109,"description":100,"descriptionZh":142,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":143,"categories":144,"keywords":147,"publishedAt":35},"01M699620EM56Z34VVN83YDPYA","以证明级严谨性编写、记录、审查、审计或重新设计 unsafe Rust。用于 unsafe 块与函数、unsafe trait 与 impl、裸指针、FFI、内联汇编、intrinsics、布局或有效性推理、并发与原子操作、SIMD 与目标特性、分配器、承载不变量的字段、安全注释或 `# Safety` 文档、健全性审查、TCB 审计、生成的 unsafe 代码、对安全或行为契约的更改，以及 unsafe 抽象面向证明的重新设计。","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Frust-skills\u002Fblob\u002Fmain\u002Funsafe_rust_review_experimental\u002Fevals\u002Funsafe-rust\u002Ffrozen-packages\u002F072a5c9d1b0000d04986f92a62ecc0ee2c7ff60c931c3fcd500128739c06c106\u002FSKILL.md",[145,146],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[32,33,31]]