Skip to content

Commit 6625918

Browse files
committed
add const implementation of from_as_i32
1 parent 14966ed commit 6625918

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

agb-fixnum/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ num-traits = { version = "0.2", default-features = false }
1616
serde = { version = "1", features = [
1717
"derive",
1818
], default-features = false, optional = true }
19+
typewit = "1.14.2"
1920

2021
[build-dependencies]
2122
quote = "1"

agb-fixnum/src/integer.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use core::{
44
};
55

66
use num_traits::Signed;
7+
use typewit::HasTypeWitness;
78

89
/// A trait for integers that don't implement unary negation
910
pub trait FixedWidthUnsignedInteger:
@@ -18,6 +19,7 @@ pub trait FixedWidthUnsignedInteger:
1819
+ num_traits::Num
1920
+ Not<Output = Self>
2021
+ num_traits::AsPrimitive<usize>
22+
+ HasTypeWitness<IntegerWitness<Self>>
2123
{
2224
/// Converts an i32 to it's own representation, panics on failure
2325
fn from_as_i32(v: i32) -> Self;
@@ -81,3 +83,27 @@ fixed_width_unsigned_integer_impl!(u16, u32);
8183

8284
fixed_width_unsigned_integer_impl!(i32, optimised_64_bit);
8385
fixed_width_unsigned_integer_impl!(u32, optimised_64_bit);
86+
87+
#[doc(hidden)]
88+
/// A const implemnetation of the trait method `from_as_i32`.
89+
pub const fn from_as_i32<I: FixedWidthUnsignedInteger>(n: i32) -> I {
90+
match HasTypeWitness::WITNESS {
91+
IntegerWitness::U32(x) => x.to_left(n as u32),
92+
IntegerWitness::I16(x) => x.to_left(n as i16),
93+
IntegerWitness::I32(x) => x.to_left(n as i32),
94+
IntegerWitness::U16(x) => x.to_left(n as u16),
95+
IntegerWitness::I8(x) => x.to_left(n as i8),
96+
IntegerWitness::U8(x) => x.to_left(n as u8),
97+
}
98+
}
99+
100+
typewit::simple_type_witness! {
101+
enum IntegerWitness {
102+
I32 = i32,
103+
U32 = u32,
104+
I16 = i16,
105+
U16 = u16,
106+
I8 = i8,
107+
U8 = u8,
108+
}
109+
}

0 commit comments

Comments
 (0)