Fix build. Apply rules to some classes of teavm-classlib

This commit is contained in:
Alexey Andreev 2015-07-23 15:31:49 +03:00
parent 4548705620
commit bda49b95bd
161 changed files with 2296 additions and 2022 deletions

View File

@ -13,14 +13,13 @@
<module name="EmptyBlock"> <module name="EmptyBlock">
<property name="tokens" value="LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_IF, <property name="tokens" value="LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_IF,
LITERAL_FOR, LITERAL_TRY, LITERAL_WHILE, STATIC_INIT"/> LITERAL_FOR, LITERAL_TRY, LITERAL_WHILE, STATIC_INIT"/>
<property name="option" value="text"/>
</module> </module>
<module name="LeftCurly"/> <module name="LeftCurly"/>
<module name="NeedBraces"/> <module name="NeedBraces"/>
<module name="RightCurly"/> <module name="RightCurly"/>
<module name="FinalClass"/>
<module name="InterfaceIsType"/> <module name="InterfaceIsType"/>
<module name="HideUtilityClassConstructor"/> <module name="HideUtilityClassConstructor"/>
<module name="MutableException"/>
<module name="EmptyStatement"/> <module name="EmptyStatement"/>
<module name="EqualsHashCode"/> <module name="EqualsHashCode"/>
<module name="InnerAssignment"/> <module name="InnerAssignment"/>
@ -49,7 +48,9 @@
<module name="LocalFinalVariableName"/> <module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/> <module name="LocalVariableName"/>
<module name="MemberName"/> <module name="MemberName"/>
<module name="MethodName"/> <module name="MethodName">
<property name="format" value="^(([A-Z][A-Z0-9]+)|([a-z][a-z0-9]*))([A-Z][a-z0-9]*)*"/>
</module>
<module name="MethodTypeParameterName"/> <module name="MethodTypeParameterName"/>
<module name="PackageName"/> <module name="PackageName"/>
<module name="ParameterName"/> <module name="ParameterName"/>

View File

@ -1,5 +1,5 @@
/\* /\*
\* Copyright 2[0-9]{3} .+ \* Copyright 2[0-9]{3}(\-2[0-9]{3})? .+
\* \*
\* Licensed under the Apache License, Version 2.0 \(the "License"\); \* Licensed under the Apache License, Version 2.0 \(the "License"\);
\* you may not use this file except in compliance with the License. \* you may not use this file except in compliance with the License.

14
pom.xml
View File

@ -123,27 +123,27 @@
<dependency> <dependency>
<groupId>org.ow2.asm</groupId> <groupId>org.ow2.asm</groupId>
<artifactId>asm-debug-all</artifactId> <artifactId>asm-debug-all</artifactId>
<version>5.0.3</version> <version>5.0.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven</groupId> <groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId> <artifactId>maven-plugin-api</artifactId>
<version>3.0</version> <version>3.3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven.plugin-tools</groupId> <groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId> <artifactId>maven-plugin-annotations</artifactId>
<version>3.0</version> <version>3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven</groupId> <groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId> <artifactId>maven-core</artifactId>
<version>3.0</version> <version>3.3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.maven</groupId> <groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId> <artifactId>maven-artifact</artifactId>
<version>3.0</version> <version>3.3.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.websocket</groupId> <groupId>javax.websocket</groupId>
@ -165,11 +165,13 @@
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version> <version>${slf4j.version}</version>
</dependency> </dependency>
<!--
<dependency> <dependency>
<groupId>org.checkerframework</groupId> <groupId>org.checkerframework</groupId>
<artifactId>checker</artifactId> <artifactId>checker</artifactId>
<version>${checker.version}</version> <version>${checker.version}</version>
</dependency> </dependency>
-->
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
@ -225,7 +227,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
<version>2.11</version> <version>2.15</version>
<executions> <executions>
<execution> <execution>
<id>validate</id> <id>validate</id>

View File

@ -78,6 +78,15 @@
<build> <build>
<plugins> <plugins>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>../checkstyle.xml</configLocation>
</configuration>
</plugin>
-->
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>

View File

