int_like
A Rust macro for defining integer-backed opaque types safely.
Originally inspired by code from Redox OS, this crate provides a convenient way to create new types that are backed by primitive integers (typically usize), providing type safety without compromising performance.
Features
- Create simple opaque types backed by any integer type
- Generate corresponding atomic types with thread-safe operations
- Zero-cost abstraction - the new types have the same size as their backing types
- Full support for common derives (
Debug,Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd)
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Usage
Simple Opaque Type
Define a simple type backed by usize:
use int_like;
/// Define an opaque type `Pid` backed by a `usize`.
int_like!;
const ZERO: Pid = from;
let pid = from;
assert_eq!;
With Atomic Support
Define both a regular type and its atomic counterpart:
use int_like;
use Ordering;
/// Define opaque types `Pid` and `AtomicPid`, backed respectively by a `usize`
/// and an `AtomicUsize`.
int_like!;
const ZERO: Pid = from;
let ATOMIC_PID: AtomicPid = default;
// Atomic operations
ATOMIC_PID.store;
let value = ATOMIC_PID.load;
assert_eq!;
Available Methods
For simple types:
from(x: T) -> Self- Create from the backing typenew(x: T) -> Self- Alternative constructorinto() -> T- Convert back to the backing typedata() -> T- Get the backing value
For atomic types:
new(x: T) -> Self- Create from the non-atomic typedefault() -> Self- Create with zero valueload(ordering) -> T- Atomic loadstore(val, ordering)- Atomic storeswap(val, ordering) -> T- Atomic swapcompare_exchange(current, new, success, failure) -> Result<T, T>- CAS operationcompare_exchange_weak(current, new, success, failure) -> Result<T, T>- Weak CASfetch_add(val, ordering) -> T- Atomic add
License
This project is licensed under the MIT License - see the LICENSE file for details.