code
stringlengths
11
173k
docstring
stringlengths
2
593k
func_name
stringlengths
2
189
language
stringclasses
1 value
repo
stringclasses
833 values
path
stringlengths
11
294
url
stringlengths
60
339
license
stringclasses
4 values
private MutableBigInteger divideMagnitude(MutableBigInteger div, MutableBigInteger quotient, boolean needRemainder ) { // assert div.intLen > 1 // D1 normalize the divisor int shift = Integer.numberOfLeadingZeros(div.value[div.offset]); // Copy divisor value to protect divisor final int dlen = div.intLen; int[] divisor; MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero if (shift > 0) { divisor = new int[dlen]; copyAndShift(div.value,div.offset,dlen,divisor,0,shift); if (Integer.numberOfLeadingZeros(value[offset]) >= shift) { int[] remarr = new int[intLen + 1]; rem = new MutableBigInteger(remarr); rem.intLen = intLen; rem.offset = 1; copyAndShift(value,offset,intLen,remarr,1,shift); } else { int[] remarr = new int[intLen + 2]; rem = new MutableBigInteger(remarr); rem.intLen = intLen+1; rem.offset = 1; int rFrom = offset; int c=0; int n2 = 32 - shift; for (int i=1; i < intLen+1; i++,rFrom++) { int b = c; c = value[rFrom]; remarr[i] = (b << shift) | (c >>> n2); } remarr[intLen+1] = c << shift; } } else { divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen); rem = new MutableBigInteger(new int[intLen + 1]); System.arraycopy(value, offset, rem.value, 1, intLen); rem.intLen = intLen; rem.offset = 1; } int nlen = rem.intLen; // Set the quotient size final int limit = nlen - dlen + 1; if (quotient.value.length < limit) { quotient.value = new int[limit]; quotient.offset = 0; } quotient.intLen = limit; int[] q = quotient.value; // Must insert leading 0 in rem if its length did not change if (rem.intLen == nlen) { rem.offset = 0; rem.value[0] = 0; rem.intLen++; } int dh = divisor[0]; long dhLong = dh & LONG_MASK; int dl = divisor[1]; // D2 Initialize j for (int j=0; j < limit-1; j++) { // D3 Calculate qhat // estimate qhat int qhat = 0; int qrem = 0; boolean skipCorrection = false; int nh = rem.value[j+rem.offset]; int nh2 = nh + 0x80000000; int nm = rem.value[j+1+rem.offset]; if (nh == dh) { qhat = ~0; qrem = nh + nm; skipCorrection = qrem + 0x80000000 < nh2; } else { long nChunk = (((long)nh) << 32) | (nm & LONG_MASK); if (nChunk >= 0) { qhat = (int) (nChunk / dhLong); qrem = (int) (nChunk - (qhat * dhLong)); } else { long tmp = divWord(nChunk, dh); qhat = (int) (tmp & LONG_MASK); qrem = (int) (tmp >>> 32); } } if (qhat == 0) continue; if (!skipCorrection) { // Correct qhat long nl = rem.value[j+2+rem.offset] & LONG_MASK; long rs = ((qrem & LONG_MASK) << 32) | nl; long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); if (unsignedLongCompare(estProduct, rs)) { qhat--; qrem = (int)((qrem & LONG_MASK) + dhLong); if ((qrem & LONG_MASK) >= dhLong) { estProduct -= (dl & LONG_MASK); rs = ((qrem & LONG_MASK) << 32) | nl; if (unsignedLongCompare(estProduct, rs)) qhat--; } } } // D4 Multiply and subtract rem.value[j+rem.offset] = 0; int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset); // D5 Test remainder if (borrow + 0x80000000 > nh2) { // D6 Add back divadd(divisor, rem.value, j+1+rem.offset); qhat--; } // Store the quotient digit q[j] = qhat; } // D7 loop on j // D3 Calculate qhat // estimate qhat int qhat = 0; int qrem = 0; boolean skipCorrection = false; int nh = rem.value[limit - 1 + rem.offset]; int nh2 = nh + 0x80000000; int nm = rem.value[limit + rem.offset]; if (nh == dh) { qhat = ~0; qrem = nh + nm; skipCorrection = qrem + 0x80000000 < nh2; } else { long nChunk = (((long) nh) << 32) | (nm & LONG_MASK); if (nChunk >= 0) { qhat = (int) (nChunk / dhLong); qrem = (int) (nChunk - (qhat * dhLong)); } else { long tmp = divWord(nChunk, dh); qhat = (int) (tmp & LONG_MASK); qrem = (int) (tmp >>> 32); } } if (qhat != 0) { if (!skipCorrection) { // Correct qhat long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK; long rs = ((qrem & LONG_MASK) << 32) | nl; long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); if (unsignedLongCompare(estProduct, rs)) { qhat--; qrem = (int) ((qrem & LONG_MASK) + dhLong); if ((qrem & LONG_MASK) >= dhLong) { estProduct -= (dl & LONG_MASK); rs = ((qrem & LONG_MASK) << 32) | nl; if (unsignedLongCompare(estProduct, rs)) qhat--; } } } // D4 Multiply and subtract int borrow; rem.value[limit - 1 + rem.offset] = 0; if(needRemainder) borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset); else borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset); // D5 Test remainder if (borrow + 0x80000000 > nh2) { // D6 Add back if(needRemainder) divadd(divisor, rem.value, limit - 1 + 1 + rem.offset); qhat--; } // Store the quotient digit q[(limit - 1)] = qhat; } if (needRemainder) { // D8 Unnormalize if (shift > 0) rem.rightShift(shift); rem.normalize(); } quotient.normalize(); return needRemainder ? rem : null; }
Divide this MutableBigInteger by the divisor. The quotient will be placed into the provided quotient object & the remainder object is returned.
MutableBigInteger::divideMagnitude
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) { // Remainder starts as dividend with space for a leading zero MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]); System.arraycopy(value, offset, rem.value, 1, intLen); rem.intLen = intLen; rem.offset = 1; int nlen = rem.intLen; int limit = nlen - 2 + 1; if (quotient.value.length < limit) { quotient.value = new int[limit]; quotient.offset = 0; } quotient.intLen = limit; int[] q = quotient.value; // D1 normalize the divisor int shift = Long.numberOfLeadingZeros(ldivisor); if (shift > 0) { ldivisor<<=shift; rem.leftShift(shift); } // Must insert leading 0 in rem if its length did not change if (rem.intLen == nlen) { rem.offset = 0; rem.value[0] = 0; rem.intLen++; } int dh = (int)(ldivisor >>> 32); long dhLong = dh & LONG_MASK; int dl = (int)(ldivisor & LONG_MASK); // D2 Initialize j for (int j = 0; j < limit; j++) { // D3 Calculate qhat // estimate qhat int qhat = 0; int qrem = 0; boolean skipCorrection = false; int nh = rem.value[j + rem.offset]; int nh2 = nh + 0x80000000; int nm = rem.value[j + 1 + rem.offset]; if (nh == dh) { qhat = ~0; qrem = nh + nm; skipCorrection = qrem + 0x80000000 < nh2; } else { long nChunk = (((long) nh) << 32) | (nm & LONG_MASK); if (nChunk >= 0) { qhat = (int) (nChunk / dhLong); qrem = (int) (nChunk - (qhat * dhLong)); } else { long tmp = divWord(nChunk, dh); qhat =(int)(tmp & LONG_MASK); qrem = (int)(tmp>>>32); } } if (qhat == 0) continue; if (!skipCorrection) { // Correct qhat long nl = rem.value[j + 2 + rem.offset] & LONG_MASK; long rs = ((qrem & LONG_MASK) << 32) | nl; long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); if (unsignedLongCompare(estProduct, rs)) { qhat--; qrem = (int) ((qrem & LONG_MASK) + dhLong); if ((qrem & LONG_MASK) >= dhLong) { estProduct -= (dl & LONG_MASK); rs = ((qrem & LONG_MASK) << 32) | nl; if (unsignedLongCompare(estProduct, rs)) qhat--; } } } // D4 Multiply and subtract rem.value[j + rem.offset] = 0; int borrow = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset); // D5 Test remainder if (borrow + 0x80000000 > nh2) { // D6 Add back divaddLong(dh,dl, rem.value, j + 1 + rem.offset); qhat--; } // Store the quotient digit q[j] = qhat; } // D7 loop on j // D8 Unnormalize if (shift > 0) rem.rightShift(shift); quotient.normalize(); rem.normalize(); return rem; }
Divide this MutableBigInteger by the divisor represented by positive long value. The quotient will be placed into the provided quotient object & the remainder object is returned.
MutableBigInteger::divideLongMagnitude
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
private int divaddLong(int dh, int dl, int[] result, int offset) { long carry = 0; long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK); result[1+offset] = (int)sum; sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry; result[offset] = (int)sum; carry = sum >>> 32; return (int)carry; }
A primitive used for division by long. Specialized version of the method divadd. dh is a high part of the divisor, dl is a low part
MutableBigInteger::divaddLong
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
static long divWord(long n, int d) { long dLong = d & LONG_MASK; long r; long q; if (dLong == 1) { q = (int)n; r = 0; return (r << 32) | (q & LONG_MASK); } // Approximate the quotient and remainder q = (n >>> 1) / (dLong >>> 1); r = n - q*dLong; // Correct the approximation while (r < 0) { r += dLong; q--; } while (r >= dLong) { r -= dLong; q++; } // n - q*dlong == r && 0 <= r <dLong, hence we're done. return (r << 32) | (q & LONG_MASK); }
This method divides a long quantity by an int to estimate qhat for two multi precision numbers. It is used when the signed value of n is less than zero. Returns long value where high 32 bits contain remainder value and low 32 bits contain quotient value.
MutableBigInteger::divWord
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
MutableBigInteger hybridGCD(MutableBigInteger b) { // Use Euclid's algorithm until the numbers are approximately the // same length, then use the binary GCD algorithm to find the GCD. MutableBigInteger a = this; MutableBigInteger q = new MutableBigInteger(); while (b.intLen != 0) { if (Math.abs(a.intLen - b.intLen) < 2) return a.binaryGCD(b); MutableBigInteger r = a.divide(b, q); a = b; b = r; } return a; }
Calculate GCD of this and b. This and b are changed by the computation.
MutableBigInteger::hybridGCD
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
private MutableBigInteger binaryGCD(MutableBigInteger v) { // Algorithm B from Knuth section 4.5.2 MutableBigInteger u = this; MutableBigInteger r = new MutableBigInteger(); // step B1 int s1 = u.getLowestSetBit(); int s2 = v.getLowestSetBit(); int k = (s1 < s2) ? s1 : s2; if (k != 0) { u.rightShift(k); v.rightShift(k); } // step B2 boolean uOdd = (k == s1); MutableBigInteger t = uOdd ? v: u; int tsign = uOdd ? -1 : 1; int lb; while ((lb = t.getLowestSetBit()) >= 0) { // steps B3 and B4 t.rightShift(lb); // step B5 if (tsign > 0) u = t; else v = t; // Special case one word numbers if (u.intLen < 2 && v.intLen < 2) { int x = u.value[u.offset]; int y = v.value[v.offset]; x = binaryGcd(x, y); r.value[0] = x; r.intLen = 1; r.offset = 0; if (k > 0) r.leftShift(k); return r; } // step B6 if ((tsign = u.difference(v)) == 0) break; t = (tsign >= 0) ? u : v; } if (k > 0) u.leftShift(k); return u; }
Calculate GCD of this and v. Assumes that this and v are not zero.
MutableBigInteger::binaryGCD
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
static int binaryGcd(int a, int b) { if (b == 0) return a; if (a == 0) return b; // Right shift a & b till their last bits equal to 1. int aZeros = Integer.numberOfTrailingZeros(a); int bZeros = Integer.numberOfTrailingZeros(b); a >>>= aZeros; b >>>= bZeros; int t = (aZeros < bZeros ? aZeros : bZeros); while (a != b) { if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return a<<t; }
Calculate GCD of a and b interpreted as unsigned integers.
MutableBigInteger::binaryGcd
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
MutableBigInteger mutableModInverse(MutableBigInteger p) { // Modulus is odd, use Schroeppel's algorithm if (p.isOdd()) return modInverse(p); // Base and modulus are even, throw exception if (isEven()) throw new ArithmeticException("BigInteger not invertible."); // Get even part of modulus expressed as a power of 2 int powersOf2 = p.getLowestSetBit(); // Construct odd part of modulus MutableBigInteger oddMod = new MutableBigInteger(p); oddMod.rightShift(powersOf2); if (oddMod.isOne()) return modInverseMP2(powersOf2); // Calculate 1/a mod oddMod MutableBigInteger oddPart = modInverse(oddMod); // Calculate 1/a mod evenMod MutableBigInteger evenPart = modInverseMP2(powersOf2); // Combine the results using Chinese Remainder Theorem MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2); MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2); MutableBigInteger temp1 = new MutableBigInteger(); MutableBigInteger temp2 = new MutableBigInteger(); MutableBigInteger result = new MutableBigInteger(); oddPart.leftShift(powersOf2); oddPart.multiply(y1, result); evenPart.multiply(oddMod, temp1); temp1.multiply(y2, temp2); result.add(temp2); return result.divide(p, temp1); }
Returns the modInverse of this mod p. This and p are not affected by the operation.
MutableBigInteger::mutableModInverse
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
MutableBigInteger modInverseMP2(int k) { if (isEven()) throw new ArithmeticException("Non-invertible. (GCD != 1)"); if (k > 64) return euclidModInverse(k); int t = inverseMod32(value[offset+intLen-1]); if (k < 33) { t = (k == 32 ? t : t & ((1 << k) - 1)); return new MutableBigInteger(t); } long pLong = (value[offset+intLen-1] & LONG_MASK); if (intLen > 1) pLong |= ((long)value[offset+intLen-2] << 32); long tLong = t & LONG_MASK; tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1)); MutableBigInteger result = new MutableBigInteger(new int[2]); result.value[0] = (int)(tLong >>> 32); result.value[1] = (int)tLong; result.intLen = 2; result.normalize(); return result; }
Returns the modInverse of this mod p. This and p are not affected by the operation. MutableBigInteger mutableModInverse(MutableBigInteger p) { // Modulus is odd, use Schroeppel's algorithm if (p.isOdd()) return modInverse(p); // Base and modulus are even, throw exception if (isEven()) throw new ArithmeticException("BigInteger not invertible."); // Get even part of modulus expressed as a power of 2 int powersOf2 = p.getLowestSetBit(); // Construct odd part of modulus MutableBigInteger oddMod = new MutableBigInteger(p); oddMod.rightShift(powersOf2); if (oddMod.isOne()) return modInverseMP2(powersOf2); // Calculate 1/a mod oddMod MutableBigInteger oddPart = modInverse(oddMod); // Calculate 1/a mod evenMod MutableBigInteger evenPart = modInverseMP2(powersOf2); // Combine the results using Chinese Remainder Theorem MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2); MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2); MutableBigInteger temp1 = new MutableBigInteger(); MutableBigInteger temp2 = new MutableBigInteger(); MutableBigInteger result = new MutableBigInteger(); oddPart.leftShift(powersOf2); oddPart.multiply(y1, result); evenPart.multiply(oddMod, temp1); temp1.multiply(y2, temp2); result.add(temp2); return result.divide(p, temp1); } /* Calculate the multiplicative inverse of this mod 2^k.
MutableBigInteger::modInverseMP2
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
static int inverseMod32(int val) { // Newton's iteration! int t = val; t *= 2 - val*t; t *= 2 - val*t; t *= 2 - val*t; t *= 2 - val*t; return t; }
Returns the multiplicative inverse of val mod 2^32. Assumes val is odd.
MutableBigInteger::inverseMod32
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) { // Copy the mod to protect original return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k); }
Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.
MutableBigInteger::modInverseBP2
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
private MutableBigInteger modInverse(MutableBigInteger mod) { MutableBigInteger p = new MutableBigInteger(mod); MutableBigInteger f = new MutableBigInteger(this); MutableBigInteger g = new MutableBigInteger(p); SignedMutableBigInteger c = new SignedMutableBigInteger(1); SignedMutableBigInteger d = new SignedMutableBigInteger(); MutableBigInteger temp = null; SignedMutableBigInteger sTemp = null; int k = 0; // Right shift f k times until odd, left shift d k times if (f.isEven()) { int trailingZeros = f.getLowestSetBit(); f.rightShift(trailingZeros); d.leftShift(trailingZeros); k = trailingZeros; } // The Almost Inverse Algorithm while (!f.isOne()) { // If gcd(f, g) != 1, number is not invertible modulo mod if (f.isZero()) throw new ArithmeticException("BigInteger not invertible."); // If f < g exchange f, g and c, d if (f.compare(g) < 0) { temp = f; f = g; g = temp; sTemp = d; d = c; c = sTemp; } // If f == g (mod 4) if (((f.value[f.offset + f.intLen - 1] ^ g.value[g.offset + g.intLen - 1]) & 3) == 0) { f.subtract(g); c.signedSubtract(d); } else { // If f != g (mod 4) f.add(g); c.signedAdd(d); } // Right shift f k times until odd, left shift d k times int trailingZeros = f.getLowestSetBit(); f.rightShift(trailingZeros); d.leftShift(trailingZeros); k += trailingZeros; } while (c.sign < 0) c.signedAdd(p); return fixup(c, p, k); }
Calculate the multiplicative inverse of this mod mod, where mod is odd. This and mod are not changed by the calculation. This method implements an algorithm due to Richard Schroeppel, that uses the same intermediate representation as Montgomery Reduction ("Montgomery Form"). The algorithm is described in an unpublished manuscript entitled "Fast Modular Reciprocals."
MutableBigInteger::modInverse
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p, int k) { MutableBigInteger temp = new MutableBigInteger(); // Set r to the multiplicative inverse of p mod 2^32 int r = -inverseMod32(p.value[p.offset+p.intLen-1]); for (int i=0, numWords = k >> 5; i < numWords; i++) { // V = R * c (mod 2^j) int v = r * c.value[c.offset + c.intLen-1]; // c = c + (v * p) p.mul(v, temp); c.add(temp); // c = c / 2^j c.intLen--; } int numBits = k & 0x1f; if (numBits != 0) { // V = R * c (mod 2^j) int v = r * c.value[c.offset + c.intLen-1]; v &= ((1<<numBits) - 1); // c = c + (v * p) p.mul(v, temp); c.add(temp); // c = c / 2^j c.rightShift(numBits); } // In theory, c may be greater than p at this point (Very rare!) while (c.compare(p) >= 0) c.subtract(p); return c; }
The Fixup Algorithm Calculates X such that X = C * 2^(-k) (mod P) Assumes C<P and P is odd.
MutableBigInteger::fixup
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
MutableBigInteger euclidModInverse(int k) { MutableBigInteger b = new MutableBigInteger(1); b.leftShift(k); MutableBigInteger mod = new MutableBigInteger(b); MutableBigInteger a = new MutableBigInteger(this); MutableBigInteger q = new MutableBigInteger(); MutableBigInteger r = b.divide(a, q); MutableBigInteger swapper = b; // swap b & r b = r; r = swapper; MutableBigInteger t1 = new MutableBigInteger(q); MutableBigInteger t0 = new MutableBigInteger(1); MutableBigInteger temp = new MutableBigInteger(); while (!b.isOne()) { r = a.divide(b, q); if (r.intLen == 0) throw new ArithmeticException("BigInteger not invertible."); swapper = r; a = swapper; if (q.intLen == 1) t1.mul(q.value[q.offset], temp); else q.multiply(t1, temp); swapper = q; q = temp; temp = swapper; t0.add(q); if (a.isOne()) return t0; r = b.divide(a, q); if (r.intLen == 0) throw new ArithmeticException("BigInteger not invertible."); swapper = b; b = r; if (q.intLen == 1) t0.mul(q.value[q.offset], temp); else q.multiply(t0, temp); swapper = q; q = temp; temp = swapper; t1.add(q); } mod.subtract(t1); return mod; }
Uses the extended Euclidean algorithm to compute the modInverse of base mod a modulus that is a power of 2. The modulus is 2^k.
MutableBigInteger::euclidModInverse
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
Apache-2.0
public MathContext(int setPrecision) { this(setPrecision, DEFAULT_ROUNDINGMODE); return; }
Constructs a new {@code MathContext} with the specified precision and the {@link RoundingMode#HALF_UP HALF_UP} rounding mode. @param setPrecision The non-negative {@code int} precision setting. @throws IllegalArgumentException if the {@code setPrecision} parameter is less than zero.
MathContext::MathContext
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
public MathContext(int setPrecision, RoundingMode setRoundingMode) { if (setPrecision < MIN_DIGITS) throw new IllegalArgumentException("Digits < 0"); if (setRoundingMode == null) throw new NullPointerException("null RoundingMode"); precision = setPrecision; roundingMode = setRoundingMode; return; }
Constructs a new {@code MathContext} with a specified precision and rounding mode. @param setPrecision The non-negative {@code int} precision setting. @param setRoundingMode The rounding mode to use. @throws IllegalArgumentException if the {@code setPrecision} parameter is less than zero. @throws NullPointerException if the rounding mode argument is {@code null}
MathContext::MathContext
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
public MathContext(String val) { boolean bad = false; int setPrecision; if (val == null) throw new NullPointerException("null String"); try { // any error here is a string format problem if (!val.startsWith("precision=")) throw new RuntimeException(); int fence = val.indexOf(' '); // could be -1 int off = 10; // where value starts setPrecision = Integer.parseInt(val.substring(10, fence)); if (!val.startsWith("roundingMode=", fence+1)) throw new RuntimeException(); off = fence + 1 + 13; String str = val.substring(off, val.length()); roundingMode = RoundingMode.valueOf(str); } catch (RuntimeException re) { throw new IllegalArgumentException("bad string format"); } if (setPrecision < MIN_DIGITS) throw new IllegalArgumentException("Digits < 0"); // the other parameters cannot be invalid if we got here precision = setPrecision; }
Constructs a new {@code MathContext} from a string. The string must be in the same format as that produced by the {@link #toString} method. <p>An {@code IllegalArgumentException} is thrown if the precision section of the string is out of range ({@code < 0}) or the string is not in the format created by the {@link #toString} method. @param val The string to be parsed @throws IllegalArgumentException if the precision section is out of range or of incorrect format @throws NullPointerException if the argument is {@code null}
MathContext::MathContext
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
public boolean equals(Object x){ MathContext mc; if (!(x instanceof MathContext)) return false; mc = (MathContext) x; return mc.precision == this.precision && mc.roundingMode == this.roundingMode; // no need for .equals() }
Compares this {@code MathContext} with the specified {@code Object} for equality. @param x {@code Object} to which this {@code MathContext} is to be compared. @return {@code true} if and only if the specified {@code Object} is a {@code MathContext} object which has exactly the same settings as this object
MathContext::equals
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
public int hashCode() { return this.precision + roundingMode.hashCode() * 59; }
Returns the hash code for this {@code MathContext}. @return hash code for this {@code MathContext}
MathContext::hashCode
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
public java.lang.String toString() { return "precision=" + precision + " " + "roundingMode=" + roundingMode.toString(); }
Returns the string representation of this {@code MathContext}. The {@code String} returned represents the settings of the {@code MathContext} object as two space-delimited words (separated by a single space character, <tt>'&#92;u0020'</tt>, and with no leading or trailing white space), as follows: <ol> <li> The string {@code "precision="}, immediately followed by the value of the precision setting as a numeric string as if generated by the {@link Integer#toString(int) Integer.toString} method. <li> The string {@code "roundingMode="}, immediately followed by the value of the {@code roundingMode} setting as a word. This word will be the same as the name of the corresponding public constant in the {@link RoundingMode} enum. </ol> <p> For example: <pre> precision=9 roundingMode=HALF_UP </pre> Additional words may be appended to the result of {@code toString} in the future if more properties are added to this class. @return a {@code String} representing the context settings
MathContext::toString
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // read in all fields // validate possibly bad fields if (precision < MIN_DIGITS) { String message = "MathContext: invalid digits in stream"; throw new java.io.StreamCorruptedException(message); } if (roundingMode == null) { String message = "MathContext: null roundingMode in stream"; throw new java.io.StreamCorruptedException(message); } }
Reconstitute the {@code MathContext} instance from a stream (that is, deserialize it). @param s the stream being read.
MathContext::readObject
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MathContext.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/MathContext.java
Apache-2.0
public BigInteger add(BigInteger val) { if (val.signum == 0) return this; if (signum == 0) return val; if (val.signum == signum) return new BigInteger(add(mag, val.mag), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) : subtract(val.mag, mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); }
Returns a BigInteger whose value is {@code (this + val)}. @param val value to be added to this BigInteger. @return {@code this + val}
BigInteger::add
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
BigInteger add(long val) { if (val == 0) return this; if (signum == 0) return valueOf(val); if (Long.signum(val) == signum) return new BigInteger(add(mag, Math.abs(val)), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); }
Package private methods used by BigDecimal code to add a BigInteger with a long. Assumes val is not equal to INFLATED.
BigInteger::add
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
private static int[] add(int[] x, long val) { int[] y; long sum = 0; int xIndex = x.length; int[] result; int highWord = (int)(val >>> 32); if (highWord == 0) { result = new int[xIndex]; sum = (x[--xIndex] & LONG_MASK) + val; result[xIndex] = (int)sum; } else { if (xIndex == 1) { result = new int[2]; sum = val + (x[0] & LONG_MASK); result[1] = (int)sum; result[0] = (int)(sum >>> 32); return result; } else { result = new int[xIndex]; sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK); result[xIndex] = (int)sum; sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32); result[xIndex] = (int)sum; } } // Copy remainder of longer number while carry propagation is required boolean carry = (sum >>> 32 != 0); while (xIndex > 0 && carry) carry = ((result[--xIndex] = x[xIndex] + 1) == 0); // Copy remainder of longer number while (xIndex > 0) result[--xIndex] = x[xIndex]; // Grow result if necessary if (carry) { int bigger[] = new int[result.length + 1]; System.arraycopy(result, 0, bigger, 1, result.length); bigger[0] = 0x01; return bigger; } return result; }
Adds the contents of the int array x and long value val. This method allocates a new int array to hold the answer and returns a reference to that array. Assumes x.length &gt; 0 and val is non-negative
BigInteger::add
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
public BigInteger multiply(BigInteger val) { if (val.signum == 0 || signum == 0) return ZERO; int xlen = mag.length; int ylen = val.mag.length; if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) { int resultSign = signum == val.signum ? 1 : -1; if (val.mag.length == 1) { return multiplyByInt(mag,val.mag[0], resultSign); } if (mag.length == 1) { return multiplyByInt(val.mag,mag[0], resultSign); } int[] result = multiplyToLen(mag, xlen, val.mag, ylen, null); result = trustedStripLeadingZeroInts(result); return new BigInteger(result, resultSign); } else { if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) { return multiplyKaratsuba(this, val); } else { return multiplyToomCook3(this, val); } } }
Returns a BigInteger whose value is {@code (this * val)}. @param val value to be multiplied by this BigInteger. @return {@code this * val}
BigInteger::multiply
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
private BigInteger[] divideAndRemainderKnuth(BigInteger val) { BigInteger[] result = new BigInteger[2]; MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); MutableBigInteger r = a.divideKnuth(b, q); result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1); result[1] = r.toBigInteger(this.signum); return result; }
Returns an array of two BigIntegers containing {@code (this / val)} followed by {@code (this % val)}. @param val value by which this BigInteger is to be divided, and the remainder computed. @return an array of two BigIntegers: the quotient {@code (this / val)} is the initial element, and the remainder {@code (this % val)} is the final element. @throws ArithmeticException if {@code val} is zero. public BigInteger[] divideAndRemainder(BigInteger val) { if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { return divideAndRemainderKnuth(val); } else { return divideAndRemainderBurnikelZiegler(val); } } /** Long division
BigInteger::divideAndRemainderKnuth
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
private BigInteger remainderKnuth(BigInteger val) { MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); return a.divideKnuth(b, q).toBigInteger(this.signum); }
Returns a BigInteger whose value is {@code (this % val)}. @param val value by which this BigInteger is to be divided, and the remainder computed. @return {@code this % val} @throws ArithmeticException if {@code val} is zero. public BigInteger remainder(BigInteger val) { if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { return remainderKnuth(val); } else { return remainderBurnikelZiegler(val); } } /** Long division
BigInteger::remainderKnuth
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
private String smallToString(int radix) { if (signum == 0) { return "0"; } // Compute upper bound on number of digit groups and allocate space int maxNumDigitGroups = (4*mag.length + 6)/7; String digitGroup[] = new String[maxNumDigitGroups]; // Translate number to string, a digit group at a time BigInteger tmp = this.abs(); int numGroups = 0; while (tmp.signum != 0) { BigInteger d = longRadix[radix]; MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(tmp.mag), b = new MutableBigInteger(d.mag); MutableBigInteger r = a.divide(b, q); BigInteger q2 = q.toBigInteger(tmp.signum * d.signum); BigInteger r2 = r.toBigInteger(tmp.signum * d.signum); digitGroup[numGroups++] = Long.toString(r2.longValue(), radix); tmp = q2; } // Put sign (if any) and first digit group into result buffer StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1); if (signum < 0) { buf.append('-'); } buf.append(digitGroup[numGroups-1]); // Append remaining digit groups padded with leading zeros for (int i=numGroups-2; i >= 0; i--) { // Prepend (any) leading zeros for this digit group int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length(); if (numLeadingZeros != 0) { buf.append(zeros[numLeadingZeros]); } buf.append(digitGroup[i]); } return buf.toString(); }
Returns the String representation of this BigInteger in the given radix. If the radix is outside the range from {@link Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, it will default to 10 (as is the case for {@code Integer.toString}). The digit-to-character mapping provided by {@code Character.forDigit} is used, and a minus sign is prepended if appropriate. (This representation is compatible with the {@link #BigInteger(String, int) (String, int)} constructor.) @param radix radix of the String representation. @return String representation of this BigInteger in the given radix. @see Integer#toString @see Character#forDigit @see #BigInteger(java.lang.String, int) public String toString(int radix) { if (signum == 0) return "0"; if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; // If it's small enough, use smallToString. if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) return smallToString(radix); // Otherwise use recursive toString, which requires positive arguments. // The results will be concatenated into this StringBuilder StringBuilder sb = new StringBuilder(); if (signum < 0) { toString(this.negate(), sb, radix, 0); sb.insert(0, '-'); } else toString(this, sb, radix, 0); return sb.toString(); } /** This method is used to perform toString when arguments are small.
BigInteger::smallToString
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/math/BigInteger.java
Apache-2.0
public DecimalFormat() { // Get the pattern for the default locale. Locale def = Locale.getDefault(Locale.Category.FORMAT); /* J2ObjC: java.text.spi is not provided. LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(NumberFormatProvider.class, def); if (!(adapter instanceof ResourceBundleBasedAdapter)) { adapter = LocaleProviderAdapter.getResourceBundleBased(); } String[] all = adapter.getLocaleResources(def).getNumberPatterns();*/ // Always applyPattern after the symbols are set this.symbols = DecimalFormatSymbols.getInstance(def); applyPattern(LocaleData.get(def).numberPattern, false); }
Creates a DecimalFormat using the default pattern and symbols for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern. <p> To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale. @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance
DecimalFormat::DecimalFormat
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public DecimalFormat(String pattern) { // Always applyPattern after the symbols are set this.symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT)); applyPattern(pattern, false); }
Creates a DecimalFormat using the given pattern and the symbols for the default {@link java.util.Locale.Category#FORMAT FORMAT} locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern. <p> To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale. @param pattern a non-localized pattern string. @exception NullPointerException if <code>pattern</code> is null @exception IllegalArgumentException if the given pattern is invalid. @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance
DecimalFormat::DecimalFormat
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public DecimalFormat (String pattern, DecimalFormatSymbols symbols) { // Always applyPattern after the symbols are set this.symbols = (DecimalFormatSymbols)symbols.clone(); applyPattern(pattern, false); }
Creates a DecimalFormat using the given pattern and symbols. Use this constructor when you need to completely customize the behavior of the format. <p> To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getInstance or getCurrencyInstance. If you need only minor adjustments to a standard format, you can modify the format returned by a NumberFormat factory method. @param pattern a non-localized pattern string @param symbols the set of symbols to be used @exception NullPointerException if any of the given arguments is null @exception IllegalArgumentException if the given pattern is invalid @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance @see java.text.DecimalFormatSymbols
DecimalFormat::DecimalFormat
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer format(double number, StringBuffer result, FieldDelegate delegate) { if (Double.isNaN(number) || (Double.isInfinite(number) && multiplier == 0)) { int iFieldStart = result.length(); result.append(symbols.getNaN()); delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, iFieldStart, result.length(), result); return result; } /* Detecting whether a double is negative is easy with the exception of * the value -0.0. This is a double which has a zero mantissa (and * exponent), but a negative sign bit. It is semantically distinct from * a zero with a positive sign bit, and this distinction is important * to certain kinds of computations. However, it's a little tricky to * detect, since (-0.0 == 0.0) and !(-0.0 < 0.0). How then, you may * ask, does it behave distinctly from +0.0? Well, 1/(-0.0) == * -Infinity. Proper detection of -0.0 is needed to deal with the * issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98. */ boolean isNegative = ((number < 0.0) || (number == 0.0 && 1/number < 0.0)) ^ (multiplier < 0); if (multiplier != 1) { number *= multiplier; } if (Double.isInfinite(number)) { if (isNegative) { append(result, negativePrefix, delegate, getNegativePrefixFieldPositions(), Field.SIGN); } else { append(result, positivePrefix, delegate, getPositivePrefixFieldPositions(), Field.SIGN); } int iFieldStart = result.length(); result.append(symbols.getInfinity()); delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, iFieldStart, result.length(), result); if (isNegative) { append(result, negativeSuffix, delegate, getNegativeSuffixFieldPositions(), Field.SIGN); } else { append(result, positiveSuffix, delegate, getPositiveSuffixFieldPositions(), Field.SIGN); } return result; } if (isNegative) { number = -number; } // at this point we are guaranteed a nonnegative finite number. assert(number >= 0 && !Double.isInfinite(number)); synchronized(digitList) { int maxIntDigits = super.getMaximumIntegerDigits(); int minIntDigits = super.getMinimumIntegerDigits(); int maxFraDigits = super.getMaximumFractionDigits(); int minFraDigits = super.getMinimumFractionDigits(); digitList.set(isNegative, number, useExponentialNotation ? maxIntDigits + maxFraDigits : maxFraDigits, !useExponentialNotation); return subformat(result, delegate, isNegative, false, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Formats a double to produce a string. @param number The double to format @param result where the text is to be appended @param delegate notified of locations of sub fields @exception ArithmeticException if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY @return The formatted number string
DecimalFormat::format
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer format(long number, StringBuffer result, FieldDelegate delegate) { boolean isNegative = (number < 0); if (isNegative) { number = -number; } // In general, long values always represent real finite numbers, so // we don't have to check for +/- Infinity or NaN. However, there // is one case we have to be careful of: The multiplier can push // a number near MIN_VALUE or MAX_VALUE outside the legal range. We // check for this before multiplying, and if it happens we use // BigInteger instead. boolean useBigInteger = false; if (number < 0) { // This can only happen if number == Long.MIN_VALUE. if (multiplier != 0) { useBigInteger = true; } } else if (multiplier != 1 && multiplier != 0) { long cutoff = Long.MAX_VALUE / multiplier; if (cutoff < 0) { cutoff = -cutoff; } useBigInteger = (number > cutoff); } if (useBigInteger) { if (isNegative) { number = -number; } BigInteger bigIntegerValue = BigInteger.valueOf(number); return format(bigIntegerValue, result, delegate, true); } number *= multiplier; if (number == 0) { isNegative = false; } else { if (multiplier < 0) { number = -number; isNegative = !isNegative; } } synchronized(digitList) { int maxIntDigits = super.getMaximumIntegerDigits(); int minIntDigits = super.getMinimumIntegerDigits(); int maxFraDigits = super.getMaximumFractionDigits(); int minFraDigits = super.getMinimumFractionDigits(); digitList.set(isNegative, number, useExponentialNotation ? maxIntDigits + maxFraDigits : 0); return subformat(result, delegate, isNegative, true, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Format a long to produce a string. @param number The long to format @param result where the text is to be appended @param delegate notified of locations of sub fields @return The formatted number string @exception ArithmeticException if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY @see java.text.FieldPosition
DecimalFormat::format
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer format(BigDecimal number, StringBuffer result, FieldPosition fieldPosition) { fieldPosition.setBeginIndex(0); fieldPosition.setEndIndex(0); return format(number, result, fieldPosition.getFieldDelegate()); }
Formats a BigDecimal to produce a string. @param number The BigDecimal to format @param result where the text is to be appended @param fieldPosition On input: an alignment field, if desired. On output: the offsets of the alignment field. @return The formatted number string @exception ArithmeticException if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY @see java.text.FieldPosition
DecimalFormat::format
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer format(BigDecimal number, StringBuffer result, FieldDelegate delegate) { if (multiplier != 1) { number = number.multiply(getBigDecimalMultiplier()); } boolean isNegative = number.signum() == -1; if (isNegative) { number = number.negate(); } synchronized(digitList) { int maxIntDigits = getMaximumIntegerDigits(); int minIntDigits = getMinimumIntegerDigits(); int maxFraDigits = getMaximumFractionDigits(); int minFraDigits = getMinimumFractionDigits(); int maximumDigits = maxIntDigits + maxFraDigits; digitList.set(isNegative, number, useExponentialNotation ? ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) : maxFraDigits, !useExponentialNotation); return subformat(result, delegate, isNegative, false, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Formats a BigDecimal to produce a string. @param number The BigDecimal to format @param result where the text is to be appended @param delegate notified of locations of sub fields @exception ArithmeticException if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY @return The formatted number string
DecimalFormat::format
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer format(BigInteger number, StringBuffer result, FieldPosition fieldPosition) { fieldPosition.setBeginIndex(0); fieldPosition.setEndIndex(0); return format(number, result, fieldPosition.getFieldDelegate(), false); }
Format a BigInteger to produce a string. @param number The BigInteger to format @param result where the text is to be appended @param fieldPosition On input: an alignment field, if desired. On output: the offsets of the alignment field. @return The formatted number string @exception ArithmeticException if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY @see java.text.FieldPosition
DecimalFormat::format
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer format(BigInteger number, StringBuffer result, FieldDelegate delegate, boolean formatLong) { if (multiplier != 1) { number = number.multiply(getBigIntegerMultiplier()); } boolean isNegative = number.signum() == -1; if (isNegative) { number = number.negate(); } synchronized(digitList) { int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits; if (formatLong) { maxIntDigits = super.getMaximumIntegerDigits(); minIntDigits = super.getMinimumIntegerDigits(); maxFraDigits = super.getMaximumFractionDigits(); minFraDigits = super.getMinimumFractionDigits(); maximumDigits = maxIntDigits + maxFraDigits; } else { maxIntDigits = getMaximumIntegerDigits(); minIntDigits = getMinimumIntegerDigits(); maxFraDigits = getMaximumFractionDigits(); minFraDigits = getMinimumFractionDigits(); maximumDigits = maxIntDigits + maxFraDigits; if (maximumDigits < 0) { maximumDigits = Integer.MAX_VALUE; } } digitList.set(isNegative, number, useExponentialNotation ? maximumDigits : 0); return subformat(result, delegate, isNegative, true, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Format a BigInteger to produce a string. @param number The BigInteger to format @param result where the text is to be appended @param delegate notified of locations of sub fields @return The formatted number string @exception ArithmeticException if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY @see java.text.FieldPosition
DecimalFormat::format
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void checkAndSetFastPathStatus() { boolean fastPathWasOn = isFastPath; if ((roundingMode == RoundingMode.HALF_EVEN) && (isGroupingUsed()) && (groupingSize == 3) && (secondaryGroupingSize == 0) && (multiplier == 1) && (!decimalSeparatorAlwaysShown) && (!useExponentialNotation)) { // The fast-path algorithm is semi-hardcoded against // minimumIntegerDigits and maximumIntegerDigits. isFastPath = ((minimumIntegerDigits == 1) && (maximumIntegerDigits >= 10)); // The fast-path algorithm is hardcoded against // minimumFractionDigits and maximumFractionDigits. if (isFastPath) { if (isCurrencyFormat) { if ((minimumFractionDigits != 2) || (maximumFractionDigits != 2)) isFastPath = false; } else if ((minimumFractionDigits != 0) || (maximumFractionDigits != 3)) isFastPath = false; } } else isFastPath = false; // Since some instance properties may have changed while still falling // in the fast-path case, we need to reinitialize fastPathData anyway. if (isFastPath) { // We need to instantiate fastPathData if not already done. if (fastPathData == null) fastPathData = new FastPathData(); // Sets up the locale specific constants used when formatting. // '0' is our default representation of zero. fastPathData.zeroDelta = symbols.getZeroDigit() - '0'; fastPathData.groupingChar = symbols.getGroupingSeparator(); // Sets up fractional constants related to currency/decimal pattern. fastPathData.fractionalMaxIntBound = (isCurrencyFormat) ? 99 : 999; fastPathData.fractionalScaleFactor = (isCurrencyFormat) ? 100.0d : 1000.0d; // Records the need for adding prefix or suffix fastPathData.positiveAffixesRequired = (positivePrefix.length() != 0) || (positiveSuffix.length() != 0); fastPathData.negativeAffixesRequired = (negativePrefix.length() != 0) || (negativeSuffix.length() != 0); // Creates a cached char container for result, with max possible size. int maxNbIntegralDigits = 10; int maxNbGroups = 3; int containerSize = Math.max(positivePrefix.length(), negativePrefix.length()) + maxNbIntegralDigits + maxNbGroups + 1 + maximumFractionDigits + Math.max(positiveSuffix.length(), negativeSuffix.length()); fastPathData.fastPathContainer = new char[containerSize]; // Sets up prefix and suffix char arrays constants. fastPathData.charsPositiveSuffix = positiveSuffix.toCharArray(); fastPathData.charsNegativeSuffix = negativeSuffix.toCharArray(); fastPathData.charsPositivePrefix = positivePrefix.toCharArray(); fastPathData.charsNegativePrefix = negativePrefix.toCharArray(); // Sets up fixed index positions for integral and fractional digits. // Sets up decimal point in cached result container. int longestPrefixLength = Math.max(positivePrefix.length(), negativePrefix.length()); int decimalPointIndex = maxNbIntegralDigits + maxNbGroups + longestPrefixLength; fastPathData.integralLastIndex = decimalPointIndex - 1; fastPathData.fractionalFirstIndex = decimalPointIndex + 1; fastPathData.fastPathContainer[decimalPointIndex] = isCurrencyFormat ? symbols.getMonetaryDecimalSeparator() : symbols.getDecimalSeparator(); } else if (fastPathWasOn) { // Previous state was fast-path and is no more. // Resets cached array constants. fastPathData.fastPathContainer = null; fastPathData.charsPositiveSuffix = null; fastPathData.charsNegativeSuffix = null; fastPathData.charsPositivePrefix = null; fastPathData.charsNegativePrefix = null; } fastPathCheckNeeded = false; }
Check validity of using fast-path for this instance. If fast-path is valid for this instance, sets fast-path state as true and initializes fast-path utility fields as needed. This method is supposed to be called rarely, otherwise that will break the fast-path performance. That means avoiding frequent changes of the properties of the instance, since for most properties, each time a change happens, a call to this method is needed at the next format call. FAST-PATH RULES: Similar to the default DecimalFormat instantiation case. More precisely: - HALF_EVEN rounding mode, - isGroupingUsed() is true, - groupingSize of 3, - multiplier is 1, - Decimal separator not mandatory, - No use of exponential notation, - minimumIntegerDigits is exactly 1 and maximumIntegerDigits at least 10 - For number of fractional digits, the exact values found in the default case: Currency : min = max = 2. Decimal : min = 0. max = 3.
DecimalFormat::checkAndSetFastPathStatus
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private boolean exactRoundUp(double fractionalPart, int scaledFractionalPartAsInt) { /* exactRoundUp() method is called by fastDoubleFormat() only. * The precondition expected to be verified by the passed parameters is : * scaledFractionalPartAsInt == * (int) (fractionalPart * fastPathData.fractionalScaleFactor). * This is ensured by fastDoubleFormat() code. */ /* We first calculate roundoff error made by fastDoubleFormat() on * the scaled fractional part. We do this with exact calculation on the * passed fractionalPart. Rounding decision will then be taken from roundoff. */ /* ---- TwoProduct(fractionalPart, scale factor (i.e. 1000.0d or 100.0d)). * * The below is an optimized exact "TwoProduct" calculation of passed * fractional part with scale factor, using Ogita's Sum2S cascaded * summation adapted as Kahan-Babuska equivalent by using FastTwoSum * (much faster) rather than Knuth's TwoSum. * * We can do this because we order the summation from smallest to * greatest, so that FastTwoSum can be used without any additional error. * * The "TwoProduct" exact calculation needs 17 flops. We replace this by * a cascaded summation of FastTwoSum calculations, each involving an * exact multiply by a power of 2. * * Doing so saves overall 4 multiplications and 1 addition compared to * using traditional "TwoProduct". * * The scale factor is either 100 (currency case) or 1000 (decimal case). * - when 1000, we replace it by (1024 - 16 - 8) = 1000. * - when 100, we replace it by (128 - 32 + 4) = 100. * Every multiplication by a power of 2 (1024, 128, 32, 16, 8, 4) is exact. * */ double approxMax; // Will always be positive. double approxMedium; // Will always be negative. double approxMin; double fastTwoSumApproximation = 0.0d; double fastTwoSumRoundOff = 0.0d; double bVirtual = 0.0d; if (isCurrencyFormat) { // Scale is 100 = 128 - 32 + 4. // Multiply by 2**n is a shift. No roundoff. No error. approxMax = fractionalPart * 128.00d; approxMedium = - (fractionalPart * 32.00d); approxMin = fractionalPart * 4.00d; } else { // Scale is 1000 = 1024 - 16 - 8. // Multiply by 2**n is a shift. No roundoff. No error. approxMax = fractionalPart * 1024.00d; approxMedium = - (fractionalPart * 16.00d); approxMin = - (fractionalPart * 8.00d); } // Shewchuk/Dekker's FastTwoSum(approxMedium, approxMin). assert(-approxMedium >= Math.abs(approxMin)); fastTwoSumApproximation = approxMedium + approxMin; bVirtual = fastTwoSumApproximation - approxMedium; fastTwoSumRoundOff = approxMin - bVirtual; double approxS1 = fastTwoSumApproximation; double roundoffS1 = fastTwoSumRoundOff; // Shewchuk/Dekker's FastTwoSum(approxMax, approxS1); assert(approxMax >= Math.abs(approxS1)); fastTwoSumApproximation = approxMax + approxS1; bVirtual = fastTwoSumApproximation - approxMax; fastTwoSumRoundOff = approxS1 - bVirtual; double roundoff1000 = fastTwoSumRoundOff; double approx1000 = fastTwoSumApproximation; double roundoffTotal = roundoffS1 + roundoff1000; // Shewchuk/Dekker's FastTwoSum(approx1000, roundoffTotal); assert(approx1000 >= Math.abs(roundoffTotal)); fastTwoSumApproximation = approx1000 + roundoffTotal; bVirtual = fastTwoSumApproximation - approx1000; // Now we have got the roundoff for the scaled fractional double scaledFractionalRoundoff = roundoffTotal - bVirtual; // ---- TwoProduct(fractionalPart, scale (i.e. 1000.0d or 100.0d)) end. /* ---- Taking the rounding decision * * We take rounding decision based on roundoff and half-even rounding * rule. * * The above TwoProduct gives us the exact roundoff on the approximated * scaled fractional, and we know that this approximation is exactly * 0.5d, since that has already been tested by the caller * (fastDoubleFormat). * * Decision comes first from the sign of the calculated exact roundoff. * - Since being exact roundoff, it cannot be positive with a scaled * fractional less than 0.5d, as well as negative with a scaled * fractional greater than 0.5d. That leaves us with following 3 cases. * - positive, thus scaled fractional == 0.500....0fff ==> round-up. * - negative, thus scaled fractional == 0.499....9fff ==> don't round-up. * - is zero, thus scaled fractioanl == 0.5 ==> half-even rounding applies : * we round-up only if the integral part of the scaled fractional is odd. * */ if (scaledFractionalRoundoff > 0.0) { return true; } else if (scaledFractionalRoundoff < 0.0) { return false; } else if ((scaledFractionalPartAsInt & 1) != 0) { return true; } return false; // ---- Taking the rounding decision end }
Returns true if rounding-up must be done on {@code scaledFractionalPartAsInt}, false otherwise. This is a utility method that takes correct half-even rounding decision on passed fractional value at the scaled decimal point (2 digits for currency case and 3 for decimal case), when the approximated fractional part after scaled decimal point is exactly 0.5d. This is done by means of exact calculations on the {@code fractionalPart} floating-point value. This method is supposed to be called by private {@code fastDoubleFormat} method only. The algorithms used for the exact calculations are : The <b><i>FastTwoSum</i></b> algorithm, from T.J.Dekker, described in the papers "<i>A Floating-Point Technique for Extending the Available Precision</i>" by Dekker, and in "<i>Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates</i>" from J.Shewchuk. A modified version of <b><i>Sum2S</i></b> cascaded summation described in "<i>Accurate Sum and Dot Product</i>" from Takeshi Ogita and All. As Ogita says in this paper this is an equivalent of the Kahan-Babuska's summation algorithm because we order the terms by magnitude before summing them. For this reason we can use the <i>FastTwoSum</i> algorithm rather than the more expensive Knuth's <i>TwoSum</i>. We do this to avoid a more expensive exact "<i>TwoProduct</i>" algorithm, like those described in Shewchuk's paper above. See comments in the code below. @param fractionalPart The fractional value on which we take rounding decision. @param scaledFractionalPartAsInt The integral part of the scaled fractional value. @return the decision that must be taken regarding half-even rounding.
DecimalFormat::exactRoundUp
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void collectIntegralDigits(int number, char[] digitsBuffer, int backwardIndex) { int index = backwardIndex; int q; int r; while (number > 999) { // Generates 3 digits per iteration. q = number / 1000; r = number - (q << 10) + (q << 4) + (q << 3); // -1024 +16 +8 = 1000. number = q; digitsBuffer[index--] = DigitArrays.DigitOnes1000[r]; digitsBuffer[index--] = DigitArrays.DigitTens1000[r]; digitsBuffer[index--] = DigitArrays.DigitHundreds1000[r]; digitsBuffer[index--] = fastPathData.groupingChar; } // Collects last 3 or less digits. digitsBuffer[index] = DigitArrays.DigitOnes1000[number]; if (number > 9) { digitsBuffer[--index] = DigitArrays.DigitTens1000[number]; if (number > 99) digitsBuffer[--index] = DigitArrays.DigitHundreds1000[number]; } fastPathData.firstUsedIndex = index; }
Collects integral digits from passed {@code number}, while setting grouping chars as needed. Updates {@code firstUsedIndex} accordingly. Loops downward starting from {@code backwardIndex} position (inclusive). @param number The int value from which we collect digits. @param digitsBuffer The char array container where digits and grouping chars are stored. @param backwardIndex the position from which we start storing digits in digitsBuffer.
DecimalFormat::collectIntegralDigits
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void collectFractionalDigits(int number, char[] digitsBuffer, int startIndex) { int index = startIndex; char digitOnes = DigitArrays.DigitOnes1000[number]; char digitTens = DigitArrays.DigitTens1000[number]; if (isCurrencyFormat) { // Currency case. Always collects fractional digits. digitsBuffer[index++] = digitTens; digitsBuffer[index++] = digitOnes; } else if (number != 0) { // Decimal case. Hundreds will always be collected digitsBuffer[index++] = DigitArrays.DigitHundreds1000[number]; // Ending zeros won't be collected. if (digitOnes != '0') { digitsBuffer[index++] = digitTens; digitsBuffer[index++] = digitOnes; } else if (digitTens != '0') digitsBuffer[index++] = digitTens; } else // This is decimal pattern and fractional part is zero. // We must remove decimal point from result. index--; fastPathData.lastFreeIndex = index; }
Collects the 2 (currency) or 3 (decimal) fractional digits from passed {@code number}, starting at {@code startIndex} position inclusive. There is no punctuation to set here (no grouping chars). Updates {@code fastPathData.lastFreeIndex} accordingly. @param number The int value from which we collect digits. @param digitsBuffer The char array container where digits are stored. @param startIndex the position from which we start storing digits in digitsBuffer.
DecimalFormat::collectFractionalDigits
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void prependPrefix(char[] prefix, int len, char[] container) { fastPathData.firstUsedIndex -= len; int startIndex = fastPathData.firstUsedIndex; // If prefix to prepend is only 1 char long, just assigns this char. // If prefix is less or equal 4, we use a dedicated algorithm that // has shown to run faster than System.arraycopy. // If more than 4, we use System.arraycopy. if (len == 1) container[startIndex] = prefix[0]; else if (len <= 4) { int dstLower = startIndex; int dstUpper = dstLower + len - 1; int srcUpper = len - 1; container[dstLower] = prefix[0]; container[dstUpper] = prefix[srcUpper]; if (len > 2) container[++dstLower] = prefix[1]; if (len == 4) container[--dstUpper] = prefix[2]; } else System.arraycopy(prefix, 0, container, startIndex, len); }
Prepends the passed {@code prefix} chars to given result {@code container}. Updates {@code fastPathData.firstUsedIndex} accordingly. @param prefix The prefix characters to prepend to result. @param len The number of chars to prepend. @param container Char array container which to prepend the prefix
DecimalFormat::prependPrefix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void appendSuffix(char[] suffix, int len, char[] container) { int startIndex = fastPathData.lastFreeIndex; // If suffix to append is only 1 char long, just assigns this char. // If suffix is less or equal 4, we use a dedicated algorithm that // has shown to run faster than System.arraycopy. // If more than 4, we use System.arraycopy. if (len == 1) container[startIndex] = suffix[0]; else if (len <= 4) { int dstLower = startIndex; int dstUpper = dstLower + len - 1; int srcUpper = len - 1; container[dstLower] = suffix[0]; container[dstUpper] = suffix[srcUpper]; if (len > 2) container[++dstLower] = suffix[1]; if (len == 4) container[--dstUpper] = suffix[2]; } else System.arraycopy(suffix, 0, container, startIndex, len); fastPathData.lastFreeIndex += len; }
Appends the passed {@code suffix} chars to given result {@code container}. Updates {@code fastPathData.lastFreeIndex} accordingly. @param suffix The suffix characters to append to result. @param len The number of chars to append. @param container Char array container which to append the suffix
DecimalFormat::appendSuffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void localizeDigits(char[] digitsBuffer) { // We will localize only the digits, using the groupingSize, // and taking into account fractional part. // First take into account fractional part. int digitsCounter = fastPathData.lastFreeIndex - fastPathData.fractionalFirstIndex; // The case when there is no fractional digits. if (digitsCounter < 0) digitsCounter = groupingSize; // Only the digits remains to localize. for (int cursor = fastPathData.lastFreeIndex - 1; cursor >= fastPathData.firstUsedIndex; cursor--) { if (digitsCounter != 0) { // This is a digit char, we must localize it. digitsBuffer[cursor] += fastPathData.zeroDelta; digitsCounter--; } else { // Decimal separator or grouping char. Reinit counter only. digitsCounter = groupingSize; } } }
Converts digit chars from {@code digitsBuffer} to current locale. Must be called before adding affixes since we refer to {@code fastPathData.firstUsedIndex} and {@code fastPathData.lastFreeIndex}, and do not support affixes (for speed reason). We loop backward starting from last used index in {@code fastPathData}. @param digitsBuffer The char array container where the digits are stored.
DecimalFormat::localizeDigits
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void fastDoubleFormat(double d, boolean negative) { char[] container = fastPathData.fastPathContainer; /* * The principle of the algorithm is to : * - Break the passed double into its integral and fractional parts * converted into integers. * - Then decide if rounding up must be applied or not by following * the half-even rounding rule, first using approximated scaled * fractional part. * - For the difficult cases (approximated scaled fractional part * being exactly 0.5d), we refine the rounding decision by calling * exactRoundUp utility method that both calculates the exact roundoff * on the approximation and takes correct rounding decision. * - We round-up the fractional part if needed, possibly propagating the * rounding to integral part if we meet a "all-nine" case for the * scaled fractional part. * - We then collect digits from the resulting integral and fractional * parts, also setting the required grouping chars on the fly. * - Then we localize the collected digits if needed, and * - Finally prepend/append prefix/suffix if any is needed. */ // Exact integral part of d. int integralPartAsInt = (int) d; // Exact fractional part of d (since we subtract it's integral part). double exactFractionalPart = d - (double) integralPartAsInt; // Approximated scaled fractional part of d (due to multiplication). double scaledFractional = exactFractionalPart * fastPathData.fractionalScaleFactor; // Exact integral part of scaled fractional above. int fractionalPartAsInt = (int) scaledFractional; // Exact fractional part of scaled fractional above. scaledFractional = scaledFractional - (double) fractionalPartAsInt; // Only when scaledFractional is exactly 0.5d do we have to do exact // calculations and take fine-grained rounding decision, since // approximated results above may lead to incorrect decision. // Otherwise comparing against 0.5d (strictly greater or less) is ok. boolean roundItUp = false; if (scaledFractional >= 0.5d) { if (scaledFractional == 0.5d) // Rounding need fine-grained decision. roundItUp = exactRoundUp(exactFractionalPart, fractionalPartAsInt); else roundItUp = true; if (roundItUp) { // Rounds up both fractional part (and also integral if needed). if (fractionalPartAsInt < fastPathData.fractionalMaxIntBound) { fractionalPartAsInt++; } else { // Propagates rounding to integral part since "all nines" case. fractionalPartAsInt = 0; integralPartAsInt++; } } } // Collecting digits. collectFractionalDigits(fractionalPartAsInt, container, fastPathData.fractionalFirstIndex); collectIntegralDigits(integralPartAsInt, container, fastPathData.integralLastIndex); // Localizing digits. if (fastPathData.zeroDelta != 0) localizeDigits(container); // Adding prefix and suffix. if (negative) { if (fastPathData.negativeAffixesRequired) addAffixes(container, fastPathData.charsNegativePrefix, fastPathData.charsNegativeSuffix); } else if (fastPathData.positiveAffixesRequired) addAffixes(container, fastPathData.charsPositivePrefix, fastPathData.charsPositiveSuffix); }
This is the main entry point for the fast-path format algorithm. At this point we are sure to be in the expected conditions to run it. This algorithm builds the formatted result and puts it in the dedicated {@code fastPathData.fastPathContainer}. @param d the double value to be formatted. @param negative Flag precising if {@code d} is negative.
DecimalFormat::fastDoubleFormat
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
String fastFormat(double d) { // (Re-)Evaluates fast-path status if needed. if (fastPathCheckNeeded) checkAndSetFastPathStatus(); if (!isFastPath ) // DecimalFormat instance is not in a fast-path state. return null; if (!Double.isFinite(d)) // Should not use fast-path for Infinity and NaN. return null; // Extracts and records sign of double value, possibly changing it // to a positive one, before calling fastDoubleFormat(). boolean negative = false; if (d < 0.0d) { negative = true; d = -d; } else if (d == 0.0d) { negative = (Math.copySign(1.0d, d) == -1.0d); d = +0.0d; } if (d > MAX_INT_AS_DOUBLE) // Filters out values that are outside expected fast-path range return null; else fastDoubleFormat(d, negative); // Returns a new string from updated fastPathContainer. return new String(fastPathData.fastPathContainer, fastPathData.firstUsedIndex, fastPathData.lastFreeIndex - fastPathData.firstUsedIndex); }
A fast-path shortcut of format(double) to be called by NumberFormat, or by format(double, ...) public methods. If instance can be applied fast-path and passed double is not NaN or Infinity, is in the integer range, we call {@code fastDoubleFormat} after changing {@code d} to its positive value if necessary. Otherwise returns null by convention since fast-path can't be exercized. @param d The double value to be formatted @return the formatted result for {@code d} as a string.
DecimalFormat::fastFormat
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private StringBuffer subformat(StringBuffer result, FieldDelegate delegate, boolean isNegative, boolean isInteger, int maxIntDigits, int minIntDigits, int maxFraDigits, int minFraDigits) { // NOTE: This isn't required anymore because DigitList takes care of this. // // // The negative of the exponent represents the number of leading // // zeros between the decimal and the first non-zero digit, for // // a value < 0.1 (e.g., for 0.00123, -fExponent == 2). If this // // is more than the maximum fraction digits, then we have an underflow // // for the printed representation. We recognize this here and set // // the DigitList representation to zero in this situation. // // if (-digitList.decimalAt >= getMaximumFractionDigits()) // { // digitList.count = 0; // } char zero = symbols.getZeroDigit(); int zeroDelta = zero - '0'; // '0' is the DigitList representation of zero char grouping = symbols.getGroupingSeparator(); char decimal = isCurrencyFormat ? symbols.getMonetaryDecimalSeparator() : symbols.getDecimalSeparator(); /* Per bug 4147706, DecimalFormat must respect the sign of numbers which * format as zero. This allows sensible computations and preserves * relations such as signum(1/x) = signum(x), where x is +Infinity or * -Infinity. Prior to this fix, we always formatted zero values as if * they were positive. Liu 7/6/98. */ if (digitList.isZero()) { digitList.decimalAt = 0; // Normalize } if (isNegative) { append(result, negativePrefix, delegate, getNegativePrefixFieldPositions(), Field.SIGN); } else { append(result, positivePrefix, delegate, getPositivePrefixFieldPositions(), Field.SIGN); } if (useExponentialNotation) { int iFieldStart = result.length(); int iFieldEnd = -1; int fFieldStart = -1; // Minimum integer digits are handled in exponential format by // adjusting the exponent. For example, 0.01234 with 3 minimum // integer digits is "123.4E-4". // Maximum integer digits are interpreted as indicating the // repeating range. This is useful for engineering notation, in // which the exponent is restricted to a multiple of 3. For // example, 0.01234 with 3 maximum integer digits is "12.34e-3". // If maximum integer digits are > 1 and are larger than // minimum integer digits, then minimum integer digits are // ignored. int exponent = digitList.decimalAt; int repeat = maxIntDigits; int minimumIntegerDigits = minIntDigits; if (repeat > 1 && repeat > minIntDigits) { // A repeating range is defined; adjust to it as follows. // If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3; // -3,-4,-5=>-6, etc. This takes into account that the // exponent we have here is off by one from what we expect; // it is for the format 0.MMMMMx10^n. if (exponent >= 1) { exponent = ((exponent - 1) / repeat) * repeat; } else { // integer division rounds towards 0 exponent = ((exponent - repeat) / repeat) * repeat; } minimumIntegerDigits = 1; } else { // No repeating range is defined; use minimum integer digits. exponent -= minimumIntegerDigits; } // We now output a minimum number of digits, and more if there // are more digits, up to the maximum number of digits. We // place the decimal point after the "integer" digits, which // are the first (decimalAt - exponent) digits. int minimumDigits = minIntDigits + minFraDigits; if (minimumDigits < 0) { // overflow? minimumDigits = Integer.MAX_VALUE; } // The number of integer digits is handled specially if the number // is zero, since then there may be no digits. int integerDigits = digitList.isZero() ? minimumIntegerDigits : digitList.decimalAt - exponent; if (minimumDigits < integerDigits) { minimumDigits = integerDigits; } int totalDigits = digitList.count; if (minimumDigits > totalDigits) { totalDigits = minimumDigits; } boolean addedDecimalSeparator = false; for (int i=0; i<totalDigits; ++i) { if (i == integerDigits) { // Record field information for caller. iFieldEnd = result.length(); result.append(decimal); addedDecimalSeparator = true; // Record field information for caller. fFieldStart = result.length(); } result.append((i < digitList.count) ? (char)(digitList.digits[i] + zeroDelta) : zero); } if (decimalSeparatorAlwaysShown && totalDigits == integerDigits) { // Record field information for caller. iFieldEnd = result.length(); result.append(decimal); addedDecimalSeparator = true; // Record field information for caller. fFieldStart = result.length(); } // Record field information if (iFieldEnd == -1) { iFieldEnd = result.length(); } delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, iFieldStart, iFieldEnd, result); if (addedDecimalSeparator) { delegate.formatted(Field.DECIMAL_SEPARATOR, Field.DECIMAL_SEPARATOR, iFieldEnd, fFieldStart, result); } if (fFieldStart == -1) { fFieldStart = result.length(); } delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION, fFieldStart, result.length(), result); // The exponent is output using the pattern-specified minimum // exponent digits. There is no maximum limit to the exponent // digits, since truncating the exponent would result in an // unacceptable inaccuracy. int fieldStart = result.length(); result.append(symbols.getExponentSeparator()); delegate.formatted(Field.EXPONENT_SYMBOL, Field.EXPONENT_SYMBOL, fieldStart, result.length(), result); // For zero values, we force the exponent to zero. We // must do this here, and not earlier, because the value // is used to determine integer digit count above. if (digitList.isZero()) { exponent = 0; } boolean negativeExponent = exponent < 0; if (negativeExponent) { exponent = -exponent; fieldStart = result.length(); result.append(symbols.getMinusSign()); delegate.formatted(Field.EXPONENT_SIGN, Field.EXPONENT_SIGN, fieldStart, result.length(), result); } digitList.set(negativeExponent, exponent); int eFieldStart = result.length(); for (int i=digitList.decimalAt; i<minExponentDigits; ++i) { result.append(zero); } for (int i=0; i<digitList.decimalAt; ++i) { result.append((i < digitList.count) ? (char)(digitList.digits[i] + zeroDelta) : zero); } delegate.formatted(Field.EXPONENT, Field.EXPONENT, eFieldStart, result.length(), result); } else { int iFieldStart = result.length(); // Output the integer portion. Here 'count' is the total // number of integer digits we will display, including both // leading zeros required to satisfy getMinimumIntegerDigits, // and actual digits present in the number. int count = minIntDigits; int digitIndex = 0; // Index into digitList.fDigits[] if (digitList.decimalAt > 0 && count < digitList.decimalAt) { count = digitList.decimalAt; } // Handle the case where getMaximumIntegerDigits() is smaller // than the real number of integer digits. If this is so, we // output the least significant max integer digits. For example, // the value 1997 printed with 2 max integer digits is just "97". if (count > maxIntDigits) { count = maxIntDigits; digitIndex = digitList.decimalAt - count; } int sizeBeforeIntegerPart = result.length(); for (int i=count-1; i>=0; --i) { if (i < digitList.decimalAt && digitIndex < digitList.count) { // Output a real digit result.append((char)(digitList.digits[digitIndex++] + zeroDelta)); } else { // Output a leading zero result.append(zero); } // Output grouping separator if necessary. Don't output a // grouping separator if i==0 though; that's at the end of // the integer part. if (isGroupingUsed() && i>0 && (groupingSize != 0) && (secondaryGroupingSize > 0 && i > groupingSize ? (i - groupingSize) % secondaryGroupingSize == 0 : i % groupingSize == 0)) { int gStart = result.length(); result.append(grouping); delegate.formatted(Field.GROUPING_SEPARATOR, Field.GROUPING_SEPARATOR, gStart, result.length(), result); } } // Determine whether or not there are any printable fractional // digits. If we've used up the digits we know there aren't. boolean fractionPresent = (minFraDigits > 0) || (!isInteger && digitIndex < digitList.count); // If there is no fraction present, and we haven't printed any // integer digits, then print a zero. Otherwise we won't print // _any_ digits, and we won't be able to parse this string. if (!fractionPresent && result.length() == sizeBeforeIntegerPart) { result.append(zero); } delegate.formatted(INTEGER_FIELD, Field.INTEGER, Field.INTEGER, iFieldStart, result.length(), result); // Output the decimal separator if we always do so. int sStart = result.length(); if (decimalSeparatorAlwaysShown || fractionPresent) { result.append(decimal); } if (sStart != result.length()) { delegate.formatted(Field.DECIMAL_SEPARATOR, Field.DECIMAL_SEPARATOR, sStart, result.length(), result); } int fFieldStart = result.length(); for (int i=0; i < maxFraDigits; ++i) { // Here is where we escape from the loop. We escape if we've // output the maximum fraction digits (specified in the for // expression above). // We also stop when we've output the minimum digits and either: // we have an integer, so there is no fractional stuff to // display, or we're out of significant digits. if (i >= minFraDigits && (isInteger || digitIndex >= digitList.count)) { break; } // Output leading fractional zeros. These are zeros that come // after the decimal but before any significant digits. These // are only output if abs(number being formatted) < 1.0. if (-1-i > (digitList.decimalAt-1)) { result.append(zero); continue; } // Output a digit, if we have any precision left, or a // zero if we don't. We don't want to output noise digits. if (!isInteger && digitIndex < digitList.count) { result.append((char)(digitList.digits[digitIndex++] + zeroDelta)); } else { result.append(zero); } } // Record field information for caller. delegate.formatted(FRACTION_FIELD, Field.FRACTION, Field.FRACTION, fFieldStart, result.length(), result); } if (isNegative) { append(result, negativeSuffix, delegate, getNegativeSuffixFieldPositions(), Field.SIGN); } else { append(result, positiveSuffix, delegate, getPositiveSuffixFieldPositions(), Field.SIGN); } return result; }
Complete the formatting of a finite number. On entry, the digitList must be filled in with the correct digits.
DecimalFormat::subformat
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void append(StringBuffer result, String string, FieldDelegate delegate, FieldPosition[] positions, Format.Field signAttribute) { int start = result.length(); if (string.length() > 0) { result.append(string); for (int counter = 0, max = positions.length; counter < max; counter++) { FieldPosition fp = positions[counter]; Format.Field attribute = fp.getFieldAttribute(); if (attribute == Field.SIGN) { attribute = signAttribute; } delegate.formatted(attribute, attribute, start + fp.getBeginIndex(), start + fp.getEndIndex(), result); } } }
Appends the String <code>string</code> to <code>result</code>. <code>delegate</code> is notified of all the <code>FieldPosition</code>s in <code>positions</code>. <p> If one of the <code>FieldPosition</code>s in <code>positions</code> identifies a <code>SIGN</code> attribute, it is mapped to <code>signAttribute</code>. This is used to map the <code>SIGN</code> attribute to the <code>EXPONENT</code> attribute as necessary. <p> This is used by <code>subformat</code> to add the prefix/suffix.
DecimalFormat::append
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private BigInteger getBigIntegerMultiplier() { if (bigIntegerMultiplier == null) { bigIntegerMultiplier = BigInteger.valueOf(multiplier); } return bigIntegerMultiplier; }
Return a BigInteger multiplier.
DecimalFormat::getBigIntegerMultiplier
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private BigDecimal getBigDecimalMultiplier() { if (bigDecimalMultiplier == null) { bigDecimalMultiplier = new BigDecimal(multiplier); } return bigDecimalMultiplier; }
Return a BigDecimal multiplier.
DecimalFormat::getBigDecimalMultiplier
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private boolean signMatches(String text, int position, char[] signs) { if (position < 0 || position >= text.length()) { return false; } char ch = text.charAt(position); for (char signCh : signs) { if (signCh == ch) { return true; } } return false; }
Returns true if specified string position char matches one of an array of Unicode characters.
DecimalFormat::signMatches
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private final boolean subparse(String text, ParsePosition parsePosition, String positivePrefix, String negativePrefix, DigitList digits, boolean isExponent, boolean status[]) { int position = parsePosition.index; int oldStart = parsePosition.index; int backup; boolean gotPositive, gotNegative; // check for positivePrefix; take longest gotPositive = text.regionMatches(position, positivePrefix, 0, positivePrefix.length()) || signMatches(text, position, PLUS_SIGNS); gotNegative = text.regionMatches(position, negativePrefix, 0, negativePrefix.length()) || signMatches(text, position, MINUS_SIGNS); if (gotPositive && gotNegative) { if (positivePrefix.length() > negativePrefix.length()) { gotNegative = false; } else if (positivePrefix.length() < negativePrefix.length()) { gotPositive = false; } } if (gotPositive) { position += positivePrefix.length(); } else if (gotNegative) { position += negativePrefix.length(); } else { parsePosition.errorIndex = position; return false; } // process digits or Inf, find decimal position status[STATUS_INFINITE] = false; if (!isExponent && text.regionMatches(position,symbols.getInfinity(),0, symbols.getInfinity().length())) { position += symbols.getInfinity().length(); status[STATUS_INFINITE] = true; } else { // We now have a string of digits, possibly with grouping symbols, // and decimal points. We want to process these into a DigitList. // We don't want to put a bunch of leading zeros into the DigitList // though, so we keep track of the location of the decimal point, // put only significant digits into the DigitList, and adjust the // exponent as needed. digits.decimalAt = digits.count = 0; char zero = symbols.getZeroDigit(); char decimal = isCurrencyFormat ? symbols.getMonetaryDecimalSeparator() : symbols.getDecimalSeparator(); char grouping = symbols.getGroupingSeparator(); String exponentString = symbols.getExponentSeparator(); boolean sawDecimal = false; boolean sawExponent = false; boolean sawDigit = false; int exponent = 0; // Set to the exponent value, if any // We have to track digitCount ourselves, because digits.count will // pin when the maximum allowable digits is reached. int digitCount = 0; backup = -1; for (; position < text.length(); ++position) { char ch = text.charAt(position); /* We recognize all digit ranges, not only the Latin digit range * '0'..'9'. We do so by using the Character.digit() method, * which converts a valid Unicode digit to the range 0..9. * * The character 'ch' may be a digit. If so, place its value * from 0 to 9 in 'digit'. First try using the locale digit, * which may or MAY NOT be a standard Unicode digit range. If * this fails, try using the standard Unicode digit ranges by * calling Character.digit(). If this also fails, digit will * have a value outside the range 0..9. */ int digit = ch - zero; if (digit < 0 || digit > 9) { digit = Character.digit(ch, 10); } if (digit == 0) { // Cancel out backup setting (see grouping handler below) backup = -1; // Do this BEFORE continue statement below!!! sawDigit = true; // Handle leading zeros if (digits.count == 0) { // Ignore leading zeros in integer part of number. if (!sawDecimal) { continue; } // If we have seen the decimal, but no significant // digits yet, then we account for leading zeros by // decrementing the digits.decimalAt into negative // values. --digits.decimalAt; } else { ++digitCount; digits.append((char)(digit + '0')); } } else if (digit > 0 && digit <= 9) { // [sic] digit==0 handled above sawDigit = true; ++digitCount; digits.append((char)(digit + '0')); // Cancel out backup setting (see grouping handler below) backup = -1; } else if (!isExponent && ch == decimal) { // If we're only parsing integers, or if we ALREADY saw the // decimal, then don't parse this one. if (isParseIntegerOnly() || sawDecimal) { break; } digits.decimalAt = digitCount; // Not digits.count! sawDecimal = true; } else if (!isExponent && ch == grouping && isGroupingUsed()) { if (sawDecimal) { break; } // Ignore grouping characters, if we are using them, but // require that they be followed by a digit. Otherwise // we backup and reprocess them. backup = position; } else if (!isExponent && text.regionMatches(position, exponentString, 0, exponentString.length()) && !sawExponent) { // Process the exponent by recursively calling this method. ParsePosition pos = new ParsePosition(position + exponentString.length()); boolean[] stat = new boolean[STATUS_LENGTH]; DigitList exponentDigits = new DigitList(); if (subparse(text, pos, "", Character.toString(symbols.getMinusSign()), exponentDigits, true, stat) && exponentDigits.fitsIntoLong(stat[STATUS_POSITIVE], true)) { position = pos.index; // Advance past the exponent exponent = (int)exponentDigits.getLong(); if (!stat[STATUS_POSITIVE]) { exponent = -exponent; } sawExponent = true; } break; // Whether we fail or succeed, we exit this loop } else { break; } } if (backup != -1) { position = backup; } // If there was no decimal point we have an integer if (!sawDecimal) { digits.decimalAt = digitCount; // Not digits.count! } // Adjust for exponent, if any digits.decimalAt += exponent; // If none of the text string was recognized. For example, parse // "x" with pattern "#0.00" (return index and error index both 0) // parse "$" with pattern "$#0.00". (return index 0 and error // index 1). if (!sawDigit && digitCount == 0) { parsePosition.index = oldStart; parsePosition.errorIndex = oldStart; return false; } } // check for suffix if (!isExponent) { if (gotPositive) { gotPositive = text.regionMatches(position,positiveSuffix,0, positiveSuffix.length()); } if (gotNegative) { gotNegative = text.regionMatches(position,negativeSuffix,0, negativeSuffix.length()); } // if both match, take longest if (gotPositive && gotNegative) { if (positiveSuffix.length() > negativeSuffix.length()) { gotNegative = false; } else if (positiveSuffix.length() < negativeSuffix.length()) { gotPositive = false; } } // fail if neither or both if (gotPositive == gotNegative) { parsePosition.errorIndex = position; return false; } parsePosition.index = position + (gotPositive ? positiveSuffix.length() : negativeSuffix.length()); // mark success! } else { parsePosition.index = position; } status[STATUS_POSITIVE] = gotPositive; if (parsePosition.index == oldStart) { parsePosition.errorIndex = position; return false; } return true; }
Parse the given text into a number. The text is parsed beginning at parsePosition, until an unparseable character is seen. @param text The string to parse. @param parsePosition The position at which to being parsing. Upon return, the first unparseable character. @param digits The DigitList to set to the parsed value. @param isExponent If true, parse an exponent. This means no infinite values and integer only. @param status Upon return contains boolean status flags indicating whether the value was infinite and whether it was positive.
DecimalFormat::subparse
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) { try { // don't allow multiple references symbols = (DecimalFormatSymbols) newSymbols.clone(); expandAffixes(); fastPathCheckNeeded = true; } catch (Exception foo) { // should never happen } }
Sets the decimal format symbols, which is generally not changed by the programmer or user. @param newSymbols desired DecimalFormatSymbols @see java.text.DecimalFormatSymbols
DecimalFormat::setDecimalFormatSymbols
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public String getPositivePrefix () { return positivePrefix; }
Get the positive prefix. <P>Examples: +123, $123, sFr123 @return the positive prefix
DecimalFormat::getPositivePrefix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setPositivePrefix (String newValue) { positivePrefix = newValue; posPrefixPattern = null; positivePrefixFieldPositions = null; fastPathCheckNeeded = true; }
Set the positive prefix. <P>Examples: +123, $123, sFr123 @param newValue the new positive prefix
DecimalFormat::setPositivePrefix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private FieldPosition[] getPositivePrefixFieldPositions() { if (positivePrefixFieldPositions == null) { if (posPrefixPattern != null) { positivePrefixFieldPositions = expandAffix(posPrefixPattern); } else { positivePrefixFieldPositions = EmptyFieldPositionArray; } } return positivePrefixFieldPositions; }
Returns the FieldPositions of the fields in the prefix used for positive numbers. This is not used if the user has explicitly set a positive prefix via <code>setPositivePrefix</code>. This is lazily created. @return FieldPositions in positive prefix
DecimalFormat::getPositivePrefixFieldPositions
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public String getNegativePrefix () { return negativePrefix; }
Get the negative prefix. <P>Examples: -123, ($123) (with negative suffix), sFr-123 @return the negative prefix
DecimalFormat::getNegativePrefix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setNegativePrefix (String newValue) { negativePrefix = newValue; negPrefixPattern = null; fastPathCheckNeeded = true; }
Set the negative prefix. <P>Examples: -123, ($123) (with negative suffix), sFr-123 @param newValue the new negative prefix
DecimalFormat::setNegativePrefix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private FieldPosition[] getNegativePrefixFieldPositions() { if (negativePrefixFieldPositions == null) { if (negPrefixPattern != null) { negativePrefixFieldPositions = expandAffix(negPrefixPattern); } else { negativePrefixFieldPositions = EmptyFieldPositionArray; } } return negativePrefixFieldPositions; }
Returns the FieldPositions of the fields in the prefix used for negative numbers. This is not used if the user has explicitly set a negative prefix via <code>setNegativePrefix</code>. This is lazily created. @return FieldPositions in positive prefix
DecimalFormat::getNegativePrefixFieldPositions
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public String getPositiveSuffix () { return positiveSuffix; }
Get the positive suffix. <P>Example: 123% @return the positive suffix
DecimalFormat::getPositiveSuffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setPositiveSuffix (String newValue) { positiveSuffix = newValue; posSuffixPattern = null; fastPathCheckNeeded = true; }
Set the positive suffix. <P>Example: 123% @param newValue the new positive suffix
DecimalFormat::setPositiveSuffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private FieldPosition[] getPositiveSuffixFieldPositions() { if (positiveSuffixFieldPositions == null) { if (posSuffixPattern != null) { positiveSuffixFieldPositions = expandAffix(posSuffixPattern); } else { positiveSuffixFieldPositions = EmptyFieldPositionArray; } } return positiveSuffixFieldPositions; }
Returns the FieldPositions of the fields in the suffix used for positive numbers. This is not used if the user has explicitly set a positive suffix via <code>setPositiveSuffix</code>. This is lazily created. @return FieldPositions in positive prefix
DecimalFormat::getPositiveSuffixFieldPositions
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public String getNegativeSuffix () { return negativeSuffix; }
Get the negative suffix. <P>Examples: -123%, ($123) (with positive suffixes) @return the negative suffix
DecimalFormat::getNegativeSuffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setNegativeSuffix (String newValue) { negativeSuffix = newValue; negSuffixPattern = null; fastPathCheckNeeded = true; }
Set the negative suffix. <P>Examples: 123% @param newValue the new negative suffix
DecimalFormat::setNegativeSuffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private FieldPosition[] getNegativeSuffixFieldPositions() { if (negativeSuffixFieldPositions == null) { if (negSuffixPattern != null) { negativeSuffixFieldPositions = expandAffix(negSuffixPattern); } else { negativeSuffixFieldPositions = EmptyFieldPositionArray; } } return negativeSuffixFieldPositions; }
Returns the FieldPositions of the fields in the suffix used for negative numbers. This is not used if the user has explicitly set a negative suffix via <code>setNegativeSuffix</code>. This is lazily created. @return FieldPositions in positive prefix
DecimalFormat::getNegativeSuffixFieldPositions
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public int getMultiplier () { return multiplier; }
Gets the multiplier for use in percent, per mille, and similar formats. @return the multiplier @see #setMultiplier(int)
DecimalFormat::getMultiplier
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setMultiplier (int newValue) { multiplier = newValue; bigDecimalMultiplier = null; bigIntegerMultiplier = null; fastPathCheckNeeded = true; }
Sets the multiplier for use in percent, per mille, and similar formats. For a percent format, set the multiplier to 100 and the suffixes to have '%' (for Arabic, use the Arabic percent sign). For a per mille format, set the multiplier to 1000 and the suffixes to have '&#92;u2030'. <P>Example: with multiplier 100, 1.23 is formatted as "123", and "123" is parsed into 1.23. @param newValue the new multiplier @see #getMultiplier
DecimalFormat::setMultiplier
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public int getGroupingSize () { return groupingSize; }
Return the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the number "123,456.78", the grouping size is 3. @return the grouping size @see #setGroupingSize @see java.text.NumberFormat#isGroupingUsed @see java.text.DecimalFormatSymbols#getGroupingSeparator
DecimalFormat::getGroupingSize
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setGroupingSize (int newValue) { groupingSize = (byte)newValue; secondaryGroupingSize = 0; fastPathCheckNeeded = true; }
Set the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the number "123,456.78", the grouping size is 3. <br> The value passed in is converted to a byte, which may lose information. @param newValue the new grouping size @see #getGroupingSize @see java.text.NumberFormat#setGroupingUsed @see java.text.DecimalFormatSymbols#setGroupingSeparator
DecimalFormat::setGroupingSize
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setDecimalSeparatorAlwaysShown(boolean newValue) { decimalSeparatorAlwaysShown = newValue; fastPathCheckNeeded = true; }
Allows you to set the behavior of the decimal separator with integers. (The decimal separator will always appear with decimals.) <P>Example: Decimal ON: 12345 &rarr; 12345.; OFF: 12345 &rarr; 12345 @param newValue {@code true} if the decimal separator is always shown; {@code false} otherwise
DecimalFormat::setDecimalSeparatorAlwaysShown
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public void setParseBigDecimal(boolean newValue) { parseBigDecimal = newValue; }
Sets whether the {@link #parse(java.lang.String, java.text.ParsePosition)} method returns <code>BigDecimal</code>. @param newValue {@code true} if the parse method returns BigDecimal; {@code false} otherwise @see #isParseBigDecimal @since 1.5
DecimalFormat::setParseBigDecimal
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public String toPattern() { return toPattern( false ); }
Synthesizes a pattern string that represents the current state of this Format object. @return a pattern string @see #applyPattern
DecimalFormat::toPattern
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
public String toLocalizedPattern() { return toPattern( true ); }
Synthesizes a localized pattern string that represents the current state of this Format object. @return a localized pattern string @see #applyPattern
DecimalFormat::toLocalizedPattern
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void expandAffixes() { // Reuse one StringBuffer for better performance StringBuffer buffer = new StringBuffer(); if (posPrefixPattern != null) { positivePrefix = expandAffix(posPrefixPattern, buffer); positivePrefixFieldPositions = null; } if (posSuffixPattern != null) { positiveSuffix = expandAffix(posSuffixPattern, buffer); positiveSuffixFieldPositions = null; } if (negPrefixPattern != null) { negativePrefix = expandAffix(negPrefixPattern, buffer); negativePrefixFieldPositions = null; } if (negSuffixPattern != null) { negativeSuffix = expandAffix(negSuffixPattern, buffer); negativeSuffixFieldPositions = null; } }
Expand the affix pattern strings into the expanded affix strings. If any affix pattern string is null, do not expand it. This method should be called any time the symbols or the affix patterns change in order to keep the expanded affix strings up to date.
DecimalFormat::expandAffixes
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private String expandAffix(String pattern, StringBuffer buffer) { buffer.setLength(0); for (int i=0; i<pattern.length(); ) { char c = pattern.charAt(i++); if (c == QUOTE) { c = pattern.charAt(i++); switch (c) { case CURRENCY_SIGN: if (i<pattern.length() && pattern.charAt(i) == CURRENCY_SIGN) { ++i; buffer.append(symbols.getInternationalCurrencySymbol()); } else { buffer.append(symbols.getCurrencySymbol()); } continue; case PATTERN_PERCENT: c = symbols.getPercent(); break; case PATTERN_PER_MILLE: c = symbols.getPerMill(); break; case PATTERN_MINUS: c = symbols.getMinusSign(); break; } } buffer.append(c); } return buffer.toString(); }
Expand an affix pattern into an affix string. All characters in the pattern are literal unless prefixed by QUOTE. The following characters after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE, PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE + CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217 currency code. Any other character after a QUOTE represents itself. QUOTE must be followed by another character; QUOTE may not occur by itself at the end of the pattern. @param pattern the non-null, possibly empty pattern @param buffer a scratch StringBuffer; its contents will be lost @return the expanded equivalent of pattern
DecimalFormat::expandAffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private FieldPosition[] expandAffix(String pattern) { ArrayList<FieldPosition> positions = null; int stringIndex = 0; for (int i=0; i<pattern.length(); ) { char c = pattern.charAt(i++); if (c == QUOTE) { int field = -1; Format.Field fieldID = null; c = pattern.charAt(i++); switch (c) { case CURRENCY_SIGN: String string; if (i<pattern.length() && pattern.charAt(i) == CURRENCY_SIGN) { ++i; string = symbols.getInternationalCurrencySymbol(); } else { string = symbols.getCurrencySymbol(); } if (string.length() > 0) { if (positions == null) { positions = new ArrayList<>(2); } FieldPosition fp = new FieldPosition(Field.CURRENCY); fp.setBeginIndex(stringIndex); fp.setEndIndex(stringIndex + string.length()); positions.add(fp); stringIndex += string.length(); } continue; case PATTERN_PERCENT: c = symbols.getPercent(); field = -1; fieldID = Field.PERCENT; break; case PATTERN_PER_MILLE: c = symbols.getPerMill(); field = -1; fieldID = Field.PERMILLE; break; case PATTERN_MINUS: c = symbols.getMinusSign(); field = -1; fieldID = Field.SIGN; break; } if (fieldID != null) { if (positions == null) { positions = new ArrayList<>(2); } FieldPosition fp = new FieldPosition(fieldID, field); fp.setBeginIndex(stringIndex); fp.setEndIndex(stringIndex + 1); positions.add(fp); } } stringIndex++; } if (positions != null) { return positions.toArray(EmptyFieldPositionArray); } return EmptyFieldPositionArray; }
Expand an affix pattern into an array of FieldPositions describing how the pattern would be expanded. All characters in the pattern are literal unless prefixed by QUOTE. The following characters after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE, PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE + CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217 currency code. Any other character after a QUOTE represents itself. QUOTE must be followed by another character; QUOTE may not occur by itself at the end of the pattern. @param pattern the non-null, possibly empty pattern @return FieldPosition array of the resulting fields.
DecimalFormat::expandAffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void appendAffix(StringBuffer buffer, String affixPattern, String expAffix, boolean localized) { if (affixPattern == null) { appendAffix(buffer, expAffix, localized); } else { int i; for (int pos=0; pos<affixPattern.length(); pos=i) { i = affixPattern.indexOf(QUOTE, pos); if (i < 0) { appendAffix(buffer, affixPattern.substring(pos), localized); break; } if (i > pos) { appendAffix(buffer, affixPattern.substring(pos, i), localized); } char c = affixPattern.charAt(++i); ++i; if (c == QUOTE) { buffer.append(c); // Fall through and append another QUOTE below } else if (c == CURRENCY_SIGN && i<affixPattern.length() && affixPattern.charAt(i) == CURRENCY_SIGN) { ++i; buffer.append(c); // Fall through and append another CURRENCY_SIGN below } else if (localized) { switch (c) { case PATTERN_PERCENT: c = symbols.getPercent(); break; case PATTERN_PER_MILLE: c = symbols.getPerMill(); break; case PATTERN_MINUS: c = symbols.getMinusSign(); break; } } buffer.append(c); } } }
Appends an affix pattern to the given StringBuffer, quoting special characters as needed. Uses the internal affix pattern, if that exists, or the literal affix, if the internal affix pattern is null. The appended string will generate the same affix pattern (or literal affix) when passed to toPattern(). @param buffer the affix string is appended to this @param affixPattern a pattern such as posPrefixPattern; may be null @param expAffix a corresponding expanded affix, such as positivePrefix. Ignored unless affixPattern is null. If affixPattern is null, then expAffix is appended as a literal affix. @param localized true if the appended pattern should contain localized pattern characters; otherwise, non-localized pattern chars are appended
DecimalFormat::appendAffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void appendAffix(StringBuffer buffer, String affix, boolean localized) { boolean needQuote; if (localized) { needQuote = affix.indexOf(symbols.getZeroDigit()) >= 0 || affix.indexOf(symbols.getGroupingSeparator()) >= 0 || affix.indexOf(symbols.getDecimalSeparator()) >= 0 || affix.indexOf(symbols.getPercent()) >= 0 || affix.indexOf(symbols.getPerMill()) >= 0 || affix.indexOf(symbols.getDigit()) >= 0 || affix.indexOf(symbols.getPatternSeparator()) >= 0 || affix.indexOf(symbols.getMinusSign()) >= 0 || affix.indexOf(CURRENCY_SIGN) >= 0; } else { needQuote = affix.indexOf(PATTERN_ZERO_DIGIT) >= 0 || affix.indexOf(PATTERN_GROUPING_SEPARATOR) >= 0 || affix.indexOf(PATTERN_DECIMAL_SEPARATOR) >= 0 || affix.indexOf(PATTERN_PERCENT) >= 0 || affix.indexOf(PATTERN_PER_MILLE) >= 0 || affix.indexOf(PATTERN_DIGIT) >= 0 || affix.indexOf(PATTERN_SEPARATOR) >= 0 || affix.indexOf(PATTERN_MINUS) >= 0 || affix.indexOf(CURRENCY_SIGN) >= 0; } if (needQuote) buffer.append('\''); if (affix.indexOf('\'') < 0) buffer.append(affix); else { for (int j=0; j<affix.length(); ++j) { char c = affix.charAt(j); buffer.append(c); if (c == '\'') buffer.append(c); } } if (needQuote) buffer.append('\''); }
Append an affix to the given StringBuffer, using quotes if there are special characters. Single quotes themselves must be escaped in either case.
DecimalFormat::appendAffix
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private String toPattern(boolean localized) { StringBuffer result = new StringBuffer(); for (int j = 1; j >= 0; --j) { if (j == 1) appendAffix(result, posPrefixPattern, positivePrefix, localized); else appendAffix(result, negPrefixPattern, negativePrefix, localized); int i; int digitCount = useExponentialNotation ? getMaximumIntegerDigits() : Math.max(groupingSize + secondaryGroupingSize, getMinimumIntegerDigits())+1; for (i = digitCount; i > 0; --i) { if (i != digitCount && isGroupingUsed() && groupingSize != 0 && (secondaryGroupingSize > 0 && i > groupingSize ? (i - groupingSize) % secondaryGroupingSize == 0 : i % groupingSize == 0)) { result.append(localized ? symbols.getGroupingSeparator() : PATTERN_GROUPING_SEPARATOR); } result.append(i <= getMinimumIntegerDigits() ? (localized ? symbols.getZeroDigit() : PATTERN_ZERO_DIGIT) : (localized ? symbols.getDigit() : PATTERN_DIGIT)); } if (getMaximumFractionDigits() > 0 || decimalSeparatorAlwaysShown) result.append(localized ? symbols.getDecimalSeparator() : PATTERN_DECIMAL_SEPARATOR); for (i = 0; i < getMaximumFractionDigits(); ++i) { if (i < getMinimumFractionDigits()) { result.append(localized ? symbols.getZeroDigit() : PATTERN_ZERO_DIGIT); } else { result.append(localized ? symbols.getDigit() : PATTERN_DIGIT); } } if (useExponentialNotation) { result.append(localized ? symbols.getExponentSeparator() : PATTERN_EXPONENT); for (i=0; i<minExponentDigits; ++i) result.append(localized ? symbols.getZeroDigit() : PATTERN_ZERO_DIGIT); } if (j == 1) { appendAffix(result, posSuffixPattern, positiveSuffix, localized); if ((negSuffixPattern == posSuffixPattern && // n == p == null negativeSuffix.equals(positiveSuffix)) || (negSuffixPattern != null && negSuffixPattern.equals(posSuffixPattern))) { if ((negPrefixPattern != null && posPrefixPattern != null && negPrefixPattern.equals("'-" + posPrefixPattern)) || (negPrefixPattern == posPrefixPattern && // n == p == null negativePrefix.equals(symbols.getMinusSign() + positivePrefix))) break; } result.append(localized ? symbols.getPatternSeparator() : PATTERN_SEPARATOR); } else appendAffix(result, negSuffixPattern, negativeSuffix, localized); } return result.toString(); }
* Does the real work of generating a pattern.
DecimalFormat::toPattern
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); digitList = new DigitList(); // We force complete fast-path reinitialization when the instance is // deserialized. See clone() comment on fastPathCheckNeeded. fastPathCheckNeeded = true; isFastPath = false; fastPathData = null; if (serialVersionOnStream < 4) { setRoundingMode(RoundingMode.HALF_EVEN); } else { setRoundingMode(getRoundingMode()); } // We only need to check the maximum counts because NumberFormat // .readObject has already ensured that the maximum is greater than the // minimum count. if (super.getMaximumIntegerDigits() > DOUBLE_INTEGER_DIGITS || super.getMaximumFractionDigits() > DOUBLE_FRACTION_DIGITS) { throw new InvalidObjectException("Digit count out of range"); } if (serialVersionOnStream < 3) { setMaximumIntegerDigits(super.getMaximumIntegerDigits()); setMinimumIntegerDigits(super.getMinimumIntegerDigits()); setMaximumFractionDigits(super.getMaximumFractionDigits()); setMinimumFractionDigits(super.getMinimumFractionDigits()); } if (serialVersionOnStream < 1) { // Didn't have exponential fields useExponentialNotation = false; } serialVersionOnStream = currentSerialVersion; }
Reads the default serializable fields from the stream and performs validations and adjustments for older serialized versions. The validations and adjustments are: <ol> <li> Verify that the superclass's digit count fields correctly reflect the limits imposed on formatting numbers other than <code>BigInteger</code> and <code>BigDecimal</code> objects. These limits are stored in the superclass for serialization compatibility with older versions, while the limits for <code>BigInteger</code> and <code>BigDecimal</code> objects are kept in this class. If, in the superclass, the minimum or maximum integer digit count is larger than <code>DOUBLE_INTEGER_DIGITS</code> or if the minimum or maximum fraction digit count is larger than <code>DOUBLE_FRACTION_DIGITS</code>, then the stream data is invalid and this method throws an <code>InvalidObjectException</code>. <li> If <code>serialVersionOnStream</code> is less than 4, initialize <code>roundingMode</code> to {@link java.math.RoundingMode#HALF_EVEN RoundingMode.HALF_EVEN}. This field is new with version 4. <li> If <code>serialVersionOnStream</code> is less than 3, then call the setters for the minimum and maximum integer and fraction digits with the values of the corresponding superclass getters to initialize the fields in this class. The fields in this class are new with version 3. <li> If <code>serialVersionOnStream</code> is less than 1, indicating that the stream was written by JDK 1.1, initialize <code>useExponentialNotation</code> to false, since it was not present in JDK 1.1. <li> Set <code>serialVersionOnStream</code> to the maximum allowed value so that default serialization will work properly if this object is streamed out again. </ol> <p>Stream versions older than 2 will not have the affix pattern variables <code>posPrefixPattern</code> etc. As a result, they will be initialized to <code>null</code>, which means the affix strings will be taken as literal values. This is exactly what we want, since that corresponds to the pre-version-2 behavior.
DecimalFormat::readObject
java
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
Apache-2.0
static String[] moduleNames() { return new String[0]; }
Returns the array of initial module names identified at link time.
SystemModulesMap::moduleNames
java
google/j2objc
jre_emul/openjdk/src/share/classes/jdk/internal/module/SystemModulesMap.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/jdk/internal/module/SystemModulesMap.java
Apache-2.0
static String[] classNames() { return new String[0]; }
Returns the array of SystemModules class names. The elements correspond to the elements in the array returned by moduleNames().
SystemModulesMap::classNames
java
google/j2objc
jre_emul/openjdk/src/share/classes/jdk/internal/module/SystemModulesMap.java
https://github.com/google/j2objc/blob/master/jre_emul/openjdk/src/share/classes/jdk/internal/module/SystemModulesMap.java
Apache-2.0
public static ByteString toBytes(String str) { return ByteString.copyFromUtf8(str); }
Contains methods for setting fields of {@code TestAllTypesLite}, {@code TestAllExtensionsLite}, and {@code TestPackedExtensionsLite}. This is analogous to the functionality in TestUtil.java but does not depend on the presence of any non-lite protos. <p>This code is not to be used outside of {@code com.google.protobuf} and subpackages. public final class TestUtilLite { private TestUtilLite() {} /** Helper to convert a String to ByteString.
TestUtilLite::toBytes
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static TestAllTypesLite.Builder getAllLiteSetBuilder() { TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder(); setAllFields(builder); return builder; }
Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by {@link #setAllFields(TestAllTypesLite.Builder)}.
TestUtilLite::getAllLiteSetBuilder
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static TestAllExtensionsLite getAllLiteExtensionsSet() { TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder(); setAllExtensions(builder); return builder.build(); }
Get a {@code TestAllExtensionsLite} with all fields set as they would be by {@link #setAllExtensions(TestAllExtensionsLite.Builder)}.
TestUtilLite::getAllLiteExtensionsSet
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static void setAllFields(TestAllTypesLite.Builder builder) { builder.setOptionalInt32(101); builder.setOptionalInt64(102); builder.setOptionalUint32(103); builder.setOptionalUint64(104); builder.setOptionalSint32(105); builder.setOptionalSint64(106); builder.setOptionalFixed32(107); builder.setOptionalFixed64(108); builder.setOptionalSfixed32(109); builder.setOptionalSfixed64(110); builder.setOptionalFloat(111); builder.setOptionalDouble(112); builder.setOptionalBool(true); builder.setOptionalString("115"); builder.setOptionalBytes(toBytes("116")); builder.setOptionalGroup(TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build()); builder.setOptionalNestedMessage( TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build()); builder.setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(119).build()); builder.setOptionalImportMessage(ImportMessageLite.newBuilder().setD(120).build()); builder.setOptionalPublicImportMessage(PublicImportMessageLite.newBuilder().setE(126).build()); builder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); builder.setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ); builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ); builder.setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAZ); builder.setOptionalStringPiece("124"); builder.setOptionalCord("125"); // ----------------------------------------------------------------- builder.addRepeatedInt32(201); builder.addRepeatedInt64(202); builder.addRepeatedUint32(203); builder.addRepeatedUint64(204); builder.addRepeatedSint32(205); builder.addRepeatedSint64(206); builder.addRepeatedFixed32(207); builder.addRepeatedFixed64(208); builder.addRepeatedSfixed32(209); builder.addRepeatedSfixed64(210); builder.addRepeatedFloat(211); builder.addRepeatedDouble(212); builder.addRepeatedBool(true); builder.addRepeatedString("215"); builder.addRepeatedBytes(toBytes("216")); builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build()); builder.addRepeatedNestedMessage( TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build()); builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(219).build()); builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(220).build()); builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAR); builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR); builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR); builder.addRepeatedStringPiece("224"); builder.addRepeatedCord("225"); // Add a second one of each field. builder.addRepeatedInt32(301); builder.addRepeatedInt64(302); builder.addRepeatedUint32(303); builder.addRepeatedUint64(304); builder.addRepeatedSint32(305); builder.addRepeatedSint64(306); builder.addRepeatedFixed32(307); builder.addRepeatedFixed64(308); builder.addRepeatedSfixed32(309); builder.addRepeatedSfixed64(310); builder.addRepeatedFloat(311); builder.addRepeatedDouble(312); builder.addRepeatedBool(false); builder.addRepeatedString("315"); builder.addRepeatedBytes(toBytes("316")); builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build()); builder.addRepeatedNestedMessage( TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build()); builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(319).build()); builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(320).build()); builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAZ); builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ); builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAZ); builder.addRepeatedStringPiece("324"); builder.addRepeatedCord("325"); // ----------------------------------------------------------------- builder.setDefaultInt32(401); builder.setDefaultInt64(402); builder.setDefaultUint32(403); builder.setDefaultUint64(404); builder.setDefaultSint32(405); builder.setDefaultSint64(406); builder.setDefaultFixed32(407); builder.setDefaultFixed64(408); builder.setDefaultSfixed32(409); builder.setDefaultSfixed64(410); builder.setDefaultFloat(411); builder.setDefaultDouble(412); builder.setDefaultBool(false); builder.setDefaultString("415"); builder.setDefaultBytes(toBytes("416")); builder.setDefaultNestedEnum(TestAllTypesLite.NestedEnum.FOO); builder.setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_FOO); builder.setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_FOO); builder.setDefaultStringPiece("424"); builder.setDefaultCord("425"); builder.setOneofUint32(601); builder.setOneofNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); builder.setOneofString("603"); builder.setOneofBytes(toBytes("604")); }
Get a {@code TestAllExtensionsLite} with all fields set as they would be by {@link #setAllExtensions(TestAllExtensionsLite.Builder)}. public static TestAllExtensionsLite getAllLiteExtensionsSet() { TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder(); setAllExtensions(builder); return builder.build(); } public static TestPackedExtensionsLite getLitePackedExtensionsSet() { TestPackedExtensionsLite.Builder builder = TestPackedExtensionsLite.newBuilder(); setPackedExtensions(builder); return builder.build(); } /** Set every field of {@code builder} to the values expected by {@code assertAllFieldsSet()}.
TestUtilLite::setAllFields
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static ExtensionRegistryLite getExtensionRegistryLite() { ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); registerAllExtensionsLite(registry); return registry.getUnmodifiable(); }
Get an unmodifiable {@link ExtensionRegistryLite} containing all the extensions of {@code TestAllExtensionsLite}.
TestUtilLite::getExtensionRegistryLite
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static void registerAllExtensionsLite(ExtensionRegistryLite registry) { UnittestLite.registerAllExtensions(registry); }
Register all of {@code TestAllExtensionsLite}'s extensions with the given {@link ExtensionRegistryLite}.
TestUtilLite::registerAllExtensionsLite
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static void setAllExtensions(TestAllExtensionsLite.Builder message) { message.setExtension(optionalInt32ExtensionLite, 101); message.setExtension(optionalInt64ExtensionLite, 102L); message.setExtension(optionalUint32ExtensionLite, 103); message.setExtension(optionalUint64ExtensionLite, 104L); message.setExtension(optionalSint32ExtensionLite, 105); message.setExtension(optionalSint64ExtensionLite, 106L); message.setExtension(optionalFixed32ExtensionLite, 107); message.setExtension(optionalFixed64ExtensionLite, 108L); message.setExtension(optionalSfixed32ExtensionLite, 109); message.setExtension(optionalSfixed64ExtensionLite, 110L); message.setExtension(optionalFloatExtensionLite, 111F); message.setExtension(optionalDoubleExtensionLite, 112D); message.setExtension(optionalBoolExtensionLite, true); message.setExtension(optionalStringExtensionLite, "115"); message.setExtension(optionalBytesExtensionLite, toBytes("116")); message.setExtension( optionalGroupExtensionLite, OptionalGroup_extension_lite.newBuilder().setA(117).build()); message.setExtension( optionalNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build()); message.setExtension( optionalForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(119).build()); message.setExtension( optionalImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(120).build()); message.setExtension( optionalPublicImportMessageExtensionLite, PublicImportMessageLite.newBuilder().setE(126).build()); message.setExtension( optionalLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); message.setExtension(optionalImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ); message.setExtension(optionalStringPieceExtensionLite, "124"); message.setExtension(optionalCordExtensionLite, "125"); // ----------------------------------------------------------------- message.addExtension(repeatedInt32ExtensionLite, 201); message.addExtension(repeatedInt64ExtensionLite, 202L); message.addExtension(repeatedUint32ExtensionLite, 203); message.addExtension(repeatedUint64ExtensionLite, 204L); message.addExtension(repeatedSint32ExtensionLite, 205); message.addExtension(repeatedSint64ExtensionLite, 206L); message.addExtension(repeatedFixed32ExtensionLite, 207); message.addExtension(repeatedFixed64ExtensionLite, 208L); message.addExtension(repeatedSfixed32ExtensionLite, 209); message.addExtension(repeatedSfixed64ExtensionLite, 210L); message.addExtension(repeatedFloatExtensionLite, 211F); message.addExtension(repeatedDoubleExtensionLite, 212D); message.addExtension(repeatedBoolExtensionLite, true); message.addExtension(repeatedStringExtensionLite, "215"); message.addExtension(repeatedBytesExtensionLite, toBytes("216")); message.addExtension( repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(217).build()); message.addExtension( repeatedNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build()); message.addExtension( repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(219).build()); message.addExtension( repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(220).build()); message.addExtension( repeatedLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build()); message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAR); message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR); message.addExtension(repeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAR); message.addExtension(repeatedStringPieceExtensionLite, "224"); message.addExtension(repeatedCordExtensionLite, "225"); // Add a second one of each field. message.addExtension(repeatedInt32ExtensionLite, 301); message.addExtension(repeatedInt64ExtensionLite, 302L); message.addExtension(repeatedUint32ExtensionLite, 303); message.addExtension(repeatedUint64ExtensionLite, 304L); message.addExtension(repeatedSint32ExtensionLite, 305); message.addExtension(repeatedSint64ExtensionLite, 306L); message.addExtension(repeatedFixed32ExtensionLite, 307); message.addExtension(repeatedFixed64ExtensionLite, 308L); message.addExtension(repeatedSfixed32ExtensionLite, 309); message.addExtension(repeatedSfixed64ExtensionLite, 310L); message.addExtension(repeatedFloatExtensionLite, 311F); message.addExtension(repeatedDoubleExtensionLite, 312D); message.addExtension(repeatedBoolExtensionLite, false); message.addExtension(repeatedStringExtensionLite, "315"); message.addExtension(repeatedBytesExtensionLite, toBytes("316")); message.addExtension( repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(317).build()); message.addExtension( repeatedNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build()); message.addExtension( repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(319).build()); message.addExtension( repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(320).build()); message.addExtension( repeatedLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build()); message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ); message.addExtension(repeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ); message.addExtension(repeatedStringPieceExtensionLite, "324"); message.addExtension(repeatedCordExtensionLite, "325"); // ----------------------------------------------------------------- message.setExtension(defaultInt32ExtensionLite, 401); message.setExtension(defaultInt64ExtensionLite, 402L); message.setExtension(defaultUint32ExtensionLite, 403); message.setExtension(defaultUint64ExtensionLite, 404L); message.setExtension(defaultSint32ExtensionLite, 405); message.setExtension(defaultSint64ExtensionLite, 406L); message.setExtension(defaultFixed32ExtensionLite, 407); message.setExtension(defaultFixed64ExtensionLite, 408L); message.setExtension(defaultSfixed32ExtensionLite, 409); message.setExtension(defaultSfixed64ExtensionLite, 410L); message.setExtension(defaultFloatExtensionLite, 411F); message.setExtension(defaultDoubleExtensionLite, 412D); message.setExtension(defaultBoolExtensionLite, false); message.setExtension(defaultStringExtensionLite, "415"); message.setExtension(defaultBytesExtensionLite, toBytes("416")); message.setExtension(defaultNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.FOO); message.setExtension(defaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_FOO); message.setExtension(defaultImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_FOO); message.setExtension(defaultStringPieceExtensionLite, "424"); message.setExtension(defaultCordExtensionLite, "425"); message.setExtension(oneofUint32ExtensionLite, 601); message.setExtension( oneofNestedMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build()); message.setExtension(oneofStringExtensionLite, "603"); message.setExtension(oneofBytesExtensionLite, toBytes("604")); }
Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}.
TestUtilLite::setAllExtensions
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static void modifyRepeatedExtensions(TestAllExtensionsLite.Builder message) { message.setExtension(repeatedInt32ExtensionLite, 1, 501); message.setExtension(repeatedInt64ExtensionLite, 1, 502L); message.setExtension(repeatedUint32ExtensionLite, 1, 503); message.setExtension(repeatedUint64ExtensionLite, 1, 504L); message.setExtension(repeatedSint32ExtensionLite, 1, 505); message.setExtension(repeatedSint64ExtensionLite, 1, 506L); message.setExtension(repeatedFixed32ExtensionLite, 1, 507); message.setExtension(repeatedFixed64ExtensionLite, 1, 508L); message.setExtension(repeatedSfixed32ExtensionLite, 1, 509); message.setExtension(repeatedSfixed64ExtensionLite, 1, 510L); message.setExtension(repeatedFloatExtensionLite, 1, 511F); message.setExtension(repeatedDoubleExtensionLite, 1, 512D); message.setExtension(repeatedBoolExtensionLite, 1, true); message.setExtension(repeatedStringExtensionLite, 1, "515"); message.setExtension(repeatedBytesExtensionLite, 1, toBytes("516")); message.setExtension( repeatedGroupExtensionLite, 1, RepeatedGroup_extension_lite.newBuilder().setA(517).build()); message.setExtension( repeatedNestedMessageExtensionLite, 1, TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build()); message.setExtension( repeatedForeignMessageExtensionLite, 1, ForeignMessageLite.newBuilder().setC(519).build()); message.setExtension( repeatedImportMessageExtensionLite, 1, ImportMessageLite.newBuilder().setD(520).build()); message.setExtension( repeatedLazyMessageExtensionLite, 1, TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build()); message.setExtension(repeatedNestedEnumExtensionLite, 1, TestAllTypesLite.NestedEnum.FOO); message.setExtension(repeatedForeignEnumExtensionLite, 1, ForeignEnumLite.FOREIGN_LITE_FOO); message.setExtension(repeatedImportEnumExtensionLite, 1, ImportEnumLite.IMPORT_LITE_FOO); message.setExtension(repeatedStringPieceExtensionLite, 1, "524"); message.setExtension(repeatedCordExtensionLite, 1, "525"); }
Modify the repeated extensions of {@code message} to contain the values expected by {@code assertRepeatedExtensionsModified()}.
TestUtilLite::modifyRepeatedExtensions
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtilLite.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtilLite.java
Apache-2.0
public static TestAllTypes getAllSet() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); setAllFields(builder); return builder.build(); }
Get a {@code TestAllTypes} with all fields set as they would be by {@link #setAllFields(TestAllTypes.Builder)}.
TestUtil::getAllSet
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static TestAllTypes.Builder getAllSetBuilder() { TestAllTypes.Builder builder = TestAllTypes.newBuilder(); setAllFields(builder); return builder; }
Get a {@code TestAllTypes.Builder} with all fields set as they would be by {@link #setAllFields(TestAllTypes.Builder)}.
TestUtil::getAllSetBuilder
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static TestAllExtensions getAllExtensionsSet() { TestAllExtensions.Builder builder = TestAllExtensions.newBuilder(); setAllExtensions(builder); return builder.build(); }
Get a {@code TestAllExtensions} with all fields set as they would be by {@link #setAllExtensions(TestAllExtensions.Builder)}.
TestUtil::getAllExtensionsSet
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void setAllFields(TestAllTypes.Builder message) { message.setOptionalInt32(101); message.setOptionalInt64(102); message.setOptionalUint32(103); message.setOptionalUint64(104); message.setOptionalSint32(105); message.setOptionalSint64(106); message.setOptionalFixed32(107); message.setOptionalFixed64(108); message.setOptionalSfixed32(109); message.setOptionalSfixed64(110); message.setOptionalFloat(111); message.setOptionalDouble(112); message.setOptionalBool(true); message.setOptionalString("115"); message.setOptionalBytes(toBytes("116")); message.setOptionalGroup(TestAllTypes.OptionalGroup.newBuilder().setA(117).build()); message.setOptionalNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(118).build()); message.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(119).build()); message.setOptionalImportMessage(ImportMessage.newBuilder().setD(120).build()); message.setOptionalPublicImportMessage(PublicImportMessage.newBuilder().setE(126).build()); message.setOptionalLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); message.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ); message.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ); message.setOptionalImportEnum(ImportEnum.IMPORT_BAZ); message.setOptionalStringPiece("124"); message.setOptionalCord("125"); // ----------------------------------------------------------------- message.addRepeatedInt32(201); message.addRepeatedInt64(202); message.addRepeatedUint32(203); message.addRepeatedUint64(204); message.addRepeatedSint32(205); message.addRepeatedSint64(206); message.addRepeatedFixed32(207); message.addRepeatedFixed64(208); message.addRepeatedSfixed32(209); message.addRepeatedSfixed64(210); message.addRepeatedFloat(211); message.addRepeatedDouble(212); message.addRepeatedBool(true); message.addRepeatedString("215"); message.addRepeatedBytes(toBytes("216")); message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(217).build()); message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(219).build()); message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(220).build()); message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(227).build()); message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR); message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR); message.addRepeatedImportEnum(ImportEnum.IMPORT_BAR); message.addRepeatedStringPiece("224"); message.addRepeatedCord("225"); // Add a second one of each field. message.addRepeatedInt32(301); message.addRepeatedInt64(302); message.addRepeatedUint32(303); message.addRepeatedUint64(304); message.addRepeatedSint32(305); message.addRepeatedSint64(306); message.addRepeatedFixed32(307); message.addRepeatedFixed64(308); message.addRepeatedSfixed32(309); message.addRepeatedSfixed64(310); message.addRepeatedFloat(311); message.addRepeatedDouble(312); message.addRepeatedBool(false); message.addRepeatedString("315"); message.addRepeatedBytes(toBytes("316")); message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(317).build()); message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(318).build()); message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(319).build()); message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(320).build()); message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(327).build()); message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ); message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ); message.addRepeatedImportEnum(ImportEnum.IMPORT_BAZ); message.addRepeatedStringPiece("324"); message.addRepeatedCord("325"); // ----------------------------------------------------------------- message.setDefaultInt32(401); message.setDefaultInt64(402); message.setDefaultUint32(403); message.setDefaultUint64(404); message.setDefaultSint32(405); message.setDefaultSint64(406); message.setDefaultFixed32(407); message.setDefaultFixed64(408); message.setDefaultSfixed32(409); message.setDefaultSfixed64(410); message.setDefaultFloat(411); message.setDefaultDouble(412); message.setDefaultBool(false); message.setDefaultString("415"); message.setDefaultBytes(toBytes("416")); message.setDefaultNestedEnum(TestAllTypes.NestedEnum.FOO); message.setDefaultForeignEnum(ForeignEnum.FOREIGN_FOO); message.setDefaultImportEnum(ImportEnum.IMPORT_FOO); message.setDefaultStringPiece("424"); message.setDefaultCord("425"); message.setOneofUint32(601); message.setOneofNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(602).build()); message.setOneofString("603"); message.setOneofBytes(toBytes("604")); }
Get a {@code TestAllExtensions} with all fields set as they would be by {@link #setAllExtensions(TestAllExtensions.Builder)}. public static TestAllExtensions getAllExtensionsSet() { TestAllExtensions.Builder builder = TestAllExtensions.newBuilder(); setAllExtensions(builder); return builder.build(); } public static TestPackedTypes getPackedSet() { TestPackedTypes.Builder builder = TestPackedTypes.newBuilder(); setPackedFields(builder); return builder.build(); } public static TestUnpackedTypes getUnpackedSet() { TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder(); setUnpackedFields(builder); return builder.build(); } public static TestPackedExtensions getPackedExtensionsSet() { TestPackedExtensions.Builder builder = TestPackedExtensions.newBuilder(); setPackedExtensions(builder); return builder.build(); } /** Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()}.
TestUtil::setAllFields
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void modifyRepeatedFields(TestAllTypes.Builder message) { message.setRepeatedInt32(1, 501); message.setRepeatedInt64(1, 502); message.setRepeatedUint32(1, 503); message.setRepeatedUint64(1, 504); message.setRepeatedSint32(1, 505); message.setRepeatedSint64(1, 506); message.setRepeatedFixed32(1, 507); message.setRepeatedFixed64(1, 508); message.setRepeatedSfixed32(1, 509); message.setRepeatedSfixed64(1, 510); message.setRepeatedFloat(1, 511); message.setRepeatedDouble(1, 512); message.setRepeatedBool(1, true); message.setRepeatedString(1, "515"); message.setRepeatedBytes(1, toBytes("516")); message.setRepeatedGroup(1, TestAllTypes.RepeatedGroup.newBuilder().setA(517).build()); message.setRepeatedNestedMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(518).build()); message.setRepeatedForeignMessage(1, ForeignMessage.newBuilder().setC(519).build()); message.setRepeatedImportMessage(1, ImportMessage.newBuilder().setD(520).build()); message.setRepeatedLazyMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(527).build()); message.setRepeatedNestedEnum(1, TestAllTypes.NestedEnum.FOO); message.setRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO); message.setRepeatedImportEnum(1, ImportEnum.IMPORT_FOO); message.setRepeatedStringPiece(1, "524"); message.setRepeatedCord(1, "525"); }
Modify the repeated fields of {@code message} to contain the values expected by {@code assertRepeatedFieldsModified()}.
TestUtil::modifyRepeatedFields
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void assertAllFieldsSet(TestAllTypesOrBuilder message) { Assert.assertTrue(message.hasOptionalInt32()); Assert.assertTrue(message.hasOptionalInt64()); Assert.assertTrue(message.hasOptionalUint32()); Assert.assertTrue(message.hasOptionalUint64()); Assert.assertTrue(message.hasOptionalSint32()); Assert.assertTrue(message.hasOptionalSint64()); Assert.assertTrue(message.hasOptionalFixed32()); Assert.assertTrue(message.hasOptionalFixed64()); Assert.assertTrue(message.hasOptionalSfixed32()); Assert.assertTrue(message.hasOptionalSfixed64()); Assert.assertTrue(message.hasOptionalFloat()); Assert.assertTrue(message.hasOptionalDouble()); Assert.assertTrue(message.hasOptionalBool()); Assert.assertTrue(message.hasOptionalString()); Assert.assertTrue(message.hasOptionalBytes()); Assert.assertTrue(message.hasOptionalGroup()); Assert.assertTrue(message.hasOptionalNestedMessage()); Assert.assertTrue(message.hasOptionalForeignMessage()); Assert.assertTrue(message.hasOptionalImportMessage()); Assert.assertTrue(message.getOptionalGroup().hasA()); Assert.assertTrue(message.getOptionalNestedMessage().hasBb()); Assert.assertTrue(message.getOptionalForeignMessage().hasC()); Assert.assertTrue(message.getOptionalImportMessage().hasD()); Assert.assertTrue(message.hasOptionalNestedEnum()); Assert.assertTrue(message.hasOptionalForeignEnum()); Assert.assertTrue(message.hasOptionalImportEnum()); Assert.assertTrue(message.hasOptionalStringPiece()); Assert.assertTrue(message.hasOptionalCord()); Assert.assertEquals(101, message.getOptionalInt32()); Assert.assertEquals(102, message.getOptionalInt64()); Assert.assertEquals(103, message.getOptionalUint32()); Assert.assertEquals(104, message.getOptionalUint64()); Assert.assertEquals(105, message.getOptionalSint32()); Assert.assertEquals(106, message.getOptionalSint64()); Assert.assertEquals(107, message.getOptionalFixed32()); Assert.assertEquals(108, message.getOptionalFixed64()); Assert.assertEquals(109, message.getOptionalSfixed32()); Assert.assertEquals(110, message.getOptionalSfixed64()); Assert.assertEquals(111, message.getOptionalFloat(), 0.0); Assert.assertEquals(112, message.getOptionalDouble(), 0.0); Assert.assertEquals(true, message.getOptionalBool()); Assert.assertEquals("115", message.getOptionalString()); Assert.assertEquals(toBytes("116"), message.getOptionalBytes()); Assert.assertEquals(117, message.getOptionalGroup().getA()); Assert.assertEquals(118, message.getOptionalNestedMessage().getBb()); Assert.assertEquals(119, message.getOptionalForeignMessage().getC()); Assert.assertEquals(120, message.getOptionalImportMessage().getD()); Assert.assertEquals(126, message.getOptionalPublicImportMessage().getE()); Assert.assertEquals(127, message.getOptionalLazyMessage().getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getOptionalNestedEnum()); Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getOptionalForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getOptionalImportEnum()); Assert.assertEquals("124", message.getOptionalStringPiece()); Assert.assertEquals("125", message.getOptionalCord()); // ----------------------------------------------------------------- Assert.assertEquals(2, message.getRepeatedInt32Count()); Assert.assertEquals(2, message.getRepeatedInt64Count()); Assert.assertEquals(2, message.getRepeatedUint32Count()); Assert.assertEquals(2, message.getRepeatedUint64Count()); Assert.assertEquals(2, message.getRepeatedSint32Count()); Assert.assertEquals(2, message.getRepeatedSint64Count()); Assert.assertEquals(2, message.getRepeatedFixed32Count()); Assert.assertEquals(2, message.getRepeatedFixed64Count()); Assert.assertEquals(2, message.getRepeatedSfixed32Count()); Assert.assertEquals(2, message.getRepeatedSfixed64Count()); Assert.assertEquals(2, message.getRepeatedFloatCount()); Assert.assertEquals(2, message.getRepeatedDoubleCount()); Assert.assertEquals(2, message.getRepeatedBoolCount()); Assert.assertEquals(2, message.getRepeatedStringCount()); Assert.assertEquals(2, message.getRepeatedBytesCount()); Assert.assertEquals(2, message.getRepeatedGroupCount()); Assert.assertEquals(2, message.getRepeatedNestedMessageCount()); Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); Assert.assertEquals(2, message.getRepeatedImportMessageCount()); Assert.assertEquals(2, message.getRepeatedLazyMessageCount()); Assert.assertEquals(2, message.getRepeatedNestedEnumCount()); Assert.assertEquals(2, message.getRepeatedForeignEnumCount()); Assert.assertEquals(2, message.getRepeatedImportEnumCount()); Assert.assertEquals(2, message.getRepeatedStringPieceCount()); Assert.assertEquals(2, message.getRepeatedCordCount()); Assert.assertEquals(201, message.getRepeatedInt32(0)); Assert.assertEquals(202, message.getRepeatedInt64(0)); Assert.assertEquals(203, message.getRepeatedUint32(0)); Assert.assertEquals(204, message.getRepeatedUint64(0)); Assert.assertEquals(205, message.getRepeatedSint32(0)); Assert.assertEquals(206, message.getRepeatedSint64(0)); Assert.assertEquals(207, message.getRepeatedFixed32(0)); Assert.assertEquals(208, message.getRepeatedFixed64(0)); Assert.assertEquals(209, message.getRepeatedSfixed32(0)); Assert.assertEquals(210, message.getRepeatedSfixed64(0)); Assert.assertEquals(211, message.getRepeatedFloat(0), 0.0); Assert.assertEquals(212, message.getRepeatedDouble(0), 0.0); Assert.assertEquals(true, message.getRepeatedBool(0)); Assert.assertEquals("215", message.getRepeatedString(0)); Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); Assert.assertEquals(217, message.getRepeatedGroup(0).getA()); Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb()); Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD()); Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); Assert.assertEquals("224", message.getRepeatedStringPiece(0)); Assert.assertEquals("225", message.getRepeatedCord(0)); Assert.assertEquals(301, message.getRepeatedInt32(1)); Assert.assertEquals(302, message.getRepeatedInt64(1)); Assert.assertEquals(303, message.getRepeatedUint32(1)); Assert.assertEquals(304, message.getRepeatedUint64(1)); Assert.assertEquals(305, message.getRepeatedSint32(1)); Assert.assertEquals(306, message.getRepeatedSint64(1)); Assert.assertEquals(307, message.getRepeatedFixed32(1)); Assert.assertEquals(308, message.getRepeatedFixed64(1)); Assert.assertEquals(309, message.getRepeatedSfixed32(1)); Assert.assertEquals(310, message.getRepeatedSfixed64(1)); Assert.assertEquals(311, message.getRepeatedFloat(1), 0.0); Assert.assertEquals(312, message.getRepeatedDouble(1), 0.0); Assert.assertEquals(false, message.getRepeatedBool(1)); Assert.assertEquals("315", message.getRepeatedString(1)); Assert.assertEquals(toBytes("316"), message.getRepeatedBytes(1)); Assert.assertEquals(317, message.getRepeatedGroup(1).getA()); Assert.assertEquals(318, message.getRepeatedNestedMessage(1).getBb()); Assert.assertEquals(319, message.getRepeatedForeignMessage(1).getC()); Assert.assertEquals(320, message.getRepeatedImportMessage(1).getD()); Assert.assertEquals(327, message.getRepeatedLazyMessage(1).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum(1)); Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getRepeatedForeignEnum(1)); Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getRepeatedImportEnum(1)); Assert.assertEquals("324", message.getRepeatedStringPiece(1)); Assert.assertEquals("325", message.getRepeatedCord(1)); // ----------------------------------------------------------------- Assert.assertTrue(message.hasDefaultInt32()); Assert.assertTrue(message.hasDefaultInt64()); Assert.assertTrue(message.hasDefaultUint32()); Assert.assertTrue(message.hasDefaultUint64()); Assert.assertTrue(message.hasDefaultSint32()); Assert.assertTrue(message.hasDefaultSint64()); Assert.assertTrue(message.hasDefaultFixed32()); Assert.assertTrue(message.hasDefaultFixed64()); Assert.assertTrue(message.hasDefaultSfixed32()); Assert.assertTrue(message.hasDefaultSfixed64()); Assert.assertTrue(message.hasDefaultFloat()); Assert.assertTrue(message.hasDefaultDouble()); Assert.assertTrue(message.hasDefaultBool()); Assert.assertTrue(message.hasDefaultString()); Assert.assertTrue(message.hasDefaultBytes()); Assert.assertTrue(message.hasDefaultNestedEnum()); Assert.assertTrue(message.hasDefaultForeignEnum()); Assert.assertTrue(message.hasDefaultImportEnum()); Assert.assertTrue(message.hasDefaultStringPiece()); Assert.assertTrue(message.hasDefaultCord()); Assert.assertEquals(401, message.getDefaultInt32()); Assert.assertEquals(402, message.getDefaultInt64()); Assert.assertEquals(403, message.getDefaultUint32()); Assert.assertEquals(404, message.getDefaultUint64()); Assert.assertEquals(405, message.getDefaultSint32()); Assert.assertEquals(406, message.getDefaultSint64()); Assert.assertEquals(407, message.getDefaultFixed32()); Assert.assertEquals(408, message.getDefaultFixed64()); Assert.assertEquals(409, message.getDefaultSfixed32()); Assert.assertEquals(410, message.getDefaultSfixed64()); Assert.assertEquals(411, message.getDefaultFloat(), 0.0); Assert.assertEquals(412, message.getDefaultDouble(), 0.0); Assert.assertEquals(false, message.getDefaultBool()); Assert.assertEquals("415", message.getDefaultString()); Assert.assertEquals(toBytes("416"), message.getDefaultBytes()); Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum()); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getDefaultForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getDefaultImportEnum()); Assert.assertEquals("424", message.getDefaultStringPiece()); Assert.assertEquals("425", message.getDefaultCord()); Assert.assertEquals(TestAllTypes.OneofFieldCase.ONEOF_BYTES, message.getOneofFieldCase()); Assert.assertFalse(message.hasOneofUint32()); Assert.assertFalse(message.hasOneofNestedMessage()); Assert.assertFalse(message.hasOneofString()); Assert.assertTrue(message.hasOneofBytes()); Assert.assertEquals(toBytes("604"), message.getOneofBytes()); }
Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the values assigned by {@code setAllFields}.
TestUtil::assertAllFieldsSet
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void assertClear(TestAllTypesOrBuilder message) { // hasBlah() should initially be false for all optional fields. Assert.assertFalse(message.hasOptionalInt32()); Assert.assertFalse(message.hasOptionalInt64()); Assert.assertFalse(message.hasOptionalUint32()); Assert.assertFalse(message.hasOptionalUint64()); Assert.assertFalse(message.hasOptionalSint32()); Assert.assertFalse(message.hasOptionalSint64()); Assert.assertFalse(message.hasOptionalFixed32()); Assert.assertFalse(message.hasOptionalFixed64()); Assert.assertFalse(message.hasOptionalSfixed32()); Assert.assertFalse(message.hasOptionalSfixed64()); Assert.assertFalse(message.hasOptionalFloat()); Assert.assertFalse(message.hasOptionalDouble()); Assert.assertFalse(message.hasOptionalBool()); Assert.assertFalse(message.hasOptionalString()); Assert.assertFalse(message.hasOptionalBytes()); Assert.assertFalse(message.hasOptionalGroup()); Assert.assertFalse(message.hasOptionalNestedMessage()); Assert.assertFalse(message.hasOptionalForeignMessage()); Assert.assertFalse(message.hasOptionalImportMessage()); Assert.assertFalse(message.hasOptionalNestedEnum()); Assert.assertFalse(message.hasOptionalForeignEnum()); Assert.assertFalse(message.hasOptionalImportEnum()); Assert.assertFalse(message.hasOptionalStringPiece()); Assert.assertFalse(message.hasOptionalCord()); // Optional fields without defaults are set to zero or something like it. Assert.assertEquals(0, message.getOptionalInt32()); Assert.assertEquals(0, message.getOptionalInt64()); Assert.assertEquals(0, message.getOptionalUint32()); Assert.assertEquals(0, message.getOptionalUint64()); Assert.assertEquals(0, message.getOptionalSint32()); Assert.assertEquals(0, message.getOptionalSint64()); Assert.assertEquals(0, message.getOptionalFixed32()); Assert.assertEquals(0, message.getOptionalFixed64()); Assert.assertEquals(0, message.getOptionalSfixed32()); Assert.assertEquals(0, message.getOptionalSfixed64()); Assert.assertEquals(0, message.getOptionalFloat(), 0.0); Assert.assertEquals(0, message.getOptionalDouble(), 0.0); Assert.assertEquals(false, message.getOptionalBool()); Assert.assertEquals("", message.getOptionalString()); Assert.assertEquals(ByteString.EMPTY, message.getOptionalBytes()); // Embedded messages should also be clear. Assert.assertFalse(message.getOptionalGroup().hasA()); Assert.assertFalse(message.getOptionalNestedMessage().hasBb()); Assert.assertFalse(message.getOptionalForeignMessage().hasC()); Assert.assertFalse(message.getOptionalImportMessage().hasD()); Assert.assertFalse(message.getOptionalPublicImportMessage().hasE()); Assert.assertFalse(message.getOptionalLazyMessage().hasBb()); Assert.assertEquals(0, message.getOptionalGroup().getA()); Assert.assertEquals(0, message.getOptionalNestedMessage().getBb()); Assert.assertEquals(0, message.getOptionalForeignMessage().getC()); Assert.assertEquals(0, message.getOptionalImportMessage().getD()); Assert.assertEquals(0, message.getOptionalPublicImportMessage().getE()); Assert.assertEquals(0, message.getOptionalLazyMessage().getBb()); // Enums without defaults are set to the first value in the enum. Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum()); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getOptionalForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getOptionalImportEnum()); Assert.assertEquals("", message.getOptionalStringPiece()); Assert.assertEquals("", message.getOptionalCord()); // Repeated fields are empty. Assert.assertEquals(0, message.getRepeatedInt32Count()); Assert.assertEquals(0, message.getRepeatedInt64Count()); Assert.assertEquals(0, message.getRepeatedUint32Count()); Assert.assertEquals(0, message.getRepeatedUint64Count()); Assert.assertEquals(0, message.getRepeatedSint32Count()); Assert.assertEquals(0, message.getRepeatedSint64Count()); Assert.assertEquals(0, message.getRepeatedFixed32Count()); Assert.assertEquals(0, message.getRepeatedFixed64Count()); Assert.assertEquals(0, message.getRepeatedSfixed32Count()); Assert.assertEquals(0, message.getRepeatedSfixed64Count()); Assert.assertEquals(0, message.getRepeatedFloatCount()); Assert.assertEquals(0, message.getRepeatedDoubleCount()); Assert.assertEquals(0, message.getRepeatedBoolCount()); Assert.assertEquals(0, message.getRepeatedStringCount()); Assert.assertEquals(0, message.getRepeatedBytesCount()); Assert.assertEquals(0, message.getRepeatedGroupCount()); Assert.assertEquals(0, message.getRepeatedNestedMessageCount()); Assert.assertEquals(0, message.getRepeatedForeignMessageCount()); Assert.assertEquals(0, message.getRepeatedImportMessageCount()); Assert.assertEquals(0, message.getRepeatedLazyMessageCount()); Assert.assertEquals(0, message.getRepeatedNestedEnumCount()); Assert.assertEquals(0, message.getRepeatedForeignEnumCount()); Assert.assertEquals(0, message.getRepeatedImportEnumCount()); Assert.assertEquals(0, message.getRepeatedStringPieceCount()); Assert.assertEquals(0, message.getRepeatedCordCount()); // hasBlah() should also be false for all default fields. Assert.assertFalse(message.hasDefaultInt32()); Assert.assertFalse(message.hasDefaultInt64()); Assert.assertFalse(message.hasDefaultUint32()); Assert.assertFalse(message.hasDefaultUint64()); Assert.assertFalse(message.hasDefaultSint32()); Assert.assertFalse(message.hasDefaultSint64()); Assert.assertFalse(message.hasDefaultFixed32()); Assert.assertFalse(message.hasDefaultFixed64()); Assert.assertFalse(message.hasDefaultSfixed32()); Assert.assertFalse(message.hasDefaultSfixed64()); Assert.assertFalse(message.hasDefaultFloat()); Assert.assertFalse(message.hasDefaultDouble()); Assert.assertFalse(message.hasDefaultBool()); Assert.assertFalse(message.hasDefaultString()); Assert.assertFalse(message.hasDefaultBytes()); Assert.assertFalse(message.hasDefaultNestedEnum()); Assert.assertFalse(message.hasDefaultForeignEnum()); Assert.assertFalse(message.hasDefaultImportEnum()); Assert.assertFalse(message.hasDefaultStringPiece()); Assert.assertFalse(message.hasDefaultCord()); // Fields with defaults have their default values (duh). Assert.assertEquals(41, message.getDefaultInt32()); Assert.assertEquals(42, message.getDefaultInt64()); Assert.assertEquals(43, message.getDefaultUint32()); Assert.assertEquals(44, message.getDefaultUint64()); Assert.assertEquals(-45, message.getDefaultSint32()); Assert.assertEquals(46, message.getDefaultSint64()); Assert.assertEquals(47, message.getDefaultFixed32()); Assert.assertEquals(48, message.getDefaultFixed64()); Assert.assertEquals(49, message.getDefaultSfixed32()); Assert.assertEquals(-50, message.getDefaultSfixed64()); Assert.assertEquals(51.5, message.getDefaultFloat(), 0.0); Assert.assertEquals(52e3, message.getDefaultDouble(), 0.0); Assert.assertEquals(true, message.getDefaultBool()); Assert.assertEquals("hello", message.getDefaultString()); Assert.assertEquals(toBytes("world"), message.getDefaultBytes()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum()); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getDefaultForeignEnum()); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getDefaultImportEnum()); Assert.assertEquals("abc", message.getDefaultStringPiece()); Assert.assertEquals("123", message.getDefaultCord()); Assert.assertFalse(message.hasOneofUint32()); Assert.assertFalse(message.hasOneofNestedMessage()); Assert.assertFalse(message.hasOneofString()); Assert.assertFalse(message.hasOneofBytes()); }
Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared, and that getting the fields returns their default values.
TestUtil::assertClear
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void assertRepeatedFieldsModified(TestAllTypesOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. Assert.assertEquals(2, message.getRepeatedInt32Count()); Assert.assertEquals(2, message.getRepeatedInt64Count()); Assert.assertEquals(2, message.getRepeatedUint32Count()); Assert.assertEquals(2, message.getRepeatedUint64Count()); Assert.assertEquals(2, message.getRepeatedSint32Count()); Assert.assertEquals(2, message.getRepeatedSint64Count()); Assert.assertEquals(2, message.getRepeatedFixed32Count()); Assert.assertEquals(2, message.getRepeatedFixed64Count()); Assert.assertEquals(2, message.getRepeatedSfixed32Count()); Assert.assertEquals(2, message.getRepeatedSfixed64Count()); Assert.assertEquals(2, message.getRepeatedFloatCount()); Assert.assertEquals(2, message.getRepeatedDoubleCount()); Assert.assertEquals(2, message.getRepeatedBoolCount()); Assert.assertEquals(2, message.getRepeatedStringCount()); Assert.assertEquals(2, message.getRepeatedBytesCount()); Assert.assertEquals(2, message.getRepeatedGroupCount()); Assert.assertEquals(2, message.getRepeatedNestedMessageCount()); Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); Assert.assertEquals(2, message.getRepeatedImportMessageCount()); Assert.assertEquals(2, message.getRepeatedLazyMessageCount()); Assert.assertEquals(2, message.getRepeatedNestedEnumCount()); Assert.assertEquals(2, message.getRepeatedForeignEnumCount()); Assert.assertEquals(2, message.getRepeatedImportEnumCount()); Assert.assertEquals(2, message.getRepeatedStringPieceCount()); Assert.assertEquals(2, message.getRepeatedCordCount()); Assert.assertEquals(201, message.getRepeatedInt32(0)); Assert.assertEquals(202L, message.getRepeatedInt64(0)); Assert.assertEquals(203, message.getRepeatedUint32(0)); Assert.assertEquals(204L, message.getRepeatedUint64(0)); Assert.assertEquals(205, message.getRepeatedSint32(0)); Assert.assertEquals(206L, message.getRepeatedSint64(0)); Assert.assertEquals(207, message.getRepeatedFixed32(0)); Assert.assertEquals(208L, message.getRepeatedFixed64(0)); Assert.assertEquals(209, message.getRepeatedSfixed32(0)); Assert.assertEquals(210L, message.getRepeatedSfixed64(0)); Assert.assertEquals(211F, message.getRepeatedFloat(0)); Assert.assertEquals(212D, message.getRepeatedDouble(0)); Assert.assertEquals(true, message.getRepeatedBool(0)); Assert.assertEquals("215", message.getRepeatedString(0)); Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); Assert.assertEquals(217, message.getRepeatedGroup(0).getA()); Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb()); Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD()); Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); Assert.assertEquals("224", message.getRepeatedStringPiece(0)); Assert.assertEquals("225", message.getRepeatedCord(0)); // Actually verify the second (modified) elements now. Assert.assertEquals(501, message.getRepeatedInt32(1)); Assert.assertEquals(502L, message.getRepeatedInt64(1)); Assert.assertEquals(503, message.getRepeatedUint32(1)); Assert.assertEquals(504L, message.getRepeatedUint64(1)); Assert.assertEquals(505, message.getRepeatedSint32(1)); Assert.assertEquals(506L, message.getRepeatedSint64(1)); Assert.assertEquals(507, message.getRepeatedFixed32(1)); Assert.assertEquals(508L, message.getRepeatedFixed64(1)); Assert.assertEquals(509, message.getRepeatedSfixed32(1)); Assert.assertEquals(510L, message.getRepeatedSfixed64(1)); Assert.assertEquals(511F, message.getRepeatedFloat(1)); Assert.assertEquals(512D, message.getRepeatedDouble(1)); Assert.assertEquals(true, message.getRepeatedBool(1)); Assert.assertEquals("515", message.getRepeatedString(1)); Assert.assertEquals(toBytes("516"), message.getRepeatedBytes(1)); Assert.assertEquals(517, message.getRepeatedGroup(1).getA()); Assert.assertEquals(518, message.getRepeatedNestedMessage(1).getBb()); Assert.assertEquals(519, message.getRepeatedForeignMessage(1).getC()); Assert.assertEquals(520, message.getRepeatedImportMessage(1).getD()); Assert.assertEquals(527, message.getRepeatedLazyMessage(1).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum(1)); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getRepeatedForeignEnum(1)); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getRepeatedImportEnum(1)); Assert.assertEquals("524", message.getRepeatedStringPiece(1)); Assert.assertEquals("525", message.getRepeatedCord(1)); }
Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the values assigned by {@code setAllFields} followed by {@code modifyRepeatedFields}.
TestUtil::assertRepeatedFieldsModified
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void setPackedFields(TestPackedTypes.Builder message) { message.addPackedInt32(601); message.addPackedInt64(602); message.addPackedUint32(603); message.addPackedUint64(604); message.addPackedSint32(605); message.addPackedSint64(606); message.addPackedFixed32(607); message.addPackedFixed64(608); message.addPackedSfixed32(609); message.addPackedSfixed64(610); message.addPackedFloat(611); message.addPackedDouble(612); message.addPackedBool(true); message.addPackedEnum(ForeignEnum.FOREIGN_BAR); // Add a second one of each field. message.addPackedInt32(701); message.addPackedInt64(702); message.addPackedUint32(703); message.addPackedUint64(704); message.addPackedSint32(705); message.addPackedSint64(706); message.addPackedFixed32(707); message.addPackedFixed64(708); message.addPackedSfixed32(709); message.addPackedSfixed64(710); message.addPackedFloat(711); message.addPackedDouble(712); message.addPackedBool(false); message.addPackedEnum(ForeignEnum.FOREIGN_BAZ); }
Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the values assigned by {@code setAllFields} followed by {@code modifyRepeatedFields}. public static void assertRepeatedFieldsModified(TestAllTypesOrBuilder message) { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. Assert.assertEquals(2, message.getRepeatedInt32Count()); Assert.assertEquals(2, message.getRepeatedInt64Count()); Assert.assertEquals(2, message.getRepeatedUint32Count()); Assert.assertEquals(2, message.getRepeatedUint64Count()); Assert.assertEquals(2, message.getRepeatedSint32Count()); Assert.assertEquals(2, message.getRepeatedSint64Count()); Assert.assertEquals(2, message.getRepeatedFixed32Count()); Assert.assertEquals(2, message.getRepeatedFixed64Count()); Assert.assertEquals(2, message.getRepeatedSfixed32Count()); Assert.assertEquals(2, message.getRepeatedSfixed64Count()); Assert.assertEquals(2, message.getRepeatedFloatCount()); Assert.assertEquals(2, message.getRepeatedDoubleCount()); Assert.assertEquals(2, message.getRepeatedBoolCount()); Assert.assertEquals(2, message.getRepeatedStringCount()); Assert.assertEquals(2, message.getRepeatedBytesCount()); Assert.assertEquals(2, message.getRepeatedGroupCount()); Assert.assertEquals(2, message.getRepeatedNestedMessageCount()); Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); Assert.assertEquals(2, message.getRepeatedImportMessageCount()); Assert.assertEquals(2, message.getRepeatedLazyMessageCount()); Assert.assertEquals(2, message.getRepeatedNestedEnumCount()); Assert.assertEquals(2, message.getRepeatedForeignEnumCount()); Assert.assertEquals(2, message.getRepeatedImportEnumCount()); Assert.assertEquals(2, message.getRepeatedStringPieceCount()); Assert.assertEquals(2, message.getRepeatedCordCount()); Assert.assertEquals(201, message.getRepeatedInt32(0)); Assert.assertEquals(202L, message.getRepeatedInt64(0)); Assert.assertEquals(203, message.getRepeatedUint32(0)); Assert.assertEquals(204L, message.getRepeatedUint64(0)); Assert.assertEquals(205, message.getRepeatedSint32(0)); Assert.assertEquals(206L, message.getRepeatedSint64(0)); Assert.assertEquals(207, message.getRepeatedFixed32(0)); Assert.assertEquals(208L, message.getRepeatedFixed64(0)); Assert.assertEquals(209, message.getRepeatedSfixed32(0)); Assert.assertEquals(210L, message.getRepeatedSfixed64(0)); Assert.assertEquals(211F, message.getRepeatedFloat(0)); Assert.assertEquals(212D, message.getRepeatedDouble(0)); Assert.assertEquals(true, message.getRepeatedBool(0)); Assert.assertEquals("215", message.getRepeatedString(0)); Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); Assert.assertEquals(217, message.getRepeatedGroup(0).getA()); Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb()); Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD()); Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0)); Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); Assert.assertEquals("224", message.getRepeatedStringPiece(0)); Assert.assertEquals("225", message.getRepeatedCord(0)); // Actually verify the second (modified) elements now. Assert.assertEquals(501, message.getRepeatedInt32(1)); Assert.assertEquals(502L, message.getRepeatedInt64(1)); Assert.assertEquals(503, message.getRepeatedUint32(1)); Assert.assertEquals(504L, message.getRepeatedUint64(1)); Assert.assertEquals(505, message.getRepeatedSint32(1)); Assert.assertEquals(506L, message.getRepeatedSint64(1)); Assert.assertEquals(507, message.getRepeatedFixed32(1)); Assert.assertEquals(508L, message.getRepeatedFixed64(1)); Assert.assertEquals(509, message.getRepeatedSfixed32(1)); Assert.assertEquals(510L, message.getRepeatedSfixed64(1)); Assert.assertEquals(511F, message.getRepeatedFloat(1)); Assert.assertEquals(512D, message.getRepeatedDouble(1)); Assert.assertEquals(true, message.getRepeatedBool(1)); Assert.assertEquals("515", message.getRepeatedString(1)); Assert.assertEquals(toBytes("516"), message.getRepeatedBytes(1)); Assert.assertEquals(517, message.getRepeatedGroup(1).getA()); Assert.assertEquals(518, message.getRepeatedNestedMessage(1).getBb()); Assert.assertEquals(519, message.getRepeatedForeignMessage(1).getC()); Assert.assertEquals(520, message.getRepeatedImportMessage(1).getD()); Assert.assertEquals(527, message.getRepeatedLazyMessage(1).getBb()); Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum(1)); Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getRepeatedForeignEnum(1)); Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getRepeatedImportEnum(1)); Assert.assertEquals("524", message.getRepeatedStringPiece(1)); Assert.assertEquals("525", message.getRepeatedCord(1)); } /** Set every field of {@code message} to a unique value.
TestUtil::setPackedFields
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0
public static void setUnpackedFields(TestUnpackedTypes.Builder message) { message.addUnpackedInt32(601); message.addUnpackedInt64(602); message.addUnpackedUint32(603); message.addUnpackedUint64(604); message.addUnpackedSint32(605); message.addUnpackedSint64(606); message.addUnpackedFixed32(607); message.addUnpackedFixed64(608); message.addUnpackedSfixed32(609); message.addUnpackedSfixed64(610); message.addUnpackedFloat(611); message.addUnpackedDouble(612); message.addUnpackedBool(true); message.addUnpackedEnum(ForeignEnum.FOREIGN_BAR); // Add a second one of each field. message.addUnpackedInt32(701); message.addUnpackedInt64(702); message.addUnpackedUint32(703); message.addUnpackedUint64(704); message.addUnpackedSint32(705); message.addUnpackedSint64(706); message.addUnpackedFixed32(707); message.addUnpackedFixed64(708); message.addUnpackedSfixed32(709); message.addUnpackedSfixed64(710); message.addUnpackedFloat(711); message.addUnpackedDouble(712); message.addUnpackedBool(false); message.addUnpackedEnum(ForeignEnum.FOREIGN_BAZ); }
Set every field of {@code message} to a unique value. Must correspond with the values applied by {@code setPackedFields}.
TestUtil::setUnpackedFields
java
google/j2objc
protobuf/tests/com/google/protobuf/TestUtil.java
https://github.com/google/j2objc/blob/master/protobuf/tests/com/google/protobuf/TestUtil.java
Apache-2.0