# Rust Development Guidelines Reference
Rust coding conventions for this repository.
Agents must follow these rules when modifying or adding Rust code.
---
## Contents
- [Core Principles](#core-principles)
- [Safety](#safety)
- [Dimension Generic Architecture](#dimension-generic-architecture)
- [Numeric Conversions](#numeric-conversions)
- [Borrowing and Ownership](#borrowing-and-ownership)
- [Error Handling](#error-handling)
- [Fluent Workflow APIs](#fluent-workflow-apis)
- [Constructor Naming](#constructor-naming)
- [Panic Policy](#panic-policy)
- [Error Types](#error-types)
- [Orthogonal variants](#orthogonal-variants)
- [Struct‑with‑named‑fields throughout](#structwithnamedfields-throughout)
- [Preserve typed sources — no boxing, no `dyn Error`](#preserve-typed-sources--no-boxing-no-dyn-error)
- [Do not stringify; carry typed context instead](#do-not-stringify-carry-typed-context-instead)
- [Derive `Clone, Debug, Error, PartialEq, Eq`](#derive-clone-debug-error-partialeq-eq)
- [Naming and Paths](#naming-and-paths)
- [Imports](#imports)
- [Module Layout](#module-layout)
- [Prelude Design](#prelude-design)
- [Documentation](#documentation)
- [Integration Tests](#integration-tests)
- [Testing Expectations](#testing-expectations)
- [Performance](#performance)
- [External Dependencies](#external-dependencies)
- [Toolchain and Package Boundary](#toolchain-and-package-boundary)
- [Formatting and Lints](#formatting-and-lints)
- [API Stability](#api-stability)
- [Logging and Diagnostics](#logging-and-diagnostics)
- [Preferred Patch Style](#preferred-patch-style)
---
## Core Principles
This project is a **scientific computational geometry library**.
Key goals:
- Correctness
- Predictable performance
- API stability
- Zero unsafe code
- Dimension-generic architecture
All design decisions should prioritize these goals.
---
## Safety
Unsafe Rust is forbidden.
The crate enforces:
```rust
#![forbid(unsafe_code)]
```
Agents must never introduce:
- `unsafe`
- `unsafe fn`
- `unsafe impl`
- `unsafe` blocks
---
## Dimension Generic Architecture
The library is generic over dimension using const generics:
```rust
const D: usize
```
Code must remain compatible with:
- 2D
- 3D
- 4D
- 5D
Avoid hard‑coding dimension assumptions unless they are explicitly isolated.
Prefer patterns like:
```rust
struct Point<const D: usize> {
coords: [f64; D],
}
```
Algorithms should operate generically over `D` whenever practical.
---
## Numeric Conversions
Avoid unchecked numeric casts in geometry, topology, tests, and benchmarks when
precision or range can matter.
Prefer repository helpers from `crate::geometry::util`, for example:
- `safe_usize_to_scalar::<T>(value)`
- `safe_scalar_to_f64(value)`
- `safe_scalar_from_f64::<T>(value)`
- `safe_coords_to_f64(coords)`
- `safe_coords_from_f64::<T, D>(coords)`
Do not silence `clippy::cast_precision_loss` with `#[expect(...)]` simply
because the current values are small. Use a safe conversion helper and handle
or justify the `Result` at the call site. A lint expectation is appropriate only
when no safe conversion applies and the invariant is documented in the code.
Avoid fallback conversions such as `unwrap_or(f64::NAN)`,
`unwrap_or(f64::INFINITY)`, or silently clamping failed conversions. These hide
the numerical state that geometric predicates and validation layers need in
order to fail explicitly.
---
## Borrowing and Ownership
Prefer **borrowing APIs** whenever possible.
### Function arguments
Prefer:
```rust
fn foo(points: &[Point<D>])
```
Instead of:
```rust
fn foo(points: Vec<Point<D>>)
```
### Return values
Prefer borrowed results:
```rust
fn vertex(&self, key: VertexKey) -> Option<&Vertex<D>>
```
Avoid unnecessary allocations.
Public APIs should also avoid unnecessary cloning. Prefer returning references
or iterators over internal data instead of cloning structures.
Avoid patterns like:
```rust
fn vertices(&self) -> Vec<Vertex<D>> {
self.vertices.clone()
}
```
Prefer borrowed views instead:
```rust
fn vertices(&self) -> &[Vertex<D>] {
&self.vertices
}
```
Cloning large structures in public APIs can introduce hidden performance
costs and should only be done when ownership transfer is required.
Only return owned values (`Vec`, `String`, etc.) when necessary.
### Lifetime-bound views and query helpers
Use Rust lifetimes to encode same-owner freshness whenever an API consults a
data structure or derived view. If a function returns an iterator, view, or
borrowed result over canonical storage, its signature should tie that result to
the lifetime of the storage it reads instead of relying only on runtime checks.
Prefer:
```rust
fn incident_simplices<'tds>(
&'tds self,
index: &'tds IncidenceView<'tds>,
) -> impl Iterator<Item = SimplexKey> + 'tds
```
or, when the returned iterator only borrows a derived index whose internal data
borrows the owner:
```rust
fn indexed_edges<'idx, 'tds>(
index: &'idx EdgeIndex<'tds>,
) -> impl Iterator<Item = EdgeKey> + 'idx
```
Prefer first-class borrowed views such as `IncidenceView<'tds>`,
`EdgeIndex<'tds>`, `SimplexNeighborIndex<'tds>`, and composite
`TriangulationAdjacency<'tds>` when a caller should build derived traversal
state once and query it many times. The view should own only the data it needs
and either borrow canonical relations for `'tds` or carry a lifetime tie to the
source snapshot for derived maps, so mutation through the same owner is
impossible while the view is alive.
Names should match ownership. A `*View` type or a method described as returning
views must borrow the canonical owner, or return values lifetime-bound to that
owner, so the view cannot outlive the data it observes. Detached, copyable
runtime references should be named `*Handle` or `*Key` instead, and APIs that
turn handles back into views must revalidate the handle against a live owner at
the conversion boundary. For example, `ConvexHull::try_facets(triangulation)`
returns borrowed `FacetView<'_>` values, while `ConvexHull::facet_handles()`
exposes the stored `FacetHandle`s explicitly.
Borrowed slices over canonical topology storage follow the same convention:
return `&[Key]` when the slice lives in the owner and the caller should not keep
it across mutation. For example, `Tds::simplex_vertices(simplex_key)` validates
the relation and lends the simplex's stored `&[VertexKey]`.
Algorithm implementations should use borrowed views for read-only observation,
classification, and validation phases. Mutation APIs that change canonical
topology should take `&mut Tds`/`&mut Triangulation` directly, or expose a guard
that holds that mutable borrow for the whole mutation or rollback window. This
ties existence and aliasing to the real owner: missing topology fails at view or
guard construction, and Rust prevents mutation while immutable views remain
live. Inside the mutable scope, collapse short-lived views into validated
`*Handle`/`*Key` commit identifiers before mutating; a live view must not span a
topology mutation.
For failure-atomic topology mutation windows, prefer scoped rollback guards over
loose `(snapshot, restore)` pairs. Use the TDS rollback primitives in
`core::tds::rollback` for free functions that already own a `&mut Tds`, and use
`TriangulationRollbackTransaction` from `core::rollback` for `Triangulation`
methods that need to call back into `self` during the rollback window. Both
compose through the same TDS snapshot primitive, restore on drop unless
committed explicitly, and use rollback-preserving clone semantics for retries.
Higher-level
`DelaunayTriangulation` operations must use the Delaunay-level rollback guard
when they also mutate insertion hints, spatial indexes, or repair bookkeeping;
the guard must restore or intentionally invalidate that auxiliary state
alongside the TDS. Do not wrap only the TDS when owner-coupled state can change.
Issue #364 completed the rollback-infrastructure audit; the separate
`remove_vertex` orientation-correctness work was resolved in #448.
Detached trial/scratch workspaces are a separate pattern: they may use
`clone_for_rollback`/`clone_from_for_rollback` directly when the canonical owner
is not mutated until the detached trial has validated and is swapped into place.
Examples include flip trial workspaces and copy-on-success cleanup operations.
Keep runtime identity or generation checks for detached handles, separately
supplied indexes, serialization boundaries, and tests that intentionally corrupt
metadata. Those checks complement lifetimes at API boundaries where Rust cannot
prove that two borrowed values came from the same owner.
---
## Error Handling
Public APIs must **not panic**.
Use explicit error propagation.
### Fallible public functions
Return `Result`:
```rust
pub fn insert_vertex(...) -> Result<VertexKey, InsertError>
```
### Lookup functions
Return `Option`:
```rust
pub fn vertex(&self, key: VertexKey) -> Option<&Vertex<D>>
```
### Infallible APIs
These should return values directly:
Infallible functions **must not return `Result`**.
If a function cannot fail under normal operation, it should return its value
directly rather than wrapping it in `Result`. Returning `Result` from
infallible APIs is considered unidiomatic and unnecessarily complicates
callers.
- `len()`
- `is_empty()`
- iterators
- accessors
- builder setters
Example:
```rust
pub fn len(&self) -> usize
```
Examples of infallible APIs include:
- accessors (`len`, `dimension`, `capacity`)
- iterators and views
- builder setters
- simple queries over internal state
If a function may fail due to invalid input or algorithmic conditions, it
should return `Result`. If the value may or may not exist (e.g. lookup by key),
return `Option`.
Do not introduce artificial error types simply to satisfy a `Result` return type.
### Builder pattern
Builder setters return `Self`.
Errors occur in `build()`.
Example:
```rust
builder
.with_capacity(100)
.with_seed(seed)
.build()?;
```
---
## Fluent Workflow APIs
Fluent APIs are a reviewed design preference for public workflows, not a
repository-wide requirement. Prefer staged method chains when the operation
naturally proceeds through configuration, proposal, transaction, dry-run,
commit, execution, or report phases.
Good fluent APIs make the valid sequence obvious and keep fallibility visible:
```rust
let result = owner
.propose_change(raw_request)?
.attempt_on(&mut owner)?;
```
Use fluent stages when they preserve useful evidence, such as a builder that
stores validated options, a proposal that carries owner/generation provenance,
or a transaction guard that owns rollback state. Coordinate this with
parse-don't-validate design: once raw input has been parsed into a
proof-bearing value, later stages should consume or borrow that value rather
than reaccepting the raw input.
Keep mutation explicit at the terminal method. Prefer names such as `build`,
`attempt_on`, `apply_to`, `commit`, `execute`, or `finish` when that method is
the point where side effects happen. Public samples should not hide mutation in
closures such as `and_then`, `map`, `inspect`, or `for_each` when a named stage
would be clearer.
Do not force fluent style onto accessors, iterators, simple queries, passive
reports, primitive/expert APIs, standard trait implementations, or one-step
operations with no meaningful intermediate state. Keep non-fluent functions
when they provide real orthogonality, such as trait dispatch hooks or low-level
primitive operations; remove or hide them when they only duplicate the fluent
workflow and broaden public surface without adding capability.
---
## Constructor Naming
Constructor names must show where raw input is parsed into proof-bearing domain
types and where already-validated values are merely assembled.
Use fallible names for raw or invariant-bearing input:
- `try_new*` is the default smart-constructor family for raw values becoming a
proof-bearing domain type.
- `try_from_*`, `TryFrom`, and clearly named `parse` methods are appropriate
when the source shape matters, especially conversions from another
representation, deserialized snapshot data, or textual/raw DTO input. Prefer
these names over owned `from_str` constructors so fallibility remains visible
in the repository's constructor taxonomy.
- `try_<variant>` is appropriate for fallible enum variant constructors, such as
`DedupPolicy::try_epsilon`, when the variant name is the clearest API.
- `try_<builder_option>` is appropriate for fallible builder setters, such as
`DelaunayTriangulationBuilder::try_toroidal`, when the builder remains an
intermediate state and final construction still happens at `build`.
- All of these names parse caller input and reject invalid values before storage.
- Raw numeric coordinates, slotmap keys, facet indexes, dimensions, UUIDs,
explicit connectivity, deserialized snapshots, and topology data are
invariant-bearing input unless a narrower validated type already carries the
proof.
- The canonical pattern is `Point::try_new`, `Vertex::try_new`, and
`FacetHandle::try_new`: validate the raw values, then store only values whose
invariants have been proved.
Use `from_validated*` only for infallible construction from proof-bearing input:
- `from_validated*` means validation evidence already exists at the call site.
- These functions should be private by default. Use `pub(crate)` only when a
non-test sibling module needs the trusted path after proving the invariant.
Do not expose `from_validated*` as public API.
- Keep trusted constructors scarce. Prefer one `from_validated*` constructor
that accepts all already-proved state (for example optional payload data) over
parallel variants such as `from_validated_*_with_data`.
- The pattern in `FacetHandle::try_new` followed by
`FacetHandle::from_validated` is the preferred shape for internal helpers.
Intentional idiomatic exceptions are allowed when no raw invalidable state is
being parsed:
- Zero-state strategies and markers may use `new`, such as geometry kernels and
simple topology-space marker values.
- Empty containers and empty triangulations may use `empty`, `new_empty`, or
`with_empty_*` because no user geometry or topology is accepted.
- Builder creation may use `Builder::new` when validation is explicitly deferred
to `build`; fallible builder setters must use descriptive `try_*` names, while
infallible builder setters keep `with_*` or domain-specific names and return
`Self`.
- Configuration and statistics types may derive or implement `Default` when the
default value is valid and documented as a policy choice or accumulator state.
- `from_*` is acceptable for passive report/view extraction or infallible
standard conversions that cannot fail for representable input. Trusted
construction from proof-bearing input should use `from_validated*` internally.
Current migration targets for API-normalization work:
- Public Delaunay construction examples should teach
`DelaunayTriangulationBuilder::new(&vertices).build()?` and its fluent
option setters/terminal variants as the canonical default-kernel workflow,
with `DelaunayTriangulation::builder(&vertices)` acceptable only as a terse
builder alias in tests and benchmarks. Public examples must not discard a
successfully constructed triangulation with an underscore-prefixed binding.
End-to-end construction examples with no more specific follow-on operation
should retain the result and finish with `dt.validate()?`; examples teaching
another API should use the result for that operation instead of adding a
redundant validation call mechanically. Do not add local helpers whose whole
purpose is hiding `DelaunayTriangulation::builder(...).build()` or the
equivalent `DelaunayTriangulationBuilder::new(...).build()` chain; such
helpers mask API friction instead of testing the canonical fluent workflow.
The legacy `DelaunayTriangulation::try_new*` and `try_with_*` wrappers are not
public API and should not exist, even as hidden compatibility shims. Use the builder
terminals (`build`, `build_with_statistics`, `build_with_kernel`, and
`build_with_kernel_and_statistics`) at call sites so options, topology
expectations, statistics, and kernels remain visible in domain order.
Shared implementation hooks should stay crate-private, named as builder
backends, and unreachable from downstream callers. Infallible empty constructors
remain `empty` and `with_empty_*` because they accept no user geometry or topology.
- `DelaunayTriangulationBuilder::try_from_vertices_and_simplices*` validates
explicit simplex specs before storing them in a private proof-bearing wrapper.
Full TDS/topology/Delaunay validation still happens at `build`, where the
assembled triangulation exists.
- `ConvexHull::try_from_triangulation` is the fallible hull-snapshot
constructor. Reserve `from_*` for infallible conversions from proof-bearing
input or passive view/report extraction.
- Broad public `from_*` helpers should be reviewed case by case. Keep them when
they consume proof-bearing inputs and cannot fail; rename to `try_from_*` when
they parse raw invalidable state.
Semgrep guardrails for constructor names should stay narrow and repo-specific.
They enforce that fallible constructor definitions do not use misleading `new`
or `from_*` names, and they protect established public parse boundaries such as
`DelaunayTriangulation` and `ConvexHull`. Do not make the rules require every
fallible boundary to be named `try_new*`; descriptive `try_*` names are allowed
for builder setters and enum variant constructors when they better describe the
operation.
Do not add `from_unchecked_*` constructors; use an explicit candidate type for
temporarily assembled state, then consume validation proof before converting to
the final domain type. Other infallible `from_*` names remain acceptable only
for total conversions, passive report/view extraction, or proof-bearing input.
### Vertex construction in public samples
Prefer `vertex!` for user-facing vertex construction examples. This includes
`README.md`, active workflow/design docs, crate-level examples, doctests,
integration-style examples under `examples/`, and benchmarks where vertex
construction is incidental setup. Integration tests should follow the same
default when they exercise a higher-level workflow such as Pachner moves,
flips, insertion, repair, or triangulation construction rather than vertex
construction itself.
Use the direct constructors only when they are the subject of the example:
- API docs for `Vertex::try_new`, `Vertex::try_new_with_data`, and related
constructor semantics.
- Tests that specifically exercise constructor behavior, type inference, error
propagation, coordinate parsing, UUID handling, or vertex-data storage.
- Explanatory text that compares `vertex!` with the constructor it expands to.
- Internal invariant tests where direct constructor calls make the tested
boundary clearer than macro syntax.
The public sample default should look like:
```rust
let vertex = vertex![0.0, 1.0]?;
let labeled: Vertex<&str, 2> = vertex![0.0, 1.0; data = "boundary"]?;
```
Keep `Vertex::try_new` and `Vertex::try_new_with_data` visible in their own
rustdocs so users can still see the fallible smart constructors and the typed
errors that the macro preserves.
---
## Panic Policy
Panics should be avoided in library code.
User-facing Rust surfaces must also avoid panic-based examples. Do not use
unwrap or expect calls in committed examples, benchmarks, Markdown Rust blocks,
or doctests. These artifacts are copied by users and should model typed error
propagation with `?`, local `thiserror` enums, or crate error types. Reserve
unwrap and expect calls for unit tests and test-only fixtures, where a panic
clearly reports a broken test assumption.
Acceptable panic situations:
- internal invariants violated
- unreachable logic errors
Do not use `debug_assert!`, `debug_assert_eq!`, or `debug_assert_ne!` in
production source. Debug-only assertions disappear in release builds, so they
cannot protect library invariants or serve as parse-don't-validate boundaries.
Encode the invariant in a type, return a typed error, or cover the assumption
with tests instead.
Prefer returning:
- `Result`
- `Option`
instead of panicking.
---
## Error Types
Errors should be defined **within the module where they are used**.
Avoid large centralized error enums.
Example:
```rust
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum InsertError {
#[error("duplicate vertex")]
DuplicateVertex,
}
```
The sub‑sections below spell out the conventions that keep error values
**debuggable, composable, and stable**. They apply to every new error enum
and to edits of existing ones.
### Orthogonal variants
Every variant represents a **distinct failure mode**. Two variants must not
overlap in meaning: if a caller can't decide which one to match on, the
taxonomy is wrong.
When the same underlying condition occurs in two different contexts
(e.g. primary failure vs. failure during fallback), model it with
**separate variants that each carry the full typed context**, not with a
single variant and a free‑form `context: String` field.
Good:
```rust
pub enum DelaunayizeError {
TopologyRepairFailed {
source: PlManifoldRepairError,
},
TopologyRepairFailedWithRebuild {
source: PlManifoldRepairError,
rebuild_error: DelaunayTriangulationConstructionError,
},
DelaunayRepairFailed {
source: DelaunayRepairError,
},
DelaunayRepairFailedWithRebuild {
source: DelaunayRepairError,
rebuild_error: DelaunayTriangulationConstructionError,
},
}
```
Each pair `Failed` / `FailedWithRebuild` is **orthogonal**: the caller
always knows whether a fallback was attempted, and if so which specific
rebuild error was produced.
### Struct‑with‑named‑fields throughout
Prefer **struct variants with named fields** over positional (tuple) variants,
even for single‑field carriers. Named fields:
- document the semantics of each payload at the declaration site,
- keep `Display` format strings readable (`{source}`, `{rebuild_error}`),
- let downstream code pattern‑match by field name without caring about
positional order,
- remain additive: adding a new field is a compile‑error surface that
forces callers to consider it.
Prefer:
```rust
#[error("Invalid facet index {index} for simplex with {facet_count} facets")]
InvalidFacetIndex {
index: u8,
facet_count: usize,
},
```
Avoid:
```rust
#[error("Invalid facet index {0} for simplex with {1} facets")]
InvalidFacetIndex(u8, usize),
```
### Preserve typed sources — no boxing, no `dyn Error`
Source and "secondary" errors must be stored **by value as typed enums**.
Do not erase them behind dynamic error objects, `anyhow::Error`, or
`message: String` fields. The whole point of the taxonomy is that consumers
can pattern-match the full structured error, while [`Error::source`] exposes
whichever field is annotated as the primary source.
- Use `#[source]` (and `#[from]` where the conversion is unambiguous) on
the typed field so `thiserror` wires up the source chain.
- Use `Box<T>` only when the **typed** payload would make the enum
unbalanced in size (e.g. `NonConvergent` carries a fat diagnostics
struct); the inner type is still fully typed.
- Never replace a typed error with a `String` just because the enum lived
in a different crate — that erases variant and source information.
```rust
// Good: typed rebuild error preserved by value; primary source chain intact.
TopologyRepairFailedWithRebuild {
#[source]
source: PlManifoldRepairError,
rebuild_error: DelaunayTriangulationConstructionError,
},
```
```rust
// Bad: stringification erases the typed variant.
TopologyRepairFailedWithRebuild {
source: PlManifoldRepairError,
rebuild_message: String,
},
```
### Do not stringify; carry typed context instead
Free‑form `message: String` fields are only acceptable when the context is
genuinely unstructured prose (rare). In practice, **most** "context" is
structured — indices, counts, keys, UUIDs, other enums — and belongs in
named fields of a struct variant.
Prefer:
```rust
#[error("Ridge indices ({omit_a}, {omit_b}) out of bounds for simplex {simplex_key:?} with {vertex_count} vertices")]
InvalidRidgeIndex {
simplex_key: SimplexKey,
omit_a: u8,
omit_b: u8,
vertex_count: usize,
},
```
Avoid:
```rust
#[error("Ridge indices out of bounds: {message}")]
InvalidRidgeIndex {
message: String,
},
```
Structured payloads support:
- test assertions via `assert_eq!` / `matches!` without string parsing,
- diagnostic tools that filter or aggregate by field,
- localization and richer `Display` implementations without rewriting
call‑sites.
### Derive `Clone, Debug, Error, PartialEq, Eq`
All error enums should derive the standard set:
```rust
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum FooError { ... }
```
- `Clone` — lets callers attach the error to multiple diagnostics paths
and lets tests construct expected values once and compare them.
- `Debug` — required for `Error`.
- `thiserror::Error` — wires up `Display` and `source()`.
- `PartialEq, Eq` — deriveable whenever all payload types are `Eq`
(integers, strings, UUIDs, keys, other `Eq` enums, `Arc<T>` /
`Box<T>` where `T: Eq`). All error enums in this crate satisfy
this today. Skip these only when a payload genuinely cannot be `Eq`
(e.g. `f64`, `io::Error`, dynamically erased error objects) — none of
which belong in error values anyway.
- `#[non_exhaustive]` — new variants must remain additive; downstream
matches need a `_` arm.
Use `assert_eq!` for fixed‑shape variants in tests; prefer `matches!` for
"just check the variant" when the payload contains long free‑form strings
or nondeterministic samples.
---
## Naming and Paths
Function names should be concise but specific. Prefer short verbs and domain
terms over names that restate the module, type, or every implementation detail.
Prefer:
```rust
fn align_offsets(...)
fn validate_link(...)
fn rebuild_candidate(...)
```
Avoid:
```rust
fn align_periodic_vertex_offsets_for_source_simplex_to_target_simplex(...)
fn validate_manifold_link_consistency_for_all_ridges(...)
fn rebuild_delaunay_triangulation_candidate_after_repair_failure(...)
```
Use short, unqualified paths inside function bodies. If a function needs a type,
trait, constant, or helper from another module, import it at the top of the
module and refer to the item by its short name locally.
---
## Imports
Always import types at the top of the module rather than using fully‑qualified
paths inline. This keeps code readable and consistent.
Prefer:
```rust
use crate::core::tds::TdsError;
fn check(err: &TdsError) -> bool { ... }
```
Instead of:
```rust
fn check(err: &crate::core::tds::TdsError) -> bool { ... }
```
Group imports from the same module into a single `use` statement with braces:
```rust
use crate::core::tds::{
SimplexKey, EntityKind, Tds, TdsError, VertexKey,
};
```
Do not add `use` statements inside function bodies just to shorten a path.
Move those imports to the top of the module. Local imports are acceptable only
when they are intentionally scoped for conditional compilation, tests, macro
expansion, or to avoid a documented name collision.
If a test module already has `use super::*;`, do not re‑import items that are
already brought into scope by the parent module's imports.
---
## Module Layout
Never use `mod.rs`.
Modules are declared from `src/lib.rs`.
Example:
```rust
pub mod core;
pub mod geometry;
pub mod algorithms;
```
Nested modules may use inline declaration:
```rust
pub mod core {
pub mod triangulation;
pub mod vertex;
}
```
---
## Prelude Design
Focused preludes should remain **small, orthogonal, and purpose-specific**.
A focused prelude should import only the items needed for a specific task.
Bundle only related, non-overlapping functionality in a focused prelude; do
not use one focused prelude as a compatibility bucket for adjacent workflows.
If a focused prelude has grown too broad or ambiguous, prefer fixing the
taxonomy over preserving backwards compatibility for unrelated re-exports.
Create a new focused prelude when a distinct workflow needs one.
Prefer focused preludes in doctests, integration tests, examples, and benchmarks
because they make intent visible at the import site.
Examples:
```text
delaunay::prelude
delaunay::prelude::triangulation
delaunay::prelude::construction
delaunay::prelude::pachner
delaunay::prelude::insertion
delaunay::prelude::deletion
delaunay::prelude::repair
delaunay::prelude::delaunayize
delaunay::prelude::validation
delaunay::prelude::query
delaunay::prelude::algorithms
delaunay::prelude::geometry
delaunay::prelude::generators
delaunay::prelude::diagnostics
delaunay::prelude::ordering
delaunay::prelude::collections
delaunay::prelude::tds
delaunay::prelude::topology::validation
delaunay::prelude::topology::spaces
```
Keep raw bistellar flip primitives out of preludes. Downstream examples should
use `delaunay::prelude::pachner` for local move workflows, the construction
prelude for `DelaunayTriangulation::insert_vertex`, and
`delaunay::prelude::deletion` when matching typed `delete_vertex` failures.
Import `delaunay::flips` directly only when testing, benchmarking, or
documenting the primitive flip layer itself.
The root `delaunay::prelude::*` is intentionally available as the
kitchen-sink prelude for new users, quick experiments, and exploratory tests.
Avoid using it in committed examples, benchmarks, and doctests when a focused
prelude communicates the workflow more clearly.
---
## Documentation
All public items must have documentation. Public functions must include a
doctest in their documentation.
Example:
```rust
/// Inserts a vertex into the triangulation.
///
/// Returns the key of the inserted vertex.
///
/// # Examples
///
/// ```rust
/// # use delaunay::prelude::construction::{DelaunayTriangulation};
/// # use delaunay::prelude::insertion::InsertionError;
/// # fn main() -> Result<(), InsertionError> {
/// let mut triangulation = DelaunayTriangulation::<_, _, _, 2>::default();
/// let key = triangulation.insert_vertex([0.0, 0.0])?;
/// assert!(triangulation.contains_vertex(key));
/// # Ok(())
/// # }
/// ```
pub fn insert_vertex(...)
```
### Private functions
Private functions must have a brief doc comment (`///`) explaining **why they
exist** — what problem they solve or what invariant they maintain. The *what*
is often clear from the signature; the *why* is not.
Prefer:
```rust
/// Aligns source-simplex periodic offsets into the target-simplex frame so
/// cross-simplex insphere predicates see consistent lifted coordinates.
fn align_periodic_offset<const D: usize>(...) -> Result<[i8; D], FlipError>
```
Use normal comments (`//`) for documentation inside function bodies or other
implementation-local notes:
```rust
fn align_periodic_offset<const D: usize>(...) -> Result<[i8; D], FlipError> {
// Compare deltas in each coordinate so conflicting frame translations are
// rejected before lifted coordinates are constructed.
...
}
```
A bare signature with no context forces readers to reverse-engineer
intent from the implementation.
After Rust changes, verify documentation builds:
```bash
just doc-check
```
or
```bash
cargo doc
```
---
## Integration Tests
Integration tests live in:
```text
tests/
```
Each integration test crate should include a crate‑level doc comment:
```rust
//! Integration tests for triangulation invariants.
```
This satisfies `clippy::missing_docs` in CI.
Fixed-bug regression integration tests belong in `tests/regressions.rs` unless
they need separate crate-level configuration, feature flags, or profile
isolation.
---
## Testing Expectations
Use focused tests while iterating on Rust changes, for example:
```bash
just test-unit
just test-doc
just test-integration
```
For final handoff validation, core Rust/Cargo changes require `just ci`.
Doctest-only, unit-test-only, integration-test-only, benchmark-only, and
example-only changes use the focused validators in
[`commands.md`](../commands.md).
Property tests are preferred for geometric invariants such as:
- Euler characteristic checks
- simplex adjacency invariants
- manifold consistency
---
## Performance
For performance-sensitive Rust changes, follow the benchmark-before-and-after
workflow in [`perf-tuning.md`](../perf-tuning.md). Add a representative benchmark
when none exists, and cover 2D through 5D for dimension-generic hot paths
whenever feasible.
Avoid unnecessary allocations.
Prefer:
- iterators
- slices
- stack arrays `[T; D]`
- fixed‑size containers
Avoid cloning large structures unless necessary.
Repair benchmarks sometimes need topology states that ordinary construction
must reject, such as codimension-1 facets incident to more than two simplices.
Keep those states behind `#[cfg(feature = "bench")]` fixture helpers and type
the fixture errors. Do not broaden normal public constructors or treat
`TopologyGuarantee::Pseudomanifold` as an invalid-topology bypass; it still
requires facet degree 1 or 2, boundary consistency, connectedness, isolated
vertex checks, and Euler validation when Level 3 runs.
---
## External Dependencies
Dependencies should be minimal.
Before adding a dependency, consider:
1. compile time impact
2. MSRV compatibility
3. maintenance status
4. dependency tree size
---
## Toolchain and Package Boundary
`Cargo.toml` owns the MSRV, and `rust-toolchain.toml` pins local and CI Rust to
that version. Keep the toolchain profile minimal and the default component set
limited to `clippy`, `rustfmt`, and `rust-src`; workflows or developers that
need cross targets or additional components should install them explicitly.
The explicit `Cargo.toml` package `include` list is the crates.io distribution
boundary. Keep it aligned with the public library, examples, benchmarks,
integration tests, active documentation, citation/release metadata, and assets
needed by docs.rs or published examples. Do not add CI-only tooling, Python
automation, or unrelated repository history to the crate artifact. Validate
changes to this boundary with:
```bash
just publish-check
```
---
## Formatting and Lints
Code must pass non-mutating checks:
```bash
just rust-core-check
```
Apply formatters and auto-fixes after reviewing check output:
```bash
just fix
```
CI treats warnings as errors.
### Lint Suppression
When suppressing a lint, use `#[expect(...)]` instead of `#[allow(...)]`.
`expect` causes a compiler warning if the lint is no longer triggered,
ensuring suppressions are removed when they become unnecessary.
Always include a `reason`:
```rust
#[expect(clippy::too_many_lines, reason = "test covers multiple cases")]
fn test_large_dataset_performance() { ... }
```
---
## API Stability
The crate is intended for external use, but it is still pre-1.0.0. Intentional
breaking changes to public types, functions, and modules are acceptable when
they improve correctness, invariants, orthogonality, or the constructor taxonomy
described above.
Do not preserve stale public APIs by adding deprecated compatibility aliases,
compatibility re-exports, or shim functions. Prefer a clean public surface with
clear migration guidance in docs and changelog material. For example,
`GlobalTopology::model` is crate-private behavior-model plumbing, and raw
toroidal input is parsed through public domain constructors such as
`ToroidalDomain::try_new` and `GlobalTopology::try_toroidal`; do not reintroduce
a public `ToroidalModel::try_new` alias.
---
## Logging and Diagnostics
Use `tracing` for committed diagnostics across production code, tests,
and benchmarks. This includes library/runtime code, non-trivial test
diagnostics, and debugging of numerical instability or topological
invariants. Prefer `tracing::debug!`, `tracing::trace!`, etc. over
ad-hoc printing.
This ensures all diagnostic output is:
- filterable via `RUST_LOG` / `tracing-subscriber`
- structured and machine-parseable
- suppressible in production builds
`eprintln!` is acceptable only for short-lived local debugging while
investigating an issue. Do not leave it in committed code when `tracing`
or a typed error path is more appropriate.
Debug hooks gated on environment variables should still use `tracing`:
```rust
#[cfg(debug_assertions)]
if std::env::var_os("DELAUNAY_DEBUG_FOO").is_some() {
tracing::debug!("diagnostic message: {value}");
}
```
### Tests and Benchmarks
- Use `tracing` for non-trivial test diagnostics rather than
`eprintln!`, especially when diagnosing geometric predicate behavior,
invariant failures, or shrink/reproduction context.
- Never log inside hot benchmark loops or Criterion-measured closures.
Emit diagnostics before or after the measured path so measurements stay
meaningful.
- Gate non-essential test and benchmark diagnostics behind feature flags.
In this repository, use `diagnostics` for test diagnostics and
`bench-logging` for benchmark diagnostics:
```rust
#[cfg(feature = "diagnostics")]
tracing::debug!("test diagnostic");
#[cfg(feature = "bench-logging")]
tracing::debug!("benchmark diagnostic");
```
---
## Preferred Patch Style
When modifying Rust code:
- make **small focused changes**
- avoid large refactors
- maintain existing naming conventions
- preserve module boundaries