πŸ¦€/πŸ”¬/17. Reference Card

Reference Card

Quick-reference for all 14+ correct-by-construction patterns with selection flowchart, pattern catalogue, composition rules, crate mapping, and types-as-guarantees cheat sheet.

Cross-references: Every chapter β€” this is the lookup table for the entire book.

Quick Reference: Correct-by-Construction Patterns

Pattern Selection Guide

Is the bug catastrophic if missed?
β”œβ”€β”€ Yes β†’ Can it be encoded in types?
β”‚         β”œβ”€β”€ Yes β†’ USE CORRECT-BY-CONSTRUCTION
β”‚         └── No  β†’ Runtime check + extensive testing
└── No  β†’ Runtime check is fine

Pattern Catalogue

#PatternKey Trait/TypePreventsRuntime CostChapter
1Typed Commandstrait IpmiCmd { type Response; }Wrong response typeZeroch02
2Single-Use Typesstruct Nonce (not Clone/Copy)Nonce/key reuseZeroch03
3Capability Tokensstruct AdminToken { _private: () }Unauthorised accessZeroch04
4Type-StateSession<Active>Protocol violationsZeroch05
5Dimensional Typesstruct Celsius(f64)Unit confusionZeroch06
6Validated Boundariesstruct ValidFru (via TryFrom)Unvalidated data useParse oncech07
7Capability Mixinstrait FanDiagMixin: HasSpi + HasI2cMissing bus accessZeroch08
8Phantom TypesRegister<Width16>Width/direction mismatchZeroch09
9Sentinel β†’ OptionOption<u8> (not 0xFF)Sentinel-as-value bugsZeroch11
10Sealed Traitstrait Cmd: private::SealedUnsound external implsZeroch11
11Non-Exhaustive Enums#[non_exhaustive] enum SkuSilent match fallthroughZeroch11
12Typestate BuilderDerBuilder<Set, Missing>Incomplete constructionZeroch11
13FromStr Validationimpl FromStr for DiagLevelUnvalidated string inputParse oncech11
14Const-Generic SizeRegisterBank<const N: usize>Buffer size mismatchZeroch11
15Safe unsafe WrapperMmioRegion::read_u32()Unchecked MMIO/FFIZeroch11
16Async Type-StateAsyncSession<Active>Async protocol violationsZeroch11
17Const AssertionsSdrSensorId<const N: u8>Invalid compile-time IDsZeroch11
18Session TypesChan<SendRequest>Out-of-order channel opsZeroch11
19Pin Self-ReferentialPin<Box<StreamParser>>Dangling intra-struct pointerZeroch11
20RAII / Dropimpl Drop for SessionResource leak on any exit pathZeroch11
21Error Type Hierarchy#[derive(Error)] enum DiagErrorSilent error swallowingZeroch11
22#[must_use]#[must_use] struct TokenSilently dropped valuesZeroch11

Composition Rules

Capability Token + Type-State = Authorised state transitions
Typed Command + Dimensional Type = Physically-typed responses
Validated Boundary + Phantom Type = Typed register access on validated config
Capability Mixin + Typed Command = Bus-aware typed operations
Single-Use Type + Type-State = Consume-on-transition protocols
Sealed Trait + Typed Command = Closed, sound command set
Sentinel β†’ Option + Validated Boundary = Clean parse-once pipeline
Typestate Builder + Capability Token = Proof-of-complete construction
FromStr + #[non_exhaustive] = Evolvable, fail-fast enum parsing
Const-Generic Size + Validated Boundary = Sized, validated protocol buffers
Safe unsafe Wrapper + Phantom Type = Typed, safe MMIO access
Async Type-State + Capability Token = Authorised async transitions
Session Types + Typed Command = Fully-typed request-response channels
Pin + Type-State = Self-referential state machines that can't move
RAII (Drop) + Type-State = State-dependent cleanup guarantees
Error Hierarchy + Validated Boundary = Typed parse errors with exhaustive handling
#[must_use] + Single-Use Type = Hard-to-ignore, hard-to-reuse tokens

Anti-Patterns to Avoid

Anti-PatternWhy It's WrongCorrect Alternative
fn read_sensor() -> f64Unitless β€” could be Β°C, Β°F, or RPMfn read_sensor() -> Celsius
fn encrypt(nonce: &[u8; 12])Nonce can be reused (borrow)fn encrypt(nonce: Nonce) (move)
fn admin_op(is_admin: bool)Caller can lie (true)fn admin_op(_: &AdminToken)
fn send(session: &Session)No state guaranteefn send(session: &Session<Active>)
fn process(data: &[u8])Not validatedfn process(data: &ValidFru)
Clone on ephemeral keysDefeats single-use guaranteeDon't derive Clone
let vendor_id: u16 = 0xFFFFSentinel carried internallylet vendor_id: Option<u16> = None
fn route(level: &str) with fallbackTypos silently defaultlet level: DiagLevel = s.parse()?
Builder::new().finish() without fieldsIncomplete object constructedTypestate builder: finish() gated on Set
let buf: Vec<u8> for fixed-size HW bufferSize only checked at runtimeRegisterBank<4096> (const generic)
Raw unsafe { ptr::read(...) } scatteredUB risk, unauditableMmioRegion::read_u32() safe wrapper
async fn transition(&mut self)Mutable borrows don't enforce stateasync fn transition(self) -> NextState
fn cleanup() called manuallyForgotten on early return / panicimpl Drop β€” compiler inserts call
fn op() -> Result<T, String>Opaque error, no variant matchingfn op() -> Result<T, DiagError> enum

Mapping to a Diagnostics Codebase

ModuleApplicable Pattern(s)
protocol_libTyped commands, type-state sessions
thermal_diagCapability mixins, dimensional types
accel_diagValidated boundaries, phantom registers
network_diagType-state (link training), capability tokens
pci_topologyPhantom types (register width), validated config, sentinel β†’ Option
event_handlerSingle-use audit tokens, capability tokens, FromStr (Component)
event_logValidated boundaries (SEL record parsing)
compute_diagDimensional types (temperature, frequency)
memory_diagValidated boundaries (SPD data), dimensional types
switch_diagType-state (port enumeration), phantom types
config_loaderFromStr (DiagLevel, FaultStatus, DiagAction)
log_analyzerValidated boundaries (CompiledPatterns)
diag_frameworkTypestate builder (DerBuilder), session types (orchestrator↔worker)
topology_libConst-generic register banks, safe MMIO wrappers

Types as Guarantees β€” Quick Mapping

GuaranteeRust EquivalentExample
"This proof exists"A typeAdminToken
"I have the proof"A value of that typelet tok = authenticate()?;
"A implies B"Function fn(A) -> Bfn activate(AdminToken) -> Session<Active>
"Both A and B"Tuple (A, B) or multi-paramfn op(a: &AdminToken, b: &LinkTrained)
"Either A or B"enum { A(A), B(B) } or Result<A, B>Result<Session<Active>, Error>
"Always true"() (unit type)Always constructible
"Impossible"! (never type) or enum Void {}Can never be constructed