qudit_core/
bitwidth.rs

1use crate::c32;
2use crate::c64;
3
4/// A trait for converting between different bit-width representations.
5pub trait BitWidthConvertible {
6    /// The 32-bit width representation of the type.
7    type Width32;
8
9    /// The 64-bit width representation of the type.
10    type Width64;
11
12    /// Converts the type into its 32-bit width representation.
13    fn to32(self) -> Self::Width32;
14
15    /// Converts the type into its 64-bit width representation.
16    fn to64(self) -> Self::Width64;
17
18    /// Constructs the type from a 32-bit width representation.
19    fn from32(width32: Self::Width32) -> Self;
20
21    /// Constructs the type from a 64-bit width representation.
22    fn from64(width64: Self::Width64) -> Self;
23}
24
25impl BitWidthConvertible for f32 {
26    type Width32 = f32;
27    type Width64 = f64;
28
29    #[inline(always)]
30    fn to32(self) -> Self::Width32 {
31        self
32    }
33
34    #[inline(always)]
35    fn to64(self) -> Self::Width64 {
36        self as f64
37    }
38
39    #[inline(always)]
40    fn from32(width32: Self::Width32) -> Self {
41        width32
42    }
43
44    #[inline(always)]
45    fn from64(width64: Self::Width64) -> Self {
46        width64 as f32
47    }
48}
49
50impl BitWidthConvertible for f64 {
51    type Width32 = f32;
52    type Width64 = f64;
53
54    #[inline(always)]
55    fn to32(self) -> Self::Width32 {
56        self as f32
57    }
58
59    #[inline(always)]
60    fn to64(self) -> Self::Width64 {
61        self
62    }
63
64    #[inline(always)]
65    fn from32(width32: Self::Width32) -> Self {
66        width32 as f64
67    }
68
69    #[inline(always)]
70    fn from64(width64: Self::Width64) -> Self {
71        width64
72    }
73}
74
75impl BitWidthConvertible for c32 {
76    type Width32 = c32;
77    type Width64 = c64;
78
79    #[inline(always)]
80    fn to32(self) -> Self::Width32 {
81        self
82    }
83
84    #[inline(always)]
85    fn to64(self) -> Self::Width64 {
86        c64::new(self.re as f64, self.im as f64)
87    }
88
89    #[inline(always)]
90    fn from32(width32: Self::Width32) -> Self {
91        width32
92    }
93
94    #[inline(always)]
95    fn from64(width64: Self::Width64) -> Self {
96        c32::new(width64.re as f32, width64.im as f32)
97    }
98}
99
100impl BitWidthConvertible for c64 {
101    type Width32 = c32;
102    type Width64 = c64;
103
104    #[inline(always)]
105    fn to32(self) -> Self::Width32 {
106        c32::new(self.re as f32, self.im as f32)
107    }
108
109    #[inline(always)]
110    fn to64(self) -> Self::Width64 {
111        self
112    }
113
114    #[inline(always)]
115    fn from32(width32: Self::Width32) -> Self {
116        c64::new(width32.re as f64, width32.im as f64)
117    }
118
119    #[inline(always)]
120    fn from64(width64: Self::Width64) -> Self {
121        width64
122    }
123}