1use crate::common::*;
4
5pub trait IntoSize
9where
10 Self::Output: Size,
11{
12 type Output;
13 fn into_size(self) -> Self::Output;
14}
15
16impl IntoSize for usize {
17 type Output = Dyn;
18
19 fn into_size(self) -> Self::Output {
20 Dyn(self)
21 }
22}
23
24impl IntoSize for Dyn {
25 type Output = Self;
26
27 fn into_size(self) -> Self::Output {
28 self
29 }
30}
31
32impl IntoSize for UTerm {
33 type Output = Self;
34
35 fn into_size(self) -> Self::Output {
36 self
37 }
38}
39
40impl<U, B> IntoSize for UInt<U, B>
41where
42 U: Unsigned,
43 B: Bit,
44{
45 type Output = Self;
46
47 fn into_size(self) -> Self::Output {
48 self
49 }
50}
51
52pub trait Size {
56 fn to_usize(&self) -> usize;
57}
58
59impl Size for Dyn {
60 fn to_usize(&self) -> usize {
61 self.0
62 }
63}
64
65impl Size for UTerm {
66 fn to_usize(&self) -> usize {
67 Self::USIZE
68 }
69}
70
71impl<U, B> Size for UInt<U, B>
72where
73 U: Unsigned,
74 B: Bit,
75{
76 fn to_usize(&self) -> usize {
77 Self::USIZE
78 }
79}
80
81pub struct Dyn(usize);
85
86typ! {
89 pub fn IsDyn<size>(size: Size) -> Bit {
90 match size {
91 Dyn => true,
92 UTerm => false,
93 #[generics(uint: Unsigned, bit: Bit)]
94 UInt::<uint, bit> => false,
95 }
96 }
97
98 pub fn IncreaseOne<size>(size: Size) -> Size {
99 match size {
100 Dyn => Dyn,
101 UTerm => U1,
102 #[generics(uint: Unsigned, bit: Bit)]
103 UInt::<uint, bit> => UInt::<uint, bit> + 1u,
104 }
105 }
106
107 pub fn DecreaseOne<size>(size: Size) -> Size {
108 match size {
109 Dyn => Option::<Dyn>,
110 #[generics(uint: Unsigned, bit: Bit)]
111 UInt::<uint, bit> => UInt::<uint, bit> - 1u
112 }
113 }
114
115 pub fn SizeAdd<lhs, rhs>(lhs: Size, rhs: Size) -> Size {
116 if IsDyn(lhs) || IsDyn(rhs) {
117 Dyn
118 } else {
119 lhs + rhs
120 }
121 }
122
123 pub fn CheckIndex<length, index>(length: Size, index: Size) {
124 if IsDyn(length) || IsDyn(index) {
125 Option::<()>
126 } else {
127 match index >= 0u && index < length {
128 B1 => (),
129 }
130 }
131 }
132
133 pub fn CheckIndexInclusive<length, index>(length: Size, index: Size) {
134 if IsDyn(length) || IsDyn(index) {
135 Option::<()>
136 } else {
137 match index >= 0u && index <= length {
138 B1 => (),
139 }
140 }
141 }
142}