topon/lib.rs
1//! # Topon — Geodineum Geometric Hash Library
2//!
3//! Deterministic geometric hashing that maps arbitrary input to points on
4//! Riemannian manifolds. Unlike traditional hashes, Topon output has meaningful
5//! geometric structure: distances, geodesics, and containment.
6//!
7//! ## Modes
8//!
9//! - [`mode::domain`] — Domain name hashing (irrational mixing, proven quality)
10//! - [`mode::speed`] — Throughput-optimized (expanding multiply-mod-1 sponge)
11//! - [`mode::hierarchical`] — Tree-structured input on hyperbolic space
12//!
13//! ## Quick start
14//!
15//! ```rust,no_run
16//! use topon::{domain_hasher, DomainHash};
17//!
18//! let hasher = domain_hasher();
19//! let coords = hasher.hash_domain("example.geo").unwrap();
20//! ```
21//!
22//! ## Hash stability
23//!
24//! Hash *values* are part of the public contract, not just the API. Until
25//! 1.0 output may change between releases: any release that changes output
26//! for any input bumps the minor version; patch releases are bit-identical.
27//! Output depends on the compile-time `GMATH_PROFILE` — values are only
28//! comparable between builds using the same profile. The profile fixes
29//! [`FixedPoint`], the g_math format every coordinate is stored in.
30
31// Determinism is the crate's core guarantee; no part of it needs `unsafe`.
32#![forbid(unsafe_code)]
33
34use g_math::fixed_point::imperative::FixedVector;
35
36include!(concat!(env!("OUT_DIR"), "/format.rs"));
37
38pub mod core;
39pub mod mixing;
40pub mod mode;
41pub mod eval;
42pub mod compat;
43
44// Re-export key types for convenience
45pub use crate::core::config::{CoordinateConfig, MAX_DIMENSION};
46pub use crate::core::manifold::{geodesic_distance, ManifoldType};
47pub use crate::mixing::geodesic::{GeodesicWalk, LabelOrder, WalkLimits};
48pub use mode::domain::DomainHasher;
49pub use mode::speed::SpeedHasher;
50pub use mode::hierarchical::HierarchicalHasher;
51
52// ============================================================================
53// Error type
54// ============================================================================
55
56/// Errors returned by Topon operations.
57///
58/// Non-exhaustive: new variants may be added in future releases without a
59/// major version bump, so downstream `match` arms need a `_` fallback.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum ToponError {
63 /// Input is empty or invalid.
64 InvalidDomain,
65 /// Underlying g_math overflow during computation.
66 MathOverflow,
67 /// Dimension or manifold configuration is invalid — the dimension is zero
68 /// or exceeds [`CoordinateConfig`]'s `MAX_DIMENSION`.
69 InvalidConfig,
70 /// A zero vector cannot be projected onto the target manifold.
71 DegenerateVector,
72 /// A hierarchical path has more labels than the configured `max_depth`.
73 /// Deep paths are an upstream (taxonomy) bug — fail loudly, never truncate.
74 DepthExceeded { max_depth: usize },
75}
76
77impl std::fmt::Display for ToponError {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 match self {
80 ToponError::InvalidDomain => write!(f, "invalid input"),
81 ToponError::MathOverflow => write!(f, "arithmetic overflow"),
82 ToponError::InvalidConfig => write!(f, "invalid configuration"),
83 ToponError::DegenerateVector => write!(f, "degenerate zero vector"),
84 ToponError::DepthExceeded { max_depth } => {
85 write!(f, "hierarchy deeper than max_depth = {}", max_depth)
86 }
87 }
88 }
89}
90
91impl std::error::Error for ToponError {}
92
93impl From<g_math::fixed_point::imperative::OverflowDetected> for ToponError {
94 fn from(_: g_math::fixed_point::imperative::OverflowDetected) -> Self {
95 ToponError::MathOverflow
96 }
97}
98
99// ============================================================================
100// Core trait
101// ============================================================================
102
103/// Core geometric hashing trait.
104///
105/// Maps raw byte input to a `FixedVector` on a Riemannian manifold.
106/// All implementations guarantee determinism, boundedness, and zero float.
107pub trait GeometricHash {
108 /// Human-readable name for this hasher.
109 fn name(&self) -> &str;
110
111 /// Hash raw bytes to a coordinate vector on the configured manifold.
112 fn hash(&self, input: &[u8]) -> Result<FixedVector<FixedPoint>, ToponError>;
113
114 /// Number of components in the output vector.
115 fn output_dimension(&self) -> usize;
116
117 /// The manifold type of the output.
118 fn manifold_type(&self) -> ManifoldType;
119}
120
121/// Domain-name convenience trait — automatically derived for all `GeometricHash` types.
122///
123/// Adds `hash_domain()` which normalizes the domain string (lowercase, trim,
124/// strip trailing dots) before hashing.
125pub trait DomainHash: GeometricHash {
126 fn hash_domain(&self, domain: &str) -> Result<FixedVector<FixedPoint>, ToponError> {
127 let normalized = crate::core::normalize::normalize_domain(domain)?;
128 self.hash(normalized.as_bytes())
129 }
130}
131
132/// Blanket implementation: every `GeometricHash` is also a `DomainHash`.
133impl<T: GeometricHash> DomainHash for T {}
134
135// ============================================================================
136// Factory functions
137// ============================================================================
138
139/// Create the default domain hasher (irrational mixing, S^128).
140///
141/// Infallible: the default [`CoordinateConfig`] is always valid (pinned by
142/// `default_config_is_valid`).
143///
144/// Note that S^128 is the *quality* default, not the fast one — it makes 129
145/// passes over the input. For throughput-sensitive callers, construct a
146/// [`DomainHasher`] at a smaller dimension, or use [`speed_hasher`].
147pub fn domain_hasher() -> DomainHasher {
148 DomainHasher::new(CoordinateConfig::default())
149 .expect("the default CoordinateConfig is always valid")
150}
151
152/// Create a speed-optimized hasher for arbitrary byte input.
153///
154/// # Errors
155///
156/// [`ToponError::InvalidConfig`] if `config` fails [`CoordinateConfig::validate`].
157pub fn speed_hasher(config: CoordinateConfig) -> Result<SpeedHasher, ToponError> {
158 SpeedHasher::new(config)
159}
160
161/// Create a hierarchical hasher for tree-structured input.
162///
163/// # Errors
164///
165/// [`ToponError::InvalidConfig`] if `config` fails [`CoordinateConfig::validate`].
166pub fn hierarchical_hasher(config: CoordinateConfig) -> Result<HierarchicalHasher, ToponError> {
167 HierarchicalHasher::new(config)
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 /// Pins the invariant that `domain_hasher()`'s `expect` relies on.
175 #[test]
176 fn default_config_is_valid() {
177 CoordinateConfig::default()
178 .validate()
179 .expect("default config must stay valid");
180 let _ = domain_hasher();
181 }
182}