Skip to content

Commit 8f82748

Browse files
committed
Implement const conversion Uint128 -> Uint256
1 parent c364aa8 commit 8f82748

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

packages/std/src/math/uint256.rs

+4
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,10 @@ impl Uint256 {
286286
pub fn saturating_mul(self, other: Self) -> Self {
287287
Self(self.0.saturating_mul(other.0))
288288
}
289+
290+
pub(crate) const fn to_words(self) -> [u64; 4] {
291+
self.0 .0
292+
}
289293
}
290294

291295
impl From<Uint128> for Uint256 {

packages/std/src/math/uint512.rs

+42
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,22 @@ impl Uint512 {
9999
Uint512(U512::from_little_endian(&value))
100100
}
101101

102+
pub const fn from_uint256(num: Uint256) -> Self {
103+
let uint256_words = num.to_words();
104+
let words: [u64; 8] = [
105+
uint256_words[0],
106+
uint256_words[1],
107+
uint256_words[2],
108+
uint256_words[3],
109+
0,
110+
0,
111+
0,
112+
0,
113+
];
114+
115+
Self(U512(words))
116+
}
117+
102118
/// Returns a copy of the number as big endian bytes.
103119
pub const fn to_be_bytes(self) -> [u8; 64] {
104120
let words = [
@@ -719,6 +735,32 @@ mod tests {
719735
);
720736
}
721737

738+
#[test]
739+
fn uint512_from_uint256() {
740+
assert_eq!(
741+
Uint512::from_uint256(Uint256::from_str("123").unwrap()),
742+
Uint512::from_str("123").unwrap()
743+
);
744+
745+
assert_eq!(
746+
Uint512::from_uint256(Uint256::from_str("9785746283745").unwrap()),
747+
Uint512::from_str("9785746283745").unwrap()
748+
);
749+
750+
assert_eq!(
751+
Uint512::from_uint256(
752+
Uint256::from_str(
753+
"97857462837575757832978493758398593853985452378423874623874628736482736487236"
754+
)
755+
.unwrap()
756+
),
757+
Uint512::from_str(
758+
"97857462837575757832978493758398593853985452378423874623874628736482736487236"
759+
)
760+
.unwrap()
761+
);
762+
}
763+
722764
#[test]
723765
fn uint512_implements_display() {
724766
let a = Uint512::from(12345u32);

0 commit comments

Comments
 (0)