18 releases
new 0.2.5 | Jan 4, 2025 |
---|---|
0.2.4 | Jan 3, 2025 |
0.2.2 | Dec 29, 2024 |
0.1.11 | Dec 23, 2024 |
#526 in Data structures
1,009 downloads per month
120KB
1.5K
SLoC
$\Sigma$-Types in Rust
Types automatically checked for invariants in debug builds only.
This crate lets you explicitly represent structures like sorted vectors as types of their own.
Features
Deref
,AsRef
, andBorrow
: ifx
implementsx.foo(..)
, then a $\Sigma$-types
wrappingx
automatically implementss.foo(..)
.- No runtime cost in release builds: When debug assertions are disabled, $\Sigma$-types are exactly the same size as their raw type, and all methods are fully inlined with no extra code added.
- All checks automatically inserted:
No more covering your code in
debug_assert!(..)
s (and inevitably missing some necessary checks). This is an extremely simple crate, but its main aim is to silently insert nothing more or less than each necessary check, and to allow libraries to credibly promise invariants about their functions' return values with an easily unwrappable, lightweight type that disappears in release builds. - Zero-size wrapper type (
repr(transparent)
): Wrapping aT
inSigma<T, ..>
creates a type that uses exactly the same binary representation asT
; all it does is add an extraPhantomData
field. no_std
(and noalloc
): all features, including error messages (via::core::fmt::Display
), work without the standard library and without heap allocation.
What does this have to do with $\Sigma$-types?
Some languages, like Coq, implement type systems that offer sigma types (or $\Sigma$-types), which represent a term (say, $A$) alongside another term (say, $B$) whose type can depend on the value of $A$. Since the type of $B$ can depend on the value of $A$, the type of $B$ often represents a proof that some property holds of this particular value for $A$. (If exactly how is unclear and you have a few minutes and a mind to be blown, see the Curry-Howard correspondence.)
We implement a subset of $\Sigma$-types in which $B$ represents a decidable proposition.
To decide whether a proof exists to inhabit the type of $B$ (which isn't directly represented),
the programmer supplies a Rust function that takes the value of $A$ and returns a Result
.
Why not call this library invariant
or something more clear?
invariant
is already a similar library,
but it requires std
and alloc
, and it uses larger structs that run checks in release builds.
That's fine, but I have a different use-case, and this aims to be more generally applicable.
Plus, $\Sigma$-types are theoretically interesting, and I'd like to evangelize a bit.
Dependencies
~0–1.8MB
~33K SLoC