Skip to main content

diskann_wide/
constant.rs

1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6/// Move a const-generic into the type domain to work around issues with the use and
7/// compile-time computation involving const-generic parameters.
8///
9/// See the notes for the various helper traits in `traits.rs`.
10pub struct Const<const N: usize> {}
11
12/// A trait to model compile-time constants.
13pub trait Constant {
14    type Type;
15    fn value() -> Self::Type;
16}
17
18impl<const N: usize> Constant for Const<N> {
19    type Type = usize;
20    fn value() -> Self::Type {
21        N
22    }
23}
24
25/// Mapping from a number of lanes to the underlying type for a bitmask.
26///
27/// In practice, the BitMask types are all unsigned integers.
28/// However, there is not a great way to express that directly in Rust.
29///
30/// Instead, we have a subset of requirements:
31/// * `std::default::Default`: For integers, defaults to 0.
32/// * `std::marker::Copy`: Needed so bitmasks can be copy as well.
33/// * `std::fmt::Debug`: Allow debug implementations.
34/// * `std::cmp::Eq`: Allow efficient equality.
35pub trait SupportedLaneCount {
36    type BitMaskType: std::default::Default + std::marker::Copy + std::fmt::Debug + std::cmp::Eq;
37}
38
39impl SupportedLaneCount for Const<1> {
40    type BitMaskType = u8;
41}
42
43impl SupportedLaneCount for Const<2> {
44    type BitMaskType = u8;
45}
46
47impl SupportedLaneCount for Const<4> {
48    type BitMaskType = u8;
49}
50
51impl SupportedLaneCount for Const<8> {
52    type BitMaskType = u8;
53}
54
55impl SupportedLaneCount for Const<16> {
56    type BitMaskType = u16;
57}
58
59impl SupportedLaneCount for Const<32> {
60    type BitMaskType = u32;
61}
62
63impl SupportedLaneCount for Const<64> {
64    type BitMaskType = u64;
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn test_const() {
73        let x: usize = Const::<1>::value();
74        assert_eq!(x, 1);
75
76        let x: usize = Const::<2>::value();
77        assert_eq!(x, 2);
78
79        let x: usize = Const::<4>::value();
80        assert_eq!(x, 4);
81
82        let x: usize = Const::<8>::value();
83        assert_eq!(x, 8);
84
85        let x: usize = Const::<16>::value();
86        assert_eq!(x, 16);
87
88        let x: usize = Const::<32>::value();
89        assert_eq!(x, 32);
90
91        let x: usize = Const::<64>::value();
92        assert_eq!(x, 64);
93    }
94}