@ -28,7 +28,10 @@ package org.teavm.classlib.impl;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class Base46 { public final class Base46 {
private Base46() {
}
public static void encodeUnsigned(StringBuilder sb, int number) { public static void encodeUnsigned(StringBuilder sb, int number) {
boolean hasMore; boolean hasMore;
do { do {
@ -47,7 +50,7 @@ public class Base46 {
public static void encodeUnsigned(StringBuilder sb, long number) { public static void encodeUnsigned(StringBuilder sb, long number) {
boolean hasMore; boolean hasMore;
do { do {
int digit = (int)(number % 46); int digit = (int) (number % 46);
number /= 46; number /= 46;
hasMore = number > 0; hasMore = number > 0;
digit = digit * 2 + (hasMore ? 1 : 0); digit = digit * 2 + (hasMore ? 1 : 0);
@ -105,11 +108,11 @@ public class Base46 {
public static char encodeDigit(int digit) { public static char encodeDigit(int digit) {
if (digit < 2) { if (digit < 2) {
return (char)(digit + ' '); return (char) (digit + ' ');
} else if (digit < 59) { } else if (digit < 59) {
return (char)(digit + 1 + ' '); return (char) (digit + 1 + ' ');
} else { } else {
return (char)(digit + 2 + ' '); return (char) (digit + 2 + ' ');
} }
} }

View File

@ -76,8 +76,8 @@ public class CountriesGenerator implements MetadataGenerator {
while (index < row.length()) { while (index < row.length()) {
next = row.indexOf('"', index); next = row.indexOf('"', index);
if (next == -1) { if (next == -1) {
throw new IllegalStateException("Syntax error at row " + rowIndex + throw new IllegalStateException("Syntax error at row " + rowIndex
": closing quote not found"); + ": closing quote not found");
} }
if (next + 1 == row.length() || row.charAt(next + 1) != '"') { if (next + 1 == row.length() || row.charAt(next + 1) != '"') {
sb.append(row.substring(index, next)); sb.append(row.substring(index, next));
@ -87,8 +87,8 @@ public class CountriesGenerator implements MetadataGenerator {
index = next + 2; index = next + 2;
} }
if (index < row.length() && row.charAt(index) != ',') { if (index < row.length() && row.charAt(index) != ',') {
throw new IllegalStateException("Syntax error at row " + rowIndex + ": closing quote must be " + throw new IllegalStateException("Syntax error at row " + rowIndex + ": closing quote must be "
"followed by either line separator or comma"); + "followed by either line separator or comma");
} }
values.add(sb.toString()); values.add(sb.toString());
} else { } else {

View File

@ -101,7 +101,7 @@ public class CurrenciesGenerator implements MetadataGenerator {
} }
@Override @Override
public Element next() { public Element next() {
Element result = (Element)nodes.item(index); Element result = (Element) nodes.item(index);
following(); following();
return result; return result;
} }
@ -129,11 +129,11 @@ public class CurrenciesGenerator implements MetadataGenerator {
switch (child.getNodeType()) { switch (child.getNodeType()) {
case Node.TEXT_NODE: case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE: case Node.CDATA_SECTION_NODE:
CharacterData cdata = (CharacterData)child; CharacterData cdata = (CharacterData) child;
sb.append(cdata.getData()); sb.append(cdata.getData());
break; break;
case Node.ENTITY_REFERENCE_NODE: case Node.ENTITY_REFERENCE_NODE:
EntityReference ref = (EntityReference)child; EntityReference ref = (EntityReference) child;
sb.append(ref.getNodeValue()); sb.append(ref.getNodeValue());
break; break;
} }

View File

@ -25,6 +25,9 @@ import org.teavm.platform.metadata.StringResource;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public final class CurrencyHelper { public final class CurrencyHelper {
private CurrencyHelper() {
}
@MetadataProvider(CurrenciesGenerator.class) @MetadataProvider(CurrenciesGenerator.class)
public static native ResourceArray<CurrencyResource> getCurrencies(); public static native ResourceArray<CurrencyResource> getCurrencies();

View File

@ -100,8 +100,8 @@ class JCLComparisonVisitor extends ClassVisitor {
if ((access & Opcodes.ACC_ABSTRACT) == 0 && method.hasModifier(ElementModifier.ABSTRACT)) { if ((access & Opcodes.ACC_ABSTRACT) == 0 && method.hasModifier(ElementModifier.ABSTRACT)) {
item.status = JCLStatus.MISSING; item.status = JCLStatus.MISSING;
} else { } else {
item.status = method.getOwnerName().equals(classReader.getName()) ? item.status = method.getOwnerName().equals(classReader.getName())
JCLStatus.FOUND : JCLStatus.PARTIAL; ? JCLStatus.FOUND : JCLStatus.PARTIAL;
} }
} }
item.visibility = (access & Opcodes.ACC_PROTECTED) != 0 ? JCLVisibility.PROTECTED : JCLVisibility.PUBLIC; item.visibility = (access & Opcodes.ACC_PROTECTED) != 0 ? JCLVisibility.PROTECTED : JCLVisibility.PUBLIC;

View File

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -25,7 +25,7 @@ package org.teavm.classlib.impl.tz;
* @author Brian S O'Neill * @author Brian S O'Neill
* @since 1.0 * @since 1.0
*/ */
public class CachedDateTimeZone extends StorableDateTimeZone { public final class CachedDateTimeZone extends StorableDateTimeZone {
private static final int cInfoCacheMask; private static final int cInfoCacheMask;
@ -38,7 +38,7 @@ public class CachedDateTimeZone extends StorableDateTimeZone {
*/ */
public static CachedDateTimeZone forZone(StorableDateTimeZone zone) { public static CachedDateTimeZone forZone(StorableDateTimeZone zone) {
if (zone instanceof CachedDateTimeZone) { if (zone instanceof CachedDateTimeZone) {
return (CachedDateTimeZone)zone; return (CachedDateTimeZone) zone;
} }
return new CachedDateTimeZone(zone); return new CachedDateTimeZone(zone);
} }
@ -101,11 +101,11 @@ public class CachedDateTimeZone extends StorableDateTimeZone {
// synchronized. // synchronized.
private Info getInfo(long millis) { private Info getInfo(long millis) {
int period = (int)(millis >> 32); int period = (int) (millis >> 32);
Info[] cache = iInfoCache; Info[] cache = iInfoCache;
int index = period & cInfoCacheMask; int index = period & cInfoCacheMask;
Info info = cache[index]; Info info = cache[index];
if (info == null || (int)((info.iPeriodStart >> 32)) != period) { if (info == null || (int) ((info.iPeriodStart >> 32)) != period) {
info = createInfo(millis); info = createInfo(millis);
cache[index] = info; cache[index] = info;
} }
@ -124,7 +124,8 @@ public class CachedDateTimeZone extends StorableDateTimeZone {
break; break;
} }
periodStart = next; periodStart = next;
chain = (chain.iNextInfo = new Info(iZone, periodStart)); chain.iNextInfo = new Info(iZone, periodStart);
chain = chain.iNextInfo;
} }
return info; return info;

View File

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -99,17 +99,10 @@ public class DateTimeZoneBuilder {
* dayOfWeek when true, retreat when false. * dayOfWeek when true, retreat when false.
* @param millisOfDay additional precision for specifying time of day of cutover * @param millisOfDay additional precision for specifying time of day of cutover
*/ */
public DateTimeZoneBuilder addCutover(int year, public DateTimeZoneBuilder addCutover(int year, char mode, int monthOfYear, int dayOfMonth, int dayOfWeek,
char mode, boolean advanceDayOfWeek, int millisOfDay) {
int monthOfYear,
int dayOfMonth,
int dayOfWeek,
boolean advanceDayOfWeek,
int millisOfDay)
{
if (iRuleSets.size() > 0) { if (iRuleSets.size() > 0) {
OfYear ofYear = new OfYear OfYear ofYear = new OfYear(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1); RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1);
lastRuleSet.setUpperLimit(year, ofYear); lastRuleSet.setUpperLimit(year, ofYear);
} }
@ -162,11 +155,9 @@ public class DateTimeZoneBuilder {
int dayOfMonth, int dayOfMonth,
int dayOfWeek, int dayOfWeek,
boolean advanceDayOfWeek, boolean advanceDayOfWeek,
int millisOfDay) int millisOfDay) {
{
if (fromYear <= toYear) { if (fromYear <= toYear) {
OfYear ofYear = new OfYear OfYear ofYear = new OfYear(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
Recurrence recurrence = new Recurrence(ofYear, saveMillis); Recurrence recurrence = new Recurrence(ofYear, saveMillis);
Rule rule = new Rule(recurrence, fromYear, toYear); Rule rule = new Rule(recurrence, fromYear, toYear);
getLastRuleSet().addRule(rule); getLastRuleSet().addRule(rule);
@ -204,7 +195,7 @@ public class DateTimeZoneBuilder {
int saveMillis = 0; int saveMillis = 0;
int ruleSetCount = iRuleSets.size(); int ruleSetCount = iRuleSets.size();
for (int i=0; i<ruleSetCount; i++) { for (int i = 0; i < ruleSetCount; i++) {
RuleSet rs = iRuleSets.get(i); RuleSet rs = iRuleSets.get(i);
Transition next = rs.firstTransition(millis); Transition next = rs.firstTransition(millis);
if (next == null) { if (next == null) {
@ -302,12 +293,7 @@ public class DateTimeZoneBuilder {
final boolean iAdvance; final boolean iAdvance;
final int iMillisOfDay; final int iMillisOfDay;
OfYear(char mode, OfYear(char mode, int monthOfYear, int dayOfMonth, int dayOfWeek, boolean advanceDayOfWeek, int millisOfDay) {
int monthOfYear,
int dayOfMonth,
int dayOfWeek, boolean advanceDayOfWeek,
int millisOfDay)
{
if (mode != 'u' && mode != 'w' && mode != 's') { if (mode != 'u' && mode != 'w' && mode != 's') {
throw new IllegalArgumentException("Unknown mode: " + mode); throw new IllegalArgumentException("Unknown mode: " + mode);
} }
@ -335,7 +321,7 @@ public class DateTimeZoneBuilder {
int dayOfMonth = Base46.decodeUnsigned(flow); int dayOfMonth = Base46.decodeUnsigned(flow);
int dayOfWeek = Base46.decode(flow); int dayOfWeek = Base46.decode(flow);
boolean advance = flow.characters[flow.pointer++] == 'y'; boolean advance = flow.characters[flow.pointer++] == 'y';
int millisOfDay = (int)StorableDateTimeZone.readUnsignedTime(flow); int millisOfDay = (int) StorableDateTimeZone.readUnsignedTime(flow);
return new OfYear(mode, monthOfYear, dayOfMonth, dayOfWeek, advance, millisOfDay); return new OfYear(mode, monthOfYear, dayOfMonth, dayOfWeek, advance, millisOfDay);
} }
@ -557,7 +543,7 @@ public class DateTimeZoneBuilder {
public static Recurrence read(CharFlow flow) { public static Recurrence read(CharFlow flow) {
OfYear ofYear = OfYear.read(flow); OfYear ofYear = OfYear.read(flow);
int saveMillis = (int)StorableDateTimeZone.readTime(flow); int saveMillis = (int) StorableDateTimeZone.readTime(flow);
return new Recurrence(ofYear, saveMillis); return new Recurrence(ofYear, saveMillis);
} }
} }
@ -678,8 +664,7 @@ public class DateTimeZoneBuilder {
if (other == null) { if (other == null) {
return true; return true;
} }
return iMillis > other.iMillis && return iMillis > other.iMillis && iWallOffset != other.iWallOffset;
iWallOffset != other.iWallOffset;
} }
} }
@ -886,8 +871,7 @@ public class DateTimeZoneBuilder {
if (iRules.size() == 2) { if (iRules.size() == 2) {
Rule startRule = iRules.get(0); Rule startRule = iRules.get(0);
Rule endRule = iRules.get(1); Rule endRule = iRules.get(1);
if (startRule.getToYear() == Integer.MAX_VALUE && if (startRule.getToYear() == Integer.MAX_VALUE && endRule.getToYear() == Integer.MAX_VALUE) {
endRule.getToYear() == Integer.MAX_VALUE) {
// With exactly two infinitely recurring rules left, a // With exactly two infinitely recurring rules left, a
// simple DSTZone can be formed. // simple DSTZone can be formed.
@ -937,11 +921,11 @@ public class DateTimeZoneBuilder {
Recurrence startRecurrence = iStartRecurrence; Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence; Recurrence endRecurrence = iEndRecurrence;
long start, end; long start;
long end;
try { try {
start = startRecurrence.next start = startRecurrence.next(instant, standardOffset, endRecurrence.getSaveMillis());
(instant, standardOffset, endRecurrence.getSaveMillis());
if (instant > 0 && start < 0) { if (instant > 0 && start < 0) {
// Overflowed. // Overflowed.
start = instant; start = instant;
@ -955,8 +939,7 @@ public class DateTimeZoneBuilder {
} }
try { try {
end = endRecurrence.next end = endRecurrence.next(instant, standardOffset, startRecurrence.getSaveMillis());
(instant, standardOffset, startRecurrence.getSaveMillis());
if (instant > 0 && end < 0) { if (instant > 0 && end < 0) {
// Overflowed. // Overflowed.
end = instant; end = instant;
@ -982,11 +965,11 @@ public class DateTimeZoneBuilder {
Recurrence startRecurrence = iStartRecurrence; Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence; Recurrence endRecurrence = iEndRecurrence;
long start, end; long start;
long end;
try { try {
start = startRecurrence.previous start = startRecurrence.previous(instant, standardOffset, endRecurrence.getSaveMillis());
(instant, standardOffset, endRecurrence.getSaveMillis());
if (instant < 0 && start > 0) { if (instant < 0 && start > 0) {
// Overflowed. // Overflowed.
start = instant; start = instant;
@ -1000,8 +983,7 @@ public class DateTimeZoneBuilder {
} }
try { try {
end = endRecurrence.previous end = endRecurrence.previous(instant, standardOffset, startRecurrence.getSaveMillis());
(instant, standardOffset, startRecurrence.getSaveMillis());
if (instant < 0 && end > 0) { if (instant < 0 && end > 0) {
// Overflowed. // Overflowed.
end = instant; end = instant;
@ -1022,11 +1004,11 @@ public class DateTimeZoneBuilder {
Recurrence startRecurrence = iStartRecurrence; Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence; Recurrence endRecurrence = iEndRecurrence;
long start, end; long start;
long end;
try { try {
start = startRecurrence.next start = startRecurrence.next(instant, standardOffset, endRecurrence.getSaveMillis());
(instant, standardOffset, endRecurrence.getSaveMillis());
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// Overflowed. // Overflowed.
start = instant; start = instant;
@ -1036,8 +1018,7 @@ public class DateTimeZoneBuilder {
} }
try { try {
end = endRecurrence.next end = endRecurrence.next(instant, standardOffset, startRecurrence.getSaveMillis());
(instant, standardOffset, startRecurrence.getSaveMillis());
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// Overflowed. // Overflowed.
end = instant; end = instant;
@ -1058,7 +1039,7 @@ public class DateTimeZoneBuilder {
} }
public static DSTZone readZone(String id, CharFlow flow) { public static DSTZone readZone(String id, CharFlow flow) {
int standardOffset = (int)readTime(flow); int standardOffset = (int) readTime(flow);
Recurrence startRecurrence = Recurrence.read(flow); Recurrence startRecurrence = Recurrence.read(flow);
Recurrence endRecurrence = Recurrence.read(flow); Recurrence endRecurrence = Recurrence.read(flow);
return new DSTZone(id, standardOffset, startRecurrence, endRecurrence); return new DSTZone(id, standardOffset, startRecurrence, endRecurrence);
@ -1075,7 +1056,7 @@ public class DateTimeZoneBuilder {
* @param tailZone optional zone for getting info beyond precalculated tables * @param tailZone optional zone for getting info beyond precalculated tables
*/ */
static PrecalculatedZone create(String id, boolean outputID, ArrayList<Transition> transitions, static PrecalculatedZone create(String id, boolean outputID, ArrayList<Transition> transitions,
DSTZone tailZone) { DSTZone tailZone) {
int size = transitions.size(); int size = transitions.size();
if (size == 0) { if (size == 0) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
@ -1086,7 +1067,7 @@ public class DateTimeZoneBuilder {
int[] standardOffsets = new int[size]; int[] standardOffsets = new int[size];
Transition last = null; Transition last = null;
for (int i=0; i<size; i++) { for (int i = 0; i < size; i++) {
Transition tr = transitions.get(i); Transition tr = transitions.get(i);
if (!tr.isTransitionFrom(last)) { if (!tr.isTransitionFrom(last)) {
@ -1100,8 +1081,7 @@ public class DateTimeZoneBuilder {
last = tr; last = tr;
} }
return new PrecalculatedZone return new PrecalculatedZone(outputID ? id : "", trans, wallOffsets, standardOffsets, tailZone);
((outputID ? id : ""), trans, wallOffsets, standardOffsets, tailZone);
} }
// All array fields have the same length. // All array fields have the same length.
@ -1116,9 +1096,8 @@ public class DateTimeZoneBuilder {
/** /**
* Constructor used ONLY for valid input, loaded via static methods. * Constructor used ONLY for valid input, loaded via static methods.
*/ */
private PrecalculatedZone(String id, long[] transitions, int[] wallOffsets, private PrecalculatedZone(String id, long[] transitions, int[] wallOffsets, int[] standardOffsets,
int[] standardOffsets, DSTZone tailZone) DSTZone tailZone) {
{
super(id); super(id);
iTransitions = transitions; iTransitions = transitions;
iWallOffsets = wallOffsets; iWallOffsets = wallOffsets;
@ -1293,7 +1272,7 @@ public class DateTimeZoneBuilder {
double distances = 0; double distances = 0;
int count = 0; int count = 0;
for (int i=1; i<transitions.length; i++) { for (int i = 1; i < transitions.length; i++) {
long diff = transitions[i] - transitions[i - 1]; long diff = transitions[i] - transitions[i - 1];
if (diff < ((366L + 365) * 24 * 60 * 60 * 1000)) { if (diff < ((366L + 365) * 24 * 60 * 60 * 1000)) {
distances += diff; distances += diff;

View File

@ -33,9 +33,12 @@ import org.teavm.platform.metadata.ResourceMap;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class DateTimeZoneProvider { public final class DateTimeZoneProvider {
private static Map<String, DateTimeZone> cache = new HashMap<>(); private static Map<String, DateTimeZone> cache = new HashMap<>();
private DateTimeZoneProvider() {
}
public static DateTimeZone getTimeZone(String id) { public static DateTimeZone getTimeZone(String id) {
if (!cache.containsKey(id)) { if (!cache.containsKey(id)) {
cache.put(id, createTimeZone(id)); cache.put(id, createTimeZone(id));
@ -142,7 +145,7 @@ public class DateTimeZoneProvider {
Score score = scoreTable.get(i); Score score = scoreTable.get(i);
int tzOffset = score.tz.getOffset(time) / 60_000; int tzOffset = score.tz.getOffset(time) / 60_000;
if (tzOffset != offset) { if (tzOffset != offset) {
score.value += (int)((last - time) / 60_000) * (Math.abs(tzOffset - offset)) / 30; score.value += (int) ((last - time) / 60_000) * (Math.abs(tzOffset - offset)) / 30;
} }
int j = i + 1; int j = i + 1;
while (j < scoreTable.size() && score.value > scoreTable.get(j).value) { while (j < scoreTable.size() && score.value > scoreTable.get(j).value) {

View File

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -74,8 +74,8 @@ public final class FixedDateTimeZone extends StorableDateTimeZone {
} }
public static FixedDateTimeZone readZone(String id, CharFlow flow) { public static FixedDateTimeZone readZone(String id, CharFlow flow) {
int wallOffset = (int)readTime(flow); int wallOffset = (int) readTime(flow);
int standardOffset = (int)readTime(flow); int standardOffset = (int) readTime(flow);
return new FixedDateTimeZone(id, wallOffset, standardOffset); return new FixedDateTimeZone(id, wallOffset, standardOffset);
} }
} }

View File

@ -38,9 +38,9 @@ public abstract class StorableDateTimeZone extends DateTimeZone {
public static void writeTime(StringBuilder sb, long time) { public static void writeTime(StringBuilder sb, long time) {
if (time % 1800_000 == 0) { if (time % 1800_000 == 0) {
Base46.encode(sb, (int)((time / 1800_000) << 1)); Base46.encode(sb, (int) ((time / 1800_000) << 1));
} else { } else {
Base46.encode(sb, (int)(((time / 60_000) << 1) | 1)); Base46.encode(sb, (int) (((time / 60_000) << 1) | 1));
} }
} }
@ -55,9 +55,9 @@ public abstract class StorableDateTimeZone extends DateTimeZone {
public static void writeUnsignedTime(StringBuilder sb, long time) { public static void writeUnsignedTime(StringBuilder sb, long time) {
if (time % 1800_000 == 0) { if (time % 1800_000 == 0) {
Base46.encodeUnsigned(sb, (int)((time / 1800_000) << 1)); Base46.encodeUnsigned(sb, (int) ((time / 1800_000) << 1));
} else { } else {
Base46.encodeUnsigned(sb, (int)(((time / 60_000) << 1) | 1)); Base46.encodeUnsigned(sb, (int) (((time / 60_000) << 1) | 1));
} }
} }
@ -105,14 +105,14 @@ public abstract class StorableDateTimeZone extends DateTimeZone {
while (index < array.length) { while (index < array.length) {
int count = Base46.decode(flow); int count = Base46.decode(flow);
if (count >= 0) { if (count >= 0) {
int t = (int)readTime(flow); int t = (int) readTime(flow);
while (count-- > 0) { while (count-- > 0) {
array[index++] = t; array[index++] = t;
} }
} else { } else {
count = ~count; count = ~count;
while (count-- > 0) { while (count-- > 0) {
array[index++] = (int)readTime(flow); array[index++] = (int) readTime(flow);
} }
} }
} }

View File

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -106,7 +106,7 @@ public class ZoneInfoCompiler {
if (newPos == ~pos) { if (newPos == ~pos) {
throw new IllegalArgumentException(str); throw new IllegalArgumentException(str);
} }
int millis = (int)mdt.getMillis(); int millis = (int) mdt.getMillis();
if (pos == 1) { if (pos == 1) {
millis = -millis; millis = -millis;
} }
@ -156,12 +156,10 @@ public class ZoneInfoCompiler {
if (offset == nextOffset) { if (offset == nextOffset) {
System.out.println("*d* Error in " + tz.getID() + " " System.out.println("*d* Error in " + tz.getID() + " "
+ new DateTime(millis, + new DateTime(millis, ISOChronology.getInstanceUTC()));
ISOChronology.getInstanceUTC()));
return false; return false;
} }
transitions.add(Long.valueOf(millis)); transitions.add(Long.valueOf(millis));
offset = nextOffset; offset = nextOffset;
@ -172,7 +170,7 @@ public class ZoneInfoCompiler {
millis = ISOChronology.getInstanceUTC().year().set(0, 2050); millis = ISOChronology.getInstanceUTC().year().set(0, 2050);
end = ISOChronology.getInstanceUTC().year().set(0, 1850); end = ISOChronology.getInstanceUTC().year().set(0, 1850);
for (int i=transitions.size(); --i>= 0; ) { for (int i = transitions.size(); --i >= 0;) {
long prev = tz.previousTransition(millis); long prev = tz.previousTransition(millis);
if (prev == millis || prev < end) { if (prev == millis || prev < end) {
break; break;
@ -184,10 +182,8 @@ public class ZoneInfoCompiler {
if (trans - 1 != millis) { if (trans - 1 != millis) {
System.out.println("*r* Error in " + tz.getID() + " " System.out.println("*r* Error in " + tz.getID() + " "
+ new DateTime(millis, + new DateTime(millis, ISOChronology.getInstanceUTC()) + " != "
ISOChronology.getInstanceUTC()) + " != " + new DateTime(trans - 1, ISOChronology.getInstanceUTC()));
+ new DateTime(trans - 1,
ISOChronology.getInstanceUTC()));
return false; return false;
} }
@ -237,8 +233,8 @@ public class ZoneInfoCompiler {
String alias = iGoodLinks.get(i + 1); String alias = iGoodLinks.get(i + 1);
Zone sourceZone = sourceMap.get(baseId); Zone sourceZone = sourceMap.get(baseId);
if (sourceZone == null) { if (sourceZone == null) {
/*throw new RuntimeException("Cannot find source zone '" + baseId + "' to link alias '" + throw new RuntimeException("Cannot find source zone '" + baseId + "' to link alias '"
alias + "' to");*/ + alias + "' to");
} else { } else {
DateTimeZoneBuilder builder = new DateTimeZoneBuilder(); DateTimeZoneBuilder builder = new DateTimeZoneBuilder();
sourceZone.addToBuilder(builder, iRuleSets); sourceZone.addToBuilder(builder, iRuleSets);
@ -257,10 +253,10 @@ public class ZoneInfoCompiler {
String alias = iBackLinks.get(i + 1); String alias = iBackLinks.get(i + 1);
StorableDateTimeZone tz = map.get(id); StorableDateTimeZone tz = map.get(id);
if (tz == null) { if (tz == null) {
/*if (pass > 0) { if (pass > 0) {
throw new RuntimeException("Cannot find time zone '" + id + "' to link alias '" + throw new RuntimeException("Cannot find time zone '" + id + "' to link alias '"
alias + "' to"); + alias + "' to");
}*/ }
} else { } else {
map.put(alias, new AliasDateTimeZone(alias, tz)); map.put(alias, new AliasDateTimeZone(alias, tz));
} }
@ -404,10 +400,9 @@ public class ZoneInfoCompiler {
if (month == 12 && day == 31) { if (month == 12 && day == 31) {
millis = parseTime("23:59:59.999"); millis = parseTime("23:59:59.999");
} else { } else {
LocalDate date = (day == -1 ? LocalDate date = day == -1 ? new LocalDate(2001, month, 1).plusMonths(1)
new LocalDate(2001, month, 1).plusMonths(1) : : new LocalDate(2001, month, day).plusDays(1);
new LocalDate(2001, month, day).plusDays(1)); advance = day != -1 && dayOfWeek != 0;
advance = (day != -1 && dayOfWeek != 0);
month = date.getMonthOfYear(); month = date.getMonthOfYear();
day = date.getDayOfMonth(); day = date.getDayOfMonth();
if (dayOfWeek != 0) { if (dayOfWeek != 0) {
@ -459,13 +454,9 @@ public class ZoneInfoCompiler {
@Override @Override
public String toString() { public String toString() {
return return "MonthOfYear: " + iMonthOfYear + "\n" + "DayOfMonth: " + iDayOfMonth + "\n" + "DayOfWeek: "
"MonthOfYear: " + iMonthOfYear + "\n" + + iDayOfWeek + "\n" + "AdvanceDayOfWeek: " + iAdvanceDayOfWeek + "\n" + "MillisOfDay: "
"DayOfMonth: " + iDayOfMonth + "\n" + + iMillisOfDay + "\n" + "ZoneChar: " + iZoneChar + "\n";
"DayOfWeek: " + iDayOfWeek + "\n" +
"AdvanceDayOfWeek: " + iAdvanceDayOfWeek + "\n" +
"MillisOfDay: " + iMillisOfDay + "\n" +
"ZoneChar: " + iZoneChar + "\n";
} }
} }
@ -500,15 +491,9 @@ public class ZoneInfoCompiler {
@Override @Override
public String toString() { public String toString() {
return return "[Rule]\n" + "Name: " + iName + "\n" + "FromYear: " + iFromYear + "\n" + "ToYear: " + iToYear + "\n"
"[Rule]\n" + + "Type: " + iType + "\n" + iDateTimeOfYear + "SaveMillis: " + iSaveMillis + "\n" + "LetterS: "
"Name: " + iName + "\n" + + iLetterS + "\n";
"FromYear: " + iFromYear + "\n" +
"ToYear: " + iToYear + "\n" +
"Type: " + iType + "\n" +
iDateTimeOfYear +
"SaveMillis: " + iSaveMillis + "\n" +
"LetterS: " + iLetterS + "\n";
} }
} }
@ -531,7 +516,7 @@ public class ZoneInfoCompiler {
* Adds recurring savings rules to the builder. * Adds recurring savings rules to the builder.
*/ */
public void addRecurring(DateTimeZoneBuilder builder) { public void addRecurring(DateTimeZoneBuilder builder) {
for (int i=0; i<iRules.size(); i++) { for (int i = 0; i < iRules.size(); i++) {
Rule rule = iRules.get(i); Rule rule = iRules.get(i);
rule.addRecurring(builder); rule.addRecurring(builder);
} }
@ -595,10 +580,7 @@ public class ZoneInfoCompiler {
addToBuilder(this, builder, ruleSets); addToBuilder(this, builder, ruleSets);
} }
private static void addToBuilder(Zone zone, private static void addToBuilder(Zone zone, DateTimeZoneBuilder builder, Map<String, RuleSet> ruleSets) {
DateTimeZoneBuilder builder,
Map<String, RuleSet> ruleSets)
{
for (; zone != null; zone = zone.iNext) { for (; zone != null; zone = zone.iNext) {
builder.setStandardOffset(zone.iOffsetMillis); builder.setStandardOffset(zone.iOffsetMillis);
@ -609,12 +591,10 @@ public class ZoneInfoCompiler {
// Check if iRules actually just refers to a savings. // Check if iRules actually just refers to a savings.
int saveMillis = parseTime(zone.iRules); int saveMillis = parseTime(zone.iRules);
builder.setFixedSavings(zone.iFormat, saveMillis); builder.setFixedSavings(zone.iFormat, saveMillis);
} } catch (Exception e) {
catch (Exception e) {
RuleSet rs = ruleSets.get(zone.iRules); RuleSet rs = ruleSets.get(zone.iRules);
if (rs == null) { if (rs == null) {
throw new IllegalArgumentException throw new IllegalArgumentException("Rules not found: " + zone.iRules);
("Rules not found: " + zone.iRules);
} }
rs.addRecurring(builder); rs.addRecurring(builder);
} }
@ -630,14 +610,9 @@ public class ZoneInfoCompiler {
@Override @Override
public String toString() { public String toString() {
String str = String str = "[Zone]\n" + "Name: " + iName + "\n" + "OffsetMillis: " + iOffsetMillis + "\n" + "Rules: "
"[Zone]\n" + + iRules + "\n" + "Format: " + iFormat + "\n" + "UntilYear: " + iUntilYear + "\n"
"Name: " + iName + "\n" + + iUntilDateTimeOfYear;
"OffsetMillis: " + iOffsetMillis + "\n" +
"Rules: " + iRules + "\n" +
"Format: " + iFormat + "\n" +
"UntilYear: " + iUntilYear + "\n" +
iUntilDateTimeOfYear;
if (iNext == null) { if (iNext == null) {
return str; return str;

View File

@ -25,7 +25,7 @@ public class CLDRDecimalData {
int listSeparator; int listSeparator;
int perMille; int perMille;
int percent; int percent;
String NaN; String nan;
String infinity; String infinity;
int minusSign; int minusSign;
int monetaryDecimalSeparator; int monetaryDecimalSeparator;
@ -52,7 +52,7 @@ public class CLDRDecimalData {
} }
public String getNaN() { public String getNaN() {
return NaN; return nan;
} }
public String getInfinity() { public String getInfinity() {

View File

@ -23,7 +23,10 @@ import org.teavm.platform.metadata.*;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class CLDRHelper { public final class CLDRHelper {
private CLDRHelper() {
}
public static String getCode(String language, String country) { public static String getCode(String language, String country) {
return !country.isEmpty() ? language + "-" + country : language; return !country.isEmpty() ? language + "-" + country : language;
} }
@ -90,8 +93,9 @@ public class CLDRHelper {
private static String[] resolveDateFormatSymbols(ResourceMap<ResourceArray<StringResource>> map, String language, private static String[] resolveDateFormatSymbols(ResourceMap<ResourceArray<StringResource>> map, String language,
String country) { String country) {
String localeCode = getCode(language, country); String localeCode = getCode(language, country);
ResourceArray<StringResource> arrayRes = map.has(localeCode) ? map.get(localeCode) : ResourceArray<StringResource> arrayRes = map.has(localeCode)
map.has(language) ? map.get(language) : map.get("root"); ? map.get(localeCode)
: map.has(language) ? map.get(language) : map.get("root");
String[] result = new String[arrayRes.size()]; String[] result = new String[arrayRes.size()];
for (int i = 0; i < result.length; ++i) { for (int i = 0; i < result.length; ++i) {
result[i] = arrayRes.get(i).getValue(); result[i] = arrayRes.get(i).getValue();
@ -198,16 +202,16 @@ public class CLDRHelper {
private static String resolveFormatSymbols(ResourceMap<StringResource> map, String language, String country) { private static String resolveFormatSymbols(ResourceMap<StringResource> map, String language, String country) {
String localeCode = getCode(language, country); String localeCode = getCode(language, country);
StringResource res = map.has(localeCode) ? map.get(localeCode) : map.has(language) ? map.get(language) : StringResource res = map.has(localeCode) ? map.get(localeCode) : map.has(language) ? map.get(language)
map.get("root"); : map.get("root");
return res.getValue(); return res.getValue();
} }
public static DecimalData resolveDecimalData(String language, String country) { public static DecimalData resolveDecimalData(String language, String country) {
ResourceMap<DecimalData> map = getDecimalDataMap(); ResourceMap<DecimalData> map = getDecimalDataMap();
String localeCode = getCode(language, country); String localeCode = getCode(language, country);
return map.has(localeCode) ? map.get(localeCode) : map.has(language) ? map.get(language) : return map.has(localeCode) ? map.get(localeCode) : map.has(language) ? map.get(language)
map.get("root"); : map.get("root");
} }
@MetadataProvider(DecimalMetadataGenerator.class) @MetadataProvider(DecimalMetadataGenerator.class)

View File

@ -15,15 +15,23 @@
*/ */
package org.teavm.classlib.impl.unicode; package org.teavm.classlib.impl.unicode;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/** /**
* *
@ -115,7 +123,7 @@ public class CLDRReader {
readTimeZones(localeName, localeInfo, input); readTimeZones(localeName, localeInfo, input);
break; break;
case "ca-gregorian.json": { case "ca-gregorian.json": {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
readEras(localeName, localeInfo, root); readEras(localeName, localeInfo, root);
readAmPms(localeName, localeInfo, root); readAmPms(localeName, localeInfo, root);
readMonths(localeName, localeInfo, root); readMonths(localeName, localeInfo, root);
@ -141,7 +149,7 @@ public class CLDRReader {
} }
private void readLanguages(String localeCode, CLDRLocale locale, InputStream input) { private void readLanguages(String localeCode, CLDRLocale locale, InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject languagesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject() JsonObject languagesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject()
.get("localeDisplayNames").getAsJsonObject().get("languages").getAsJsonObject(); .get("localeDisplayNames").getAsJsonObject().get("languages").getAsJsonObject();
for (Map.Entry<String, JsonElement> property : languagesJson.entrySet()) { for (Map.Entry<String, JsonElement> property : languagesJson.entrySet()) {
@ -153,7 +161,7 @@ public class CLDRReader {
} }
private void readCountries(String localeCode, CLDRLocale locale, InputStream input) { private void readCountries(String localeCode, CLDRLocale locale, InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject countriesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject() JsonObject countriesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject()
.get("localeDisplayNames").getAsJsonObject().get("territories").getAsJsonObject(); .get("localeDisplayNames").getAsJsonObject().get("territories").getAsJsonObject();
for (Map.Entry<String, JsonElement> property : countriesJson.entrySet()) { for (Map.Entry<String, JsonElement> property : countriesJson.entrySet()) {
@ -165,7 +173,7 @@ public class CLDRReader {
} }
private void readTimeZones(String localeCode, CLDRLocale locale, InputStream input) { private void readTimeZones(String localeCode, CLDRLocale locale, InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject zonesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject() JsonObject zonesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject()
.get("dates").getAsJsonObject().get("timeZoneNames").getAsJsonObject().get("zone") .get("dates").getAsJsonObject().get("timeZoneNames").getAsJsonObject().get("zone")
.getAsJsonObject(); .getAsJsonObject();
@ -195,7 +203,7 @@ public class CLDRReader {
} }
private void readCurrencies(String localeCode, CLDRLocale locale, InputStream input) { private void readCurrencies(String localeCode, CLDRLocale locale, InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject currenciesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject() JsonObject currenciesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject()
.get("numbers").getAsJsonObject().get("currencies").getAsJsonObject(); .get("numbers").getAsJsonObject().get("currencies").getAsJsonObject();
for (Map.Entry<String, JsonElement> currencyEntry : currenciesJson.entrySet()) { for (Map.Entry<String, JsonElement> currencyEntry : currenciesJson.entrySet()) {
@ -211,7 +219,7 @@ public class CLDRReader {
} }
private void readNumbers(String localeCode, CLDRLocale locale, InputStream input) { private void readNumbers(String localeCode, CLDRLocale locale, InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject numbersJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject() JsonObject numbersJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject()
.get("numbers").getAsJsonObject(); .get("numbers").getAsJsonObject();
String numbering = numbersJson.get("defaultNumberingSystem").getAsString(); String numbering = numbersJson.get("defaultNumberingSystem").getAsString();
@ -224,7 +232,7 @@ public class CLDRReader {
locale.decimalData.exponentSeparator = symbolsJson.get("exponential").getAsString(); locale.decimalData.exponentSeparator = symbolsJson.get("exponential").getAsString();
locale.decimalData.perMille = symbolsJson.get("perMille").getAsString().charAt(0); locale.decimalData.perMille = symbolsJson.get("perMille").getAsString().charAt(0);
locale.decimalData.infinity = symbolsJson.get("infinity").getAsString(); locale.decimalData.infinity = symbolsJson.get("infinity").getAsString();
locale.decimalData.NaN = symbolsJson.get("nan").getAsString(); locale.decimalData.nan = symbolsJson.get("nan").getAsString();
JsonObject numberJson = numbersJson.get("decimalFormats-numberSystem-" + numbering).getAsJsonObject(); JsonObject numberJson = numbersJson.get("decimalFormats-numberSystem-" + numbering).getAsJsonObject();
locale.numberFormat = numberJson.get("standard").getAsString(); locale.numberFormat = numberJson.get("standard").getAsString();
@ -327,7 +335,7 @@ public class CLDRReader {
} }
private void readWeekData(InputStream input) { private void readWeekData(InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject weekJson = root.get("supplemental").getAsJsonObject().get("weekData").getAsJsonObject(); JsonObject weekJson = root.get("supplemental").getAsJsonObject().get("weekData").getAsJsonObject();
JsonObject minDaysJson = weekJson.get("minDays").getAsJsonObject(); JsonObject minDaysJson = weekJson.get("minDays").getAsJsonObject();
for (Map.Entry<String, JsonElement> property : minDaysJson.entrySet()) { for (Map.Entry<String, JsonElement> property : minDaysJson.entrySet()) {
@ -340,7 +348,7 @@ public class CLDRReader {
} }
private void readLikelySubtags(InputStream input) { private void readLikelySubtags(InputStream input) {
JsonObject root = (JsonObject)new JsonParser().parse(new InputStreamReader(input)); JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject likelySubtagsJson = root.get("supplemental").getAsJsonObject().get("likelySubtags") JsonObject likelySubtagsJson = root.get("supplemental").getAsJsonObject().get("likelySubtags")
.getAsJsonObject(); .getAsJsonObject();
for (Map.Entry<String, JsonElement> property : likelySubtagsJson.entrySet()) { for (Map.Entry<String, JsonElement> property : likelySubtagsJson.entrySet()) {

View File

@ -28,29 +28,17 @@ public class DateSymbolsMetadataGenerator implements MetadataGenerator {
public Resource generateMetadata(MetadataGeneratorContext context, MethodReference method) { public Resource generateMetadata(MetadataGeneratorContext context, MethodReference method) {
switch (method.getName()) { switch (method.getName()) {
case "getErasMap": case "getErasMap":
return generateSymbols(context, new ResourceExtractor() { return generateSymbols(context, locale -> locale.getEras());
@Override public String[] extract(CLDRLocale locale) { return locale.getEras(); }
});
case "getAmPmMap": case "getAmPmMap":
return generateSymbols(context, new ResourceExtractor() { return generateSymbols(context, locale -> locale.getDayPeriods());
@Override public String[] extract(CLDRLocale locale) { return locale.getDayPeriods(); }
});
case "getMonthMap": case "getMonthMap":
return generateSymbols(context, new ResourceExtractor() { return generateSymbols(context, locale -> locale.getMonths());
@Override public String[] extract(CLDRLocale locale) { return locale.getMonths(); }
});
case "getShortMonthMap": case "getShortMonthMap":
return generateSymbols(context, new ResourceExtractor() { return generateSymbols(context, locale -> locale.getShortMonths());
@Override public String[] extract(CLDRLocale locale) { return locale.getShortMonths(); }
});
case "getWeekdayMap": case "getWeekdayMap":
return generateSymbols(context, new ResourceExtractor() { return generateSymbols(context, locale -> locale.getWeekdays());
@Override public String[] extract(CLDRLocale locale) { return locale.getWeekdays(); }
});
case "getShortWeekdayMap": case "getShortWeekdayMap":
return generateSymbols(context, new ResourceExtractor() { return generateSymbols(context, locale -> locale.getShortWeekdays());
@Override public String[] extract(CLDRLocale locale) { return locale.getShortWeekdays(); }
});
default: default:
throw new AssertionError("Unsupported method: " + method); throw new AssertionError("Unsupported method: " + method);
} }
@ -71,7 +59,7 @@ public class DateSymbolsMetadataGenerator implements MetadataGenerator {
return result; return result;
} }
private static interface ResourceExtractor { private interface ResourceExtractor {
String[] extract(CLDRLocale locale); String[] extract(CLDRLocale locale);
} }
} }

View File

@ -24,9 +24,12 @@ import org.teavm.classlib.impl.CharFlow;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class UnicodeHelper { public final class UnicodeHelper {
private UnicodeHelper() {
}
static char hexDigit(int value) { static char hexDigit(int value) {
return value < 10 ? (char)('0' + value) : (char)('A' + value); return value < 10 ? (char) ('0' + value) : (char) ('A' + value);
} }
static int valueOfHexDigit(char digit) { static int valueOfHexDigit(char digit) {
@ -66,21 +69,21 @@ public class UnicodeHelper {
public static char encodeByte(byte b) { public static char encodeByte(byte b) {
if (b < '\"' - ' ') { if (b < '\"' - ' ') {
return (char)(b + ' '); return (char) (b + ' ');
} else if (b < '\\' - ' ' - 1) { } else if (b < '\\' - ' ' - 1) {
return (char)(b + ' ' + 1); return (char) (b + ' ' + 1);
} else { } else {
return (char)(b + ' ' + 2); return (char) (b + ' ' + 2);
} }
} }
public static byte decodeByte(char c) { public static byte decodeByte(char c) {
if (c > '\\') { if (c > '\\') {
return (byte)(c - ' ' - 2); return (byte) (c - ' ' - 2);
} else if (c > '"') { } else if (c > '"') {
return (byte)(c - ' ' - 1); return (byte) (c - ' ' - 1);
} else { } else {
return (byte)(c - ' '); return (byte) (c - ' ');
} }
} }
@ -95,13 +98,13 @@ public class UnicodeHelper {
} }
i += count; i += count;
if (count < 80) { if (count < 80) {
sb.append(UnicodeHelper.encodeByte((byte)(b + 32))); sb.append(UnicodeHelper.encodeByte((byte) (b + 32)));
sb.append(UnicodeHelper.encodeByte((byte)count)); sb.append(UnicodeHelper.encodeByte((byte) count));
} else { } else {
sb.append(UnicodeHelper.encodeByte((byte)64)); sb.append(UnicodeHelper.encodeByte((byte) 64));
sb.append(UnicodeHelper.encodeByte(b)); sb.append(UnicodeHelper.encodeByte(b));
for (int j = 0; j < 3; ++j) { for (int j = 0; j < 3; ++j) {
sb.append(UnicodeHelper.encodeByte((byte)(count & 0x3F))); sb.append(UnicodeHelper.encodeByte((byte) (count & 0x3F)));
count /= 0x40; count /= 0x40;
} }
} }

View File

@ -30,7 +30,7 @@ import org.teavm.common.IntegerArray;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class UnicodeSupport { public final class UnicodeSupport {
private static AtomicBoolean filled = new AtomicBoolean(); private static AtomicBoolean filled = new AtomicBoolean();
private static volatile CountDownLatch latch = new CountDownLatch(1); private static volatile CountDownLatch latch = new CountDownLatch(1);
private static int[] digitValues; private static int[] digitValues;
@ -70,6 +70,9 @@ public class UnicodeSupport {
classMap.put("Pf", Character.FINAL_QUOTE_PUNCTUATION); classMap.put("Pf", Character.FINAL_QUOTE_PUNCTUATION);
} }
private UnicodeSupport() {
}
private static void parseUnicodeData() { private static void parseUnicodeData() {
IntegerArray digitValues = new IntegerArray(4096); IntegerArray digitValues = new IntegerArray(4096);
IntegerArray classes = new IntegerArray(65536); IntegerArray classes = new IntegerArray(65536);
@ -119,7 +122,7 @@ public class UnicodeSupport {
UnicodeSupport.digitValues = mergePairs(digitValues.getAll(), letterDigitValues.getAll()); UnicodeSupport.digitValues = mergePairs(digitValues.getAll(), letterDigitValues.getAll());
UnicodeSupport.classes = new byte[classes.size()]; UnicodeSupport.classes = new byte[classes.size()];
for (int i = 0; i < classes.size(); ++i) { for (int i = 0; i < classes.size(); ++i) {
UnicodeSupport.classes[i] = (byte)classes.get(i); UnicodeSupport.classes[i] = (byte) classes.get(i);
} }
} }

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -78,13 +77,15 @@ public class TBufferedInputStream extends TFilterInputStream {
System.arraycopy(localBuf, 0, newbuf, 0, localBuf.length); System.arraycopy(localBuf, 0, newbuf, 0, localBuf.length);
// Reassign buf, which will invalidate any local references // Reassign buf, which will invalidate any local references
// FIXME: what if buf was null? // FIXME: what if buf was null?
localBuf = buf = newbuf; buf = newbuf;
localBuf = buf;
} else if (markpos > 0) { } else if (markpos > 0) {
System.arraycopy(localBuf, markpos, localBuf, 0, localBuf.length - markpos); System.arraycopy(localBuf, markpos, localBuf, 0, localBuf.length - markpos);
} }
/* Set the new position and mark position */ /* Set the new position and mark position */
pos -= markpos; pos -= markpos;
count = markpos = 0; count = 0;
markpos = 0;
int bytesread = localIn.read(localBuf, pos, localBuf.length - pos); int bytesread = localIn.read(localBuf, pos, localBuf.length - pos);
count = bytesread <= 0 ? pos : pos + bytesread; count = bytesread <= 0 ? pos : pos + bytesread;
return bytesread; return bytesread;
@ -245,7 +246,7 @@ public class TBufferedInputStream extends TFilterInputStream {
return amount; return amount;
} }
// Couldn't get all the bytes, skip what we read // Couldn't get all the bytes, skip what we read
read += (count - pos); read += count - pos;
pos = count; pos = count;
return read; return read;
} }

View File

@ -122,7 +122,7 @@ public class TBufferedReader extends TReader {
index += n; index += n;
return n; return n;
} else { } else {
n -= (count - index); n -= count - index;
long skipped = innerReader.skip(n); long skipped = innerReader.skip(n);
if (skipped == n) { if (skipped == n) {
fillBuffer(0); fillBuffer(0);

View File

@ -54,7 +54,7 @@ public class TByteArrayInputStream extends TInputStream {
@Override @Override
public long skip(long n) { public long skip(long n) {
int bytesSkipped = (int)TMath.min(n, count - pos); int bytesSkipped = (int) TMath.min(n, count - pos);
pos += bytesSkipped; pos += bytesSkipped;
return bytesSkipped; return bytesSkipped;
} }

View File

@ -38,7 +38,7 @@ public class TByteArrayOutputStream extends TOutputStream {
@Override @Override
public void write(int b) { public void write(int b) {
ensureCapacity(count + 1); ensureCapacity(count + 1);
buf[count++] = (byte)b; buf[count++] = (byte) b;
} }
@Override @Override

View File

@ -23,5 +23,5 @@ import org.teavm.classlib.java.lang.TAutoCloseable;
*/ */
public interface TCloseable extends TAutoCloseable { public interface TCloseable extends TAutoCloseable {
@Override @Override
public void close() throws TIOException; void close() throws TIOException;
} }

View File

@ -54,14 +54,16 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
if (temp < 0) { if (temp < 0) {
throw new TEOFException(); throw new TEOFException();
} }
return (byte)temp; return (byte) temp;
} }
private int readToBuff(int count) throws TIOException { private int readToBuff(int count) throws TIOException {
int offset = 0; int offset = 0;
while(offset < count) { while (offset < count) {
int bytesRead = in.read(buff, offset, count - offset); int bytesRead = in.read(buff, offset, count - offset);
if(bytesRead == -1) return bytesRead; if (bytesRead == -1) {
return bytesRead;
}
offset += bytesRead; offset += bytesRead;
} }
return offset; return offset;
@ -69,7 +71,7 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
@Override @Override
public final char readChar() throws TIOException { public final char readChar() throws TIOException {
if (readToBuff(2) < 0){ if (readToBuff(2) < 0) {
throw new TEOFException(); throw new TEOFException();
} }
return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff)); return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
@ -120,7 +122,7 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
@Override @Override
public final int readInt() throws TIOException { public final int readInt() throws TIOException {
if (readToBuff(4) < 0){ if (readToBuff(4) < 0) {
throw new TEOFException(); throw new TEOFException();
} }
return ((buff[0] & 0xff) << 24) | ((buff[1] & 0xff) << 16) | ((buff[2] & 0xff) << 8) | (buff[3] & 0xff); return ((buff[0] & 0xff) << 24) | ((buff[1] & 0xff) << 16) | ((buff[2] & 0xff) << 8) | (buff[3] & 0xff);
@ -141,7 +143,7 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
return TString.wrap(line.toString()); return TString.wrap(line.toString());
case (byte) '\r': case (byte) '\r':
if (foundTerminator) { if (foundTerminator) {
((TPushbackInputStream)in).unread(nextByte); ((TPushbackInputStream) in).unread(nextByte);
return TString.wrap(line.toString()); return TString.wrap(line.toString());
} }
foundTerminator = true; foundTerminator = true;
@ -154,7 +156,7 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
return TString.wrap(line.toString()); return TString.wrap(line.toString());
default: default:
if (foundTerminator) { if (foundTerminator) {
((TPushbackInputStream)in).unread(nextByte); ((TPushbackInputStream) in).unread(nextByte);
return TString.wrap(line.toString()); return TString.wrap(line.toString());
} }
line.append((char) nextByte); line.append((char) nextByte);
@ -164,19 +166,19 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
@Override @Override
public final long readLong() throws TIOException { public final long readLong() throws TIOException {
if (readToBuff(8) < 0){ if (readToBuff(8) < 0) {
throw new TEOFException(); throw new TEOFException();
} }
int i1 = ((buff[0] & 0xff) << 24) | ((buff[1] & 0xff) << 16) | int i1 = ((buff[0] & 0xff) << 24) | ((buff[1] & 0xff) << 16)
((buff[2] & 0xff) << 8) | (buff[3] & 0xff); | ((buff[2] & 0xff) << 8) | (buff[3] & 0xff);
int i2 = ((buff[4] & 0xff) << 24) | ((buff[5] & 0xff) << 16) | int i2 = ((buff[4] & 0xff) << 24) | ((buff[5] & 0xff) << 16)
((buff[6] & 0xff) << 8) | (buff[7] & 0xff); | ((buff[6] & 0xff) << 8) | (buff[7] & 0xff);
return ((i1 & 0xffffffffL) << 32) | (i2 & 0xffffffffL); return ((i1 & 0xffffffffL) << 32) | (i2 & 0xffffffffL);
} }
@Override @Override
public final short readShort() throws TIOException { public final short readShort() throws TIOException {
if (readToBuff(2) < 0){ if (readToBuff(2) < 0) {
throw new TEOFException(); throw new TEOFException();
} }
return (short) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff)); return (short) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
@ -193,7 +195,7 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
@Override @Override
public final int readUnsignedShort() throws TIOException { public final int readUnsignedShort() throws TIOException {
if (readToBuff(2) < 0){ if (readToBuff(2) < 0) {
throw new TEOFException(); throw new TEOFException();
} }
return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff)); return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
@ -223,8 +225,12 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
@Override @Override
public final int skipBytes(int count) throws TIOException { public final int skipBytes(int count) throws TIOException {
int skipped = 0; int skipped = 0;
long skip;
while (skipped < count && (skip = in.skip(count - skipped)) != 0) { while (skipped < count) {
long skip = in.skip(count - skipped);
if (skip == 0) {
break;
}
skipped += skip; skipped += skip;
} }
if (skipped < 0) { if (skipped < 0) {
@ -239,11 +245,12 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
int s = 0; int s = 0;
int a; int a;
while (count < utfSize) { while (count < utfSize) {
char ch = (char)buf[offset + count++]; char ch = (char) buf[offset + count++];
out[s] = ch; out[s] = ch;
a = out[s];
if (ch < '\u0080') { if (ch < '\u0080') {
s++; s++;
} else if (((a = out[s]) & 0xe0) == 0xc0) { } else if ((a & 0xe0) == 0xc0) {
if (count >= utfSize) { if (count >= utfSize) {
throw new TUTFDataFormatException(TString.wrap("End of stream reached")); throw new TUTFDataFormatException(TString.wrap("End of stream reached"));
} }
@ -261,7 +268,7 @@ public class TDataInputStream extends TFilterInputStream implements TDataInput {
if (((b & 0xC0) != 0x80) || ((c & 0xC0) != 0x80)) { if (((b & 0xC0) != 0x80) || ((c & 0xC0) != 0x80)) {
throw new TUTFDataFormatException(TString.wrap("Malformed UTF-8 sequence")); throw new TUTFDataFormatException(TString.wrap("Malformed UTF-8 sequence"));
} }
out[s++] = (char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)); out[s++] = (char) (((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F));
} else { } else {
throw new TUTFDataFormatException(TString.wrap("Malformed UTF-8 sequence")); throw new TUTFDataFormatException(TString.wrap("Malformed UTF-8 sequence"));
} }

View File

@ -18,7 +18,7 @@ package org.teavm.classlib.java.io;
import org.teavm.classlib.java.lang.TString; import org.teavm.classlib.java.lang.TString;
public interface TDataOutput{ public interface TDataOutput {
void write(int b) throws TIOException; void write(int b) throws TIOException;
void write(byte[] b) throws TIOException; void write(byte[] b) throws TIOException;

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,16 +13,15 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.io; package org.teavm.classlib.java.io;
import org.teavm.classlib.java.lang.*; import org.teavm.classlib.java.lang.*;
public class TDataOutputStream extends TFilterOutputStream implements TDataOutput{ public class TDataOutputStream extends TFilterOutputStream implements TDataOutput {
/** /**
* The number of bytes written out so far. * The number of bytes written out so far.
*/ */
protected int written; protected int written;
byte buff[]; byte[] buff;
public TDataOutputStream(TOutputStream out) { public TDataOutputStream(TOutputStream out) {
super(out); super(out);
@ -43,7 +41,7 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
} }
@Override @Override
public void write(byte buffer[], int offset, int count) throws TIOException { public void write(byte[] buffer, int offset, int count) throws TIOException {
if (buffer == null) { if (buffer == null) {
throw new TNullPointerException(); throw new TNullPointerException();
} }
@ -74,7 +72,7 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
if (str.length() == 0) { if (str.length() == 0) {
return; return;
} }
byte bytes[] = new byte[str.length()]; byte[] bytes = new byte[str.length()];
for (int index = 0; index < str.length(); index++) { for (int index = 0; index < str.length(); index++) {
bytes[index] = (byte) str.charAt(index); bytes[index] = (byte) str.charAt(index);
} }
@ -92,7 +90,7 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
@Override @Override
public final void writeChars(TString str) throws TIOException { public final void writeChars(TString str) throws TIOException {
byte newBytes[] = new byte[str.length() * 2]; byte[] newBytes = new byte[str.length() * 2];
for (int index = 0; index < str.length(); index++) { for (int index = 0; index < str.length(); index++) {
int newIndex = index == 0 ? index : index * 2; int newIndex = index == 0 ? index : index * 2;
newBytes[newIndex] = (byte) (str.charAt(index) >> 8); newBytes[newIndex] = (byte) (str.charAt(index) >> 8);
@ -136,8 +134,7 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
written += 8; written += 8;
} }
int writeLongToBuffer(long val, int writeLongToBuffer(long val, byte[] buffer, int offset) throws TIOException {
byte[] buffer, int offset) throws TIOException {
buffer[offset++] = (byte) (val >> 56); buffer[offset++] = (byte) (val >> 56);
buffer[offset++] = (byte) (val >> 48); buffer[offset++] = (byte) (val >> 48);
buffer[offset++] = (byte) (val >> 40); buffer[offset++] = (byte) (val >> 40);
@ -157,8 +154,7 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
written += 2; written += 2;
} }
int writeShortToBuffer(int val, int writeShortToBuffer(int val, byte[] buffer, int offset) throws TIOException {
byte[] buffer, int offset) throws TIOException {
buffer[offset++] = (byte) (val >> 8); buffer[offset++] = (byte) (val >> 8);
buffer[offset++] = (byte) val; buffer[offset++] = (byte) val;
return offset; return offset;
@ -170,7 +166,7 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
if (utfCount > 65535) { if (utfCount > 65535) {
throw new TIOException(TString.wrap("UTF Error")); throw new TIOException(TString.wrap("UTF Error"));
} }
byte[] buffer = new byte[(int)utfCount + 2]; byte[] buffer = new byte[(int) utfCount + 2];
int offset = 0; int offset = 0;
offset = writeShortToBuffer((int) utfCount, buffer, offset); offset = writeShortToBuffer((int) utfCount, buffer, offset);
offset = writeUTFBytesToBuffer(str, buffer, offset); offset = writeUTFBytesToBuffer(str, buffer, offset);
@ -178,7 +174,8 @@ public class TDataOutputStream extends TFilterOutputStream implements TDataOutpu
} }
long countUTFBytes(TString str) { long countUTFBytes(TString str) {
int utfCount = 0, length = str.length(); int utfCount = 0;
int length = str.length();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
int charValue = str.charAt(i); int charValue = str.charAt(i);
if (charValue > 0 && charValue <= 127) { if (charValue > 0 && charValue <= 127) {

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -38,14 +38,14 @@ public abstract class TInputStream extends TObject implements TCloseable {
if (bt < 0) { if (bt < 0) {
return i == 0 ? -1 : i; return i == 0 ? -1 : i;
} }
b[off++] = (byte)bt; b[off++] = (byte) bt;
} }
return len > 0 ? len : -1; return len > 0 ? len : -1;
} }
public long skip(long n) throws TIOException { public long skip(long n) throws TIOException {
if (n < TInteger.MAX_VALUE) { if (n < TInteger.MAX_VALUE) {
return skip((int)n); return skip((int) n);
} else { } else {
for (long i = 0; i < n; ++i) { for (long i = 0; i < n; ++i) {
if (read() < 0) { if (read() < 0) {

View File

@ -117,7 +117,7 @@ public class TOutputStreamWriter extends TWriter {
@Override @Override
public void write(int oneChar) throws TIOException { public void write(int oneChar) throws TIOException {
char[] array = { (char)oneChar }; char[] array = { (char) oneChar };
write(array, 0, array.length); write(array, 0, array.length);
} }

View File

@ -70,7 +70,7 @@ public class TPushbackInputStream extends TFilterInputStream {
} }
// Is there a pushback byte available? // Is there a pushback byte available?
if (pos < buf.length) { if (pos < buf.length) {
return (buf[pos++] & 0xFF); return buf[pos++] & 0xFF;
} }
// Assume read() in the InputStream will return low-order byte or -1 // Assume read() in the InputStream will return low-order byte or -1
// if end of stream. // if end of stream.
@ -90,7 +90,9 @@ public class TPushbackInputStream extends TFilterInputStream {
throw new TArrayIndexOutOfBoundsException(TString.wrap("Length out of bounds: " + length)); throw new TArrayIndexOutOfBoundsException(TString.wrap("Length out of bounds: " + length));
} }
int copiedBytes = 0, copyLength = 0, newOffset = offset; int copiedBytes = 0;
int copyLength = 0;
int newOffset = offset;
// Are there pushback bytes available? // Are there pushback bytes available?
if (pos < buf.length) { if (pos < buf.length) {
copyLength = (buf.length - pos >= length) ? length : buf.length - pos; copyLength = (buf.length - pos >= length) ? length : buf.length - pos;

View File

@ -48,7 +48,7 @@ public abstract class TReader implements TCloseable {
char[] buffer = new char[1024]; char[] buffer = new char[1024];
long skipped = 0; long skipped = 0;
while (skipped < n) { while (skipped < n) {
int charsRead = read(buffer, 0, (int)TMath.min(n, buffer.length)); int charsRead = read(buffer, 0, (int) TMath.min(n, buffer.length));
if (charsRead < 0) { if (charsRead < 0) {
break; break;
} }

View File

@ -27,7 +27,7 @@ import org.teavm.classlib.java.lang.TString;
public class TStringReader extends TReader { public class TStringReader extends TReader {
private TString string; private TString string;
private int index; private int index;
private int mark = 0; private int mark;
public TStringReader(TString string) { public TStringReader(TString string) {
if (string == null) { if (string == null) {

View File

@ -33,15 +33,15 @@ public abstract class TWriter implements TAppendable, TCloseable, TFlushable {
this.lock = lock; this.lock = lock;
} }
public void write(char buf[]) throws TIOException { public void write(char[] buf) throws TIOException {
write(buf, 0, buf.length); write(buf, 0, buf.length);
} }
public abstract void write(char buf[], int offset, int count) throws TIOException; public abstract void write(char[] buf, int offset, int count) throws TIOException;
public void write(int oneChar) throws TIOException { public void write(int oneChar) throws TIOException {
synchronized (lock) { synchronized (lock) {
char oneCharArray[] = new char[1]; char[] oneCharArray = new char[1];
oneCharArray[0] = (char) oneChar; oneCharArray[0] = (char) oneChar;
write(oneCharArray); write(oneCharArray);
} }
@ -55,7 +55,7 @@ public abstract class TWriter implements TAppendable, TCloseable, TFlushable {
if (count < 0) { if (count < 0) {
throw new StringIndexOutOfBoundsException(); throw new StringIndexOutOfBoundsException();
} }
char buf[] = new char[count]; char[] buf = new char[count];
str.getChars(offset, offset + count, buf, 0); str.getChars(offset, offset + count, buf, 0);
synchronized (lock) { synchronized (lock) {
write(buf, 0, buf.length); write(buf, 0, buf.length);

View File

@ -54,7 +54,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
} }
public TAbstractStringBuilder(TString value) { public TAbstractStringBuilder(TString value) {
this((TCharSequence)value); this((TCharSequence) value);
} }
public TAbstractStringBuilder(TCharSequence value) { public TAbstractStringBuilder(TCharSequence value) {
@ -164,7 +164,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
} else { } else {
insertSpace(target, target + 1); insertSpace(target, target + 1);
} }
buffer[target++] = Character.forDigit((int)value, radix); buffer[target++] = Character.forDigit((int) value, radix);
} else { } else {
int sz = 1; int sz = 1;
long pos = 1; long pos = 1;
@ -180,7 +180,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
buffer[target++] = '-'; buffer[target++] = '-';
} }
while (pos > 0) { while (pos > 0) {
buffer[target++] = TCharacter.forDigit((int)(value / pos), radix); buffer[target++] = TCharacter.forDigit((int) (value / pos), radix);
value %= pos; value %= pos;
pos /= radix; pos /= radix;
} }
@ -254,7 +254,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
} }
bit >>= 1; bit >>= 1;
} }
mantissa = (int)((value / (digit / FLOAT_DECIMAL_FACTOR)) + 0.5f); mantissa = (int) ((value / (digit / FLOAT_DECIMAL_FACTOR)) + 0.5f);
} else { } else {
int bit = 32; int bit = 32;
exp = 0; exp = 0;
@ -267,7 +267,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
bit >>= 1; bit >>= 1;
} }
exp = -exp; exp = -exp;
mantissa = (int)(((value * FLOAT_MAX_POS) / digit) + 0.5f); mantissa = (int) (((value * FLOAT_MAX_POS) / digit) + 0.5f);
} }
// Remove trailing zeros // Remove trailing zeros
@ -320,7 +320,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
} else { } else {
intDigit = 0; intDigit = 0;
} }
buffer[target++] = (char)('0' + intDigit); buffer[target++] = (char) ('0' + intDigit);
if (--intPart == 0) { if (--intPart == 0) {
buffer[target++] = '.'; buffer[target++] = '.';
} }
@ -335,9 +335,9 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
buffer[target++] = '-'; buffer[target++] = '-';
} }
if (exp >= 10) { if (exp >= 10) {
buffer[target++] = (char)('0' + exp / 10); buffer[target++] = (char) ('0' + exp / 10);
} }
buffer[target++] = (char)('0' + exp % 10); buffer[target++] = (char) ('0' + exp % 10);
} }
return this; return this;
} }
@ -408,7 +408,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
} }
bit >>= 1; bit >>= 1;
} }
mantissa = (long)(((value / digit) * DOUBLE_DECIMAL_FACTOR) + 0.5); mantissa = (long) (((value / digit) * DOUBLE_DECIMAL_FACTOR) + 0.5);
} else { } else {
int bit = 256; int bit = 256;
exp = 0; exp = 0;
@ -421,7 +421,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
bit >>= 1; bit >>= 1;
} }
exp = -exp; exp = -exp;
mantissa = (long)(((value * DOUBLE_MAX_POS) / digit) + 0.5); mantissa = (long) (((value * DOUBLE_MAX_POS) / digit) + 0.5);
} }
// Remove trailing zeros // Remove trailing zeros
@ -472,12 +472,12 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
for (int i = 0; i < digits; ++i) { for (int i = 0; i < digits; ++i) {
int intDigit; int intDigit;
if (pos > 0) { if (pos > 0) {
intDigit = (int)(mantissa / pos); intDigit = (int) (mantissa / pos);
mantissa %= pos; mantissa %= pos;
} else { } else {
intDigit = 0; intDigit = 0;
} }
buffer[target++] = (char)('0' + intDigit); buffer[target++] = (char) ('0' + intDigit);
if (--intPart == 0) { if (--intPart == 0) {
buffer[target++] = '.'; buffer[target++] = '.';
} }
@ -492,13 +492,13 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
buffer[target++] = '-'; buffer[target++] = '-';
} }
if (exp >= 100) { if (exp >= 100) {
buffer[target++] = (char)('0' + exp / 100); buffer[target++] = (char) ('0' + exp / 100);
exp %= 100; exp %= 100;
buffer[target++] = (char)('0' + exp / 10); buffer[target++] = (char) ('0' + exp / 10);
} else if (exp >= 10) { } else if (exp >= 10) {
buffer[target++] = (char)('0' + exp / 10); buffer[target++] = (char) ('0' + exp / 10);
} }
buffer[target++] = (char)('0' + exp % 10); buffer[target++] = (char) ('0' + exp % 10);
} }
return this; return this;
} }
@ -553,7 +553,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
protected TAbstractStringBuilder appendCodePoint(int codePoint) { protected TAbstractStringBuilder appendCodePoint(int codePoint) {
if (codePoint < TCharacter.MIN_SUPPLEMENTARY_CODE_POINT) { if (codePoint < TCharacter.MIN_SUPPLEMENTARY_CODE_POINT) {
return append((char)codePoint); return append((char) codePoint);
} }
ensureCapacity(length + 2); ensureCapacity(length + 2);
buffer[length++] = TCharacter.highSurrogate(codePoint); buffer[length++] = TCharacter.highSurrogate(codePoint);
@ -632,7 +632,7 @@ class TAbstractStringBuilder extends TObject implements TSerializable, TCharSequ
} }
protected TAbstractStringBuilder append(TStringBuffer s) { protected TAbstractStringBuilder append(TStringBuffer s) {
return append((TCharSequence)s); return append((TCharSequence) s);
} }
protected TAbstractStringBuilder insert(int index, TCharSequence s) { protected TAbstractStringBuilder insert(int index, TCharSequence s) {

View File

@ -88,7 +88,7 @@ public class TBoolean extends TObject implements TSerializable, TComparable<TBoo
if (this == obj) { if (this == obj) {
return true; return true;
} }
return obj instanceof TBoolean && ((TBoolean)obj).value == value; return obj instanceof TBoolean && ((TBoolean) obj).value == value;
} }
public boolean getBoolean(TString key) { public boolean getBoolean(TString key) {

View File

@ -75,7 +75,7 @@ public class TByte extends TNumber implements TComparable<TByte> {
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
return other instanceof TByte && ((TByte)other).value == value; return other instanceof TByte && ((TByte) other).value == value;
} }
@Override @Override
@ -101,7 +101,7 @@ public class TByte extends TNumber implements TComparable<TByte> {
if (value < MIN_VALUE || value >= MAX_VALUE) { if (value < MIN_VALUE || value >= MAX_VALUE) {
throw new TNumberFormatException(); throw new TNumberFormatException();
} }
return (byte)value; return (byte) value;
} }
public static TByte valueOf(TString s, int radix) throws TNumberFormatException { public static TByte valueOf(TString s, int radix) throws TNumberFormatException {
@ -117,6 +117,6 @@ public class TByte extends TNumber implements TComparable<TByte> {
if (value.intValue() < MIN_VALUE || value.intValue() >= MAX_VALUE) { if (value.intValue() < MIN_VALUE || value.intValue() >= MAX_VALUE) {
throw new TNumberFormatException(); throw new TNumberFormatException();
} }
return TByte.valueOf((byte)value.intValue()); return TByte.valueOf((byte) value.intValue());
} }
} }

View File

@ -133,7 +133,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
if (this == other) { if (this == other) {
return true; return true;
} }
return other instanceof TCharacter && ((TCharacter)other).value == value; return other instanceof TCharacter && ((TCharacter) other).value == value;
} }
@Override @Override
@ -178,13 +178,13 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static int toCodePoint(char high, char low) { public static int toCodePoint(char high, char low) {
return (((high & SURROGATE_BIT_INV_MASK) << MEANINGFUL_SURROGATE_BITS) | (low & SURROGATE_BIT_INV_MASK)) + return (((high & SURROGATE_BIT_INV_MASK) << MEANINGFUL_SURROGATE_BITS) | (low & SURROGATE_BIT_INV_MASK))
MIN_SUPPLEMENTARY_CODE_POINT; + MIN_SUPPLEMENTARY_CODE_POINT;
} }
public static int codePointAt(TCharSequence seq, int index) { public static int codePointAt(TCharSequence seq, int index) {
if (index >= seq.length() - 1 || !isHighSurrogate(seq.charAt(index)) || if (index >= seq.length() - 1 || !isHighSurrogate(seq.charAt(index))
!isLowSurrogate(seq.charAt(index + 1))) { || !isLowSurrogate(seq.charAt(index + 1))) {
return seq.charAt(index); return seq.charAt(index);
} else { } else {
return toCodePoint(seq.charAt(index), seq.charAt(index + 1)); return toCodePoint(seq.charAt(index), seq.charAt(index + 1));
@ -224,15 +224,15 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
public static char highSurrogate(int codePoint) { public static char highSurrogate(int codePoint) {
codePoint -= MIN_SUPPLEMENTARY_CODE_POINT; codePoint -= MIN_SUPPLEMENTARY_CODE_POINT;
return (char)(HIGH_SURROGATE_BITS | (codePoint >> MEANINGFUL_SURROGATE_BITS) & SURROGATE_BIT_INV_MASK); return (char) (HIGH_SURROGATE_BITS | (codePoint >> MEANINGFUL_SURROGATE_BITS) & SURROGATE_BIT_INV_MASK);
} }
public static char lowSurrogate(int codePoint) { public static char lowSurrogate(int codePoint) {
return (char)(LOW_SURROGATE_BITS | codePoint & SURROGATE_BIT_INV_MASK); return (char) (LOW_SURROGATE_BITS | codePoint & SURROGATE_BIT_INV_MASK);
} }
public static char toLowerCase(char ch) { public static char toLowerCase(char ch) {
return (char)toLowerCase((int)ch); return (char) toLowerCase((int) ch);
} }
public static int toLowerCase(int ch) { public static int toLowerCase(int ch) {
@ -240,7 +240,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static char toUpperCase(char ch) { public static char toUpperCase(char ch) {
return (char)toUpperCase((int)ch); return (char) toUpperCase((int) ch);
} }
public static int toUpperCase(int codePoint) { public static int toUpperCase(int codePoint) {
@ -248,7 +248,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static int digit(char ch, int radix) { public static int digit(char ch, int radix) {
return digit((int)ch, radix); return digit((int) ch, radix);
} }
public static int digit(int codePoint, int radix) { public static int digit(int codePoint, int radix) {
@ -260,7 +260,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static int getNumericValue(char ch) { public static int getNumericValue(char ch) {
return getNumericValue((int)ch); return getNumericValue((int) ch);
} }
public static int getNumericValue(int codePoint) { public static int getNumericValue(int codePoint) {
@ -285,11 +285,11 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
if (radix < MIN_RADIX || radix > MAX_RADIX || digit >= radix) { if (radix < MIN_RADIX || radix > MAX_RADIX || digit >= radix) {
return '\0'; return '\0';
} }
return digit < 10 ? (char)('0' + digit) : (char)('a' + digit - 10); return digit < 10 ? (char) ('0' + digit) : (char) ('a' + digit - 10);
} }
public static boolean isDigit(char ch) { public static boolean isDigit(char ch) {
return isDigit((int)ch); return isDigit((int) ch);
} }
public static boolean isDigit(int codePoint) { public static boolean isDigit(int codePoint) {
@ -322,7 +322,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
dst[dstIndex + 1] = lowSurrogate(codePoint); dst[dstIndex + 1] = lowSurrogate(codePoint);
return 2; return 2;
} else { } else {
dst[dstIndex] = (char)codePoint; dst[dstIndex] = (char) codePoint;
return 1; return 1;
} }
} }
@ -331,7 +331,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
if (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT) { if (codePoint >= MIN_SUPPLEMENTARY_CODE_POINT) {
return new char[] { highSurrogate(codePoint), lowSurrogate(codePoint) }; return new char[] { highSurrogate(codePoint), lowSurrogate(codePoint) };
} else { } else {
return new char[] { (char)codePoint }; return new char[] { (char) codePoint };
} }
} }
@ -361,8 +361,8 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
public static int offsetByCodePoints(TCharSequence seq, int index, int codePointOffset) { public static int offsetByCodePoints(TCharSequence seq, int index, int codePointOffset) {
for (int i = 0; i < codePointOffset; ++i) { for (int i = 0; i < codePointOffset; ++i) {
if (index < seq.length() - 1 && isHighSurrogate(seq.charAt(index)) && if (index < seq.length() - 1 && isHighSurrogate(seq.charAt(index))
isLowSurrogate(seq.charAt(index + 1))) { && isLowSurrogate(seq.charAt(index + 1))) {
index += 2; index += 2;
} else { } else {
index++; index++;
@ -383,7 +383,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isISOControl(char ch) { public static boolean isISOControl(char ch) {
return isISOControl((int)ch); return isISOControl((int) ch);
} }
public static boolean isISOControl(int codePoint) { public static boolean isISOControl(int codePoint) {
@ -391,11 +391,11 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static int getType(char c) { public static int getType(char c) {
return getType((int)c); return getType((int) c);
} }
public static int getType(int codePoint) { public static int getType(int codePoint) {
if (isBmpCodePoint(codePoint) && isSurrogate((char)codePoint)) { if (isBmpCodePoint(codePoint) && isSurrogate((char) codePoint)) {
return SURROGATE; return SURROGATE;
} }
UnicodeHelper.Range[] classes = getClasses(); UnicodeHelper.Range[] classes = getClasses();
@ -416,7 +416,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isLowerCase(char ch) { public static boolean isLowerCase(char ch) {
return isLowerCase((int)ch); return isLowerCase((int) ch);
} }
public static boolean isLowerCase(int codePoint) { public static boolean isLowerCase(int codePoint) {
@ -424,7 +424,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isUpperCase(char ch) { public static boolean isUpperCase(char ch) {
return isUpperCase((int)ch); return isUpperCase((int) ch);
} }
public static boolean isUpperCase(int codePoint) { public static boolean isUpperCase(int codePoint) {
@ -432,7 +432,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isTitleCase(char ch) { public static boolean isTitleCase(char ch) {
return isTitleCase((int)ch); return isTitleCase((int) ch);
} }
public static boolean isTitleCase(int codePoint) { public static boolean isTitleCase(int codePoint) {
@ -440,7 +440,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isDefined(char ch) { public static boolean isDefined(char ch) {
return isDefined((int)ch); return isDefined((int) ch);
} }
public static boolean isDefined(int codePoint) { public static boolean isDefined(int codePoint) {
@ -448,7 +448,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isLetter(char ch) { public static boolean isLetter(char ch) {
return isLetter((int)ch); return isLetter((int) ch);
} }
public static boolean isLetter(int codePoint) { public static boolean isLetter(int codePoint) {
@ -465,7 +465,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isLetterOrDigit(char ch) { public static boolean isLetterOrDigit(char ch) {
return isLetterOrDigit((int)ch); return isLetterOrDigit((int) ch);
} }
public static boolean isLetterOrDigit(int codePoint) { public static boolean isLetterOrDigit(int codePoint) {
@ -488,7 +488,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isJavaIdentifierStart(char ch) { public static boolean isJavaIdentifierStart(char ch) {
return isJavaIdentifierStart((int)ch); return isJavaIdentifierStart((int) ch);
} }
public static boolean isJavaIdentifierStart(int codePoint) { public static boolean isJavaIdentifierStart(int codePoint) {
@ -513,7 +513,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isJavaIdentifierPart(char ch) { public static boolean isJavaIdentifierPart(char ch) {
return isJavaIdentifierPart((int)ch); return isJavaIdentifierPart((int) ch);
} }
public static boolean isJavaIdentifierPart(int codePoint) { public static boolean isJavaIdentifierPart(int codePoint) {
@ -550,7 +550,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isUnicodeIdentifierStart(char ch) { public static boolean isUnicodeIdentifierStart(char ch) {
return isUnicodeIdentifierStart((int)ch); return isUnicodeIdentifierStart((int) ch);
} }
public static boolean isUnicodeIdentifierStart(int codePoint) { public static boolean isUnicodeIdentifierStart(int codePoint) {
@ -568,7 +568,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isUnicodeIdentifierPart(char ch) { public static boolean isUnicodeIdentifierPart(char ch) {
return isUnicodeIdentifierPart((int)ch); return isUnicodeIdentifierPart((int) ch);
} }
public static boolean isUnicodeIdentifierPart(int codePoint) { public static boolean isUnicodeIdentifierPart(int codePoint) {
@ -590,12 +590,12 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isIdentifierIgnorable(char ch) { public static boolean isIdentifierIgnorable(char ch) {
return isIdentifierIgnorable((int)ch); return isIdentifierIgnorable((int) ch);
} }
public static boolean isIdentifierIgnorable(int codePoint) { public static boolean isIdentifierIgnorable(int codePoint) {
if (codePoint >= 0x00 && codePoint <= 0x08 || codePoint >= 0x0E && codePoint <= 0x1B || if (codePoint >= 0x00 && codePoint <= 0x08 || codePoint >= 0x0E && codePoint <= 0x1B
codePoint >= 0x7F && codePoint <= 0x9F) { || codePoint >= 0x7F && codePoint <= 0x9F) {
return true; return true;
} }
return getType(codePoint) == FORMAT; return getType(codePoint) == FORMAT;
@ -616,7 +616,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isSpaceChar(char ch) { public static boolean isSpaceChar(char ch) {
return isSpaceChar((int)ch); return isSpaceChar((int) ch);
} }
public static boolean isSpaceChar(int codePoint) { public static boolean isSpaceChar(int codePoint) {
@ -631,7 +631,7 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static boolean isWhitespace(char ch) { public static boolean isWhitespace(char ch) {
return isWhitespace((int)ch); return isWhitespace((int) ch);
} }
public static boolean isWhitespace(int codePoint) { public static boolean isWhitespace(int codePoint) {
@ -668,6 +668,6 @@ public class TCharacter extends TObject implements TComparable<TCharacter> {
} }
public static char reverseBytes(char ch) { public static char reverseBytes(char ch) {
return (char)((ch >> 8) | (ch << 8)); return (char) ((ch >> 8) | (ch << 8));
} }
} }

View File

@ -49,7 +49,7 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
if (cls == null) { if (cls == null) {
return null; return null;
} }
TClass<?> result = (TClass<?>)(Object)Platform.asJavaClass(cls.getJavaClass()); TClass<?> result = (TClass<?>) (Object) Platform.asJavaClass(cls.getJavaClass());
if (result == null) { if (result == null) {
result = new TClass<>(cls); result = new TClass<>(cls);
} }
@ -122,47 +122,47 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TVoid> voidClass() { static TClass<TVoid> voidClass() {
return (TClass<TVoid>)getClass(Platform.getPrimitives().getVoidClass()); return (TClass<TVoid>) getClass(Platform.getPrimitives().getVoidClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TBoolean> booleanClass() { static TClass<TBoolean> booleanClass() {
return (TClass<TBoolean>)getClass(Platform.getPrimitives().getBooleanClass()); return (TClass<TBoolean>) getClass(Platform.getPrimitives().getBooleanClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TCharacter> charClass() { static TClass<TCharacter> charClass() {
return (TClass<TCharacter>)getClass(Platform.getPrimitives().getCharClass()); return (TClass<TCharacter>) getClass(Platform.getPrimitives().getCharClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TByte> byteClass() { static TClass<TByte> byteClass() {
return (TClass<TByte>)getClass(Platform.getPrimitives().getByteClass()); return (TClass<TByte>) getClass(Platform.getPrimitives().getByteClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TShort> shortClass() { static TClass<TShort> shortClass() {
return (TClass<TShort>)getClass(Platform.getPrimitives().getShortClass()); return (TClass<TShort>) getClass(Platform.getPrimitives().getShortClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TInteger> intClass() { static TClass<TInteger> intClass() {
return (TClass<TInteger>)getClass(Platform.getPrimitives().getIntClass()); return (TClass<TInteger>) getClass(Platform.getPrimitives().getIntClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TLong> longClass() { static TClass<TLong> longClass() {
return (TClass<TLong>)getClass(Platform.getPrimitives().getLongClass()); return (TClass<TLong>) getClass(Platform.getPrimitives().getLongClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TFloat> floatClass() { static TClass<TFloat> floatClass() {
return (TClass<TFloat>)getClass(Platform.getPrimitives().getFloatClass()); return (TClass<TFloat>) getClass(Platform.getPrimitives().getFloatClass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static TClass<TDouble> doubleClass() { static TClass<TDouble> doubleClass() {
return (TClass<TDouble>)getClass(Platform.getPrimitives().getDoubleClass()); return (TClass<TDouble>) getClass(Platform.getPrimitives().getDoubleClass());
} }
public boolean desiredAssertionStatus() { public boolean desiredAssertionStatus() {
@ -171,21 +171,21 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public TClass<? super T> getSuperclass() { public TClass<? super T> getSuperclass() {
return (TClass<? super T>)getClass(platformClass.getMetadata().getSuperclass()); return (TClass<? super T>) getClass(platformClass.getMetadata().getSuperclass());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T[] getEnumConstants() { public T[] getEnumConstants() {
return isEnum() ? (T[])Platform.getEnumConstants(platformClass) : null; return isEnum() ? (T[]) Platform.getEnumConstants(platformClass) : null;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T cast(TObject obj) { public T cast(TObject obj) {
if (obj != null && !isAssignableFrom((TClass<?>)(Object)obj.getClass())) { if (obj != null && !isAssignableFrom((TClass<?>) (Object) obj.getClass())) {
throw new TClassCastException(TString.wrap(obj.getClass().getName() + throw new TClassCastException(TString.wrap(obj.getClass().getName()
" is not subtype of " + name)); + " is not subtype of " + name));
} }
return (T)obj; return (T) obj;
} }
public TClassLoader getClassLoader() { public TClassLoader getClassLoader() {
@ -212,7 +212,7 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
if (instance == null) { if (instance == null) {
throw new TInstantiationException(); throw new TInstantiationException();
} }
return (T)instance; return (T) instance;
} }
public TClass<?> getDeclaringClass() { public TClass<?> getDeclaringClass() {
@ -228,7 +228,7 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
if (!clazz.isAssignableFrom(this)) { if (!clazz.isAssignableFrom(this)) {
throw new TClassCastException(); throw new TClassCastException();
} }
return (TClass<? extends U>)this; return (TClass<? extends U>) this;
} }
@Override @Override
@ -241,13 +241,13 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
@Override @Override
public <S extends TAnnotation> S getAnnotation(TClass<S> annotationClass) { public <S extends TAnnotation> S getAnnotation(TClass<S> annotationClass) {
ensureAnnotationsByType(); ensureAnnotationsByType();
return (S)annotationsByType.get(annotationClass); return (S) annotationsByType.get(annotationClass);
} }
@Override @Override
public TAnnotation[] getAnnotations() { public TAnnotation[] getAnnotations() {
if (annotationsCache == null) { if (annotationsCache == null) {
annotationsCache = (TAnnotation[])Platform.getAnnotations(getPlatformClass()); annotationsCache = (TAnnotation[]) Platform.getAnnotations(getPlatformClass());
} }
return annotationsCache.clone(); return annotationsCache.clone();
} }
@ -263,7 +263,7 @@ public class TClass<T> extends TObject implements TAnnotatedElement {
} }
annotationsByType = new HashMap<>(); annotationsByType = new HashMap<>();
for (TAnnotation annot : getAnnotations()) { for (TAnnotation annot : getAnnotations()) {
annotationsByType.put((TClass<?>)(Object)annot.annotationType(), annot); annotationsByType.put((TClass<?>) (Object) annot.annotationType(), annot);
} }
} }
} }

View File

@ -23,7 +23,7 @@ import org.teavm.platform.Platform;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
class TConsoleOutputStream_stderr extends TOutputStream { class TConsoleOutputStreamStderr extends TOutputStream {
@Override @Override
public void write(int b) throws TIOException { public void write(int b) throws TIOException {
Platform.getConsole().error(b); Platform.getConsole().error(b);

View File

@ -23,7 +23,7 @@ import org.teavm.platform.Platform;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
class TConsoleOutputStream_stdout extends TOutputStream { class TConsoleOutputStreamStdout extends TOutputStream {
@Override @Override
public void write(int b) throws TIOException { public void write(int b) throws TIOException {
Platform.getConsole().output(b); Platform.getConsole().output(b);

View File

@ -50,17 +50,17 @@ public class TDouble extends TNumber implements TComparable<TDouble> {
@Override @Override
public int intValue() { public int intValue() {
return (int)value; return (int) value;
} }
@Override @Override
public long longValue() { public long longValue() {
return (long)value; return (long) value;
} }
@Override @Override
public float floatValue() { public float floatValue() {
return (float)value; return (float) value;
} }
public static TDouble valueOf(double d) { public static TDouble valueOf(double d) {
@ -198,13 +198,13 @@ public class TDouble extends TNumber implements TComparable<TDouble> {
if (this == other) { if (this == other) {
return true; return true;
} }
return other instanceof TDouble && ((TDouble)other).value == value; return other instanceof TDouble && ((TDouble) other).value == value;
} }
@Override @Override
public int hashCode() { public int hashCode() {
long h = doubleToLongBits(value); long h = doubleToLongBits(value);
return (int)(h >>> 32) ^ ((int)h | 0); return (int) (h >>> 32) ^ ((int) h | 0);
} }
public static int compare(double a, double b) { public static int compare(double a, double b) {
@ -258,7 +258,7 @@ public class TDouble extends TNumber implements TComparable<TDouble> {
} else { } else {
doubleMantissa = abs * 0x1p1022 * binaryExponent(negExp - 1022); doubleMantissa = abs * 0x1p1022 * binaryExponent(negExp - 1022);
} }
long mantissa = (long)(doubleMantissa + 0.5) & 0xFFFFFFFFFFFFFL; long mantissa = (long) (doubleMantissa + 0.5) & 0xFFFFFFFFFFFFFL;
return mantissa | ((exp + 1023L) << 52) | (value < 0 || 1 / value == NEGATIVE_INFINITY ? (1L << 63) : 0); return mantissa | ((exp + 1023L) << 52) | (value < 0 || 1 / value == NEGATIVE_INFINITY ? (1L << 63) : 0);
} }
@ -273,12 +273,12 @@ public class TDouble extends TNumber implements TComparable<TDouble> {
} }
} }
boolean negative = (bits & (1L << 63)) != 0; boolean negative = (bits & (1L << 63)) != 0;
int rawExp = (int)((bits >> 52) & 0x7FFL); int rawExp = (int) ((bits >> 52) & 0x7FFL);
long mantissa = bits & 0xFFFFFFFFFFFFFL; long mantissa = bits & 0xFFFFFFFFFFFFFL;
if (rawExp == 0) { if (rawExp == 0) {
mantissa <<= 1; mantissa <<= 1;
} else { } else {
mantissa |= (1L << 52); mantissa |= 1L << 52;
} }
double value = mantissa * binaryExponent(rawExp - 1023 - 52); double value = mantissa * binaryExponent(rawExp - 1023 - 52);
return !negative ? value : -value; return !negative ? value : -value;
@ -294,14 +294,14 @@ public class TDouble extends TNumber implements TComparable<TDouble> {
int sz = 0; int sz = 0;
long bits = doubleToLongBits(d); long bits = doubleToLongBits(d);
boolean subNormal = false; boolean subNormal = false;
int exp = (int)((bits >>> 52) & 0x7FF) - 1023; int exp = (int) ((bits >>> 52) & 0x7FF) - 1023;
long mantissa = bits & 0xFFFFFFFFFFFFFL; long mantissa = bits & 0xFFFFFFFFFFFFFL;
if (exp == -1023) { if (exp == -1023) {
++exp; ++exp;
subNormal = true; subNormal = true;
} }
for (int i = 0; i < 13; ++i) { for (int i = 0; i < 13; ++i) {
int digit = (int)(mantissa & 0xF); int digit = (int) (mantissa & 0xF);
if (digit > 0 || sz > 0) { if (digit > 0 || sz > 0) {
buffer[sz++] = TCharacter.forDigit(digit, 16); buffer[sz++] = TCharacter.forDigit(digit, 16);
} }

View File

@ -62,15 +62,14 @@ public abstract class TEnum<E extends TEnum<E>> extends TObject implements TComp
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public final TClass<E> getDeclaringClass() { public final TClass<E> getDeclaringClass() {
return (TClass<E>)(Object)getClass(); return (TClass<E>) (Object) getClass();
} }
@Override @Override
public final int compareTo(E o) { public final int compareTo(E o) {
if (o.getDeclaringClass() != getDeclaringClass()) { if (o.getDeclaringClass() != getDeclaringClass()) {
throw new TIllegalArgumentException(TString.wrap("Can't compare " + throw new TIllegalArgumentException(TString.wrap("Can't compare "
getDeclaringClass().getName().toString() + " to " + + getDeclaringClass().getName().toString() + " to " + o.getDeclaringClass().getName().toString()));
o.getDeclaringClass().getName().toString()));
} }
return TInteger.compare(ordinal, o.ordinal()); return TInteger.compare(ordinal, o.ordinal());
} }
@ -86,7 +85,7 @@ public abstract class TEnum<E extends TEnum<E>> extends TObject implements TComp
return constant; return constant;
} }
} }
throw new TIllegalArgumentException(TString.wrap("Enum " + enumType.getName() + " does not have the " + name + throw new TIllegalArgumentException(TString.wrap("Enum " + enumType.getName() + " does not have the " + name
"constant")); + "constant"));
} }
} }

View File

@ -39,7 +39,7 @@ public class TFloat extends TNumber implements TComparable<TFloat> {
} }
public TFloat(double value) { public TFloat(double value) {
this((float)value); this((float) value);
} }
public TFloat(TString value) throws TNumberFormatException { public TFloat(TString value) throws TNumberFormatException {
@ -48,12 +48,12 @@ public class TFloat extends TNumber implements TComparable<TFloat> {
@Override @Override
public int intValue() { public int intValue() {
return (int)value; return (int) value;
} }
@Override @Override
public long longValue() { public long longValue() {
return (long)value; return (long) value;
} }
@Override @Override
@ -84,7 +84,7 @@ public class TFloat extends TNumber implements TComparable<TFloat> {
if (this == other) { if (this == other) {
return true; return true;
} }
return other instanceof TFloat && ((TFloat)other).value == value; return other instanceof TFloat && ((TFloat) other).value == value;
} }
@Override @Override
@ -260,7 +260,7 @@ public class TFloat extends TNumber implements TComparable<TFloat> {
} else { } else {
doubleMantissa = abs * 0x1p126f * binaryExponent(negExp - 126); doubleMantissa = abs * 0x1p126f * binaryExponent(negExp - 126);
} }
int mantissa = (int)(doubleMantissa + 0.5f) & 0x7FFFFF; int mantissa = (int) (doubleMantissa + 0.5f) & 0x7FFFFF;
return mantissa | ((exp + 127) << 23) | (value < 0 || 1 / value == NEGATIVE_INFINITY ? (1 << 31) : 0); return mantissa | ((exp + 127) << 23) | (value < 0 || 1 / value == NEGATIVE_INFINITY ? (1 << 31) : 0);
} }
@ -280,7 +280,7 @@ public class TFloat extends TNumber implements TComparable<TFloat> {
if (rawExp == 0) { if (rawExp == 0) {
mantissa <<= 1; mantissa <<= 1;
} else { } else {
mantissa |= (1L << 23); mantissa |= 1L << 23;
} }
float value = mantissa * binaryExponent(rawExp - 127 - 23); float value = mantissa * binaryExponent(rawExp - 127 - 23);
return !negative ? value : -value; return !negative ? value : -value;

View File

@ -86,8 +86,8 @@ public class TInteger extends TNumber implements TComparable<TInteger> {
throw new TNumberFormatException(TString.wrap("String contains invalid digits: " + s)); throw new TNumberFormatException(TString.wrap("String contains invalid digits: " + s));
} }
if (digit >= radix) { if (digit >= radix) {
throw new TNumberFormatException(TString.wrap("String contains digits out of radix " + radix + throw new TNumberFormatException(TString.wrap("String contains digits out of radix " + radix
": " + s)); + ": " + s));
} }
value = radix * value + digit; value = radix * value + digit;
if (value < 0) { if (value < 0) {
@ -164,7 +164,7 @@ public class TInteger extends TNumber implements TComparable<TInteger> {
if (this == other) { if (this == other) {
return true; return true;
} }
return other instanceof TInteger && ((TInteger)other).value == value; return other instanceof TInteger && ((TInteger) other).value == value;
} }
public static TInteger getInteger(TString nm) { public static TInteger getInteger(TString nm) {

View File

@ -65,8 +65,8 @@ public class TLong extends TNumber implements TComparable<TLong> {
throw new TNumberFormatException(TString.wrap("String contains invalid digits: " + s)); throw new TNumberFormatException(TString.wrap("String contains invalid digits: " + s));
} }
if (digit >= radix) { if (digit >= radix) {
throw new TNumberFormatException(TString.wrap("String contains digits out of radix " + radix + throw new TNumberFormatException(TString.wrap("String contains digits out of radix " + radix
": " + s)); + ": " + s));
} }
value = radix * value + digit; value = radix * value + digit;
if (value < 0) { if (value < 0) {
@ -155,7 +155,7 @@ public class TLong extends TNumber implements TComparable<TLong> {
} }
@Override @Override
public int intValue() { public int intValue() {
return (int)value; return (int) value;
} }
@Override @Override
@ -211,7 +211,7 @@ public class TLong extends TNumber implements TComparable<TLong> {
if (this == other) { if (this == other) {
return true; return true;
} }
return other instanceof TLong && ((TLong)other).value == value; return other instanceof TLong && ((TLong) other).value == value;
} }
@GeneratedBy(LongNativeGenerator.class) @GeneratedBy(LongNativeGenerator.class)
@ -315,7 +315,7 @@ public class TLong extends TNumber implements TComparable<TLong> {
i = ((i & 0x0700070007000700L) >> 8) + (i & 0x0007000700070007L); i = ((i & 0x0700070007000700L) >> 8) + (i & 0x0007000700070007L);
i = ((i & 0x000F0000000F0000L) >> 16) + (i & 0x0000000F0000000FL); i = ((i & 0x000F0000000F0000L) >> 16) + (i & 0x0000000F0000000FL);
i = ((i & 0x0000001F00000000L) >> 32) + (i & 0x000000000000001FL); i = ((i & 0x0000001F00000000L) >> 32) + (i & 0x000000000000001FL);
return (int)i; return (int) i;
} }
public static long rotateLeft(long i, int distance) { public static long rotateLeft(long i, int distance) {
@ -346,6 +346,6 @@ public class TLong extends TNumber implements TComparable<TLong> {
} }
public static int signum(long i) { public static int signum(long i) {
return (int)((i >> 63) | (-i >>> 63)); return (int) ((i >> 63) | (-i >>> 63));
} }
} }

View File

@ -22,8 +22,8 @@ import org.teavm.javascript.spi.GeneratedBy;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public final class TMath extends TObject { public final class TMath extends TObject {
public static double E = 2.71828182845904523536; public static final double E = 2.71828182845904523536;
public static double PI = 3.14159265358979323846; public static final double PI = 3.14159265358979323846;
private TMath() { private TMath() {
} }
@ -72,7 +72,7 @@ public final class TMath extends TObject {
} }
public static double IEEEremainder(double f1, double f2) { public static double IEEEremainder(double f1, double f2) {
int n = (int)(f1 / f2); int n = (int) (f1 / f2);
return f1 - n * f2; return f1 - n * f2;
} }
@ -93,11 +93,11 @@ public final class TMath extends TObject {
public static native double atan2(double y, double x); public static native double atan2(double y, double x);
public static int round(float a) { public static int round(float a) {
return (int)(a + signum(a) * 0.5f); return (int) (a + signum(a) * 0.5f);
} }
public static long round(double a) { public static long round(double a) {
return (long)(a + signum(a) * 0.5); return (long) (a + signum(a) * 0.5);
} }
@GeneratedBy(MathNativeGenerator.class) @GeneratedBy(MathNativeGenerator.class)
@ -156,7 +156,7 @@ public final class TMath extends TObject {
} }
public static float ulp(float d) { public static float ulp(float d) {
return (float)pow(2, getExponent(d) - 23); return (float) pow(2, getExponent(d) - 23);
} }
public static double signum(double d) { public static double signum(double d) {

View File

@ -31,10 +31,10 @@ public abstract class TNumber extends TObject implements TSerializable {
public abstract double doubleValue(); public abstract double doubleValue();
public byte byteValue() { public byte byteValue() {
return (byte)intValue(); return (byte) intValue();
} }
public short shortValue() { public short shortValue() {
return (short)intValue(); return (short) intValue();
} }
} }

View File

@ -238,7 +238,7 @@ public class TObject {
} }
@Rename("wait") @Rename("wait")
public final void wait0(long timeout) throws TInterruptedException{ public final void wait0(long timeout) throws TInterruptedException {
try { try {
wait(timeout, 0); wait(timeout, 0);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
@ -247,7 +247,7 @@ public class TObject {
} }
@Rename("wait") @Rename("wait")
private final void wait0(long timeout, int nanos) throws TInterruptedException { private void wait0(long timeout, int nanos) throws TInterruptedException {
if (!holdsLock(this)) { if (!holdsLock(this)) {
throw new TIllegalMonitorStateException(); throw new TIllegalMonitorStateException();
} }
@ -255,14 +255,14 @@ public class TObject {
} }
@Async @Async
private native final void waitImpl(long timeout, int nanos) throws TInterruptedException; private native void waitImpl(long timeout, int nanos) throws TInterruptedException;
public final void waitImpl(long timeout, int nanos, final AsyncCallback<Void> callback) { public final void waitImpl(long timeout, int nanos, final AsyncCallback<Void> callback) {
final NotifyListenerImpl listener = new NotifyListenerImpl(this, callback, monitor.count); final NotifyListenerImpl listener = new NotifyListenerImpl(this, callback, monitor.count);
monitor.notifyListeners.add(listener); monitor.notifyListeners.add(listener);
if (timeout > 0 || nanos > 0) { if (timeout > 0 || nanos > 0) {
listener.timerId = Platform.schedule(listener, timeout >= Integer.MAX_VALUE ? Integer.MAX_VALUE : listener.timerId = Platform.schedule(listener, timeout >= Integer.MAX_VALUE ? Integer.MAX_VALUE
(int)timeout); : (int) timeout);
} }
monitorExit(this, monitor.count); monitorExit(this, monitor.count);
} }
@ -332,7 +332,7 @@ public class TObject {
@Rename("wait") @Rename("wait")
public final void wait0() throws TInterruptedException { public final void wait0() throws TInterruptedException {
try { try {
wait(0l); wait(0L);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
throw new TInterruptedException(); throw new TInterruptedException();
} }
@ -343,6 +343,6 @@ public class TObject {
} }
public static TObject wrap(Object obj) { public static TObject wrap(Object obj) {
return (TObject)obj; return (TObject) obj;
} }
} }

View File

@ -1,17 +1,17 @@
/* /*
* Copyright 2015 Steve Hannah. * Copyright 2013 Steve Hannah.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.lang; package org.teavm.classlib.java.lang;
@ -35,7 +35,7 @@ public class TRuntime {
* Returns the amount of free memory in the system. Calling the gc method * Returns the amount of free memory in the system. Calling the gc method
* may result in increasing the value returned by freeMemory. * may result in increasing the value returned by freeMemory.
*/ */
public long freeMemory(){ public long freeMemory() {
return Integer.MAX_VALUE; return Integer.MAX_VALUE;
} }

View File

@ -74,7 +74,7 @@ public class TShort extends TNumber implements TComparable<TShort> {
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
return other instanceof TShort && ((TShort)other).value == value; return other instanceof TShort && ((TShort) other).value == value;
} }
@Override @Override
@ -96,7 +96,7 @@ public class TShort extends TNumber implements TComparable<TShort> {
if (value < MIN_VALUE || value > MAX_VALUE) { if (value < MIN_VALUE || value > MAX_VALUE) {
throw new TNumberFormatException(); throw new TNumberFormatException();
} }
return (short)value; return (short) value;
} }
public static short parseShort(TString s) throws TNumberFormatException { public static short parseShort(TString s) throws TNumberFormatException {
@ -116,10 +116,10 @@ public class TShort extends TNumber implements TComparable<TShort> {
if (value < MIN_VALUE || value > MAX_VALUE) { if (value < MIN_VALUE || value > MAX_VALUE) {
throw new TNumberFormatException(); throw new TNumberFormatException();
} }
return valueOf((short)value); return valueOf((short) value);
} }
public static short reverseBytes(short i) { public static short reverseBytes(short i) {
return (short)((i << 8) | (i >>> 8)); return (short) ((i << 8) | (i >>> 8));
} }
} }

View File

@ -72,11 +72,11 @@ public final class TStackTraceElement extends TObject implements TSerializable {
if (!(obj instanceof TStackTraceElement)) { if (!(obj instanceof TStackTraceElement)) {
return false; return false;
} }
TStackTraceElement other = (TStackTraceElement)obj; TStackTraceElement other = (TStackTraceElement) obj;
return TObjects.equals(declaringClass, other.declaringClass) && return TObjects.equals(declaringClass, other.declaringClass)
TObjects.equals(methodName, other.methodName) && && TObjects.equals(methodName, other.methodName)
TObjects.equals(fileName, other.fileName) && && TObjects.equals(fileName, other.fileName)
lineNumber == other.lineNumber; && lineNumber == other.lineNumber;
} }
@Override @Override

View File

@ -20,8 +20,8 @@ package org.teavm.classlib.java.lang;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public final class TStrictMath extends TObject { public final class TStrictMath extends TObject {
public static double E = 2.71828182845904523536; public static final double E = 2.71828182845904523536;
public static double PI = 3.14159265358979323846; public static final double PI = 3.14159265358979323846;
private TStrictMath() { private TStrictMath() {
} }

View File

@ -96,7 +96,7 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
characters[charCount++] = TCharacter.highSurrogate(codePoint); characters[charCount++] = TCharacter.highSurrogate(codePoint);
characters[charCount++] = TCharacter.lowSurrogate(codePoint); characters[charCount++] = TCharacter.lowSurrogate(codePoint);
} else { } else {
characters[charCount++] = (char)codePoint; characters[charCount++] = (char) codePoint;
} }
} }
if (charCount < characters.length) { if (charCount < characters.length) {
@ -152,8 +152,8 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
} }
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
if (srcBegin < 0 || srcBegin > srcEnd || srcEnd > length() || dstBegin < 0 || if (srcBegin < 0 || srcBegin > srcEnd || srcEnd > length() || dstBegin < 0
dstBegin + (srcEnd - srcBegin) > dst.length) { || dstBegin + (srcEnd - srcBegin) > dst.length) {
throw new TIndexOutOfBoundsException(); throw new TIndexOutOfBoundsException();
} }
while (srcBegin < srcEnd) { while (srcBegin < srcEnd) {
@ -286,7 +286,7 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
public int indexOf(int ch, int fromIndex) { public int indexOf(int ch, int fromIndex) {
if (ch < TCharacter.MIN_SUPPLEMENTARY_CODE_POINT) { if (ch < TCharacter.MIN_SUPPLEMENTARY_CODE_POINT) {
char bmpChar = (char)ch; char bmpChar = (char) ch;
for (int i = fromIndex; i < characters.length; ++i) { for (int i = fromIndex; i < characters.length; ++i) {
if (characters[i] == bmpChar) { if (characters[i] == bmpChar) {
return i; return i;
@ -311,7 +311,7 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
public int lastIndexOf(int ch, int fromIndex) { public int lastIndexOf(int ch, int fromIndex) {
if (ch < TCharacter.MIN_SUPPLEMENTARY_CODE_POINT) { if (ch < TCharacter.MIN_SUPPLEMENTARY_CODE_POINT) {
char bmpChar = (char)ch; char bmpChar = (char) ch;
for (int i = fromIndex; i >= 0; --i) { for (int i = fromIndex; i >= 0; --i) {
if (characters[i] == bmpChar) { if (characters[i] == bmpChar) {
return i; return i;
@ -458,7 +458,7 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
@Override @Override
public String toString() { public String toString() {
return (String)(Object)this; return (String) (Object) this;
} }
public char[] toCharArray() { public char[] toCharArray() {
@ -521,7 +521,7 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
if (!(other instanceof TString)) { if (!(other instanceof TString)) {
return false; return false;
} }
TString str = (TString)other; TString str = (TString) other;
if (str.length() != length()) { if (str.length() != length()) {
return false; return false;
} }
@ -581,7 +581,7 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
} }
public static TString wrap(String str) { public static TString wrap(String str) {
return (TString)(Object)str; return (TString) (Object) str;
} }
public TString toLowerCase() { public TString toLowerCase() {
@ -591,8 +591,8 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
int[] codePoints = new int[characters.length]; int[] codePoints = new int[characters.length];
int codePointCount = 0; int codePointCount = 0;
for (int i = 0; i < characters.length; ++i) { for (int i = 0; i < characters.length; ++i) {
if (i == characters.length - 1 || !TCharacter.isHighSurrogate(characters[i]) || if (i == characters.length - 1 || !TCharacter.isHighSurrogate(characters[i])
!TCharacter.isLowSurrogate(characters[i + 1])) { || !TCharacter.isLowSurrogate(characters[i + 1])) {
codePoints[codePointCount++] = TCharacter.toLowerCase(characters[i]); codePoints[codePointCount++] = TCharacter.toLowerCase(characters[i]);
} else { } else {
codePoints[codePointCount++] = TCharacter.toLowerCase(TCharacter.toCodePoint( codePoints[codePointCount++] = TCharacter.toLowerCase(TCharacter.toCodePoint(
@ -610,8 +610,8 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
int[] codePoints = new int[characters.length]; int[] codePoints = new int[characters.length];
int codePointCount = 0; int codePointCount = 0;
for (int i = 0; i < characters.length; ++i) { for (int i = 0; i < characters.length; ++i) {
if (i == characters.length - 1 || !TCharacter.isHighSurrogate(characters[i]) || if (i == characters.length - 1 || !TCharacter.isHighSurrogate(characters[i])
!TCharacter.isLowSurrogate(characters[i + 1])) { || !TCharacter.isLowSurrogate(characters[i + 1])) {
codePoints[codePointCount++] = TCharacter.toUpperCase(characters[i]); codePoints[codePointCount++] = TCharacter.toUpperCase(characters[i]);
} else { } else {
codePoints[codePointCount++] = TCharacter.toUpperCase(TCharacter.toCodePoint( codePoints[codePointCount++] = TCharacter.toUpperCase(TCharacter.toCodePoint(

View File

@ -26,8 +26,8 @@ import org.teavm.javascript.spi.GeneratedBy;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public final class TSystem extends TObject { public final class TSystem extends TObject {
public static final TPrintStream out = new TPrintStream(new TConsoleOutputStream_stdout(), false); public static final TPrintStream out = new TPrintStream(new TConsoleOutputStreamStdout(), false);
public static final TPrintStream err = new TPrintStream(new TConsoleOutputStream_stderr(), false); public static final TPrintStream err = new TPrintStream(new TConsoleOutputStreamStderr(), false);
private TSystem() { private TSystem() {
} }
@ -40,8 +40,8 @@ public final class TSystem extends TObject {
if (src == null || dest == null) { if (src == null || dest == null) {
throw new TNullPointerException(TString.wrap("Either src or dest is null")); throw new TNullPointerException(TString.wrap("Either src or dest is null"));
} }
if (srcPos < 0 || destPos < 0 || length < 0 || srcPos + length > TArray.getLength(src) || if (srcPos < 0 || destPos < 0 || length < 0 || srcPos + length > TArray.getLength(src)
destPos + length > TArray.getLength(dest)) { || destPos + length > TArray.getLength(dest)) {
throw new TIndexOutOfBoundsException(); throw new TIndexOutOfBoundsException();
} }
if (src != dest) { if (src != dest) {
@ -52,7 +52,7 @@ public final class TSystem extends TObject {
} }
if (srcType != targetType) { if (srcType != targetType) {
if (!srcType.isPrimitive() && !targetType.isPrimitive()) { if (!srcType.isPrimitive() && !targetType.isPrimitive()) {
Object[] srcArray = (Object[])(Object)src; Object[] srcArray = (Object[]) (Object) src;
int pos = srcPos; int pos = srcPos;
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
Object elem = srcArray[pos++]; Object elem = srcArray[pos++];
@ -108,7 +108,7 @@ public final class TSystem extends TObject {
} }
public static int identityHashCode(Object x) { public static int identityHashCode(Object x) {
return ((TObject)x).identity(); return ((TObject) x).identity();
} }
public static TString lineSeparator() { public static TString lineSeparator() {

View File

@ -27,13 +27,13 @@ import org.teavm.platform.async.AsyncCallback;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class TThread extends TObject implements TRunnable { public class TThread extends TObject implements TRunnable {
private static Window window = (Window)JS.getGlobal(); private static Window window = (Window) JS.getGlobal();
private static TThread mainThread = new TThread(TString.wrap("main")); private static TThread mainThread = new TThread(TString.wrap("main"));
private static TThread currentThread = mainThread; private static TThread currentThread = mainThread;
private static long nextId = 1; private static long nextId = 1;
private static int activeCount = 1; private static int activeCount = 1;
private long id; private long id;
private int priority = 0; private int priority;
private long timeSliceStart; private long timeSliceStart;
private int yieldCount; private int yieldCount;
private final Object finishedLock = new Object(); private final Object finishedLock = new Object();
@ -52,10 +52,10 @@ public class TThread extends TObject implements TRunnable {
} }
public TThread(TRunnable target) { public TThread(TRunnable target) {
this(target, null ); this(target, null);
} }
public TThread(TRunnable target, TString name ) { public TThread(TRunnable target, TString name) {
this.name = name; this.name = name;
this.target = target; this.target = target;
id = nextId++; id = nextId++;
@ -84,7 +84,7 @@ public class TThread extends TObject implements TRunnable {
currentThread.timeSliceStart = System.currentTimeMillis(); currentThread.timeSliceStart = System.currentTimeMillis();
} }
static TThread getMainThread(){ static TThread getMainThread() {
return mainThread; return mainThread;
} }
@ -93,7 +93,7 @@ public class TThread extends TObject implements TRunnable {
if (target != null) { if (target != null) {
target.run(); target.run();
} }
synchronized(finishedLock) { synchronized (finishedLock) {
finishedLock.notifyAll(); finishedLock.notifyAll();
} }
} }
@ -182,7 +182,7 @@ public class TThread extends TObject implements TRunnable {
private static void sleep(long millis, final AsyncCallback<Void> callback) { private static void sleep(long millis, final AsyncCallback<Void> callback) {
final TThread current = currentThread(); final TThread current = currentThread();
int intMillis = millis < Integer.MAX_VALUE ? (int)millis : Integer.MAX_VALUE; int intMillis = millis < Integer.MAX_VALUE ? (int) millis : Integer.MAX_VALUE;
SleepHandler handler = new SleepHandler(current, callback); SleepHandler handler = new SleepHandler(current, callback);
handler.scheduleId = Platform.schedule(handler, intMillis); handler.scheduleId = Platform.schedule(handler, intMillis);
current.interruptHandler = handler; current.interruptHandler = handler;
@ -221,11 +221,11 @@ public class TThread extends TObject implements TRunnable {
} }
} }
public final void setPriority(int newPriority){ public final void setPriority(int newPriority) {
this.priority = newPriority; this.priority = newPriority;
} }
public final int getPriority(){ public final int getPriority() {
return this.priority; return this.priority;
} }

View File

@ -134,18 +134,18 @@ public class AnnotationDependencyListener extends AbstractDependencyListener {
public void methodReached(DependencyAgent agent, MethodDependency method, CallLocation location) { public void methodReached(DependencyAgent agent, MethodDependency method, CallLocation location) {
ValueType type = method.getMethod().getResultType(); ValueType type = method.getMethod().getResultType();
while (type instanceof ValueType.Array) { while (type instanceof ValueType.Array) {
type = ((ValueType.Array)type).getItemType(); type = ((ValueType.Array) type).getItemType();
} }
if (type instanceof ValueType.Object) { if (type instanceof ValueType.Object) {
String className = ((ValueType.Object)type).getClassName(); String className = ((ValueType.Object) type).getClassName();
ClassReader cls = agent.getClassSource().get(className); ClassReader cls = agent.getClassSource().get(className);
if (cls != null && cls.hasModifier(ElementModifier.ANNOTATION)) { if (cls != null && cls.hasModifier(ElementModifier.ANNOTATION)) {
agent.linkClass(className, location); agent.linkClass(className, location);
} }
} }
if (method.getMethod().hasModifier(ElementModifier.STATIC) && if (method.getMethod().hasModifier(ElementModifier.STATIC)
method.getMethod().getName().equals("$$__readAnnotations__$$")) { && method.getMethod().getName().equals("$$__readAnnotations__$$")) {
ClassReader cls = agent.getClassSource().get(method.getReference().getClassName()); ClassReader cls = agent.getClassSource().get(method.getReference().getClassName());
if (cls != null) { if (cls != null) {
for (AnnotationReader annotation : cls.getAnnotations().all()) { for (AnnotationReader annotation : cls.getAnnotations().all()) {
@ -259,7 +259,7 @@ public class AnnotationDependencyListener extends AbstractDependencyListener {
return pe.constant(value.getString()); return pe.constant(value.getString());
case AnnotationValue.LIST: { case AnnotationValue.LIST: {
List<AnnotationValue> list = value.getList(); List<AnnotationValue> list = value.getList();
ValueType itemType = ((ValueType.Array)type).getItemType(); ValueType itemType = ((ValueType.Array) type).getItemType();
ValueEmitter array = pe.constructArray(itemType, list.size()); ValueEmitter array = pe.constructArray(itemType, list.size());
for (int i = 0; i < list.size(); ++i) { for (int i = 0; i < list.size(); ++i) {
array.unwrapArray(ArrayElementType.OBJECT).setElement(i, array.unwrapArray(ArrayElementType.OBJECT).setElement(i,

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,11 +13,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
import java.util.Random;
import java.io.Serializable; import java.io.Serializable;
import java.util.Random;
/** /**
* This class represents immutable integer numbers of arbitrary length. Large * This class represents immutable integer numbers of arbitrary length. Large
@ -49,7 +47,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* is represented as [ Integer.MIN_VALUE ] The magnitude array may be longer * is represented as [ Integer.MIN_VALUE ] The magnitude array may be longer
* than strictly necessary, which results in additional trailing zeros. * than strictly necessary, which results in additional trailing zeros.
*/ */
transient int digits[]; transient int[] digits;
/** /**
* The length of this in measured in ints. Can be less than digits.length(). * The length of this in measured in ints. Can be less than digits.length().
@ -103,7 +101,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
private transient int firstNonzeroDigit = -2; private transient int firstNonzeroDigit = -2;
/** Cache for the hash code. */ /** Cache for the hash code. */
private transient int hashCode = 0; private transient int hashCode;
/** /**
* Constructs a random non-negative {@code BigInteger} instance in the range * Constructs a random non-negative {@code BigInteger} instance in the range
@ -325,10 +323,10 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
if ((val & 0xFFFFFFFF00000000L) == 0) { if ((val & 0xFFFFFFFF00000000L) == 0) {
// It fits in one 'int' // It fits in one 'int'
numberLength = 1; numberLength = 1;
digits = new int[] { (int)val }; digits = new int[] { (int) val };
} else { } else {
numberLength = 2; numberLength = 2;
digits = new int[] { (int)val, (int)(val >> 32) }; digits = new int[] { (int) val, (int) (val >> 32) };
} }
} }
@ -342,7 +340,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* @param digits * @param digits
* The magnitude of the number * The magnitude of the number
*/ */
TBigInteger(int signum, int digits[]) { TBigInteger(int signum, int[] digits) {
if (digits.length == 0) { if (digits.length == 0) {
sign = 0; sign = 0;
numberLength = 1; numberLength = 1;
@ -362,8 +360,9 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
} }
return MINUS_ONE; return MINUS_ONE;
} else if (val <= 10) { } else if (val <= 10) {
return SMALL_VALUES[(int)val]; return SMALL_VALUES[(int) val];
} else {// (val > 10) } else {
// (val > 10)
return new TBigInteger(1, val); return new TBigInteger(1, val);
} }
} }
@ -395,7 +394,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
int hB; int hB;
if (bytesLen - (numberLength << 2) == 1) { if (bytesLen - (numberLength << 2) == 1) {
bytes[0] = (byte)((sign < 0) ? -1 : 0); bytes[0] = (byte) ((sign < 0) ? -1 : 0);
highBytes = 4; highBytes = 4;
firstByteNumber++; firstByteNumber++;
} else { } else {
@ -413,7 +412,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
bytesInInteger = highBytes; bytesInInteger = highBytes;
} }
for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
bytes[--bytesLen] = (byte)digit; bytes[--bytesLen] = (byte) digit;
} }
while (bytesLen > firstByteNumber) { while (bytesLen > firstByteNumber) {
digit = ~temp.digits[digitIndex]; digit = ~temp.digits[digitIndex];
@ -422,7 +421,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
bytesInInteger = highBytes; bytesInInteger = highBytes;
} }
for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
bytes[--bytesLen] = (byte)digit; bytes[--bytesLen] = (byte) digit;
} }
} }
} else { } else {
@ -433,7 +432,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
bytesInInteger = highBytes; bytesInInteger = highBytes;
} }
for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
bytes[--bytesLen] = (byte)digit; bytes[--bytesLen] = (byte) digit;
} }
} }
} }
@ -480,8 +479,8 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
int substrEnd = startChar + ((topChars == 0) ? charsPerInt : topChars); int substrEnd = startChar + ((topChars == 0) ? charsPerInt : topChars);
int newDigit; int newDigit;
for (int substrStart = startChar; substrStart < endChar; substrStart = substrEnd, substrEnd = substrStart + for (int substrStart = startChar; substrStart < endChar; substrStart = substrEnd, substrEnd = substrStart
charsPerInt) { + charsPerInt) {
int bigRadixDigit = Integer.parseInt(val.substring(substrStart, substrEnd), radix); int bigRadixDigit = Integer.parseInt(val.substring(substrStart, substrEnd), radix);
newDigit = TMultiplication.multiplyByInt(digits, digitIndex, bigRadix); newDigit = TMultiplication.multiplyByInt(digits, digitIndex, bigRadix);
newDigit += TElementary.inplaceAdd(digits, digitIndex, bigRadixDigit); newDigit += TElementary.inplaceAdd(digits, digitIndex, bigRadixDigit);
@ -501,7 +500,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* @return {@code abs(this)}. * @return {@code abs(this)}.
*/ */
public TBigInteger abs() { public TBigInteger abs() {
return ((sign < 0) ? new TBigInteger(1, numberLength, digits) : this); return sign < 0 ? new TBigInteger(1, numberLength, digits) : this;
} }
/** /**
@ -510,7 +509,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* @return {@code -this}. * @return {@code -this}.
*/ */
public TBigInteger negate() { public TBigInteger negate() {
return ((sign == 0) ? this : new TBigInteger(-sign, numberLength, digits)); return sign == 0 ? this : new TBigInteger(-sign, numberLength, digits);
} }
/** /**
@ -566,7 +565,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
if ((n == 0) || (sign == 0)) { if ((n == 0) || (sign == 0)) {
return this; return this;
} }
return ((n > 0) ? TBitLevel.shiftRight(this, n) : TBitLevel.shiftLeft(this, -n)); return n > 0 ? TBitLevel.shiftRight(this, n) : TBitLevel.shiftLeft(this, -n);
} }
/** /**
@ -584,10 +583,10 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* otherwise * otherwise
*/ */
public TBigInteger shiftLeft(int n) { public TBigInteger shiftLeft(int n) {
if ((n == 0) || (sign == 0)) { if (n == 0 || sign == 0) {
return this; return this;
} }
return ((n > 0) ? TBitLevel.shiftLeft(this, n) : TBitLevel.shiftRight(this, -n)); return n > 0 ? TBitLevel.shiftLeft(this, n) : TBitLevel.shiftRight(this, -n);
} }
TBigInteger shiftLeftOneBit() { TBigInteger shiftLeftOneBit() {
@ -627,17 +626,17 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
*/ */
public boolean testBit(int n) { public boolean testBit(int n) {
if (n == 0) { if (n == 0) {
return ((digits[0] & 1) != 0); return (digits[0] & 1) != 0;
} }
if (n < 0) { if (n < 0) {
throw new ArithmeticException("Negative bit address"); throw new ArithmeticException("Negative bit address");
} }
int intCount = n >> 5; int intCount = n >> 5;
if (intCount >= numberLength) { if (intCount >= numberLength) {
return (sign < 0); return sign < 0;
} }
int digit = digits[intCount]; int digit = digits[intCount];
n = (1 << (n & 31)); // int with 1 set to the needed position n = 1 << (n & 31); // int with 1 set to the needed position
if (sign < 0) { if (sign < 0) {
int firstNonZeroDigit = getFirstNonzeroDigit(); int firstNonZeroDigit = getFirstNonzeroDigit();
if (intCount < firstNonZeroDigit) { if (intCount < firstNonZeroDigit) {
@ -648,7 +647,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
digit = ~digit; digit = ~digit;
} }
} }
return ((digit & n) != 0); return (digit & n) != 0;
} }
/** /**
@ -730,7 +729,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
} }
// (sign != 0) implies that exists some non zero digit // (sign != 0) implies that exists some non zero digit
int i = getFirstNonzeroDigit(); int i = getFirstNonzeroDigit();
return ((i << 5) + Integer.numberOfTrailingZeros(digits[i])); return i << 5 + Integer.numberOfTrailingZeros(digits[i]);
} }
/** /**
@ -840,7 +839,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
*/ */
@Override @Override
public int intValue() { public int intValue() {
return (sign * digits[0]); return sign * digits[0];
} }
/** /**
@ -851,9 +850,9 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
*/ */
@Override @Override
public long longValue() { public long longValue() {
long value = (numberLength > 1) ? (((long)digits[1]) << 32) | (digits[0] & 0xFFFFFFFFL) long value = (numberLength > 1) ? (((long) digits[1]) << 32) | (digits[0] & 0xFFFFFFFFL)
: (digits[0] & 0xFFFFFFFFL); : (digits[0] & 0xFFFFFFFFL);
return (sign * value); return sign * value;
} }
/** /**
@ -868,7 +867,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
*/ */
@Override @Override
public float floatValue() { public float floatValue() {
return (float)doubleValue(); return (float) doubleValue();
} }
/** /**
@ -913,7 +912,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
return -val.sign; return -val.sign;
} }
// Equal sign and equal numberLength // Equal sign and equal numberLength
return (sign * TElementary.compareArrays(digits, val.digits, numberLength)); return sign * TElementary.compareArrays(digits, val.digits, numberLength);
} }
/** /**
@ -926,7 +925,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* if {@code val == null}. * if {@code val == null}.
*/ */
public TBigInteger min(TBigInteger val) { public TBigInteger min(TBigInteger val) {
return ((this.compareTo(val) == LESS) ? this : val); return (this.compareTo(val) == LESS) ? this : val;
} }
/** /**
@ -939,7 +938,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
* if {@code val == null} * if {@code val == null}
*/ */
public TBigInteger max(TBigInteger val) { public TBigInteger max(TBigInteger val) {
return ((this.compareTo(val) == GREATER) ? this : val); return this.compareTo(val) == GREATER ? this : val;
} }
/** /**
@ -953,7 +952,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
return hashCode; return hashCode;
} }
for (int i = 0; i < digits.length; i++) { for (int i = 0; i < digits.length; i++) {
hashCode = (hashCode * 33 + (digits[i] & 0xffffffff)); hashCode = hashCode * 33 + (digits[i] & 0xffffffff);
} }
hashCode = hashCode * sign; hashCode = hashCode * sign;
return hashCode; return hashCode;
@ -974,7 +973,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
return true; return true;
} }
if (x instanceof TBigInteger) { if (x instanceof TBigInteger) {
TBigInteger x1 = (TBigInteger)x; TBigInteger x1 = (TBigInteger) x;
return sign == x1.sign && numberLength == x1.numberLength && equalsArrays(x1.digits); return sign == x1.sign && numberLength == x1.numberLength && equalsArrays(x1.digits);
} }
return false; return false;
@ -1038,8 +1037,8 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
// Optimization for small operands // Optimization for small operands
// (op2.bitLength() < 64) and (op1.bitLength() < 64) // (op2.bitLength() < 64) and (op1.bitLength() < 64)
if (((val1.numberLength == 1) || ((val1.numberLength == 2) && (val1.digits[1] > 0))) && if (((val1.numberLength == 1) || ((val1.numberLength == 2) && (val1.digits[1] > 0)))
(val2.numberLength == 1 || (val2.numberLength == 2 && val2.digits[1] > 0))) { && (val2.numberLength == 1 || (val2.numberLength == 2 && val2.digits[1] > 0))) {
return TBigInteger.valueOf(TDivision.gcdBinary(val1.longValue(), val2.longValue())); return TBigInteger.valueOf(TDivision.gcdBinary(val1.longValue(), val2.longValue()));
} }
@ -1133,9 +1132,9 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
int thisSign = sign; int thisSign = sign;
int quotientLength = thisLen - divisorLen + 1; int quotientLength = thisLen - divisorLen + 1;
int remainderLength = divisorLen; int remainderLength = divisorLen;
int quotientSign = ((thisSign == divisorSign) ? 1 : -1); int quotientSign = thisSign == divisorSign ? 1 : -1;
int quotientDigits[] = new int[quotientLength]; int[] quotientDigits = new int[quotientLength];
int remainderDigits[] = TDivision.divide(quotientDigits, quotientLength, thisDigits, thisLen, divisorDigits, int[] remainderDigits = TDivision.divide(quotientDigits, quotientLength, thisDigits, thisLen, divisorDigits,
divisorLen); divisorLen);
TBigInteger result0 = new TBigInteger(quotientSign, quotientLength, quotientDigits); TBigInteger result0 = new TBigInteger(quotientSign, quotientLength, quotientDigits);
TBigInteger result1 = new TBigInteger(thisSign, remainderLength, remainderDigits); TBigInteger result1 = new TBigInteger(thisSign, remainderLength, remainderDigits);
@ -1161,7 +1160,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
} }
int divisorSign = divisor.sign; int divisorSign = divisor.sign;
if (divisor.isOne()) { if (divisor.isOne()) {
return ((divisor.sign > 0) ? this : this.negate()); return divisor.sign > 0 ? this : this.negate();
} }
int thisSign = sign; int thisSign = sign;
int thisLen = numberLength; int thisLen = numberLength;
@ -1173,17 +1172,17 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
} }
return valueOf(val); return valueOf(val);
} }
int cmp = ((thisLen != divisorLen) ? ((thisLen > divisorLen) ? 1 : -1) : TElementary.compareArrays(digits, int cmp = thisLen != divisorLen ? (thisLen > divisorLen ? 1 : -1) : TElementary.compareArrays(digits,
divisor.digits, thisLen)); divisor.digits, thisLen);
if (cmp == EQUALS) { if (cmp == EQUALS) {
return ((thisSign == divisorSign) ? ONE : MINUS_ONE); return thisSign == divisorSign ? ONE : MINUS_ONE;
} }
if (cmp == LESS) { if (cmp == LESS) {
return ZERO; return ZERO;
} }
int resLength = thisLen - divisorLen + 1; int resLength = thisLen - divisorLen + 1;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
int resSign = ((thisSign == divisorSign) ? 1 : -1); int resSign = thisSign == divisorSign ? 1 : -1;
if (divisorLen == 1) { if (divisorLen == 1) {
TDivision.divideArrayByInt(resDigits, digits, thisLen, divisor.digits[0]); TDivision.divideArrayByInt(resDigits, digits, thisLen, divisor.digits[0]);
} else { } else {
@ -1218,7 +1217,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
return this; return this;
} }
int resLength = divisorLen; int resLength = divisorLen;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
if (resLength == 1) { if (resLength == 1) {
resDigits[0] = TDivision.remainderArrayByInt(digits, thisLen, divisor.digits[0]); resDigits[0] = TDivision.remainderArrayByInt(digits, thisLen, divisor.digits[0]);
} else { } else {
@ -1263,7 +1262,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
throw new ArithmeticException("BigInteger not invertible."); throw new ArithmeticException("BigInteger not invertible.");
} }
res = ((sign < 0) ? m.subtract(res) : res); res = sign < 0 ? m.subtract(res) : res;
return res; return res;
} }
@ -1402,7 +1401,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
/** Tests if {@code this.abs()} is equals to {@code ONE} */ /** Tests if {@code this.abs()} is equals to {@code ONE} */
boolean isOne() { boolean isOne() {
return ((numberLength == 1) && (digits[0] == 1)); return numberLength == 1 && digits[0] == 1;
} }
/** /**
@ -1416,8 +1415,8 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
int i = 0; int i = 0;
// Put bytes to the int array starting from the end of the byte array // Put bytes to the int array starting from the end of the byte array
while (bytesLen > highBytes) { while (bytesLen > highBytes) {
digits[i++] = (byteValues[--bytesLen] & 0xFF) | (byteValues[--bytesLen] & 0xFF) << 8 | digits[i++] = (byteValues[--bytesLen] & 0xFF) | (byteValues[--bytesLen] & 0xFF) << 8
(byteValues[--bytesLen] & 0xFF) << 16 | (byteValues[--bytesLen] & 0xFF) << 24; | (byteValues[--bytesLen] & 0xFF) << 16 | (byteValues[--bytesLen] & 0xFF) << 24;
} }
// Put the first bytes in the highest element of the int array // Put the first bytes in the highest element of the int array
for (int j = 0; j < bytesLen; j++) { for (int j = 0; j < bytesLen; j++) {
@ -1439,15 +1438,15 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
digits[numberLength - 1] = -1; digits[numberLength - 1] = -1;
// Put bytes to the int array starting from the end of the byte array // Put bytes to the int array starting from the end of the byte array
while (bytesLen > highBytes) { while (bytesLen > highBytes) {
digits[i] = (byteValues[--bytesLen] & 0xFF) | (byteValues[--bytesLen] & 0xFF) << 8 | digits[i] = (byteValues[--bytesLen] & 0xFF) | (byteValues[--bytesLen] & 0xFF) << 8
(byteValues[--bytesLen] & 0xFF) << 16 | (byteValues[--bytesLen] & 0xFF) << 24; | (byteValues[--bytesLen] & 0xFF) << 16 | (byteValues[--bytesLen] & 0xFF) << 24;
if (digits[i] != 0) { if (digits[i] != 0) {
digits[i] = -digits[i]; digits[i] = -digits[i];
firstNonzeroDigit = i; firstNonzeroDigit = i;
i++; i++;
while (bytesLen > highBytes) { while (bytesLen > highBytes) {
digits[i] = (byteValues[--bytesLen] & 0xFF) | (byteValues[--bytesLen] & 0xFF) << 8 | digits[i] = (byteValues[--bytesLen] & 0xFF) | (byteValues[--bytesLen] & 0xFF) << 8
(byteValues[--bytesLen] & 0xFF) << 16 | (byteValues[--bytesLen] & 0xFF) << 24; | (byteValues[--bytesLen] & 0xFF) << 16 | (byteValues[--bytesLen] & 0xFF) << 24;
digits[i] = ~digits[i]; digits[i] = ~digits[i];
i++; i++;
} }
@ -1505,7 +1504,7 @@ public class TBigInteger extends Number implements Comparable<TBigInteger>, Seri
} }
int intCount = exp >> 5; int intCount = exp >> 5;
int bitN = exp & 31; int bitN = exp & 31;
int resDigits[] = new int[intCount + 1]; int[] resDigits = new int[intCount + 1];
resDigits[intCount] = 1 << bitN; resDigits[intCount] = 1 << bitN;
return new TBigInteger(1, intCount + 1, resDigits); return new TBigInteger(1, intCount + 1, resDigits);
} }

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**
@ -43,7 +41,7 @@ class TBitLevel {
if (val.sign == 0) { if (val.sign == 0) {
return 0; return 0;
} }
int bLength = (val.numberLength << 5); int bLength = val.numberLength << 5;
int highDigit = val.digits[val.numberLength - 1]; int highDigit = val.digits[val.numberLength - 1];
if (val.sign < 0) { if (val.sign < 0) {
@ -71,7 +69,8 @@ class TBitLevel {
for (; i < val.numberLength; i++) { for (; i < val.numberLength; i++) {
bCount += Integer.bitCount(val.digits[i]); bCount += Integer.bitCount(val.digits[i]);
} }
} else {// (sign < 0) } else {
// (sign < 0)
// this digit absorbs the carry // this digit absorbs the carry
bCount += Integer.bitCount(-val.digits[i]); bCount += Integer.bitCount(-val.digits[i]);
for (i++; i < val.numberLength; i++) { for (i++; i < val.numberLength; i++) {
@ -89,7 +88,7 @@ class TBitLevel {
*/ */
static boolean testBit(TBigInteger val, int n) { static boolean testBit(TBigInteger val, int n) {
// PRE: 0 <= n < val.bitLength() // PRE: 0 <= n < val.bitLength()
return ((val.digits[n >> 5] & (1 << (n & 31))) != 0); return (val.digits[n >> 5] & (1 << (n & 31))) != 0;
} }
/** /**
@ -99,15 +98,15 @@ class TBitLevel {
* the number of the lowest bits to check * the number of the lowest bits to check
* @return false if all bits are 0s, true otherwise * @return false if all bits are 0s, true otherwise
*/ */
static boolean nonZeroDroppedBits(int numberOfBits, int digits[]) { static boolean nonZeroDroppedBits(int numberOfBits, int[] digits) {
int intCount = numberOfBits >> 5; int intCount = numberOfBits >> 5;
int bitCount = numberOfBits & 31; int bitCount = numberOfBits & 31;
int i; int i;
for (i = 0; (i < intCount) && (digits[i] == 0); i++) { for (i = 0; i < intCount && digits[i] == 0; i++) {
// do nothing // do nothing
} }
return ((i != intCount) || (digits[i] << (32 - bitCount) != 0)); return i != intCount || digits[i] << (32 - bitCount) != 0;
} }
/** @see TBigInteger#shiftLeft(int) */ /** @see TBigInteger#shiftLeft(int) */
@ -115,7 +114,7 @@ class TBitLevel {
int intCount = count >> 5; int intCount = count >> 5;
count &= 31; // %= 32 count &= 31; // %= 32
int resLength = source.numberLength + intCount + ((count == 0) ? 0 : 1); int resLength = source.numberLength + intCount + ((count == 0) ? 0 : 1);
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
shiftLeft(resDigits, source.digits, intCount, count); shiftLeft(resDigits, source.digits, intCount, count);
TBigInteger result = new TBigInteger(source.sign, resLength, resDigits); TBigInteger result = new TBigInteger(source.sign, resLength, resDigits);
@ -129,8 +128,8 @@ class TBitLevel {
// val should have enough place (and one digit more) // val should have enough place (and one digit more)
static void inplaceShiftLeft(TBigInteger val, int count) { static void inplaceShiftLeft(TBigInteger val, int count) {
int intCount = count >> 5; // count of integers int intCount = count >> 5; // count of integers
val.numberLength += intCount + val.numberLength += intCount
(Integer.numberOfLeadingZeros(val.digits[val.numberLength - 1]) - (count & 31) >= 0 ? 0 : 1); + (Integer.numberOfLeadingZeros(val.digits[val.numberLength - 1]) - (count & 31) >= 0 ? 0 : 1);
shiftLeft(val.digits, val.digits, intCount, count & 31); shiftLeft(val.digits, val.digits, intCount, count & 31);
val.cutOffLeadingZeroes(); val.cutOffLeadingZeroes();
val.unCache(); val.unCache();
@ -149,7 +148,7 @@ class TBitLevel {
* @param count * @param count
* an additional shift distance in bits * an additional shift distance in bits
*/ */
static void shiftLeft(int result[], int source[], int intCount, int count) { static void shiftLeft(int[] result, int[] source, int intCount, int count) {
if (count == 0) { if (count == 0) {
System.arraycopy(source, 0, result, intCount, result.length - intCount); System.arraycopy(source, 0, result, intCount, result.length - intCount);
} else { } else {
@ -183,7 +182,7 @@ class TBitLevel {
* the length of {@code source}; may be less than * the length of {@code source}; may be less than
* {@code source.length} * {@code source.length}
*/ */
static void shiftLeftOneBit(int result[], int source[], int srcLen) { static void shiftLeftOneBit(int[] result, int[] source, int srcLen) {
int carry = 0; int carry = 0;
for (int i = 0; i < srcLen; i++) { for (int i = 0; i < srcLen; i++) {
int val = source[i]; int val = source[i];
@ -198,7 +197,7 @@ class TBitLevel {
static TBigInteger shiftLeftOneBit(TBigInteger source) { static TBigInteger shiftLeftOneBit(TBigInteger source) {
int srcLen = source.numberLength; int srcLen = source.numberLength;
int resLen = srcLen + 1; int resLen = srcLen + 1;
int resDigits[] = new int[resLen]; int[] resDigits = new int[resLen];
shiftLeftOneBit(resDigits, source.digits, srcLen); shiftLeftOneBit(resDigits, source.digits, srcLen);
TBigInteger result = new TBigInteger(source.sign, resLen, resDigits); TBigInteger result = new TBigInteger(source.sign, resLen, resDigits);
result.cutOffLeadingZeroes(); result.cutOffLeadingZeroes();
@ -210,11 +209,11 @@ class TBitLevel {
int intCount = count >> 5; // count of integers int intCount = count >> 5; // count of integers
count &= 31; // count of remaining bits count &= 31; // count of remaining bits
if (intCount >= source.numberLength) { if (intCount >= source.numberLength) {
return ((source.sign < 0) ? TBigInteger.MINUS_ONE : TBigInteger.ZERO); return source.sign < 0 ? TBigInteger.MINUS_ONE : TBigInteger.ZERO;
} }
int i; int i;
int resLength = source.numberLength - intCount; int resLength = source.numberLength - intCount;
int resDigits[] = new int[resLength + 1]; int[] resDigits = new int[resLength + 1];
shiftRight(resDigits, resLength, source.digits, intCount, count); shiftRight(resDigits, resLength, source.digits, intCount, count);
if (source.sign < 0) { if (source.sign < 0) {
@ -244,8 +243,9 @@ class TBitLevel {
*/ */
static void inplaceShiftRight(TBigInteger val, int count) { static void inplaceShiftRight(TBigInteger val, int count) {
int sign = val.signum(); int sign = val.signum();
if (count == 0 || val.signum() == 0) if (count == 0 || val.signum() == 0) {
return; return;
}
int intCount = count >> 5; // count of integers int intCount = count >> 5; // count of integers
val.numberLength -= intCount; val.numberLength -= intCount;
if (!shiftRight(val.digits, val.numberLength, val.digits, intCount, count & 31) && sign < 0) { if (!shiftRight(val.digits, val.numberLength, val.digits, intCount, count & 31) && sign < 0) {
@ -279,7 +279,7 @@ class TBitLevel {
* the number of bits to be shifted * the number of bits to be shifted
* @return dropped bit's are all zero (i.e. remaider is zero) * @return dropped bit's are all zero (i.e. remaider is zero)
*/ */
static boolean shiftRight(int result[], int resultLen, int source[], int intCount, int count) { static boolean shiftRight(int[] result, int resultLen, int[] source, int intCount, int count) {
int i; int i;
boolean allZero = true; boolean allZero = true;
for (i = 0; i < intCount; i++) { for (i = 0; i < intCount; i++) {
@ -295,7 +295,7 @@ class TBitLevel {
for (i = 0; i < resultLen - 1; i++) { for (i = 0; i < resultLen - 1; i++) {
result[i] = (source[i + intCount] >>> count) | (source[i + intCount + 1] << leftShiftCount); result[i] = (source[i + intCount] >>> count) | (source[i + intCount + 1] << leftShiftCount);
} }
result[i] = (source[i + intCount] >>> count); result[i] = source[i + intCount] >>> count;
i++; i++;
} }
@ -317,7 +317,7 @@ class TBitLevel {
int intCount = n >> 5; int intCount = n >> 5;
int bitN = n & 31; int bitN = n & 31;
int resLength = Math.max(intCount + 1, val.numberLength) + 1; int resLength = Math.max(intCount + 1, val.numberLength) + 1;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
int i; int i;
int bitNumber = 1 << bitN; int bitNumber = 1 << bitN;
@ -348,7 +348,8 @@ class TBitLevel {
} }
} }
} }
} else {// case where val is positive } else {
// case where val is positive
resDigits[intCount] ^= bitNumber; resDigits[intCount] ^= bitNumber;
} }
TBigInteger result = new TBigInteger(resSign, resLength, resDigits); TBigInteger result = new TBigInteger(resSign, resLength, resDigits);

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**
@ -24,7 +22,8 @@ package org.teavm.classlib.java.math;
class TConversion { class TConversion {
/** Just to denote that this class can't be instantiated */ /** Just to denote that this class can't be instantiated */
private TConversion() {} private TConversion() {
}
/** /**
* Holds the maximal exponent for each radix, so that radix<sup>digitFitInInt[radix]</sup> * Holds the maximal exponent for each radix, so that radix<sup>digitFitInInt[radix]</sup>
@ -39,7 +38,7 @@ class TConversion {
* 2 ^ 31, bigRadices[8] = 10 ^ 9, etc. * 2 ^ 31, bigRadices[8] = 10 ^ 9, etc.
*/ */
static final int bigRadices[] = { -2147483648, 1162261467, 1073741824, 1220703125, 362797056, 1977326743, static final int[] bigRadices = { -2147483648, 1162261467, 1073741824, 1220703125, 362797056, 1977326743,
1073741824, 387420489, 1000000000, 214358881, 429981696, 815730721, 1475789056, 170859375, 268435456, 1073741824, 387420489, 1000000000, 214358881, 429981696, 815730721, 1475789056, 170859375, 268435456,
410338673, 612220032, 893871739, 1280000000, 1801088541, 113379904, 148035889, 191102976, 244140625, 410338673, 612220032, 893871739, 1280000000, 1801088541, 113379904, 148035889, 191102976, 244140625,
308915776, 387420489, 481890304, 594823321, 729000000, 887503681, 1073741824, 1291467969, 1544804416, 308915776, 387420489, 481890304, 594823321, 729000000, 887503681, 1073741824, 1291467969, 1544804416,
@ -50,7 +49,7 @@ class TConversion {
static String bigInteger2String(TBigInteger val, int radix) { static String bigInteger2String(TBigInteger val, int radix) {
int sign = val.sign; int sign = val.sign;
int numberLength = val.numberLength; int numberLength = val.numberLength;
int digits[] = val.digits; int[] digits = val.digits;
if (sign == 0) { if (sign == 0) {
return "0"; return "0";
@ -70,11 +69,11 @@ class TConversion {
bitsForRadixDigit = Math.log(radix) / Math.log(2); bitsForRadixDigit = Math.log(radix) / Math.log(2);
int resLengthInChars = (int) (val.abs().bitLength() / bitsForRadixDigit + ((sign < 0) ? 1 : 0)) + 1; int resLengthInChars = (int) (val.abs().bitLength() / bitsForRadixDigit + ((sign < 0) ? 1 : 0)) + 1;
char result[] = new char[resLengthInChars]; char[] result = new char[resLengthInChars];
int currentChar = resLengthInChars; int currentChar = resLengthInChars;
int resDigit; int resDigit;
if (radix != 16) { if (radix != 16) {
int temp[] = new int[numberLength]; int[] temp = new int[numberLength];
System.arraycopy(digits, 0, temp, 0, numberLength); System.arraycopy(digits, 0, temp, 0, numberLength);
int tempLen = numberLength; int tempLen = numberLength;
int charsPerInt = digitFitInInt[radix]; int charsPerInt = digitFitInInt[radix];
@ -88,7 +87,8 @@ class TConversion {
int previous = currentChar; int previous = currentChar;
do { do {
result[--currentChar] = Character.forDigit(resDigit % radix, radix); result[--currentChar] = Character.forDigit(resDigit % radix, radix);
} while (((resDigit /= radix) != 0) && (currentChar != 0)); resDigit /= radix;
} while (resDigit != 0 && currentChar != 0);
int delta = charsPerInt - previous + currentChar; int delta = charsPerInt - previous + currentChar;
for (i = 0; i < delta && currentChar > 0; i++) { for (i = 0; i < delta && currentChar > 0; i++) {
result[--currentChar] = '0'; result[--currentChar] = '0';
@ -129,10 +129,10 @@ class TConversion {
static String toDecimalScaledString(TBigInteger val, int scale) { static String toDecimalScaledString(TBigInteger val, int scale) {
int sign = val.sign; int sign = val.sign;
int numberLength = val.numberLength; int numberLength = val.numberLength;
int digits[] = val.digits; int[] digits = val.digits;
int resLengthInChars; int resLengthInChars;
int currentChar; int currentChar;
char result[]; char[] result;
if (sign == 0) { if (sign == 0) {
switch (scale) { switch (scale) {
@ -190,7 +190,7 @@ class TConversion {
} while (v != 0); } while (v != 0);
} }
} else { } else {
int temp[] = new int[numberLength]; int[] temp = new int[numberLength];
int tempLen = numberLength; int tempLen = numberLength;
System.arraycopy(digits, 0, temp, 0, tempLen); System.arraycopy(digits, 0, temp, 0, tempLen);
BIG_LOOP: while (true) { BIG_LOOP: while (true) {
@ -208,7 +208,8 @@ class TConversion {
int previous = currentChar; int previous = currentChar;
do { do {
result[--currentChar] = (char) (0x0030 + (resDigit % 10)); result[--currentChar] = (char) (0x0030 + (resDigit % 10));
} while ((resDigit /= 10) != 0 && currentChar != 0); resDigit /= 10;
} while (resDigit != 0 && currentChar != 0);
int delta = 9 - previous + currentChar; int delta = 9 - previous + currentChar;
for (int i = 0; (i < delta) && (currentChar > 0); i++) { for (int i = 0; (i < delta) && (currentChar > 0); i++) {
result[--currentChar] = '0'; result[--currentChar] = '0';
@ -225,7 +226,7 @@ class TConversion {
currentChar++; currentChar++;
} }
} }
boolean negNumber = (sign < 0); boolean negNumber = sign < 0;
int exponent = resLengthInChars - currentChar - scale - 1; int exponent = resLengthInChars - currentChar - scale - 1;
if (scale == 0) { if (scale == 0) {
if (negNumber) { if (negNumber) {
@ -282,9 +283,9 @@ class TConversion {
static String toDecimalScaledString(long value, int scale) { static String toDecimalScaledString(long value, int scale) {
int resLengthInChars; int resLengthInChars;
int currentChar; int currentChar;
char result[]; char[] result;
boolean negNumber = value < 0; boolean negNumber = value < 0;
if(negNumber) { if (negNumber) {
value = -value; value = -value;
} }
if (value == 0) { if (value == 0) {
@ -313,7 +314,7 @@ class TConversion {
// +1 - one char for sign if needed. // +1 - one char for sign if needed.
// +7 - For "special case 2" (see below) we have 7 free chars for // +7 - For "special case 2" (see below) we have 7 free chars for
// inserting necessary scaled digits. // inserting necessary scaled digits.
result = new char[resLengthInChars+1]; result = new char[resLengthInChars + 1];
// Allocated [resLengthInChars+1] characters. // Allocated [resLengthInChars+1] characters.
// a free latest character may be used for "special case 1" (see below) // a free latest character may be used for "special case 1" (see below)
currentChar = resLengthInChars; currentChar = resLengthInChars;
@ -324,7 +325,7 @@ class TConversion {
result[--currentChar] = (char) (0x0030 + (prev - v * 10)); result[--currentChar] = (char) (0x0030 + (prev - v * 10));
} while (v != 0); } while (v != 0);
long exponent = (long)resLengthInChars - (long)currentChar - scale - 1L; long exponent = (long) resLengthInChars - (long) currentChar - scale - 1L;
if (scale == 0) { if (scale == 0) {
if (negNumber) { if (negNumber) {
result[--currentChar] = '-'; result[--currentChar] = '-';
@ -334,8 +335,8 @@ class TConversion {
if (scale > 0 && exponent >= -6) { if (scale > 0 && exponent >= -6) {
if (exponent >= 0) { if (exponent >= 0) {
// special case 1 // special case 1
int insertPoint = currentChar + (int)exponent; int insertPoint = currentChar + (int) exponent;
for(int j = resLengthInChars - 1; j >= insertPoint; j--) { for (int j = resLengthInChars - 1; j >= insertPoint; j--) {
result[j + 1] = result[j]; result[j + 1] = result[j];
} }
result[++insertPoint] = '.'; result[++insertPoint] = '.';
@ -364,7 +365,7 @@ class TConversion {
if (endPoint - startPoint >= 1) { if (endPoint - startPoint >= 1) {
result1.append(result[currentChar]); result1.append(result[currentChar]);
result1.append('.'); result1.append('.');
result1.append(result, currentChar+1, resLengthInChars - currentChar-1); result1.append(result, currentChar + 1, resLengthInChars - currentChar - 1);
} else { } else {
result1.append(result, currentChar, resLengthInChars - currentChar); result1.append(result, currentChar, resLengthInChars - currentChar);
} }
@ -382,8 +383,8 @@ class TConversion {
if (a >= 0) { if (a >= 0) {
long bLong = 1000000000L; long bLong = 1000000000L;
quot = (a / bLong); quot = a / bLong;
rem = (a % bLong); rem = a % bLong;
} else { } else {
/* /*
* Make the dividend positive shifting it right by 1 bit then get * Make the dividend positive shifting it right by 1 bit then get

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**
@ -39,6 +37,8 @@ package org.teavm.classlib.java.math;
* </ul> * </ul>
*/ */
class TDivision { class TDivision {
private TDivision() {
}
/** /**
* Divides the array 'a' by the array 'b' and gets the quotient and the * Divides the array 'a' by the array 'b' and gets the quotient and the
@ -60,11 +60,11 @@ class TDivision {
* the divisor's length * the divisor's length
* @return the remainder * @return the remainder
*/ */
static int[] divide(int quot[], int quotLength, int a[], int aLength, int b[], int bLength) { static int[] divide(int[] quot, int quotLength, int[] a, int aLength, int[] b, int bLength) {
int normA[] = new int[aLength + 1]; // the normalized dividend int[] normA = new int[aLength + 1]; // the normalized dividend
// an extra byte is needed for correct shift // an extra byte is needed for correct shift
int normB[] = new int[bLength + 1]; // the normalized divisor; int[] normB = new int[bLength + 1]; // the normalized divisor;
int normBLength = bLength; int normBLength = bLength;
/* /*
* Step D1: normalize a and b and put the results to a1 and b1 the * Step D1: normalize a and b and put the results to a1 and b1 the
@ -90,7 +90,7 @@ class TDivision {
// set guessDigit to the largest unsigned int value // set guessDigit to the largest unsigned int value
guessDigit = -1; guessDigit = -1;
} else { } else {
long product = (((normA[j] & 0xffffffffL) << 32) + (normA[j - 1] & 0xffffffffL)); long product = ((normA[j] & 0xffffffffL) << 32) + (normA[j - 1] & 0xffffffffL);
long res = TDivision.divideLongByInt(product, firstDivisorDigit); long res = TDivision.divideLongByInt(product, firstDivisorDigit);
guessDigit = (int) res; // the quotient of divideLongByInt guessDigit = (int) res; // the quotient of divideLongByInt
int rem = (int) (res >> 32); // the remainder of int rem = (int) (res >> 32); // the remainder of
@ -125,7 +125,7 @@ class TDivision {
} else { } else {
rem = (int) longR; rem = (int) longR;
} }
} while (((leftHand ^ 0x8000000000000000L) > (rightHand ^ 0x8000000000000000L))); } while ((leftHand ^ 0x8000000000000000L) > (rightHand ^ 0x8000000000000000L));
} }
} }
// Step D4: multiply normB by guessDigit and subtract the production // Step D4: multiply normB by guessDigit and subtract the production
@ -177,7 +177,7 @@ class TDivision {
* the divisor * the divisor
* @return remainder * @return remainder
*/ */
static int divideArrayByInt(int dest[], int src[], final int srcLength, final int divisor) { static int divideArrayByInt(int[] dest, int[] src, final int srcLength, final int divisor) {
long rem = 0; long rem = 0;
long bLong = divisor & 0xffffffffL; long bLong = divisor & 0xffffffffL;
@ -186,8 +186,8 @@ class TDivision {
long temp = (rem << 32) | (src[i] & 0xffffffffL); long temp = (rem << 32) | (src[i] & 0xffffffffL);
long quot; long quot;
if (temp >= 0) { if (temp >= 0) {
quot = (temp / bLong); quot = temp / bLong;
rem = (temp % bLong); rem = temp % bLong;
} else { } else {
/* /*
* make the dividend positive shifting it right by 1 bit then * make the dividend positive shifting it right by 1 bit then
@ -231,7 +231,7 @@ class TDivision {
* the divisor * the divisor
* @return remainder * @return remainder
*/ */
static int remainderArrayByInt(int src[], final int srcLength, final int divisor) { static int remainderArrayByInt(int[] src, final int srcLength, final int divisor) {
long result = 0; long result = 0;
@ -274,8 +274,8 @@ class TDivision {
long bLong = b & 0xffffffffL; long bLong = b & 0xffffffffL;
if (a >= 0) { if (a >= 0) {
quot = (a / bLong); quot = a / bLong;
rem = (a % bLong); rem = a % bLong;
} else { } else {
/* /*
* Make the dividend positive shifting it right by 1 bit then get * Make the dividend positive shifting it right by 1 bit then get
@ -316,8 +316,8 @@ class TDivision {
int valLen = val.numberLength; int valLen = val.numberLength;
int valSign = val.sign; int valSign = val.sign;
if (valLen == 1) { if (valLen == 1) {
long a = (valDigits[0] & 0xffffffffL); long a = valDigits[0] & 0xffffffffL;
long b = (divisor & 0xffffffffL); long b = divisor & 0xffffffffL;
long quo = a / b; long quo = a / b;
long rem = a % b; long rem = a % b;
if (valSign != divisorSign) { if (valSign != divisorSign) {
@ -329,10 +329,9 @@ class TDivision {
return new TBigInteger[] { TBigInteger.valueOf(quo), TBigInteger.valueOf(rem) }; return new TBigInteger[] { TBigInteger.valueOf(quo), TBigInteger.valueOf(rem) };
} }
int quotientLength = valLen; int quotientLength = valLen;
int quotientSign = ((valSign == divisorSign) ? 1 : -1); int quotientSign = valSign == divisorSign ? 1 : -1;
int quotientDigits[] = new int[quotientLength]; int[] quotientDigits = new int[quotientLength];
int remainderDigits[]; int[] remainderDigits = { TDivision.divideArrayByInt(quotientDigits, valDigits, valLen, divisor) };
remainderDigits = new int[] { TDivision.divideArrayByInt(quotientDigits, valDigits, valLen, divisor) };
TBigInteger result0 = new TBigInteger(quotientSign, quotientLength, quotientDigits); TBigInteger result0 = new TBigInteger(quotientSign, quotientLength, quotientDigits);
TBigInteger result1 = new TBigInteger(valSign, 1, remainderDigits); TBigInteger result1 = new TBigInteger(valSign, 1, remainderDigits);
result0.cutOffLeadingZeroes(); result0.cutOffLeadingZeroes();
@ -356,7 +355,7 @@ class TDivision {
* the multiplier of b * the multiplier of b
* @return the carry element of subtraction * @return the carry element of subtraction
*/ */
static int multiplyAndSubtract(int a[], int start, int b[], int bLen, int c) { static int multiplyAndSubtract(int[] a, int start, int[] b, int bLen, int c) {
long carry0 = 0; long carry0 = 0;
long carry1 = 0; long carry1 = 0;
@ -472,7 +471,7 @@ class TDivision {
op2 >>>= Long.numberOfTrailingZeros(op2); op2 >>>= Long.numberOfTrailingZeros(op2);
} }
} while (op1 != 0); } while (op1 != 0);
return (op2 << pow2Count); return op2 << pow2Count;
} }
/** /**
@ -493,7 +492,10 @@ class TDivision {
int m = p.numberLength * 32; int m = p.numberLength * 32;
// PRE: a \in [1, p - 1] // PRE: a \in [1, p - 1]
TBigInteger u, v, r, s; TBigInteger u;
TBigInteger v;
TBigInteger r;
TBigInteger s;
u = p.copy(); // make copy to use inplace method u = p.copy(); // make copy to use inplace method
v = a.copy(); v = a.copy();
int max = Math.max(v.numberLength, u.numberLength); int max = Math.max(v.numberLength, u.numberLength);
@ -536,8 +538,9 @@ class TDivision {
while (u.compareTo(v) <= TBigInteger.EQUALS) { while (u.compareTo(v) <= TBigInteger.EQUALS) {
TElementary.inplaceSubtract(v, u); TElementary.inplaceSubtract(v, u);
if (v.signum() == 0) if (v.signum() == 0) {
break; break;
}
toShift = v.getLowestSetBit(); toShift = v.getLowestSetBit();
TBitLevel.inplaceShiftRight(v, toShift); TBitLevel.inplaceShiftRight(v, toShift);
TElementary.inplaceAdd(s, r); TElementary.inplaceAdd(s, r);
@ -608,7 +611,11 @@ class TDivision {
*/ */
static TBigInteger modInverseHars(TBigInteger a, TBigInteger m) { static TBigInteger modInverseHars(TBigInteger a, TBigInteger m) {
// PRE: (a > 0) and (m > 0) // PRE: (a > 0) and (m > 0)
TBigInteger u, v, r, s, temp; TBigInteger u;
TBigInteger v;
TBigInteger r;
TBigInteger s;
TBigInteger temp;
// u = MAX(a,m), v = MIN(a,m) // u = MAX(a,m), v = MIN(a,m)
if (a.compareTo(m) == TBigInteger.LESS) { if (a.compareTo(m) == TBigInteger.LESS) {
u = m; u = m;
@ -675,9 +682,10 @@ class TDivision {
* *
* @see #oddModPow(BigInteger, BigInteger, BigInteger) * @see #oddModPow(BigInteger, BigInteger, BigInteger)
*/ */
static TBigInteger slidingWindow(TBigInteger x2, TBigInteger a2, TBigInteger exponent, TBigInteger modulus, int n2) { static TBigInteger slidingWindow(TBigInteger x2, TBigInteger a2, TBigInteger exponent,
TBigInteger modulus, int n2) {
// fill odd low pows of a2 // fill odd low pows of a2
TBigInteger pows[] = new TBigInteger[8]; TBigInteger[] pows = new TBigInteger[8];
TBigInteger res = x2; TBigInteger res = x2;
int lowexp; int lowexp;
TBigInteger x3; TBigInteger x3;
@ -730,7 +738,7 @@ class TDivision {
*/ */
static TBigInteger oddModPow(TBigInteger base, TBigInteger exponent, TBigInteger modulus) { static TBigInteger oddModPow(TBigInteger base, TBigInteger exponent, TBigInteger modulus) {
// PRE: (base > 0), (exponent > 0), (modulus > 0) and (odd modulus) // PRE: (base > 0), (exponent > 0), (modulus > 0) and (odd modulus)
int k = (modulus.numberLength << 5); // r = 2^k int k = modulus.numberLength << 5; // r = 2^k
// n-residue of base [base * r (mod modulus)] // n-residue of base [base * r (mod modulus)]
TBigInteger a2 = base.shiftLeft(k).mod(modulus); TBigInteger a2 = base.shiftLeft(k).mod(modulus);
// n-residue of base [1 * r (mod modulus)] // n-residue of base [1 * r (mod modulus)]
@ -818,7 +826,7 @@ class TDivision {
private static void monReduction(int[] res, TBigInteger modulus, int n2) { private static void monReduction(int[] res, TBigInteger modulus, int n2) {
/* res + m*modulus_digits */ /* res + m*modulus_digits */
int[] modulus_digits = modulus.digits; int[] modulusDigits = modulus.digits;
int modulusLen = modulus.numberLength; int modulusLen = modulus.numberLength;
long outerCarry = 0; long outerCarry = 0;
@ -826,7 +834,7 @@ class TDivision {
long innnerCarry = 0; long innnerCarry = 0;
int m = (int) TMultiplication.unsignedMultAddAdd(res[i], n2, 0, 0); int m = (int) TMultiplication.unsignedMultAddAdd(res[i], n2, 0, 0);
for (int j = 0; j < modulusLen; j++) { for (int j = 0; j < modulusLen; j++) {
innnerCarry = TMultiplication.unsignedMultAddAdd(m, modulus_digits[j], res[i + j], (int) innnerCarry); innnerCarry = TMultiplication.unsignedMultAddAdd(m, modulusDigits[j], res[i + j], (int) innnerCarry);
res[i + j] = (int) innnerCarry; res[i + j] = (int) innnerCarry;
innnerCarry >>>= 32; innnerCarry >>>= 32;
} }
@ -863,7 +871,7 @@ class TDivision {
*/ */
static TBigInteger monPro(TBigInteger a, TBigInteger b, TBigInteger modulus, int n2) { static TBigInteger monPro(TBigInteger a, TBigInteger b, TBigInteger modulus, int n2) {
int modulusLen = modulus.numberLength; int modulusLen = modulus.numberLength;
int res[] = new int[(modulusLen << 1) + 1]; int[] res = new int[(modulusLen << 1) + 1];
TMultiplication.multArraysPAP(a.digits, Math.min(modulusLen, a.numberLength), b.digits, TMultiplication.multArraysPAP(a.digits, Math.min(modulusLen, a.numberLength), b.digits,
Math.min(modulusLen, b.numberLength), res); Math.min(modulusLen, b.numberLength), res);
monReduction(res, modulus, n2); monReduction(res, modulus, n2);
@ -877,13 +885,13 @@ class TDivision {
* @see #monPro(TBigInteger, TBigInteger, TBigInteger, long) * @see #monPro(TBigInteger, TBigInteger, TBigInteger, long)
* @see #monSquare(TBigInteger, TBigInteger, long) * @see #monSquare(TBigInteger, TBigInteger, long)
*/ */
static TBigInteger finalSubtraction(int res[], TBigInteger modulus) { static TBigInteger finalSubtraction(int[] res, TBigInteger modulus) {
// skipping leading zeros // skipping leading zeros
int modulusLen = modulus.numberLength; int modulusLen = modulus.numberLength;
boolean doSub = res[modulusLen] != 0; boolean doSub = res[modulusLen] != 0;
if (!doSub) { if (!doSub) {
int modulusDigits[] = modulus.digits; int[] modulusDigits = modulus.digits;
doSub = true; doSub = true;
for (int i = modulusLen - 1; i >= 0; i--) { for (int i = modulusLen - 1; i >= 0; i--) {
if (res[i] != modulusDigits[i]) { if (res[i] != modulusDigits[i]) {
@ -921,7 +929,7 @@ class TDivision {
for (int i = 1; i < n; i++) { for (int i = 1; i < n; i++) {
if (TBitLevel.testBit(x.multiply(y), i)) { if (TBitLevel.testBit(x.multiply(y), i)) {
// Adding 2^i to y (setting the i-th bit) // Adding 2^i to y (setting the i-th bit)
y.digits[i >> 5] |= (1 << (i & 31)); y.digits[i >> 5] |= 1 << (i & 31);
} }
} }
return y; return y;

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**
@ -51,13 +49,14 @@ class TElementary {
for (i = size - 1; (i >= 0) && (a[i] == b[i]); i--) { for (i = size - 1; (i >= 0) && (a[i] == b[i]); i--) {
// do nothing // do nothing
} }
return ((i < 0) ? TBigInteger.EQUALS : (a[i] & 0xFFFFFFFFL) < (b[i] & 0xFFFFFFFFL) ? TBigInteger.LESS return i < 0
: TBigInteger.GREATER); ? TBigInteger.EQUALS
: (a[i] & 0xFFFFFFFFL) < (b[i] & 0xFFFFFFFFL) ? TBigInteger.LESS : TBigInteger.GREATER;
} }
/** @see TBigInteger#add(TBigInteger) */ /** @see TBigInteger#add(TBigInteger) */
static TBigInteger add(TBigInteger op1, TBigInteger op2) { static TBigInteger add(TBigInteger op1, TBigInteger op2) {
int resDigits[]; int[] resDigits;
int resSign; int resSign;
int op1Sign = op1.sign; int op1Sign = op1.sign;
int op2Sign = op2.sign; int op2Sign = op2.sign;
@ -72,8 +71,8 @@ class TElementary {
int op2Len = op2.numberLength; int op2Len = op2.numberLength;
if (op1Len + op2Len == 2) { if (op1Len + op2Len == 2) {
long a = (op1.digits[0] & 0xFFFFFFFFL); long a = op1.digits[0] & 0xFFFFFFFFL;
long b = (op2.digits[0] & 0xFFFFFFFFL); long b = op2.digits[0] & 0xFFFFFFFFL;
long res; long res;
int valueLo; int valueLo;
int valueHi; int valueHi;
@ -82,8 +81,8 @@ class TElementary {
res = a + b; res = a + b;
valueLo = (int) res; valueLo = (int) res;
valueHi = (int) (res >>> 32); valueHi = (int) (res >>> 32);
return ((valueHi == 0) ? new TBigInteger(op1Sign, valueLo) : new TBigInteger(op1Sign, 2, new int[] { return valueHi == 0 ? new TBigInteger(op1Sign, valueLo) : new TBigInteger(op1Sign, 2, new int[] {
valueLo, valueHi })); valueLo, valueHi });
} }
return TBigInteger.valueOf((op1Sign < 0) ? (b - a) : (a - b)); return TBigInteger.valueOf((op1Sign < 0) ? (b - a) : (a - b));
} else if (op1Sign == op2Sign) { } else if (op1Sign == op2Sign) {
@ -92,8 +91,9 @@ class TElementary {
resDigits = (op1Len >= op2Len) ? add(op1.digits, op1Len, op2.digits, op2Len) : add(op2.digits, op2Len, resDigits = (op1Len >= op2Len) ? add(op1.digits, op1Len, op2.digits, op2Len) : add(op2.digits, op2Len,
op1.digits, op1Len); op1.digits, op1Len);
} else { // signs are different } else { // signs are different
int cmp = ((op1Len != op2Len) ? ((op1Len > op2Len) ? 1 : -1) int cmp = op1Len != op2Len
: compareArrays(op1.digits, op2.digits, op1Len)); ? (op1Len > op2Len ? 1 : -1)
: compareArrays(op1.digits, op2.digits, op1Len);
if (cmp == TBigInteger.EQUALS) { if (cmp == TBigInteger.EQUALS) {
return TBigInteger.ZERO; return TBigInteger.ZERO;
@ -115,7 +115,7 @@ class TElementary {
/** /**
* Performs {@code res = a + b}. * Performs {@code res = a + b}.
*/ */
private static void add(int res[], int a[], int aSize, int b[], int bSize) { private static void add(int[] res, int[] a, int aSize, int[] b, int bSize) {
// PRE: a.length < max(aSize, bSize) // PRE: a.length < max(aSize, bSize)
int i; int i;
@ -155,7 +155,7 @@ class TElementary {
/** @see TBigInteger#subtract(TBigInteger) */ /** @see TBigInteger#subtract(TBigInteger) */
static TBigInteger subtract(TBigInteger op1, TBigInteger op2) { static TBigInteger subtract(TBigInteger op1, TBigInteger op2) {
int resSign; int resSign;
int resDigits[]; int[] resDigits;
int op1Sign = op1.sign; int op1Sign = op1.sign;
int op2Sign = op2.sign; int op2Sign = op2.sign;
@ -168,8 +168,8 @@ class TElementary {
int op1Len = op1.numberLength; int op1Len = op1.numberLength;
int op2Len = op2.numberLength; int op2Len = op2.numberLength;
if (op1Len + op2Len == 2) { if (op1Len + op2Len == 2) {
long a = (op1.digits[0] & 0xFFFFFFFFL); long a = op1.digits[0] & 0xFFFFFFFFL;
long b = (op2.digits[0] & 0xFFFFFFFFL); long b = op2.digits[0] & 0xFFFFFFFFL;
if (op1Sign < 0) { if (op1Sign < 0) {
a = -a; a = -a;
} }
@ -178,8 +178,9 @@ class TElementary {
} }
return TBigInteger.valueOf(a - b); return TBigInteger.valueOf(a - b);
} }
int cmp = ((op1Len != op2Len) ? ((op1Len > op2Len) ? 1 : -1) : TElementary.compareArrays(op1.digits, op2.digits, int cmp = op1Len != op2Len
op1Len)); ? (op1Len > op2Len ? 1 : -1)
: TElementary.compareArrays(op1.digits, op2.digits, op1Len);
if (cmp == TBigInteger.LESS) { if (cmp == TBigInteger.LESS) {
resSign = -op2Sign; resSign = -op2Sign;
@ -205,7 +206,7 @@ class TElementary {
* Performs {@code res = a - b}. It is assumed the magnitude of a is not * Performs {@code res = a - b}. It is assumed the magnitude of a is not
* less than the magnitude of b. * less than the magnitude of b.
*/ */
private static void subtract(int res[], int a[], int aSize, int b[], int bSize) { private static void subtract(int[] res, int[] a, int aSize, int[] b, int bSize) {
// PRE: a[] >= b[] // PRE: a[] >= b[]
int i; int i;
long borrow = 0; long borrow = 0;
@ -229,9 +230,9 @@ class TElementary {
* *
* @return {@code a + b} * @return {@code a + b}
*/ */
private static int[] add(int a[], int aSize, int b[], int bSize) { private static int[] add(int[] a, int aSize, int[] b, int bSize) {
// PRE: a[] >= b[] // PRE: a[] >= b[]
int res[] = new int[aSize + 1]; int[] res = new int[aSize + 1];
add(res, a, aSize, b, bSize); add(res, a, aSize, b, bSize);
return res; return res;
} }
@ -259,7 +260,7 @@ class TElementary {
* *
* @return a possible generated carry (0 or 1) * @return a possible generated carry (0 or 1)
*/ */
static int inplaceAdd(int a[], final int aSize, final int addend) { static int inplaceAdd(int[] a, final int aSize, final int addend) {
long carry = addend & 0xFFFFFFFFL; long carry = addend & 0xFFFFFFFFL;
for (int i = 0; (carry != 0) && (i < aSize); i++) { for (int i = 0; (carry != 0) && (i < aSize); i++) {
@ -303,7 +304,7 @@ class TElementary {
/** /**
* Performs {@code res = b - a} * Performs {@code res = b - a}
*/ */
private static void inverseSubtract(int res[], int a[], int aSize, int b[], int bSize) { private static void inverseSubtract(int[] res, int[] a, int aSize, int[] b, int bSize) {
int i; int i;
long borrow = 0; long borrow = 0;
if (aSize < bSize) { if (aSize < bSize) {
@ -339,9 +340,9 @@ class TElementary {
* *
* @return {@code a - b} * @return {@code a - b}
*/ */
private static int[] subtract(int a[], int aSize, int b[], int bSize) { private static int[] subtract(int[] a, int aSize, int[] b, int bSize) {
// PRE: a[] >= b[] // PRE: a[] >= b[]
int res[] = new int[aSize]; int[] res = new int[aSize];
subtract(res, a, aSize, b, bSize); subtract(res, a, aSize, b, bSize);
return res; return res;
} }
@ -387,17 +388,17 @@ class TElementary {
* any number * any number
*/ */
static void completeInPlaceAdd(TBigInteger op1, TBigInteger op2) { static void completeInPlaceAdd(TBigInteger op1, TBigInteger op2) {
if (op1.sign == 0) if (op1.sign == 0) {
System.arraycopy(op2.digits, 0, op1.digits, 0, op2.numberLength); System.arraycopy(op2.digits, 0, op1.digits, 0, op2.numberLength);
else if (op2.sign == 0) } else if (op2.sign == 0) {
return; return;
else if (op1.sign == op2.sign) } else if (op1.sign == op2.sign) {
add(op1.digits, op1.digits, op1.numberLength, op2.digits, op2.numberLength); add(op1.digits, op1.digits, op1.numberLength, op2.digits, op2.numberLength);
else { } else {
int sign = unsignedArraysCompare(op1.digits, op2.digits, op1.numberLength, op2.numberLength); int sign = unsignedArraysCompare(op1.digits, op2.digits, op1.numberLength, op2.numberLength);
if (sign > 0) if (sign > 0) {
subtract(op1.digits, op1.digits, op1.numberLength, op2.digits, op2.numberLength); subtract(op1.digits, op1.digits, op1.numberLength, op2.digits, op2.numberLength);
else { } else {
inverseSubtract(op1.digits, op1.digits, op1.numberLength, op2.digits, op2.numberLength); inverseSubtract(op1.digits, op1.digits, op1.numberLength, op2.digits, op2.numberLength);
op1.sign = -op1.sign; op1.sign = -op1.sign;
} }
@ -413,12 +414,11 @@ class TElementary {
* then b * then b
*/ */
private static int unsignedArraysCompare(int[] a, int[] b, int aSize, int bSize) { private static int unsignedArraysCompare(int[] a, int[] b, int aSize, int bSize) {
if (aSize > bSize) if (aSize > bSize) {
return 1; return 1;
else if (aSize < bSize) } else if (aSize < bSize) {
return -1; return -1;
} else {
else {
int i; int i;
for (i = aSize - 1; i >= 0 && a[i] == b[i]; i--) { for (i = aSize - 1; i >= 0 && a[i] == b[i]; i--) {
// do nothing // do nothing
@ -427,5 +427,4 @@ class TElementary {
: TBigInteger.GREATER); : TBigInteger.GREATER);
} }
} }
} }

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**
@ -32,7 +30,8 @@ class TLogical {
/** Just to denote that this class can't be instantiated. */ /** Just to denote that this class can't be instantiated. */
private TLogical() {} private TLogical() {
}
/** @see TBigInteger#not() */ /** @see TBigInteger#not() */
@ -43,7 +42,7 @@ class TLogical {
if (val.equals(TBigInteger.MINUS_ONE)) { if (val.equals(TBigInteger.MINUS_ONE)) {
return TBigInteger.ZERO; return TBigInteger.ZERO;
} }
int resDigits[] = new int[val.numberLength + 1]; int[] resDigits = new int[val.numberLength + 1];
int i; int i;
if (val.sign > 0) { if (val.sign > 0) {
@ -62,7 +61,8 @@ class TLogical {
} }
} }
// Here a carry 1 was generated // Here a carry 1 was generated
} else {// (val.sign < 0) } else {
// (val.sign < 0)
// ~val = -val - 1 // ~val = -val - 1
for (i = 0; val.digits[i] == 0; i++) { for (i = 0; val.digits[i] == 0; i++) {
resDigits[i] = -1; resDigits[i] = -1;
@ -83,7 +83,7 @@ class TLogical {
if (that.sign == 0 || val.sign == 0) { if (that.sign == 0 || val.sign == 0) {
return TBigInteger.ZERO; return TBigInteger.ZERO;
} }
if (that.equals(TBigInteger.MINUS_ONE)){ if (that.equals(TBigInteger.MINUS_ONE)) {
return val; return val;
} }
if (val.equals(TBigInteger.MINUS_ONE)) { if (val.equals(TBigInteger.MINUS_ONE)) {
@ -117,8 +117,8 @@ class TLogical {
return TBigInteger.ZERO; return TBigInteger.ZERO;
} }
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
for ( ; i < resLength; i++) { for (; i < resLength; i++) {
resDigits[i] = val.digits[i] & that.digits[i]; resDigits[i] = val.digits[i] & that.digits[i];
} }
@ -139,7 +139,7 @@ class TLogical {
return TBigInteger.ZERO; return TBigInteger.ZERO;
} }
int resLength = positive.numberLength; int resLength = positive.numberLength;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
// Must start from max(iPos, iNeg) // Must start from max(iPos, iNeg)
int i = Math.max(iPos, iNeg); int i = Math.max(iPos, iNeg);
@ -148,13 +148,13 @@ class TLogical {
i++; i++;
} }
int limit = Math.min(negative.numberLength, positive.numberLength); int limit = Math.min(negative.numberLength, positive.numberLength);
for ( ; i < limit; i++) { for (; i < limit; i++) {
resDigits[i] = ~negative.digits[i] & positive.digits[i]; resDigits[i] = ~negative.digits[i] & positive.digits[i];
} }
// if the negative was shorter must copy the remaining digits // if the negative was shorter must copy the remaining digits
// from positive // from positive
if (i >= negative.numberLength) { if (i >= negative.numberLength) {
for ( ; i < positive.numberLength; i++) { for (; i < positive.numberLength; i++) {
resDigits[i] = positive.digits[i]; resDigits[i] = positive.digits[i];
} }
} // else positive ended and must "copy" virtual 0's, do nothing then } // else positive ended and must "copy" virtual 0's, do nothing then
@ -177,7 +177,7 @@ class TLogical {
} }
int resLength; int resLength;
int resDigits[]; int[] resDigits;
int i = Math.max(iShorter, iLonger); int i = Math.max(iShorter, iLonger);
int digit; int digit;
if (iShorter > iLonger) { if (iShorter > iLonger) {
@ -188,13 +188,19 @@ class TLogical {
digit = -shorter.digits[i] & -longer.digits[i]; digit = -shorter.digits[i] & -longer.digits[i];
} }
if (digit == 0) { if (digit == 0) {
for (i++; i < shorter.numberLength && (digit = ~(longer.digits[i] | shorter.digits[i])) == 0; i++) { for (i++; i < shorter.numberLength; i++) {
// do nothing digit = ~(longer.digits[i] | shorter.digits[i]);
if (digit != 0) {
break;
}
} }
if (digit == 0) { if (digit == 0) {
// shorter has only the remaining virtual sign bits // shorter has only the remaining virtual sign bits
for ( ; i < longer.numberLength && (digit = ~longer.digits[i]) == 0; i++) { for (; i < longer.numberLength; i++) {
// do nothing digit = ~longer.digits[i];
if (digit != 0) {
break;
}
} }
if (digit == 0) { if (digit == 0) {
resLength = longer.numberLength + 1; resLength = longer.numberLength + 1;
@ -209,12 +215,12 @@ class TLogical {
resLength = longer.numberLength; resLength = longer.numberLength;
resDigits = new int[resLength]; resDigits = new int[resLength];
resDigits[i] = -digit; resDigits[i] = -digit;
for (i++; i < shorter.numberLength; i++){ for (i++; i < shorter.numberLength; i++) {
// resDigits[i] = ~(~longer.digits[i] & ~shorter.digits[i];) // resDigits[i] = ~(~longer.digits[i] & ~shorter.digits[i];)
resDigits[i] = longer.digits[i] | shorter.digits[i]; resDigits[i] = longer.digits[i] | shorter.digits[i];
} }
// shorter has only the remaining virtual sign bits // shorter has only the remaining virtual sign bits
for( ; i < longer.numberLength; i++){ for (; i < longer.numberLength; i++) {
resDigits[i] = longer.digits[i]; resDigits[i] = longer.digits[i];
} }
@ -224,7 +230,7 @@ class TLogical {
/** @see TBigInteger#andNot(TBigInteger) */ /** @see TBigInteger#andNot(TBigInteger) */
static TBigInteger andNot(TBigInteger val, TBigInteger that) { static TBigInteger andNot(TBigInteger val, TBigInteger that) {
if (that.sign == 0 ) { if (that.sign == 0) {
return val; return val;
} }
if (val.sign == 0) { if (val.sign == 0) {
@ -233,7 +239,7 @@ class TLogical {
if (val.equals(TBigInteger.MINUS_ONE)) { if (val.equals(TBigInteger.MINUS_ONE)) {
return that.not(); return that.not();
} }
if (that.equals(TBigInteger.MINUS_ONE)){ if (that.equals(TBigInteger.MINUS_ONE)) {
return TBigInteger.ZERO; return TBigInteger.ZERO;
} }
@ -257,14 +263,14 @@ class TLogical {
/** @return sign = 1, magnitude = val.magnitude & ~that.magnitude*/ /** @return sign = 1, magnitude = val.magnitude & ~that.magnitude*/
static TBigInteger andNotPositive(TBigInteger val, TBigInteger that) { static TBigInteger andNotPositive(TBigInteger val, TBigInteger that) {
// PRE: both arguments are positive // PRE: both arguments are positive
int resDigits[] = new int[val.numberLength]; int[] resDigits = new int[val.numberLength];
int limit = Math.min(val.numberLength, that.numberLength); int limit = Math.min(val.numberLength, that.numberLength);
int i; int i;
for (i = val.getFirstNonzeroDigit(); i < limit; i++) { for (i = val.getFirstNonzeroDigit(); i < limit; i++) {
resDigits[i] = val.digits[i] & ~that.digits[i]; resDigits[i] = val.digits[i] & ~that.digits[i];
} }
for ( ; i < val.numberLength; i++) { for (; i < val.numberLength; i++) {
resDigits[i] = val.digits[i]; resDigits[i] = val.digits[i];
} }
@ -284,11 +290,11 @@ class TLogical {
} }
int resLength = Math.min(positive.numberLength, negative.numberLength); int resLength = Math.min(positive.numberLength, negative.numberLength);
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
// Always start from first non zero of positive // Always start from first non zero of positive
int i = iPos; int i = iPos;
for ( ; i < iNeg; i++) { for (; i < iNeg; i++) {
// resDigits[i] = positive.digits[i] & -1 (~0) // resDigits[i] = positive.digits[i] & -1 (~0)
resDigits[i] = positive.digits[i]; resDigits[i] = positive.digits[i];
} }
@ -296,7 +302,7 @@ class TLogical {
resDigits[i] = positive.digits[i] & (negative.digits[i] - 1); resDigits[i] = positive.digits[i] & (negative.digits[i] - 1);
i++; i++;
} }
for ( ; i < resLength; i++) { for (; i < resLength; i++) {
// resDigits[i] = positive.digits[i] & ~(~negative.digits[i]); // resDigits[i] = positive.digits[i] & ~(~negative.digits[i]);
resDigits[i] = positive.digits[i] & negative.digits[i]; resDigits[i] = positive.digits[i] & negative.digits[i];
} }
@ -310,7 +316,7 @@ class TLogical {
static TBigInteger andNotNegativePositive(TBigInteger negative, TBigInteger positive) { static TBigInteger andNotNegativePositive(TBigInteger negative, TBigInteger positive) {
// PRE: negative < 0 && positive > 0 // PRE: negative < 0 && positive > 0
int resLength; int resLength;
int resDigits[]; int[] resDigits;
int limit; int limit;
int digit; int digit;
@ -326,7 +332,7 @@ class TLogical {
if (iPos > iNeg) { if (iPos > iNeg) {
resDigits = new int[resLength]; resDigits = new int[resLength];
limit = Math.min(negative.numberLength, iPos); limit = Math.min(negative.numberLength, iPos);
for ( ; i < limit; i++) { for (; i < limit; i++) {
// 1st case: resDigits [i] = -(-negative.digits[i] & (~0)) // 1st case: resDigits [i] = -(-negative.digits[i] & (~0))
// otherwise: resDigits[i] = ~(~negative.digits[i] & ~0) ; // otherwise: resDigits[i] = ~(~negative.digits[i] & ~0) ;
resDigits[i] = negative.digits[i]; resDigits[i] = negative.digits[i];
@ -341,16 +347,25 @@ class TLogical {
digit = -negative.digits[i] & ~positive.digits[i]; digit = -negative.digits[i] & ~positive.digits[i];
if (digit == 0) { if (digit == 0) {
limit = Math.min(positive.numberLength, negative.numberLength); limit = Math.min(positive.numberLength, negative.numberLength);
for (i++; i < limit && (digit = ~(negative.digits[i] | positive.digits[i])) == 0; i++) { for (i++; i < limit; i++) {
// do nothing digit = ~(negative.digits[i] | positive.digits[i]);
if (digit != 0) {
break;
}
} }
if (digit == 0) { if (digit == 0) {
// the shorter has only the remaining virtual sign bits // the shorter has only the remaining virtual sign bits
for ( ; i < positive.numberLength && (digit = ~positive.digits[i]) == 0; i++) { for (; i < positive.numberLength; i++) {
// do nothing digit = ~positive.digits[i];
if (digit != 0) {
break;
}
} }
for ( ; i < negative.numberLength && (digit = ~negative.digits[i]) == 0; i++) { for (; i < negative.numberLength; i++) {
// do nothing digit = ~negative.digits[i];
if (digit != 0) {
break;
}
} }
if (digit == 0) { if (digit == 0) {
resLength++; resLength++;
@ -368,15 +383,15 @@ class TLogical {
} }
limit = Math.min(positive.numberLength, negative.numberLength); limit = Math.min(positive.numberLength, negative.numberLength);
for ( ; i < limit; i++) { for (; i < limit; i++) {
//resDigits[i] = ~(~negative.digits[i] & ~positive.digits[i]); //resDigits[i] = ~(~negative.digits[i] & ~positive.digits[i]);
resDigits[i] = negative.digits[i] | positive.digits[i]; resDigits[i] = negative.digits[i] | positive.digits[i];
} }
// Actually one of the next two cycles will be executed // Actually one of the next two cycles will be executed
for ( ; i < negative.numberLength; i++) { for (; i < negative.numberLength; i++) {
resDigits[i] = negative.digits[i]; resDigits[i] = negative.digits[i];
} }
for ( ; i < positive.numberLength; i++) { for (; i < positive.numberLength; i++) {
resDigits[i] = positive.digits[i]; resDigits[i] = positive.digits[i];
} }
@ -395,7 +410,7 @@ class TLogical {
} }
int resLength = that.numberLength; int resLength = that.numberLength;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
int limit; int limit;
int i = iVal; int i = iVal;
if (iVal < iThat) { if (iVal < iThat) {
@ -407,7 +422,7 @@ class TLogical {
resDigits[i] = ~val.digits[i]; resDigits[i] = ~val.digits[i];
} }
if (i == val.numberLength) { if (i == val.numberLength) {
for ( ; i < iThat; i++) { for (; i < iThat; i++) {
// resDigits[i] = -1 & -1; // resDigits[i] = -1 & -1;
resDigits[i] = -1; resDigits[i] = -1;
} }
@ -417,7 +432,7 @@ class TLogical {
// resDigits[i] = ~val.digits[i] & ~-that.digits[i]; // resDigits[i] = ~val.digits[i] & ~-that.digits[i];
resDigits[i] = ~val.digits[i] & (that.digits[i] - 1); resDigits[i] = ~val.digits[i] & (that.digits[i] - 1);
} }
} else if (iThat < iVal ) { } else if (iThat < iVal) {
// resDigits[i] = -val.digits[i] & ~~that.digits[i]; // resDigits[i] = -val.digits[i] & ~~that.digits[i];
resDigits[i] = -val.digits[i] & that.digits[i]; resDigits[i] = -val.digits[i] & that.digits[i];
} else { } else {
@ -430,7 +445,7 @@ class TLogical {
// resDigits[i] = ~val.digits[i] & ~~that.digits[i]; // resDigits[i] = ~val.digits[i] & ~~that.digits[i];
resDigits[i] = ~val.digits[i] & that.digits[i]; resDigits[i] = ~val.digits[i] & that.digits[i];
} }
for ( ; i < that.numberLength; i++) { for (; i < that.numberLength; i++) {
// resDigits[i] = -1 & ~~that.digits[i]; // resDigits[i] = -1 & ~~that.digits[i];
resDigits[i] = that.digits[i]; resDigits[i] = that.digits[i];
} }
@ -478,13 +493,13 @@ class TLogical {
// PRE: longer and shorter are positive; // PRE: longer and shorter are positive;
// PRE: longer has at least as many digits as shorter // PRE: longer has at least as many digits as shorter
int resLength = longer.numberLength; int resLength = longer.numberLength;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
int i = Math.min(longer.getFirstNonzeroDigit(), shorter.getFirstNonzeroDigit()); int i = Math.min(longer.getFirstNonzeroDigit(), shorter.getFirstNonzeroDigit());
for (i = 0; i < shorter.numberLength; i++) { for (i = 0; i < shorter.numberLength; i++) {
resDigits[i] = longer.digits[i] | shorter.digits[i]; resDigits[i] = longer.digits[i] | shorter.digits[i];
} }
for ( ; i < resLength; i++) { for (; i < resLength; i++) {
resDigits[i] = longer.digits[i]; resDigits[i] = longer.digits[i];
} }
@ -493,7 +508,7 @@ class TLogical {
} }
/** @return sign = -1, magnitude = -(-val.magnitude | -that.magnitude) */ /** @return sign = -1, magnitude = -(-val.magnitude | -that.magnitude) */
static TBigInteger orNegative(TBigInteger val, TBigInteger that){ static TBigInteger orNegative(TBigInteger val, TBigInteger that) {
// PRE: val and that are negative; // PRE: val and that are negative;
// PRE: val has at least as many trailing zeros digits as that // PRE: val has at least as many trailing zeros digits as that
int iThat = that.getFirstNonzeroDigit(); int iThat = that.getFirstNonzeroDigit();
@ -502,12 +517,12 @@ class TLogical {
if (iVal >= that.numberLength) { if (iVal >= that.numberLength) {
return that; return that;
}else if (iThat >= val.numberLength) { } else if (iThat >= val.numberLength) {
return val; return val;
} }
int resLength = Math.min(val.numberLength, that.numberLength); int resLength = Math.min(val.numberLength, that.numberLength);
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
//Looking for the first non-zero digit of the result //Looking for the first non-zero digit of the result
if (iThat == iVal) { if (iThat == iVal) {
@ -530,7 +545,7 @@ class TLogical {
} }
/** @return sign = -1, magnitude = -(positive.magnitude | -negative.magnitude) */ /** @return sign = -1, magnitude = -(positive.magnitude | -negative.magnitude) */
static TBigInteger orDiffSigns(TBigInteger positive, TBigInteger negative){ static TBigInteger orDiffSigns(TBigInteger positive, TBigInteger negative) {
// Jumping over the least significant zero bits // Jumping over the least significant zero bits
int iNeg = negative.getFirstNonzeroDigit(); int iNeg = negative.getFirstNonzeroDigit();
int iPos = positive.getFirstNonzeroDigit(); int iPos = positive.getFirstNonzeroDigit();
@ -543,9 +558,9 @@ class TLogical {
return negative; return negative;
} }
int resLength = negative.numberLength; int resLength = negative.numberLength;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
if (iNeg < iPos ) { if (iNeg < iPos) {
// We know for sure that this will // We know for sure that this will
// be the first non zero digit in the result // be the first non zero digit in the result
for (i = iNeg; i < iPos; i++) { for (i = iNeg; i < iPos; i++) {
@ -555,20 +570,21 @@ class TLogical {
i = iPos; i = iPos;
resDigits[i] = -positive.digits[i]; resDigits[i] = -positive.digits[i];
limit = Math.min(positive.numberLength, iNeg); limit = Math.min(positive.numberLength, iNeg);
for(i++; i < limit; i++ ) { for (i++; i < limit; i++) {
resDigits[i] = ~positive.digits[i]; resDigits[i] = ~positive.digits[i];
} }
if (i != positive.numberLength) { if (i != positive.numberLength) {
resDigits[i] = ~(-negative.digits[i] | positive.digits[i]); resDigits[i] = ~(-negative.digits[i] | positive.digits[i]);
} else{ } else {
for (; i<iNeg; i++) { for (; i < iNeg; i++) {
resDigits[i] = -1; resDigits[i] = -1;
} }
// resDigits[i] = ~(-negative.digits[i] | 0); // resDigits[i] = ~(-negative.digits[i] | 0);
resDigits[i] = negative.digits[i] - 1; resDigits[i] = negative.digits[i] - 1;
} }
i++; i++;
} else {// iNeg == iPos } else {
// iNeg == iPos
// Applying two complement to negative and to result // Applying two complement to negative and to result
i = iPos; i = iPos;
resDigits[i] = -(-negative.digits[i] | positive.digits[i]); resDigits[i] = -(-negative.digits[i] | positive.digits[i]);
@ -580,7 +596,7 @@ class TLogical {
// resDigits[i] = ~(~negative.digits[i] | positive.digits[i] ); // resDigits[i] = ~(~negative.digits[i] | positive.digits[i] );
resDigits[i] = negative.digits[i] & ~positive.digits[i]; resDigits[i] = negative.digits[i] & ~positive.digits[i];
} }
for( ; i < negative.numberLength; i++) { for (; i < negative.numberLength; i++) {
resDigits[i] = negative.digits[i]; resDigits[i] = negative.digits[i];
} }
@ -630,12 +646,12 @@ class TLogical {
// PRE: longer and shorter are positive; // PRE: longer and shorter are positive;
// PRE: longer has at least as many digits as shorter // PRE: longer has at least as many digits as shorter
int resLength = longer.numberLength; int resLength = longer.numberLength;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
int i = Math.min(longer.getFirstNonzeroDigit(), shorter.getFirstNonzeroDigit()); int i = Math.min(longer.getFirstNonzeroDigit(), shorter.getFirstNonzeroDigit());
for ( ; i < shorter.numberLength; i++) { for (; i < shorter.numberLength; i++) {
resDigits[i] = longer.digits[i] ^ shorter.digits[i]; resDigits[i] = longer.digits[i] ^ shorter.digits[i];
} }
for( ; i < longer.numberLength; i++ ){ for (; i < longer.numberLength; i++) {
resDigits[i] = longer.digits[i]; resDigits[i] = longer.digits[i];
} }
@ -645,11 +661,11 @@ class TLogical {
} }
/** @return sign = 0, magnitude = -val.magnitude ^ -that.magnitude */ /** @return sign = 0, magnitude = -val.magnitude ^ -that.magnitude */
static TBigInteger xorNegative(TBigInteger val, TBigInteger that){ static TBigInteger xorNegative(TBigInteger val, TBigInteger that) {
// PRE: val and that are negative // PRE: val and that are negative
// PRE: val has at least as many trailing zero digits as that // PRE: val has at least as many trailing zero digits as that
int resLength = Math.max(val.numberLength, that.numberLength); int resLength = Math.max(val.numberLength, that.numberLength);
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
int iVal = val.getFirstNonzeroDigit(); int iVal = val.getFirstNonzeroDigit();
int iThat = that.getFirstNonzeroDigit(); int iThat = that.getFirstNonzeroDigit();
int i = iThat; int i = iThat;
@ -667,7 +683,7 @@ class TLogical {
// Remains digits in that? // Remains digits in that?
if (i == that.numberLength) { if (i == that.numberLength) {
//Jumping over the remaining zero to the first non one //Jumping over the remaining zero to the first non one
for ( ;i < iVal; i++) { for (; i < iVal; i++) {
//resDigits[i] = 0 ^ -1; //resDigits[i] = 0 ^ -1;
resDigits[i] = -1; resDigits[i] = -1;
} }
@ -685,11 +701,11 @@ class TLogical {
resDigits[i] = val.digits[i] ^ that.digits[i]; resDigits[i] = val.digits[i] ^ that.digits[i];
} }
//Perform ^ between val digits and -1 until val ends //Perform ^ between val digits and -1 until val ends
for ( ; i < val.numberLength; i++) { for (; i < val.numberLength; i++) {
//resDigits[i] = ~val.digits[i] ^ -1 ; //resDigits[i] = ~val.digits[i] ^ -1 ;
resDigits[i] = val.digits[i] ; resDigits[i] = val.digits[i];
} }
for ( ; i < that.numberLength; i++) { for (; i < that.numberLength; i++) {
//resDigits[i] = -1 ^ ~that.digits[i] ; //resDigits[i] = -1 ^ ~that.digits[i] ;
resDigits[i] = that.digits[i]; resDigits[i] = that.digits[i];
} }
@ -700,9 +716,9 @@ class TLogical {
} }
/** @return sign = 1, magnitude = -(positive.magnitude ^ -negative.magnitude)*/ /** @return sign = 1, magnitude = -(positive.magnitude ^ -negative.magnitude)*/
static TBigInteger xorDiffSigns(TBigInteger positive, TBigInteger negative){ static TBigInteger xorDiffSigns(TBigInteger positive, TBigInteger negative) {
int resLength = Math.max(negative.numberLength, positive.numberLength); int resLength = Math.max(negative.numberLength, positive.numberLength);
int resDigits[]; int[] resDigits;
int iNeg = negative.getFirstNonzeroDigit(); int iNeg = negative.getFirstNonzeroDigit();
int iPos = positive.getFirstNonzeroDigit(); int iPos = positive.getFirstNonzeroDigit();
int i; int i;
@ -723,7 +739,7 @@ class TLogical {
//if the negative has no more elements, must fill the //if the negative has no more elements, must fill the
//result with the remaining digits of the positive //result with the remaining digits of the positive
if (i == negative.numberLength) { if (i == negative.numberLength) {
for ( ; i < positive.numberLength; i++) { for (; i < positive.numberLength; i++) {
//resDigits[i] = ~(positive.digits[i] ^ -1) -> ~(~positive.digits[i]) //resDigits[i] = ~(positive.digits[i] ^ -1) -> ~(~positive.digits[i])
resDigits[i] = positive.digits[i]; resDigits[i] = positive.digits[i];
} }
@ -746,11 +762,11 @@ class TLogical {
} else { } else {
//if the positive has no more elements must fill the remaining digits with //if the positive has no more elements must fill the remaining digits with
//the negative ones //the negative ones
for ( ; i < iNeg; i++) { for (; i < iNeg; i++) {
// resDigits[i] = ~(0 ^ 0) // resDigits[i] = ~(0 ^ 0)
resDigits[i] = -1; resDigits[i] = -1;
} }
for ( ; i < negative.numberLength; i++) { for (; i < negative.numberLength; i++) {
//resDigits[i] = ~(~negative.digits[i] ^ 0) //resDigits[i] = ~(~negative.digits[i] ^ 0)
resDigits[i] = negative.digits[i]; resDigits[i] = negative.digits[i];
} }
@ -762,16 +778,25 @@ class TLogical {
digit = positive.digits[i] ^ -negative.digits[i]; digit = positive.digits[i] ^ -negative.digits[i];
if (digit == 0) { if (digit == 0) {
limit = Math.min(positive.numberLength, negative.numberLength); limit = Math.min(positive.numberLength, negative.numberLength);
for (i++; i < limit && (digit = positive.digits[i] ^ ~negative.digits[i]) == 0; i++) { for (i++; i < limit; i++) {
// do nothing digit = positive.digits[i] ^ ~negative.digits[i];
if (digit != 0) {
break;
}
} }
if (digit == 0) { if (digit == 0) {
// shorter has only the remaining virtual sign bits // shorter has only the remaining virtual sign bits
for ( ; i < positive.numberLength && (digit = ~positive.digits[i]) == 0; i++) { for (; i < positive.numberLength; i++) {
// do nothing digit = ~positive.digits[i];
if (digit != 0) {
break;
}
} }
for ( ; i < negative.numberLength && (digit = ~negative.digits[i]) == 0; i++) { for (; i < negative.numberLength; i++) {
// do nothing digit = ~negative.digits[i];
if (digit != 0) {
break;
}
} }
if (digit == 0) { if (digit == 0) {
resLength = resLength + 1; resLength = resLength + 1;
@ -789,14 +814,14 @@ class TLogical {
} }
limit = Math.min(negative.numberLength, positive.numberLength); limit = Math.min(negative.numberLength, positive.numberLength);
for ( ; i < limit; i++) { for (; i < limit; i++) {
resDigits[i] = ~(~negative.digits[i] ^ positive.digits[i]); resDigits[i] = ~(~negative.digits[i] ^ positive.digits[i]);
} }
for ( ; i < positive.numberLength; i++) { for (; i < positive.numberLength; i++) {
// resDigits[i] = ~(positive.digits[i] ^ -1) // resDigits[i] = ~(positive.digits[i] ^ -1)
resDigits[i] = positive.digits[i]; resDigits[i] = positive.digits[i];
} }
for ( ; i < negative.numberLength; i++) { for (; i < negative.numberLength; i++) {
// resDigits[i] = ~(0 ^ ~negative.digits[i]) // resDigits[i] = ~(0 ^ ~negative.digits[i])
resDigits[i] = negative.digits[i]; resDigits[i] = negative.digits[i];
} }

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
import java.io.Serializable; import java.io.Serializable;
@ -249,9 +247,9 @@ public final class TMathContext implements Serializable {
*/ */
@Override @Override
public boolean equals(Object x) { public boolean equals(Object x) {
return ((x instanceof TMathContext) return x instanceof TMathContext
&& (((TMathContext) x).getPrecision() == precision) && (((TMathContext) x) && (((TMathContext) x).getPrecision() == precision) && (((TMathContext) x)
.getRoundingMode() == roundingMode)); .getRoundingMode() == roundingMode);
} }
/** /**
@ -262,7 +260,7 @@ public final class TMathContext implements Serializable {
@Override @Override
public int hashCode() { public int hashCode() {
// Make place for the necessary bits to represent 8 rounding modes // Make place for the necessary bits to represent 8 rounding modes
return ((precision << 3) | roundingMode.ordinal()); return (precision << 3) | roundingMode.ordinal();
} }
/** /**

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**
@ -23,7 +21,8 @@ package org.teavm.classlib.java.math;
class TMultiplication { class TMultiplication {
/** Just to denote that this class can't be instantiated. */ /** Just to denote that this class can't be instantiated. */
private TMultiplication() {} private TMultiplication() {
}
/** /**
* Break point in digits (number of {@code int} elements) * Break point in digits (number of {@code int} elements)
@ -35,7 +34,7 @@ class TMultiplication {
* An array with powers of ten that fit in the type {@code int}. * An array with powers of ten that fit in the type {@code int}.
* ({@code 10^0,10^1,...,10^9}) * ({@code 10^0,10^1,...,10^9})
*/ */
static final int tenPows[] = { static final int[] tenPows = {
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000
}; };
@ -43,7 +42,7 @@ class TMultiplication {
* An array with powers of five that fit in the type {@code int}. * An array with powers of five that fit in the type {@code int}.
* ({@code 5^0,5^1,...,5^13}) * ({@code 5^0,5^1,...,5^13})
*/ */
static final int fivePows[] = { static final int[] fivePows = {
1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625,
1953125, 9765625, 48828125, 244140625, 1220703125 1953125, 9765625, 48828125, 244140625, 1220703125
}; };
@ -58,9 +57,7 @@ class TMultiplication {
* An array with the first powers of five in {@code BigInteger} version. * An array with the first powers of five in {@code BigInteger} version.
* ({@code 5^0,5^1,...,5^31}) * ({@code 5^0,5^1,...,5^31})
*/ */
static final TBigInteger bigFivePows[] = new TBigInteger[32]; static final TBigInteger[] bigFivePows = new TBigInteger[32];
static { static {
int i; int i;
@ -93,7 +90,8 @@ class TMultiplication {
* v = v<sub>1</sub> * B + v<sub>0</sub><br> * v = v<sub>1</sub> * B + v<sub>0</sub><br>
* *
* *
* u*v = (u<sub>1</sub> * v<sub>1</sub>) * B<sub>2</sub> + ((u<sub>1</sub> - u<sub>0</sub>) * (v<sub>0</sub> - v<sub>1</sub>) + u<sub>1</sub> * v<sub>1</sub> + * u*v = (u<sub>1</sub> * v<sub>1</sub>) * B<sub>2</sub> + ((u<sub>1</sub> - u<sub>0</sub>)
* * (v<sub>0</sub> - v<sub>1</sub>) + u<sub>1</sub> * v<sub>1</sub> +
* u<sub>0</sub> * v<sub>0</sub> ) * B + u<sub>0</sub> * v<sub>0</sub><br> * u<sub>0</sub> * v<sub>0</sub> ) * B + u<sub>0</sub> * v<sub>0</sub><br>
*</tt> *</tt>
* @param op1 first factor of the product * @param op1 first factor of the product
@ -124,8 +122,7 @@ class TMultiplication {
TBigInteger upper = karatsuba(upperOp1, upperOp2); TBigInteger upper = karatsuba(upperOp1, upperOp2);
TBigInteger lower = karatsuba(lowerOp1, lowerOp2); TBigInteger lower = karatsuba(lowerOp1, lowerOp2);
TBigInteger middle = karatsuba( upperOp1.subtract(lowerOp1), TBigInteger middle = karatsuba(upperOp1.subtract(lowerOp1), lowerOp2.subtract(upperOp2));
lowerOp2.subtract(upperOp2));
middle = middle.add(upper).add(lower); middle = middle.add(upper).add(lower);
middle = middle.shiftLeft(ndiv2); middle = middle.shiftLeft(ndiv2);
upper = upper.shiftLeft(ndiv2 << 1); upper = upper.shiftLeft(ndiv2 << 1);
@ -229,15 +226,15 @@ class TMultiplication {
// A special case when both numbers don't exceed int // A special case when both numbers don't exceed int
if (resLength == 2) { if (resLength == 2) {
long val = unsignedMultAddAdd(a.digits[0], b.digits[0], 0, 0); long val = unsignedMultAddAdd(a.digits[0], b.digits[0], 0, 0);
int valueLo = (int)val; int valueLo = (int) val;
int valueHi = (int)(val >>> 32); int valueHi = (int) (val >>> 32);
return ((valueHi == 0) return valueHi == 0
? new TBigInteger(resSign, valueLo) ? new TBigInteger(resSign, valueLo)
: new TBigInteger(resSign, 2, new int[]{valueLo, valueHi})); : new TBigInteger(resSign, 2, new int[] { valueLo, valueHi });
} }
int[] aDigits = a.digits; int[] aDigits = a.digits;
int[] bDigits = b.digits; int[] bDigits = b.digits;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
// Common case // Common case
multArraysPAP(aDigits, aLen, bDigits, bLen, resDigits); multArraysPAP(aDigits, aLen, bDigits, bLen, resDigits);
TBigInteger result = new TBigInteger(resSign, resLength, resDigits); TBigInteger result = new TBigInteger(resSign, resLength, resDigits);
@ -246,32 +243,34 @@ class TMultiplication {
} }
static void multArraysPAP(int[] aDigits, int aLen, int[] bDigits, int bLen, int[] resDigits) { static void multArraysPAP(int[] aDigits, int aLen, int[] bDigits, int bLen, int[] resDigits) {
if(aLen == 0 || bLen == 0) return; if (aLen == 0 || bLen == 0) {
return;
}
if(aLen == 1) { if (aLen == 1) {
resDigits[bLen] = multiplyByInt(resDigits, bDigits, bLen, aDigits[0]); resDigits[bLen] = multiplyByInt(resDigits, bDigits, bLen, aDigits[0]);
} else if(bLen == 1) { } else if (bLen == 1) {
resDigits[aLen] = multiplyByInt(resDigits, aDigits, aLen, bDigits[0]); resDigits[aLen] = multiplyByInt(resDigits, aDigits, aLen, bDigits[0]);
} else { } else {
multPAP(aDigits, bDigits, resDigits, aLen, bLen); multPAP(aDigits, bDigits, resDigits, aLen, bLen);
} }
} }
static void multPAP(int a[], int b[], int t[], int aLen, int bLen) { static void multPAP(int[] a, int[] b, int[] t, int aLen, int bLen) {
if(a == b && aLen == bLen) { if (a == b && aLen == bLen) {
square(a, aLen, t); square(a, aLen, t);
return; return;
} }
for(int i = 0; i < aLen; i++){ for (int i = 0; i < aLen; i++) {
long carry = 0; long carry = 0;
int aI = a[i]; int aI = a[i];
for (int j = 0; j < bLen; j++){ for (int j = 0; j < bLen; j++) {
carry = unsignedMultAddAdd(aI, b[j], t[i+j], (int)carry); carry = unsignedMultAddAdd(aI, b[j], t[i + j], (int) carry);
t[i+j] = (int) carry; t[i + j] = (int) carry;
carry >>>= 32; carry >>>= 32;
} }
t[i+bLen] = (int) carry; t[i + bLen] = (int) carry;
} }
} }
@ -283,14 +282,14 @@ class TMultiplication {
* @param factor the multiplier * @param factor the multiplier
* @return the top digit of production * @return the top digit of production
*/ */
private static int multiplyByInt(int res[], int a[], final int aSize, final int factor) { private static int multiplyByInt(int[] res, int[] a, final int aSize, final int factor) {
long carry = 0; long carry = 0;
for (int i = 0; i < aSize; i++) { for (int i = 0; i < aSize; i++) {
carry = unsignedMultAddAdd(a[i], factor, (int)carry, 0); carry = unsignedMultAddAdd(a[i], factor, (int) carry, 0);
res[i] = (int)carry; res[i] = (int) carry;
carry >>>= 32; carry >>>= 32;
} }
return (int)carry; return (int) carry;
} }
@ -301,7 +300,7 @@ class TMultiplication {
* @param factor the multiplier * @param factor the multiplier
* @return the top digit of production * @return the top digit of production
*/ */
static int multiplyByInt(int a[], final int aSize, final int factor) { static int multiplyByInt(int[] a, final int aSize, final int factor) {
return multiplyByInt(a, a, aSize, factor); return multiplyByInt(a, a, aSize, factor);
} }
@ -321,15 +320,15 @@ class TMultiplication {
if (aNumberLength == 1) { if (aNumberLength == 1) {
long res = unsignedMultAddAdd(aDigits[0], factor, 0, 0); long res = unsignedMultAddAdd(aDigits[0], factor, 0, 0);
int resLo = (int)res; int resLo = (int) res;
int resHi = (int)(res >>> 32); int resHi = (int) (res >>> 32);
return ((resHi == 0) return resHi == 0
? new TBigInteger(resSign, resLo) ? new TBigInteger(resSign, resLo)
: new TBigInteger(resSign, 2, new int[]{resLo, resHi})); : new TBigInteger(resSign, 2, new int[] { resLo, resHi });
} }
// Common case // Common case
int resLength = aNumberLength + 1; int resLength = aNumberLength + 1;
int resDigits[] = new int[resLength]; int[] resDigits = new int[resLength];
resDigits[aNumberLength] = multiplyByInt(resDigits, aDigits, aNumberLength, factor); resDigits[aNumberLength] = multiplyByInt(resDigits, aDigits, aNumberLength, factor);
TBigInteger result = new TBigInteger(resSign, resLength, resDigits); TBigInteger result = new TBigInteger(resSign, resLength, resDigits);
@ -349,11 +348,10 @@ class TMultiplication {
} }
// acc = base^(2^i) // acc = base^(2^i)
//a limit where karatsuba performs a faster square than the square algorithm //a limit where karatsuba performs a faster square than the square algorithm
if ( acc.numberLength == 1 ){ if (acc.numberLength == 1) {
acc = acc.multiply(acc); // square acc = acc.multiply(acc); // square
} } else {
else{ acc = new TBigInteger(1, square(acc.digits, acc.numberLength, new int[acc.numberLength << 1]));
acc = new TBigInteger(1, square(acc.digits, acc.numberLength, new int [acc.numberLength<<1]));
} }
} }
// exponent == 1, multiply one more time // exponent == 1, multiply one more time
@ -369,26 +367,26 @@ class TMultiplication {
static int[] square(int[] a, int aLen, int[] res) { static int[] square(int[] a, int aLen, int[] res) {
long carry; long carry;
for(int i = 0; i < aLen; i++){ for (int i = 0; i < aLen; i++) {
carry = 0; carry = 0;
for (int j = i+1; j < aLen; j++){ for (int j = i + 1; j < aLen; j++) {
carry = unsignedMultAddAdd(a[i], a[j], res[i+j], (int)carry); carry = unsignedMultAddAdd(a[i], a[j], res[i + j], (int) carry);
res[i+j] = (int) carry; res[i + j] = (int) carry;
carry >>>= 32; carry >>>= 32;
} }
res[i+aLen] = (int) carry; res[i + aLen] = (int) carry;
} }
TBitLevel.shiftLeftOneBit(res, res, aLen << 1); TBitLevel.shiftLeftOneBit(res, res, aLen << 1);
carry = 0; carry = 0;
for(int i = 0, index = 0; i < aLen; i++, index++){ for (int i = 0, index = 0; i < aLen; i++, index++) {
carry = unsignedMultAddAdd(a[i], a[i], res[index],(int)carry); carry = unsignedMultAddAdd(a[i], a[i], res[index], (int) carry);
res[index] = (int) carry; res[index] = (int) carry;
carry >>>= 32; carry >>>= 32;
index++; index++;
carry += res[index] & 0xFFFFFFFFL; carry += res[index] & 0xFFFFFFFFL;
res[index] = (int)carry; res[index] = (int) carry;
carry >>>= 32; carry >>>= 32;
} }
return res; return res;
@ -403,9 +401,9 @@ class TMultiplication {
*/ */
static TBigInteger multiplyByTenPow(TBigInteger val, long exp) { static TBigInteger multiplyByTenPow(TBigInteger val, long exp) {
// PRE: exp >= 0 // PRE: exp >= 0
return ((exp < tenPows.length) return exp < tenPows.length
? multiplyByPositiveInt(val, tenPows[(int)exp]) ? multiplyByPositiveInt(val, tenPows[(int) exp])
: val.multiply(powerOf10(exp))); : val.multiply(powerOf10(exp));
} }
/** /**
@ -417,7 +415,7 @@ class TMultiplication {
*/ */
static TBigInteger powerOf10(long exp) { static TBigInteger powerOf10(long exp) {
// PRE: exp >= 0 // PRE: exp >= 0
int intExp = (int)exp; int intExp = (int) exp;
// "SMALL POWERS" // "SMALL POWERS"
if (exp < bigTenPows.length) { if (exp < bigTenPows.length) {
// The largest power that fit in 'long' type // The largest power that fit in 'long' type
@ -434,7 +432,7 @@ class TMultiplication {
* To check if there is free memory to allocate a BigInteger of the * To check if there is free memory to allocate a BigInteger of the
* estimated size, measured in bytes: 1 + [exp / log10(2)] * estimated size, measured in bytes: 1 + [exp / log10(2)]
*/ */
long byteArraySize = 1 + (long)(exp / 2.4082399653118496); long byteArraySize = 1 + (long) (exp / 2.4082399653118496);
if (byteArraySize > 1000000) { if (byteArraySize > 1000000) {
throw new ArithmeticException("power of ten too big"); throw new ArithmeticException("power of ten too big");
@ -454,7 +452,7 @@ class TMultiplication {
TBigInteger res = powerOfFive; TBigInteger res = powerOfFive;
long longExp = exp - Integer.MAX_VALUE; long longExp = exp - Integer.MAX_VALUE;
intExp = (int)(exp % Integer.MAX_VALUE); intExp = (int) (exp % Integer.MAX_VALUE);
while (longExp > Integer.MAX_VALUE) { while (longExp > Integer.MAX_VALUE) {
res = res.multiply(powerOfFive); res = res.multiply(powerOfFive);
longExp -= Integer.MAX_VALUE; longExp -= Integer.MAX_VALUE;
@ -484,7 +482,8 @@ class TMultiplication {
return multiplyByPositiveInt(val, fivePows[exp]); return multiplyByPositiveInt(val, fivePows[exp]);
} else if (exp < bigFivePows.length) { } else if (exp < bigFivePows.length) {
return val.multiply(bigFivePows[exp]); return val.multiply(bigFivePows[exp]);
} else {// Large powers of five } else {
// Large powers of five
return val.multiply(bigFivePows[1].pow(exp)); return val.multiply(bigFivePows[1].pow(exp));
} }
} }

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
import java.util.Arrays; import java.util.Arrays;
@ -30,7 +28,7 @@ class TPrimality {
} }
/** All prime numbers with bit length lesser than 10 bits. */ /** All prime numbers with bit length lesser than 10 bits. */
private static final int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, private static final int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307,
311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433,
@ -41,7 +39,7 @@ class TPrimality {
1009, 1013, 1019, 1021 }; 1009, 1013, 1019, 1021 };
/** All {@code BigInteger} prime numbers with bit length lesser than 8 bits. */ /** All {@code BigInteger} prime numbers with bit length lesser than 8 bits. */
private static final TBigInteger BIprimes[] = new TBigInteger[primes.length]; private static final TBigInteger[] BIprimes = new TBigInteger[primes.length];
/** /**
* It encodes how many iterations of Miller-Rabin test are need to get an * It encodes how many iterations of Miller-Rabin test are need to get an
@ -62,7 +60,8 @@ class TPrimality {
private static final int[][] offsetPrimes = { null, null, { 0, 2 }, { 2, 2 }, { 4, 2 }, { 6, 5 }, { 11, 7 }, private static final int[][] offsetPrimes = { null, null, { 0, 2 }, { 2, 2 }, { 4, 2 }, { 6, 5 }, { 11, 7 },
{ 18, 13 }, { 31, 23 }, { 54, 43 }, { 97, 75 } }; { 18, 13 }, { 31, 23 }, { 54, 43 }, { 97, 75 } };
static {// To initialize the dual table of BigInteger primes static {
// To initialize the dual table of BigInteger primes
for (int i = 0; i < primes.length; i++) { for (int i = 0; i < primes.length; i++) {
BIprimes[i] = TBigInteger.valueOf(primes[i]); BIprimes[i] = TBigInteger.valueOf(primes[i]);
} }
@ -79,11 +78,12 @@ class TPrimality {
*/ */
static TBigInteger nextProbablePrime(TBigInteger n) { static TBigInteger nextProbablePrime(TBigInteger n) {
// PRE: n >= 0 // PRE: n >= 0
int i, j; int i;
int j;
int certainty; int certainty;
int gapSize = 1024; // for searching of the next probable prime number int gapSize = 1024; // for searching of the next probable prime number
int modules[] = new int[primes.length]; int[] modules = new int[primes.length];
boolean isDivisible[] = new boolean[gapSize]; boolean[] isDivisible = new boolean[gapSize];
TBigInteger startPoint; TBigInteger startPoint;
TBigInteger probPrime; TBigInteger probPrime;
// If n < "last prime of table" searches next prime in the table // If n < "last prime of table" searches next prime in the table
@ -153,7 +153,7 @@ class TPrimality {
// PRE: bitLength >= 2; // PRE: bitLength >= 2;
// For small numbers get a random prime from the prime table // For small numbers get a random prime from the prime table
if (bitLength <= 10) { if (bitLength <= 10) {
int rp[] = offsetPrimes[bitLength]; int[] rp = offsetPrimes[bitLength];
return BIprimes[rp[0] + rnd.nextInt(rp[1])]; return BIprimes[rp[0] + rnd.nextInt(rp[1])];
} }
int shiftCount = (-bitLength) & 31; int shiftCount = (-bitLength) & 31;
@ -161,7 +161,8 @@ class TPrimality {
TBigInteger n = new TBigInteger(1, last, new int[last]); TBigInteger n = new TBigInteger(1, last, new int[last]);
last--; last--;
do {// To fill the array with random integers do {
// To fill the array with random integers
for (int i = 0; i < n.numberLength; i++) { for (int i = 0; i < n.numberLength; i++) {
n.digits[i] = rnd.nextInt(); n.digits[i] = rnd.nextInt();
} }
@ -190,8 +191,8 @@ class TPrimality {
return false; return false;
} }
// To check if 'n' exists in the table (it fit in 10 bits) // To check if 'n' exists in the table (it fit in 10 bits)
if ((n.numberLength == 1) && ((n.digits[0] & 0XFFFFFC00) == 0)) { if (n.numberLength == 1 && (n.digits[0] & 0XFFFFFC00) == 0) {
return (Arrays.binarySearch(primes, n.digits[0]) >= 0); return Arrays.binarySearch(primes, n.digits[0]) >= 0;
} }
// To check if 'n' is divisible by some prime of the table // To check if 'n' is divisible by some prime of the table
for (int i = 1; i < primes.length; i++) { for (int i = 1; i < primes.length; i++) {
@ -227,32 +228,33 @@ class TPrimality {
// PRE: n >= 0, t >= 0 // PRE: n >= 0, t >= 0
TBigInteger x; // x := UNIFORM{2...n-1} TBigInteger x; // x := UNIFORM{2...n-1}
TBigInteger y; // y := x^(q * 2^j) mod n TBigInteger y; // y := x^(q * 2^j) mod n
TBigInteger n_minus_1 = n.subtract(TBigInteger.ONE); // n-1 TBigInteger nMinus1 = n.subtract(TBigInteger.ONE); // n-1
int bitLength = n_minus_1.bitLength(); // ~ log2(n-1) int bitLength = nMinus1.bitLength(); // ~ log2(n-1)
// (q,k) such that: n-1 = q * 2^k and q is odd // (q,k) such that: n-1 = q * 2^k and q is odd
int k = n_minus_1.getLowestSetBit(); int k = nMinus1.getLowestSetBit();
TBigInteger q = n_minus_1.shiftRight(k); TBigInteger q = nMinus1.shiftRight(k);
Random rnd = new Random(); Random rnd = new Random();
for (int i = 0; i < t; i++) { for (int i = 0; i < t; i++) {
// To generate a witness 'x', first it use the primes of table // To generate a witness 'x', first it use the primes of table
if (i < primes.length) { if (i < primes.length) {
x = BIprimes[i]; x = BIprimes[i];
} else {/* } else {
* It generates random witness only if it's necesssary. Note /*
* that all methods would call Miller-Rabin with t <= 50 so * It generates random witness only if it's necessary. Note
* this part is only to do more robust the algorithm * that all methods would call Miller-Rabin with t <= 50 so
*/ * this part is only to do more robust the algorithm
*/
do { do {
x = new TBigInteger(bitLength, rnd); x = new TBigInteger(bitLength, rnd);
} while ((x.compareTo(n) >= TBigInteger.EQUALS) || (x.sign == 0) || x.isOne()); } while ((x.compareTo(n) >= TBigInteger.EQUALS) || (x.sign == 0) || x.isOne());
} }
y = x.modPow(q, n); y = x.modPow(q, n);
if (y.isOne() || y.equals(n_minus_1)) { if (y.isOne() || y.equals(nMinus1)) {
continue; continue;
} }
for (int j = 1; j < k; j++) { for (int j = 1; j < k; j++) {
if (y.equals(n_minus_1)) { if (y.equals(nMinus1)) {
continue; continue;
} }
y = y.multiply(y).mod(n); y = y.multiply(y).mod(n);
@ -260,7 +262,7 @@ class TPrimality {
return false; return false;
} }
} }
if (!y.equals(n_minus_1)) { if (!y.equals(nMinus1)) {
return false; return false;
} }
} }

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.math; package org.teavm.classlib.java.math;
/** /**

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.net; package org.teavm.classlib.java.net;
import org.teavm.classlib.java.io.TSerializable; import org.teavm.classlib.java.io.TSerializable;
@ -42,7 +40,7 @@ public final class TURI implements TComparable<TURI>, TSerializable {
private transient TString fragment; private transient TString fragment;
private transient boolean opaque; private transient boolean opaque;
private transient boolean absolute; private transient boolean absolute;
private transient boolean serverAuthority = false; private transient boolean serverAuthority;
private transient int hash = -1; private transient int hash = -1;
private TURI() { private TURI() {
@ -124,8 +122,8 @@ public final class TURI implements TComparable<TURI>, TSerializable {
* if the temporary created string doesn't fit to the * if the temporary created string doesn't fit to the
* specification RFC2396 or could not be parsed correctly. * specification RFC2396 or could not be parsed correctly.
*/ */
public TURI(TString scheme, TString userinfo, TString host, int port, TString path, TString query, TString fragment) public TURI(TString scheme, TString userinfo, TString host, int port, TString path, TString query,
throws TURISyntaxException { TString fragment) throws TURISyntaxException {
if (scheme == null && userinfo == null && host == null && path == null && query == null && fragment == null) { if (scheme == null && userinfo == null && host == null && path == null && query == null && fragment == null) {
this.path = TString.wrap(""); this.path = TString.wrap("");
@ -273,7 +271,10 @@ public final class TURI implements TComparable<TURI>, TSerializable {
TString temp = uri; TString temp = uri;
// assign uri string to the input value per spec // assign uri string to the input value per spec
string = uri; string = uri;
int index, index1, index2, index3; int index;
int index1;
int index2;
int index3;
// parse into Fragment, Scheme, and SchemeSpecificPart // parse into Fragment, Scheme, and SchemeSpecificPart
// then parse SchemeSpecificPart if necessary // then parse SchemeSpecificPart if necessary
@ -287,7 +288,8 @@ public final class TURI implements TComparable<TURI>, TSerializable {
} }
// Scheme and SchemeSpecificPart // Scheme and SchemeSpecificPart
index = index1 = temp.indexOf(':'); index = temp.indexOf(':');
index1 = index;
index2 = temp.indexOf('/'); index2 = temp.indexOf('/');
index3 = temp.indexOf('?'); index3 = temp.indexOf('?');
@ -444,8 +446,11 @@ public final class TURI implements TComparable<TURI>, TSerializable {
return; return;
} }
TString temp, tempUserinfo = null, tempHost = null; TString temp;
int index, hostindex = 0; TString tempUserinfo = null;
TString tempHost = null;
int index;
int hostindex = 0;
int tempPort = -1; int tempPort = -1;
temp = authority; temp = authority;
@ -952,7 +957,8 @@ public final class TURI implements TComparable<TURI>, TSerializable {
return s; return s;
} }
int index = 0, previndex = 0; int index = 0;
int previndex = 0;
while ((index = s.indexOf('%', previndex)) != -1) { while ((index = s.indexOf('%', previndex)) != -1) {
result.append(s.substring(previndex, index + 1)); result.append(s.substring(previndex, index + 1));
result.append(s.substring(index + 1, index + 3).toLowerCase()); result.append(s.substring(index + 1, index + 3).toLowerCase());
@ -972,9 +978,17 @@ public final class TURI implements TComparable<TURI>, TSerializable {
return first.equals(second); return first.equals(second);
} }
int index = 0, previndex = 0; int index = 0;
while ((index = first.indexOf('%', previndex)) != -1 int previndex = 0;
&& second.indexOf('%', previndex) == index) { while (true) {
index = first.indexOf('%', previndex);
if (index == -1) {
break;
}
if (second.indexOf('%', previndex) != index) {
break;
}
boolean match = first.substring(previndex, index).equals(second.substring(previndex, index)); boolean match = first.substring(previndex, index).equals(second.substring(previndex, index));
if (!match) { if (!match) {
return false; return false;

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.net; package org.teavm.classlib.java.net;
import org.teavm.classlib.java.io.TByteArrayOutputStream; import org.teavm.classlib.java.io.TByteArrayOutputStream;
@ -32,6 +30,8 @@ import org.teavm.classlib.java.lang.TStringBuilder;
class TURIEncoderDecoder { class TURIEncoderDecoder {
static final TString digits = TString.wrap("0123456789ABCDEF"); static final TString digits = TString.wrap("0123456789ABCDEF");
private TURIEncoderDecoder() {
}
/** /**
* Validate a string by checking if it contains any characters other than: * Validate a string by checking if it contains any characters other than:

View File

@ -1,12 +1,11 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Copyright 2015 Alexey Andreev.
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.classlib.java.net; package org.teavm.classlib.java.net;
import org.teavm.classlib.java.lang.TException; import org.teavm.classlib.java.lang.TException;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
/** /**
@ -25,8 +40,8 @@ public abstract class TBuffer {
public final TBuffer position(int newPosition) { public final TBuffer position(int newPosition) {
if (newPosition < 0 || newPosition > limit) { if (newPosition < 0 || newPosition > limit) {
throw new IllegalArgumentException("New position " + newPosition + " is outside of range [0;" + throw new IllegalArgumentException("New position " + newPosition + " is outside of range [0;"
limit + "]"); + limit + "]");
} }
position = newPosition; position = newPosition;
if (newPosition < mark) { if (newPosition < mark) {
@ -41,8 +56,8 @@ public abstract class TBuffer {
public final TBuffer limit(int newLimit) { public final TBuffer limit(int newLimit) {
if (newLimit < 0 || newLimit > capacity) { if (newLimit < 0 || newLimit > capacity) {
throw new IllegalArgumentException("New limit " + newLimit + " is outside of range [0;" + throw new IllegalArgumentException("New limit " + newLimit + " is outside of range [0;"
capacity + "]"); + capacity + "]");
} }
if (mark > newLimit) { if (mark > newLimit) {
mark = -1; mark = -1;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
import org.teavm.classlib.java.lang.TRuntimeException; import org.teavm.classlib.java.lang.TRuntimeException;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
/** /**

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
import org.teavm.classlib.java.lang.TComparable; import org.teavm.classlib.java.lang.TComparable;
@ -60,8 +75,8 @@ public abstract class TByteBuffer extends TBuffer implements TComparable<TByteBu
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last byte in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last byte in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -99,8 +114,8 @@ public abstract class TByteBuffer extends TBuffer implements TComparable<TByteBu
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last byte in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last byte in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -139,8 +154,8 @@ public abstract class TByteBuffer extends TBuffer implements TComparable<TByteBu
@Override @Override
public String toString() { public String toString() {
return "[ByteBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark " + return "[ByteBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark "
(mark >= 0 ? " at " + mark : " is not set") + "]"; + (mark >= 0 ? " at " + mark : " is not set") + "]";
} }
@Override @Override
@ -161,7 +176,7 @@ public abstract class TByteBuffer extends TBuffer implements TComparable<TByteBu
if (!(obj instanceof TByteBuffer)) { if (!(obj instanceof TByteBuffer)) {
return false; return false;
} }
TByteBuffer other = (TByteBuffer)obj; TByteBuffer other = (TByteBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
/** /**
@ -112,9 +127,9 @@ class TByteBufferImpl extends TByteBuffer {
int b = array[start + position + 1] & 0xFF; int b = array[start + position + 1] & 0xFF;
position += 2; position += 2;
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
return (char)((a << 8) | b); return (char) ((a << 8) | b);
} else { } else {
return (char)((b << 8) | a); return (char) ((b << 8) | a);
} }
} }
@ -127,11 +142,11 @@ class TByteBufferImpl extends TByteBuffer {
throw new TBufferOverflowException(); throw new TBufferOverflowException();
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
} else { } else {
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
} }
return this; return this;
} }
@ -144,9 +159,9 @@ class TByteBufferImpl extends TByteBuffer {
int a = array[start + index] & 0xFF; int a = array[start + index] & 0xFF;
int b = array[start + index + 1] & 0xFF; int b = array[start + index + 1] & 0xFF;
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
return (char)((a << 8) | b); return (char) ((a << 8) | b);
} else { } else {
return (char)((b << 8) | a); return (char) ((b << 8) | a);
} }
} }
@ -159,11 +174,11 @@ class TByteBufferImpl extends TByteBuffer {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")"); throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")");
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + index] = (byte)(value >> 8); array[start + index] = (byte) (value >> 8);
array[start + index + 1] = (byte)value; array[start + index + 1] = (byte) value;
} else { } else {
array[start + index] = (byte)value; array[start + index] = (byte) value;
array[start + index + 1] = (byte)(value >> 8); array[start + index + 1] = (byte) (value >> 8);
} }
return this; return this;
} }
@ -187,9 +202,9 @@ class TByteBufferImpl extends TByteBuffer {
int b = array[start + position + 1] & 0xFF; int b = array[start + position + 1] & 0xFF;
position += 2; position += 2;
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
return (short)((a << 8) | b); return (short) ((a << 8) | b);
} else { } else {
return (short)((b << 8) | a); return (short) ((b << 8) | a);
} }
} }
@ -202,11 +217,11 @@ class TByteBufferImpl extends TByteBuffer {
throw new TBufferOverflowException(); throw new TBufferOverflowException();
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
} else { } else {
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
} }
return this; return this;
} }
@ -219,9 +234,9 @@ class TByteBufferImpl extends TByteBuffer {
int a = array[start + index] & 0xFF; int a = array[start + index] & 0xFF;
int b = array[start + index + 1] & 0xFF; int b = array[start + index + 1] & 0xFF;
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
return (short)((a << 8) | b); return (short) ((a << 8) | b);
} else { } else {
return (short)((b << 8) | a); return (short) ((b << 8) | a);
} }
} }
@ -234,11 +249,11 @@ class TByteBufferImpl extends TByteBuffer {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")"); throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")");
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + index] = (byte)(value >> 8); array[start + index] = (byte) (value >> 8);
array[start + index + 1] = (byte)value; array[start + index + 1] = (byte) value;
} else { } else {
array[start + index] = (byte)value; array[start + index] = (byte) value;
array[start + index + 1] = (byte)(value >> 8); array[start + index + 1] = (byte) (value >> 8);
} }
return this; return this;
} }
@ -279,15 +294,15 @@ class TByteBufferImpl extends TByteBuffer {
throw new TBufferOverflowException(); throw new TBufferOverflowException();
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte)(value >> 24); array[start + position++] = (byte) (value >> 24);
array[start + position++] = (byte)(value >> 16); array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
} else { } else {
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte)(value >> 16); array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte)(value >> 24); array[start + position++] = (byte) (value >> 24);
} }
return this; return this;
} }
@ -317,15 +332,15 @@ class TByteBufferImpl extends TByteBuffer {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")"); throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")");
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + index] = (byte)(value >> 24); array[start + index] = (byte) (value >> 24);
array[start + index + 1] = (byte)(value >> 16); array[start + index + 1] = (byte) (value >> 16);
array[start + index + 2] = (byte)(value >> 8); array[start + index + 2] = (byte) (value >> 8);
array[start + index + 3] = (byte)value; array[start + index + 3] = (byte) value;
} else { } else {
array[start + index] = (byte)value; array[start + index] = (byte) value;
array[start + index + 1] = (byte)(value >> 8); array[start + index + 1] = (byte) (value >> 8);
array[start + index + 2] = (byte)(value >> 16); array[start + index + 2] = (byte) (value >> 16);
array[start + index + 3] = (byte)(value >> 24); array[start + index + 3] = (byte) (value >> 24);
} }
return this; return this;
} }
@ -370,23 +385,23 @@ class TByteBufferImpl extends TByteBuffer {
throw new TBufferOverflowException(); throw new TBufferOverflowException();
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte)(value >> 56); array[start + position++] = (byte) (value >> 56);
array[start + position++] = (byte)(value >> 48); array[start + position++] = (byte) (value >> 48);
array[start + position++] = (byte)(value >> 40); array[start + position++] = (byte) (value >> 40);
array[start + position++] = (byte)(value >> 32); array[start + position++] = (byte) (value >> 32);
array[start + position++] = (byte)(value >> 24); array[start + position++] = (byte) (value >> 24);
array[start + position++] = (byte)(value >> 16); array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
} else { } else {
array[start + position++] = (byte)value; array[start + position++] = (byte) value;
array[start + position++] = (byte)(value >> 8); array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte)(value >> 16); array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte)(value >> 24); array[start + position++] = (byte) (value >> 24);
array[start + position++] = (byte)(value >> 32); array[start + position++] = (byte) (value >> 32);
array[start + position++] = (byte)(value >> 40); array[start + position++] = (byte) (value >> 40);
array[start + position++] = (byte)(value >> 48); array[start + position++] = (byte) (value >> 48);
array[start + position++] = (byte)(value >> 56); array[start + position++] = (byte) (value >> 56);
} }
return this; return this;
} }
@ -421,23 +436,23 @@ class TByteBufferImpl extends TByteBuffer {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")"); throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")");
} }
if (order == TByteOrder.BIG_ENDIAN) { if (order == TByteOrder.BIG_ENDIAN) {
array[start + index + 0] = (byte)(value >> 56); array[start + index + 0] = (byte) (value >> 56);
array[start + index + 1] = (byte)(value >> 48); array[start + index + 1] = (byte) (value >> 48);
array[start + index + 2] = (byte)(value >> 40); array[start + index + 2] = (byte) (value >> 40);
array[start + index + 3] = (byte)(value >> 32); array[start + index + 3] = (byte) (value >> 32);
array[start + index + 4] = (byte)(value >> 24); array[start + index + 4] = (byte) (value >> 24);
array[start + index + 5] = (byte)(value >> 16); array[start + index + 5] = (byte) (value >> 16);
array[start + index + 6] = (byte)(value >> 8); array[start + index + 6] = (byte) (value >> 8);
array[start + index + 7] = (byte)value; array[start + index + 7] = (byte) value;
} else { } else {
array[start + index + 0] = (byte)value; array[start + index + 0] = (byte) value;
array[start + index + 1] = (byte)(value >> 8); array[start + index + 1] = (byte) (value >> 8);
array[start + index + 2] = (byte)(value >> 16); array[start + index + 2] = (byte) (value >> 16);
array[start + index + 3] = (byte)(value >> 24); array[start + index + 3] = (byte) (value >> 24);
array[start + index + 4] = (byte)(value >> 24); array[start + index + 4] = (byte) (value >> 24);
array[start + index + 5] = (byte)(value >> 24); array[start + index + 5] = (byte) (value >> 24);
array[start + index + 6] = (byte)(value >> 24); array[start + index + 6] = (byte) (value >> 24);
array[start + index + 7] = (byte)(value >> 24); array[start + index + 7] = (byte) (value >> 24);
} }
return this; return this;
} }

View File

@ -97,8 +97,8 @@ public abstract class TCharBuffer extends TBuffer implements Comparable<TCharBuf
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last char in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last char in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -146,8 +146,8 @@ public abstract class TCharBuffer extends TBuffer implements Comparable<TCharBuf
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last char in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last char in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -176,8 +176,8 @@ public abstract class TCharBuffer extends TBuffer implements Comparable<TCharBuf
throw new IndexOutOfBoundsException("Start " + start + " is outside of range [0;" + src.length() + ")"); throw new IndexOutOfBoundsException("Start " + start + " is outside of range [0;" + src.length() + ")");
} }
if (end > src.length()) { if (end > src.length()) {
throw new IndexOutOfBoundsException("The last char in src " + end + " is outside " + throw new IndexOutOfBoundsException("The last char in src " + end + " is outside "
"of string of size " + src.length()); + "of string of size " + src.length());
} }
if (start > end) { if (start > end) {
throw new IndexOutOfBoundsException("Start " + start + " must be before end " + end); throw new IndexOutOfBoundsException("Start " + start + " must be before end " + end);
@ -238,7 +238,7 @@ public abstract class TCharBuffer extends TBuffer implements Comparable<TCharBuf
if (!(obj instanceof TCharBuffer)) { if (!(obj instanceof TCharBuffer)) {
return false; return false;
} }
TCharBuffer other = (TCharBuffer)obj; TCharBuffer other = (TCharBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -27,15 +27,15 @@ class TCharBufferOverByteBufferBigEndian extends TCharBufferOverByteBuffer {
@Override @Override
char getChar(int index) { char getChar(int index) {
int value = ((byteByffer.array[start + index * 2] & 0xFF) << 8) | int value = ((byteByffer.array[start + index * 2] & 0xFF) << 8)
(byteByffer.array[start + index * 2 + 1] & 0xFF); | (byteByffer.array[start + index * 2 + 1] & 0xFF);
return (char)value; return (char) value;
} }
@Override @Override
void putChar(int index, char value) { void putChar(int index, char value) {
byteByffer.array[start + index * 2] = (byte)(value >> 8); byteByffer.array[start + index * 2] = (byte) (value >> 8);
byteByffer.array[start + index * 2 + 1] = (byte)value; byteByffer.array[start + index * 2 + 1] = (byte) value;
} }
@Override @Override

View File

@ -27,15 +27,15 @@ class TCharBufferOverByteBufferLittleEndian extends TCharBufferOverByteBuffer {
@Override @Override
char getChar(int index) { char getChar(int index) {
int value = ((byteByffer.array[start + index * 2 + 1] & 0xFF) << 8) | int value = ((byteByffer.array[start + index * 2 + 1] & 0xFF) << 8)
(byteByffer.array[start + index * 2] & 0xFF); | (byteByffer.array[start + index * 2] & 0xFF);
return (char)value; return (char) value;
} }
@Override @Override
void putChar(int index, char value) { void putChar(int index, char value) {
byteByffer.array[start + index * 2] = (byte)value; byteByffer.array[start + index * 2] = (byte) value;
byteByffer.array[start + index * 2 + 1] = (byte)(value >> 8); byteByffer.array[start + index * 2 + 1] = (byte) (value >> 8);
} }
@Override @Override

View File

@ -64,8 +64,8 @@ public abstract class TDoubleBuffer extends TBuffer implements Comparable<TDoubl
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last double in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last double in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -113,8 +113,8 @@ public abstract class TDoubleBuffer extends TBuffer implements Comparable<TDoubl
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last double in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last double in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -159,8 +159,8 @@ public abstract class TDoubleBuffer extends TBuffer implements Comparable<TDoubl
@Override @Override
public String toString() { public String toString() {
return "[DoubleBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark " + return "[DoubleBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark "
(mark >= 0 ? " at " + mark : " is not set") + "]"; + (mark >= 0 ? " at " + mark : " is not set") + "]";
} }
@Override @Override
@ -169,7 +169,7 @@ public abstract class TDoubleBuffer extends TBuffer implements Comparable<TDoubl
int pos = position; int pos = position;
for (int i = position; i < limit; ++i) { for (int i = position; i < limit; ++i) {
long elem = Double.doubleToLongBits(getElement(pos++)); long elem = Double.doubleToLongBits(getElement(pos++));
hashCode = 31 * hashCode + (int)elem + (int)(elem >>> 32); hashCode = 31 * hashCode + (int) elem + (int) (elem >>> 32);
} }
return hashCode; return hashCode;
} }
@ -182,7 +182,7 @@ public abstract class TDoubleBuffer extends TBuffer implements Comparable<TDoubl
if (!(obj instanceof TDoubleBuffer)) { if (!(obj instanceof TDoubleBuffer)) {
return false; return false;
} }
TDoubleBuffer other = (TDoubleBuffer)obj; TDoubleBuffer other = (TDoubleBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -45,23 +45,23 @@ class TDoubleBufferOverByteBuffer extends TDoubleBufferImpl {
double getElement(int index) { double getElement(int index) {
long value; long value;
if (byteOrder == TByteOrder.BIG_ENDIAN) { if (byteOrder == TByteOrder.BIG_ENDIAN) {
value = (((long)byteByffer.array[start + index * 8] & 0xFF) << 56) | value = (((long) byteByffer.array[start + index * 8] & 0xFF) << 56)
(((long)byteByffer.array[start + index * 8 + 1] & 0xFF) << 48) | | (((long) byteByffer.array[start + index * 8 + 1] & 0xFF) << 48)
(((long)byteByffer.array[start + index * 8 + 2] & 0xFF) << 40) | | (((long) byteByffer.array[start + index * 8 + 2] & 0xFF) << 40)
(((long)byteByffer.array[start + index * 8 + 3] & 0xFF) << 32) | | (((long) byteByffer.array[start + index * 8 + 3] & 0xFF) << 32)
(((long)byteByffer.array[start + index * 8 + 4] & 0xFF) << 24) | | (((long) byteByffer.array[start + index * 8 + 4] & 0xFF) << 24)
(((long)byteByffer.array[start + index * 8 + 5] & 0xFF) << 16) | | (((long) byteByffer.array[start + index * 8 + 5] & 0xFF) << 16)
(((long)byteByffer.array[start + index * 8 + 6] & 0xFF) << 8) | | (((long) byteByffer.array[start + index * 8 + 6] & 0xFF) << 8)
(byteByffer.array[start + index * 8 + 7] & 0xFF); | (byteByffer.array[start + index * 8 + 7] & 0xFF);
} else { } else {
value = (byteByffer.array[start + index * 8] & 0xFF) | value = (byteByffer.array[start + index * 8] & 0xFF)
(((long)byteByffer.array[start + index * 8 + 1] & 0xFF) << 8) | | (((long) byteByffer.array[start + index * 8 + 1] & 0xFF) << 8)
(((long)byteByffer.array[start + index * 8 + 2] & 0xFF) << 16) | | (((long) byteByffer.array[start + index * 8 + 2] & 0xFF) << 16)
(((long)byteByffer.array[start + index * 8 + 3] & 0xFF) << 24) | | (((long) byteByffer.array[start + index * 8 + 3] & 0xFF) << 24)
(((long)byteByffer.array[start + index * 8 + 4] & 0xFF) << 32) | | (((long) byteByffer.array[start + index * 8 + 4] & 0xFF) << 32)
(((long)byteByffer.array[start + index * 8 + 5] & 0xFF) << 40) | | (((long) byteByffer.array[start + index * 8 + 5] & 0xFF) << 40)
(((long)byteByffer.array[start + index * 8 + 6] & 0xFF) << 48) | | (((long) byteByffer.array[start + index * 8 + 6] & 0xFF) << 48)
(((long)byteByffer.array[start + index * 8 + 7] & 0xFF) << 56); | (((long) byteByffer.array[start + index * 8 + 7] & 0xFF) << 56);
} }
return Double.longBitsToDouble(value); return Double.longBitsToDouble(value);
} }
@ -70,23 +70,23 @@ class TDoubleBufferOverByteBuffer extends TDoubleBufferImpl {
void putElement(int index, double d) { void putElement(int index, double d) {
long value = Double.doubleToLongBits(d); long value = Double.doubleToLongBits(d);
if (byteOrder == TByteOrder.BIG_ENDIAN) { if (byteOrder == TByteOrder.BIG_ENDIAN) {
byteByffer.array[start + index * 8] = (byte)(value >> 56); byteByffer.array[start + index * 8] = (byte) (value >> 56);
byteByffer.array[start + index * 8 + 1] = (byte)(value >> 48); byteByffer.array[start + index * 8 + 1] = (byte) (value >> 48);
byteByffer.array[start + index * 8 + 2] = (byte)(value >> 40); byteByffer.array[start + index * 8 + 2] = (byte) (value >> 40);
byteByffer.array[start + index * 8 + 3] = (byte)(value >> 32); byteByffer.array[start + index * 8 + 3] = (byte) (value >> 32);
byteByffer.array[start + index * 8 + 4] = (byte)(value >> 24); byteByffer.array[start + index * 8 + 4] = (byte) (value >> 24);
byteByffer.array[start + index * 8 + 5] = (byte)(value >> 16); byteByffer.array[start + index * 8 + 5] = (byte) (value >> 16);
byteByffer.array[start + index * 8 + 6] = (byte)(value >> 8); byteByffer.array[start + index * 8 + 6] = (byte) (value >> 8);
byteByffer.array[start + index * 8 + 7] = (byte)value; byteByffer.array[start + index * 8 + 7] = (byte) value;
} else { } else {
byteByffer.array[start + index * 8] = (byte)value; byteByffer.array[start + index * 8] = (byte) value;
byteByffer.array[start + index * 8 + 1] = (byte)(value >> 8); byteByffer.array[start + index * 8 + 1] = (byte) (value >> 8);
byteByffer.array[start + index * 8 + 2] = (byte)(value >> 16); byteByffer.array[start + index * 8 + 2] = (byte) (value >> 16);
byteByffer.array[start + index * 8 + 3] = (byte)(value >> 24); byteByffer.array[start + index * 8 + 3] = (byte) (value >> 24);
byteByffer.array[start + index * 8 + 4] = (byte)(value >> 32); byteByffer.array[start + index * 8 + 4] = (byte) (value >> 32);
byteByffer.array[start + index * 8 + 5] = (byte)(value >> 40); byteByffer.array[start + index * 8 + 5] = (byte) (value >> 40);
byteByffer.array[start + index * 8 + 6] = (byte)(value >> 48); byteByffer.array[start + index * 8 + 6] = (byte) (value >> 48);
byteByffer.array[start + index * 8 + 7] = (byte)(value >> 56); byteByffer.array[start + index * 8 + 7] = (byte) (value >> 56);
} }
} }

View File

@ -64,8 +64,8 @@ public abstract class TFloatBuffer extends TBuffer implements Comparable<TFloatB
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last float in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last float in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -113,8 +113,8 @@ public abstract class TFloatBuffer extends TBuffer implements Comparable<TFloatB
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last float in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last float in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -159,8 +159,8 @@ public abstract class TFloatBuffer extends TBuffer implements Comparable<TFloatB
@Override @Override
public String toString() { public String toString() {
return "[FloatBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark " + return "[FloatBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark "
(mark >= 0 ? " at " + mark : " is not set") + "]"; + (mark >= 0 ? " at " + mark : " is not set") + "]";
} }
@Override @Override
@ -181,7 +181,7 @@ public abstract class TFloatBuffer extends TBuffer implements Comparable<TFloatB
if (!(obj instanceof TFloatBuffer)) { if (!(obj instanceof TFloatBuffer)) {
return false; return false;
} }
TFloatBuffer other = (TFloatBuffer)obj; TFloatBuffer other = (TFloatBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -33,20 +33,20 @@ class TFloatBufferOverByteBufferBigEndian extends TFloatBufferOverByteBuffer {
@Override @Override
float getElement(int index) { float getElement(int index) {
int value = (byteByffer.array[start + index * 4] & 0xFF) | int value = (byteByffer.array[start + index * 4] & 0xFF)
((byteByffer.array[start + index * 4 + 1] & 0xFF) << 8) | | ((byteByffer.array[start + index * 4 + 1] & 0xFF) << 8)
((byteByffer.array[start + index * 4 + 2] & 0xFF) << 16) | | ((byteByffer.array[start + index * 4 + 2] & 0xFF) << 16)
((byteByffer.array[start + index * 4 + 3] & 0xFF) << 24); | ((byteByffer.array[start + index * 4 + 3] & 0xFF) << 24);
return Float.intBitsToFloat(value); return Float.intBitsToFloat(value);
} }
@Override @Override
void putElement(int index, float f) { void putElement(int index, float f) {
int value = Float.floatToIntBits(f); int value = Float.floatToIntBits(f);
byteByffer.array[start + index * 4] = (byte)value; byteByffer.array[start + index * 4] = (byte) value;
byteByffer.array[start + index * 4 + 1] = (byte)(value >> 8); byteByffer.array[start + index * 4 + 1] = (byte) (value >> 8);
byteByffer.array[start + index * 4 + 2] = (byte)(value >> 16); byteByffer.array[start + index * 4 + 2] = (byte) (value >> 16);
byteByffer.array[start + index * 4 + 3] = (byte)(value >> 24); byteByffer.array[start + index * 4 + 3] = (byte) (value >> 24);
} }
@Override @Override

View File

@ -33,20 +33,20 @@ class TFloatBufferOverByteBufferLittleEndian extends TFloatBufferOverByteBuffer
@Override @Override
float getElement(int index) { float getElement(int index) {
int value = ((byteByffer.array[start + index * 4] & 0xFF) << 24) | int value = ((byteByffer.array[start + index * 4] & 0xFF) << 24)
((byteByffer.array[start + index * 4 + 1] & 0xFF) << 16) | | ((byteByffer.array[start + index * 4 + 1] & 0xFF) << 16)
((byteByffer.array[start + index * 4 + 2] & 0xFF) << 8) | | ((byteByffer.array[start + index * 4 + 2] & 0xFF) << 8)
(byteByffer.array[start + index * 4 + 3] & 0xFF); | (byteByffer.array[start + index * 4 + 3] & 0xFF);
return Float.intBitsToFloat(value); return Float.intBitsToFloat(value);
} }
@Override @Override
void putElement(int index, float f) { void putElement(int index, float f) {
int value = Float.floatToIntBits(f); int value = Float.floatToIntBits(f);
byteByffer.array[start + index * 4] = (byte)(value >> 24); byteByffer.array[start + index * 4] = (byte) (value >> 24);
byteByffer.array[start + index * 4 + 1] = (byte)(value >> 16); byteByffer.array[start + index * 4 + 1] = (byte) (value >> 16);
byteByffer.array[start + index * 4 + 2] = (byte)(value >> 8); byteByffer.array[start + index * 4 + 2] = (byte) (value >> 8);
byteByffer.array[start + index * 4 + 3] = (byte)value; byteByffer.array[start + index * 4 + 3] = (byte) value;
} }
@Override @Override

View File

@ -64,8 +64,8 @@ public abstract class TIntBuffer extends TBuffer implements Comparable<TIntBuffe
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last int in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last int in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -113,8 +113,8 @@ public abstract class TIntBuffer extends TBuffer implements Comparable<TIntBuffe
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last int in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last int in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -159,8 +159,8 @@ public abstract class TIntBuffer extends TBuffer implements Comparable<TIntBuffe
@Override @Override
public String toString() { public String toString() {
return "[IntBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark " + return "[IntBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark "
(mark >= 0 ? " at " + mark : " is not set") + "]"; + (mark >= 0 ? " at " + mark : " is not set") + "]";
} }
@Override @Override
@ -181,7 +181,7 @@ public abstract class TIntBuffer extends TBuffer implements Comparable<TIntBuffe
if (!(obj instanceof TIntBuffer)) { if (!(obj instanceof TIntBuffer)) {
return false; return false;
} }
TIntBuffer other = (TIntBuffer)obj; TIntBuffer other = (TIntBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -33,18 +33,18 @@ class TIntBufferOverByteBufferBigEndian extends TIntBufferOverByteBuffer {
@Override @Override
int getElement(int index) { int getElement(int index) {
return ((byteByffer.array[start + index * 4] & 0xFF) << 24) | return ((byteByffer.array[start + index * 4] & 0xFF) << 24)
((byteByffer.array[start + index * 4 + 1] & 0xFF) << 16) | | ((byteByffer.array[start + index * 4 + 1] & 0xFF) << 16)
((byteByffer.array[start + index * 4 + 2] & 0xFF) << 8) | | ((byteByffer.array[start + index * 4 + 2] & 0xFF) << 8)
(byteByffer.array[start + index * 4 + 3] & 0xFF); | (byteByffer.array[start + index * 4 + 3] & 0xFF);
} }
@Override @Override
void putElement(int index, int value) { void putElement(int index, int value) {
byteByffer.array[start + index * 4] = (byte)(value >> 24); byteByffer.array[start + index * 4] = (byte) (value >> 24);
byteByffer.array[start + index * 4 + 1] = (byte)(value >> 16); byteByffer.array[start + index * 4 + 1] = (byte) (value >> 16);
byteByffer.array[start + index * 4 + 2] = (byte)(value >> 8); byteByffer.array[start + index * 4 + 2] = (byte) (value >> 8);
byteByffer.array[start + index * 4 + 3] = (byte)value; byteByffer.array[start + index * 4 + 3] = (byte) value;
} }
@Override @Override

View File

@ -33,18 +33,18 @@ class TIntBufferOverByteBufferLittleEndian extends TIntBufferOverByteBuffer {
@Override @Override
int getElement(int index) { int getElement(int index) {
return (byteByffer.array[start + index * 4] & 0xFF) | return (byteByffer.array[start + index * 4] & 0xFF)
((byteByffer.array[start + index * 4 + 1] & 0xFF) << 8) | | ((byteByffer.array[start + index * 4 + 1] & 0xFF) << 8)
((byteByffer.array[start + index * 4 + 2] & 0xFF) << 16) | | ((byteByffer.array[start + index * 4 + 2] & 0xFF) << 16)
((byteByffer.array[start + index * 4 + 3] & 0xFF) << 24); | ((byteByffer.array[start + index * 4 + 3] & 0xFF) << 24);
} }
@Override @Override
void putElement(int index, int value) { void putElement(int index, int value) {
byteByffer.array[start + index * 4] = (byte)value; byteByffer.array[start + index * 4] = (byte) value;
byteByffer.array[start + index * 4 + 1] = (byte)(value >> 8); byteByffer.array[start + index * 4 + 1] = (byte) (value >> 8);
byteByffer.array[start + index * 4 + 2] = (byte)(value >> 16); byteByffer.array[start + index * 4 + 2] = (byte) (value >> 16);
byteByffer.array[start + index * 4 + 3] = (byte)(value >> 24); byteByffer.array[start + index * 4 + 3] = (byte) (value >> 24);
} }
@Override @Override

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
import org.teavm.classlib.java.lang.TIllegalStateException; import org.teavm.classlib.java.lang.TIllegalStateException;

View File

@ -64,8 +64,8 @@ public abstract class TLongBuffer extends TBuffer implements Comparable<TLongBuf
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last long in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last long in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -113,8 +113,8 @@ public abstract class TLongBuffer extends TBuffer implements Comparable<TLongBuf
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last long in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last long in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -159,8 +159,8 @@ public abstract class TLongBuffer extends TBuffer implements Comparable<TLongBuf
@Override @Override
public String toString() { public String toString() {
return "[LongBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark " + return "[LongBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark "
(mark >= 0 ? " at " + mark : " is not set") + "]"; + (mark >= 0 ? " at " + mark : " is not set") + "]";
} }
@Override @Override
@ -169,7 +169,7 @@ public abstract class TLongBuffer extends TBuffer implements Comparable<TLongBuf
int pos = position; int pos = position;
for (int i = position; i < limit; ++i) { for (int i = position; i < limit; ++i) {
long elem = getElement(pos++); long elem = getElement(pos++);
hashCode = 31 * hashCode + (int)elem + (int)(elem >>> 32); hashCode = 31 * hashCode + (int) elem + (int) (elem >>> 32);
} }
return hashCode; return hashCode;
} }
@ -182,7 +182,7 @@ public abstract class TLongBuffer extends TBuffer implements Comparable<TLongBuf
if (!(obj instanceof TLongBuffer)) { if (!(obj instanceof TLongBuffer)) {
return false; return false;
} }
TLongBuffer other = (TLongBuffer)obj; TLongBuffer other = (TLongBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -33,26 +33,26 @@ class TLongBufferOverByteBufferBigEndian extends TLongBufferOverByteBuffer {
@Override @Override
long getElement(int index) { long getElement(int index) {
return (((long)byteByffer.array[start + index * 8] & 0xFF) << 56) | return (((long) byteByffer.array[start + index * 8] & 0xFF) << 56)
(((long)byteByffer.array[start + index * 8 + 1] & 0xFF) << 48) | | (((long) byteByffer.array[start + index * 8 + 1] & 0xFF) << 48)
(((long)byteByffer.array[start + index * 8 + 2] & 0xFF) << 40) | | (((long) byteByffer.array[start + index * 8 + 2] & 0xFF) << 40)
(((long)byteByffer.array[start + index * 8 + 3] & 0xFF) << 32) | | (((long) byteByffer.array[start + index * 8 + 3] & 0xFF) << 32)
(((long)byteByffer.array[start + index * 8 + 4] & 0xFF) << 24) | | (((long) byteByffer.array[start + index * 8 + 4] & 0xFF) << 24)
(((long)byteByffer.array[start + index * 8 + 5] & 0xFF) << 16) | | (((long) byteByffer.array[start + index * 8 + 5] & 0xFF) << 16)
(((long)byteByffer.array[start + index * 8 + 6] & 0xFF) << 8) | | (((long) byteByffer.array[start + index * 8 + 6] & 0xFF) << 8)
(byteByffer.array[start + index * 8 + 7] & 0xFF); | (byteByffer.array[start + index * 8 + 7] & 0xFF);
} }
@Override @Override
void putElement(int index, long value) { void putElement(int index, long value) {
byteByffer.array[start + index * 8] = (byte)(value >> 56); byteByffer.array[start + index * 8] = (byte) (value >> 56);
byteByffer.array[start + index * 8 + 1] = (byte)(value >> 48); byteByffer.array[start + index * 8 + 1] = (byte) (value >> 48);
byteByffer.array[start + index * 8 + 2] = (byte)(value >> 40); byteByffer.array[start + index * 8 + 2] = (byte) (value >> 40);
byteByffer.array[start + index * 8 + 3] = (byte)(value >> 32); byteByffer.array[start + index * 8 + 3] = (byte) (value >> 32);
byteByffer.array[start + index * 8 + 4] = (byte)(value >> 24); byteByffer.array[start + index * 8 + 4] = (byte) (value >> 24);
byteByffer.array[start + index * 8 + 5] = (byte)(value >> 16); byteByffer.array[start + index * 8 + 5] = (byte) (value >> 16);
byteByffer.array[start + index * 8 + 6] = (byte)(value >> 8); byteByffer.array[start + index * 8 + 6] = (byte) (value >> 8);
byteByffer.array[start + index * 8 + 7] = (byte)value; byteByffer.array[start + index * 8 + 7] = (byte) value;
} }
@Override @Override

View File

@ -33,26 +33,26 @@ class TLongBufferOverByteBufferLittleEndian extends TLongBufferOverByteBuffer {
@Override @Override
long getElement(int index) { long getElement(int index) {
return (byteByffer.array[start + index * 8] & 0xFF) | return (byteByffer.array[start + index * 8] & 0xFF)
(((long)byteByffer.array[start + index * 8 + 1] & 0xFF) << 8) | | (((long) byteByffer.array[start + index * 8 + 1] & 0xFF) << 8)
(((long)byteByffer.array[start + index * 8 + 2] & 0xFF) << 16) | | (((long) byteByffer.array[start + index * 8 + 2] & 0xFF) << 16)
(((long)byteByffer.array[start + index * 8 + 3] & 0xFF) << 24) | | (((long) byteByffer.array[start + index * 8 + 3] & 0xFF) << 24)
(((long)byteByffer.array[start + index * 8 + 4] & 0xFF) << 32) | | (((long) byteByffer.array[start + index * 8 + 4] & 0xFF) << 32)
(((long)byteByffer.array[start + index * 8 + 5] & 0xFF) << 40) | | (((long) byteByffer.array[start + index * 8 + 5] & 0xFF) << 40)
(((long)byteByffer.array[start + index * 8 + 6] & 0xFF) << 48) | | (((long) byteByffer.array[start + index * 8 + 6] & 0xFF) << 48)
(((long)byteByffer.array[start + index * 8 + 7] & 0xFF) << 56); | (((long) byteByffer.array[start + index * 8 + 7] & 0xFF) << 56);
} }
@Override @Override
void putElement(int index, long value) { void putElement(int index, long value) {
byteByffer.array[start + index * 8] = (byte)value; byteByffer.array[start + index * 8] = (byte) value;
byteByffer.array[start + index * 8 + 1] = (byte)(value >> 8); byteByffer.array[start + index * 8 + 1] = (byte) (value >> 8);
byteByffer.array[start + index * 8 + 2] = (byte)(value >> 16); byteByffer.array[start + index * 8 + 2] = (byte) (value >> 16);
byteByffer.array[start + index * 8 + 3] = (byte)(value >> 24); byteByffer.array[start + index * 8 + 3] = (byte) (value >> 24);
byteByffer.array[start + index * 8 + 4] = (byte)(value >> 32); byteByffer.array[start + index * 8 + 4] = (byte) (value >> 32);
byteByffer.array[start + index * 8 + 5] = (byte)(value >> 40); byteByffer.array[start + index * 8 + 5] = (byte) (value >> 40);
byteByffer.array[start + index * 8 + 6] = (byte)(value >> 48); byteByffer.array[start + index * 8 + 6] = (byte) (value >> 48);
byteByffer.array[start + index * 8 + 7] = (byte)(value >> 56); byteByffer.array[start + index * 8 + 7] = (byte) (value >> 56);
} }
@Override @Override

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.nio; package org.teavm.classlib.java.nio;
import org.teavm.classlib.java.lang.TUnsupportedOperationException; import org.teavm.classlib.java.lang.TUnsupportedOperationException;

View File

@ -64,8 +64,8 @@ public abstract class TShortBuffer extends TBuffer implements Comparable<TShortB
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + dst.length + ")");
} }
if (offset + length > dst.length) { if (offset + length > dst.length) {
throw new IndexOutOfBoundsException("The last short in dst " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last short in dst " + (offset + length) + " is outside "
"of array of size " + dst.length); + "of array of size " + dst.length);
} }
if (remaining() < length) { if (remaining() < length) {
throw new TBufferUnderflowException(); throw new TBufferUnderflowException();
@ -113,8 +113,8 @@ public abstract class TShortBuffer extends TBuffer implements Comparable<TShortB
throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")"); throw new IndexOutOfBoundsException("Offset " + offset + " is outside of range [0;" + src.length + ")");
} }
if (offset + length > src.length) { if (offset + length > src.length) {
throw new IndexOutOfBoundsException("The last short in src " + (offset + length) + " is outside " + throw new IndexOutOfBoundsException("The last short in src " + (offset + length) + " is outside "
"of array of size " + src.length); + "of array of size " + src.length);
} }
if (length < 0) { if (length < 0) {
throw new IndexOutOfBoundsException("Length " + length + " must be non-negative"); throw new IndexOutOfBoundsException("Length " + length + " must be non-negative");
@ -159,8 +159,8 @@ public abstract class TShortBuffer extends TBuffer implements Comparable<TShortB
@Override @Override
public String toString() { public String toString() {
return "[ShortBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark " + return "[ShortBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity + ", mark "
(mark >= 0 ? " at " + mark : " is not set") + "]"; + (mark >= 0 ? " at " + mark : " is not set") + "]";
} }
@Override @Override
@ -181,7 +181,7 @@ public abstract class TShortBuffer extends TBuffer implements Comparable<TShortB
if (!(obj instanceof TShortBuffer)) { if (!(obj instanceof TShortBuffer)) {
return false; return false;
} }
TShortBuffer other = (TShortBuffer)obj; TShortBuffer other = (TShortBuffer) obj;
int sz = remaining(); int sz = remaining();
if (sz != other.remaining()) { if (sz != other.remaining()) {
return false; return false;

View File

@ -33,15 +33,15 @@ class TShortBufferOverByteBufferBigEndian extends TShortBufferOverByteBuffer {
@Override @Override
short getElement(int index) { short getElement(int index) {
int value = ((byteByffer.array[start + index * 2] & 0xFF) << 8) | int value = ((byteByffer.array[start + index * 2] & 0xFF) << 8)
(byteByffer.array[start + index * 2 + 1] & 0xFF); | (byteByffer.array[start + index * 2 + 1] & 0xFF);
return (short)value; return (short) value;
} }
@Override @Override
void putElement(int index, short value) { void putElement(int index, short value) {
byteByffer.array[start + index * 2] = (byte)(value >> 8); byteByffer.array[start + index * 2] = (byte) (value >> 8);
byteByffer.array[start + index * 2 + 1] = (byte)value; byteByffer.array[start + index * 2 + 1] = (byte) value;
} }
@Override @Override

View File

@ -33,15 +33,15 @@ class TShortBufferOverByteBufferLittleEndian extends TShortBufferOverByteBuffer
@Override @Override
short getElement(int index) { short getElement(int index) {
int value = (byteByffer.array[start + index * 2] & 0xFF) | int value = (byteByffer.array[start + index * 2] & 0xFF)
((byteByffer.array[start + index * 2 + 1] & 0xFF) << 8); | ((byteByffer.array[start + index * 2 + 1] & 0xFF) << 8);
return (short)value; return (short) value;
} }
@Override @Override
void putElement(int index, short value) { void putElement(int index, short value) {
byteByffer.array[start + index * 2] = (byte)value; byteByffer.array[start + index * 2] = (byte) value;
byteByffer.array[start + index * 2 + 1] = (byte)(value >> 8); byteByffer.array[start + index * 2 + 1] = (byte) (value >> 8);
} }
@Override @Override

View File

@ -38,12 +38,12 @@ public abstract class TCharsetDecoder {
protected TCharsetDecoder(TCharset cs, float averageCharsPerByte, float maxCharsPerByte) { protected TCharsetDecoder(TCharset cs, float averageCharsPerByte, float maxCharsPerByte) {
if (averageCharsPerByte <= 0) { if (averageCharsPerByte <= 0) {
throw new IllegalArgumentException("averageCharsPerByte must be positive. Actual value is " + throw new IllegalArgumentException("averageCharsPerByte must be positive. Actual value is "
averageCharsPerByte); + averageCharsPerByte);
} }
if (maxCharsPerByte <= 0) { if (maxCharsPerByte <= 0) {
throw new IllegalArgumentException("maxCharsPerByte must be positive. Actual value is " + throw new IllegalArgumentException("maxCharsPerByte must be positive. Actual value is "
maxCharsPerByte); + maxCharsPerByte);
} }
this.charset = cs; this.charset = cs;
this.averageCharsPerByte = averageCharsPerByte; this.averageCharsPerByte = averageCharsPerByte;
@ -191,7 +191,7 @@ public abstract class TCharsetDecoder {
reset(); reset();
} }
TCharBuffer out = TCharBuffer.allocate(Math.max(8, (int)(in.remaining() * averageCharsPerByte))); TCharBuffer out = TCharBuffer.allocate(Math.max(8, (int) (in.remaining() * averageCharsPerByte)));
TCoderResult result; TCoderResult result;
while (true) { while (true) {
result = decode(in, out, false); result = decode(in, out, false);

View File

@ -46,7 +46,7 @@ public abstract class TCharsetEncoder {
} }
protected TCharsetEncoder(TCharset cs, float averageBytesPerChar, float maxBytesPerChar) { protected TCharsetEncoder(TCharset cs, float averageBytesPerChar, float maxBytesPerChar) {
this(cs, averageBytesPerChar, maxBytesPerChar, new byte[] { (byte)'?' }); this(cs, averageBytesPerChar, maxBytesPerChar, new byte[] { (byte) '?' });
} }
public final TCharset charset() { public final TCharset charset() {
@ -160,7 +160,7 @@ public abstract class TCharsetEncoder {
return TByteBuffer.allocate(0); return TByteBuffer.allocate(0);
} }
reset(); reset();
TByteBuffer output = TByteBuffer.allocate((int)(in.remaining() * averageBytesPerChar)); TByteBuffer output = TByteBuffer.allocate((int) (in.remaining() * averageBytesPerChar));
TCoderResult result; TCoderResult result;
while (true) { while (true) {
@ -225,7 +225,7 @@ public abstract class TCharsetEncoder {
public boolean canEncode(CharSequence sequence) { public boolean canEncode(CharSequence sequence) {
TCharBuffer cb; TCharBuffer cb;
if (sequence instanceof TCharBuffer) { if (sequence instanceof TCharBuffer) {
cb = ((TCharBuffer)sequence).duplicate(); cb = ((TCharBuffer) sequence).duplicate();
} else { } else {
cb = TCharBuffer.wrap(sequence); cb = TCharBuffer.wrap(sequence);
} }

Some files were not shown because too many files have changed in this diff Show More