Skip to content

Commit c152a67

Browse files
committed
std/math/big: add Int.Bytes
1 parent 8dc6cdd commit c152a67

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

std/math/big/int.jule

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -923,6 +923,17 @@ impl Int {
923923
ret buf
924924
}
925925

926+
// Returns the absolute value of x as a big-endian byte slice.
927+
//
928+
// To use a fixed length slice, or a preallocated one, use [Int.FillBytes].
929+
fn Bytes(*self): []byte {
930+
// This function is may used in cryptographic operations. It must not leak
931+
// anything but the Int's sign and bit size through side-channels. Any
932+
// changes must be reviewed by a security expert.
933+
mut buf := make([]byte, len(self.abs)*_S)
934+
ret buf[bytesW(self.abs, buf):]
935+
}
936+
926937
// Sets self to x.
927938
fn SetU64(mut *self, x: u64) {
928939
setWU64(&self.abs, x)

std/math/big/int_test.jule

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,4 +225,21 @@ fn testBinomial(t: &testing::T) {
225225
t.Errorf("Binomial({}, {}) = {}; want {}", test.n, test.k, prod, test.want)
226226
}
227227
}
228+
}
229+
230+
#test
231+
fn testSetBytes(t: &testing::T) {
232+
for _, prime in primes {
233+
let mut i: Int
234+
i.SetStr(prime, 0)
235+
236+
bytes := i.Bytes()
237+
238+
let mut j: Int
239+
j.SetBytes(bytes)
240+
241+
if i.Cmp(&j) != 0 {
242+
t.Errorf("Failed: {}", prime)
243+
}
244+
}
228245
}

0 commit comments

Comments
 (0)