1 // Copyright 2021 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Helper functions that operate on {Digits} vectors of digits.
6
7 #ifndef V8_BIGINT_VECTOR_ARITHMETIC_H_
8 #define V8_BIGINT_VECTOR_ARITHMETIC_H_
9
10 #include "src/bigint/bigint.h"
11 #include "src/bigint/digit-arithmetic.h"
12
13 namespace v8 {
14 namespace bigint {
15
16 // Z += X. Returns carry on overflow.
17 digit_t AddAndReturnOverflow(RWDigits Z, Digits X);
18
19 // Z -= X. Returns borrow on overflow.
20 digit_t SubAndReturnBorrow(RWDigits Z, Digits X);
21
22 // X += y.
Add(RWDigits X,digit_t y)23 inline void Add(RWDigits X, digit_t y) {
24 digit_t carry = y;
25 int i = 0;
26 do {
27 X[i] = digit_add2(X[i], carry, &carry);
28 i++;
29 } while (carry != 0);
30 }
31
32 // X -= y.
Subtract(RWDigits X,digit_t y)33 inline void Subtract(RWDigits X, digit_t y) {
34 digit_t borrow = y;
35 int i = 0;
36 do {
37 X[i] = digit_sub(X[i], borrow, &borrow);
38 i++;
39 } while (borrow != 0);
40 }
41
42 // These add exactly Y's digits to the matching digits in X, storing the
43 // result in (part of) Z, and return the carry/borrow.
44 digit_t AddAndReturnCarry(RWDigits Z, Digits X, Digits Y);
45 digit_t SubtractAndReturnBorrow(RWDigits Z, Digits X, Digits Y);
46
IsDigitNormalized(Digits X)47 inline bool IsDigitNormalized(Digits X) { return X.len() == 0 || X.msd() != 0; }
IsBitNormalized(Digits X)48 inline bool IsBitNormalized(Digits X) {
49 return (X.msd() >> (kDigitBits - 1)) == 1;
50 }
51
GreaterThanOrEqual(Digits A,Digits B)52 inline bool GreaterThanOrEqual(Digits A, Digits B) {
53 return Compare(A, B) >= 0;
54 }
55
BitLength(Digits X)56 inline int BitLength(Digits X) {
57 return X.len() * kDigitBits - CountLeadingZeros(X.msd());
58 }
59
60 } // namespace bigint
61 } // namespace v8
62
63 #endif // V8_BIGINT_VECTOR_ARITHMETIC_H_
64