bit_int/
lib.rs

1// SPDX-FileCopyrightText: 2024 Shun Sakai
2//
3// SPDX-License-Identifier: Apache-2.0 OR MIT
4
5//! The `bit-int` crate is a library for providing arbitrary fixed bit-width
6//! integers.
7//!
8//! The value is represented by either of the following types:
9//!
10//! - The [`BitInt`] type represents a `N`-bit signed integer. This type is
11//!   similar to `signed _BitInt(n)` in [C23], or arbitrary fixed bit-width
12//!   signed integer types (e.g., `i7`) in [Zig].
13//! - The [`BitUint`] type represents a `N`-bit unsigned integer. This type is
14//!   similar to `unsigned _BitInt(n)` in C23, or arbitrary fixed bit-width
15//!   unsigned integer types (e.g., `u7`) in Zig.
16//!
17//! The largest size of `N` depends on the size of the underlying type in bits.
18//! Therefore, when the underlying type of [`BitInt`] is [`i32`], the largest
19//! size of `N` is [`i32::BITS`], and when the underlying type of [`BitUint`] is
20//! [`u64`], the largest size of `N` is [`u64::BITS`].
21//!
22//! # Examples
23//!
24//! ## Signed integer type
25//!
26//! ```
27//! use bit_int::BitInt;
28//!
29//! type Int = BitInt<i8, 7>;
30//!
31//! let n = Int::MIN;
32//! assert_eq!(format!("{n}"), "-64");
33//!
34//! let n = n.checked_add(106).unwrap();
35//! // Gets the contained value as the underlying type.
36//! assert_eq!(n.get(), 42);
37//!
38//! let n = n.checked_add(21).unwrap();
39//! assert_eq!(n.get(), 63);
40//! assert_eq!(n, Int::MAX);
41//!
42//! assert_eq!(n.checked_add(22), None);
43//! ```
44//!
45//! ## Unsigned integer type
46//!
47//! ```
48//! use bit_int::BitUint;
49//!
50//! type Uint = BitUint<u8, 7>;
51//!
52//! let n = Uint::MIN;
53//! assert_eq!(format!("{n}"), "0");
54//!
55//! let n = n.checked_add(42).unwrap();
56//! // Gets the contained value as the underlying type.
57//! assert_eq!(n.get(), 42);
58//!
59//! let n = n.checked_add(85).unwrap();
60//! assert_eq!(n.get(), 127);
61//! assert_eq!(n, Uint::MAX);
62//!
63//! assert_eq!(n.checked_add(86), None);
64//! ```
65//!
66//! [C23]: https://en.cppreference.com/w/c/23
67//! [Zig]: https://ziglang.org/
68
69#![doc(html_root_url = "https://docs.rs/bit-int/0.2.0/")]
70#![no_std]
71// Lint levels of rustc.
72#![deny(missing_docs)]
73
74#[cfg(test)]
75#[macro_use]
76extern crate alloc;
77
78mod bit_int;
79mod bit_uint;
80
81pub use crate::{
82    bit_int::{BitI8, BitI16, BitI32, BitI64, BitI128, BitInt, BitIsize},
83    bit_uint::{BitU8, BitU16, BitU32, BitU64, BitU128, BitUint, BitUsize},
84};