Skip to content

Commit 311e115

Browse files
committed
address review comments: compile-time check, avoid extra mem copying
1 parent 8642dab commit 311e115

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

soroban-sdk/src/crypto/bls12_381.rs

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,21 +34,30 @@ impl<const N: usize> BigInt<N> {
3434
borrow != 0
3535
}
3636

37-
pub fn copy_into_slice(&self, slice: &mut [u8]) {
38-
if slice.len() != N * 8 {
39-
sdk_panic!("BigInt::copy_into_slice with mismatched slice length")
37+
pub fn copy_into_array<const M: usize>(&self, slice: &mut [u8; M]) {
38+
const {
39+
if M != N * 8 {
40+
panic!("BigInt::copy_into_array with mismatched array length")
41+
}
4042
}
43+
4144
for i in 0..N {
4245
let limb_bytes = self.0[N - 1 - i].to_be_bytes();
4346
slice[i * 8..(i + 1) * 8].copy_from_slice(&limb_bytes);
4447
}
4548
}
49+
50+
pub fn is_zero(&self) -> bool {
51+
self.0 == [0; N]
52+
}
4653
}
4754

48-
impl<const N: usize, const M: usize> Into<BigInt<N>> for BytesN<M> {
55+
impl<const N: usize, const M: usize> Into<BigInt<N>> for &BytesN<M> {
4956
fn into(self) -> BigInt<N> {
50-
if M != N * 8 {
51-
sdk_panic!("BytesN::Into<BigInt> - length mismatch")
57+
const {
58+
if M != N * 8 {
59+
panic!("BytesN::Into<BigInt> - length mismatch")
60+
}
5261
}
5362

5463
let array = self.to_array();
@@ -154,6 +163,8 @@ impl Fp {
154163
self.0.env()
155164
}
156165

166+
/// Maps to a `G1Affine` point via [simplified SWU
167+
/// mapping](https://www.rfc-editor.org/rfc/rfc9380.html#name-simplified-swu-for-ab-0)
157168
pub fn map_to_g1(&self) -> G1Affine {
158169
self.env().crypto().bls12_381().map_fp_to_g1(self)
159170
}
@@ -177,12 +188,11 @@ impl Neg for Fp {
177188
type Output = Fp;
178189

179190
fn neg(self) -> Self::Output {
180-
if self.to_array() == [0; 48] {
191+
let fp_bigint: BigInt<6> = (&self.0).into();
192+
if fp_bigint.is_zero() {
181193
return self;
182194
}
183195

184-
let env = self.env().clone();
185-
let fp_bigint: BigInt<6> = self.0.into();
186196
// BLS12-381 base field modulus
187197
let mut res = BigInt([
188198
13402431016077863595,
@@ -195,8 +205,8 @@ impl Neg for Fp {
195205
// Compute modulus - value
196206
res.sub_with_borrow(&fp_bigint);
197207
let mut bytes = [0u8; 48];
198-
res.copy_into_slice(&mut bytes);
199-
Fp::from_array(&env, &bytes)
208+
res.copy_into_array(&mut bytes);
209+
Fp::from_array(&self.env(), &bytes)
200210
}
201211
}
202212

0 commit comments

Comments
 (0)