Skip to main content

use_computing_constants/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Reusable computing constants expressed as plain integer values.
4
5/// Exact computing constant for the number of bits in one byte.
6pub const BITS_PER_BYTE: usize = 8;
7
8/// Exact computing constant for the number of bits in one nibble.
9pub const NIBBLE_BITS: usize = 4;
10
11/// Exact computing constant for the number of distinct values in one byte.
12pub const BYTE_VALUES: usize = 256;
13
14/// Binary storage constant for one kibibyte, in bytes.
15pub const KIBIBYTE: usize = 1024;
16
17/// Binary storage constant for one mebibyte, in bytes.
18pub const MEBIBYTE: usize = 1024 * KIBIBYTE;
19
20/// Binary storage constant for one gibibyte, in bytes.
21pub const GIBIBYTE: usize = 1024 * MEBIBYTE;
22
23/// Binary storage constant for one tebibyte, in bytes.
24pub const TEBIBYTE: usize = 1024 * GIBIBYTE;
25
26/// Decimal storage constant for one kilobyte, in bytes.
27pub const KILOBYTE: usize = 1000;
28
29/// Decimal storage constant for one megabyte, in bytes.
30pub const MEGABYTE: usize = 1000 * KILOBYTE;
31
32/// Decimal storage constant for one gigabyte, in bytes.
33pub const GIGABYTE: usize = 1000 * MEGABYTE;
34
35/// Decimal storage constant for one terabyte, in bytes.
36pub const TERABYTE: usize = 1000 * GIGABYTE;
37
38#[cfg(test)]
39mod tests {
40    use super::{BITS_PER_BYTE, BYTE_VALUES, KIBIBYTE, KILOBYTE, MEBIBYTE, MEGABYTE, NIBBLE_BITS};
41
42    #[test]
43    fn byte_size_relationships_hold() {
44        assert_eq!(BYTE_VALUES, 1usize << BITS_PER_BYTE);
45        assert_eq!(NIBBLE_BITS * 2, BITS_PER_BYTE);
46    }
47
48    #[test]
49    fn binary_storage_relationships_hold() {
50        assert_eq!(MEBIBYTE, 1024 * KIBIBYTE);
51    }
52
53    #[test]
54    fn decimal_storage_relationships_hold() {
55        assert_eq!(MEGABYTE, 1000 * KILOBYTE);
56    }
57}