Skip to content

Commit 8538b9c

Browse files
committed
Use grow_be_int to write sign extension code more compact
1 parent a9aadf7 commit 8538b9c

File tree

2 files changed

+2
-31
lines changed

2 files changed

+2
-31
lines changed

packages/std/src/math/int256.rs

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,20 +65,7 @@ impl Int256 {
6565
/// [`from_be_bytes`]: Self::from_be_bytes
6666
#[inline]
6767
pub const fn new(value: i128) -> Self {
68-
// See https://en.wikipedia.org/wiki/Sign_extension
69-
let b = value.to_be_bytes();
70-
if value.is_negative() {
71-
Self::from_be_bytes([
72-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
73-
0xFF, 0xFF, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10],
74-
b[11], b[12], b[13], b[14], b[15],
75-
])
76-
} else {
77-
Self::from_be_bytes([
78-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5],
79-
b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15],
80-
])
81-
}
68+
Self::from_be_bytes(grow_be_int(value.to_be_bytes()))
8269
}
8370

8471
/// Creates a Int256(0)

packages/std/src/math/int512.rs

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -66,23 +66,7 @@ impl Int512 {
6666
/// [`from_be_bytes`]: Self::from_be_bytes
6767
#[inline]
6868
pub const fn new(value: i128) -> Self {
69-
// See https://en.wikipedia.org/wiki/Sign_extension
70-
let b = value.to_be_bytes();
71-
if value.is_negative() {
72-
Self::from_be_bytes([
73-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
74-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
75-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
76-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
77-
b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15],
78-
])
79-
} else {
80-
Self::from_be_bytes([
81-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b[0], b[1], b[2], b[3],
83-
b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15],
84-
])
85-
}
69+
Self::from_be_bytes(grow_be_int(value.to_be_bytes()))
8670
}
8771

8872
/// Creates a Int512(0)

0 commit comments

Comments
 (0)