From a3eaa1fc18e0f409f6bbfca31a76da9f91790044 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Wed, 17 Mar 2021 10:14:32 +0300 Subject: [PATCH] Add EnumSet.range --- .../teavm/classlib/java/util/TEnumSet.java | 30 +++++++++++++++---- .../classlib/java/util/TGenericEnumSet.java | 3 +- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/util/TEnumSet.java b/classlib/src/main/java/org/teavm/classlib/java/util/TEnumSet.java index e30476767..ef06bea3c 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/util/TEnumSet.java +++ b/classlib/src/main/java/org/teavm/classlib/java/util/TEnumSet.java @@ -17,8 +17,10 @@ package org.teavm.classlib.java.util; import java.io.Serializable; import java.util.AbstractSet; +import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import java.util.Objects; public abstract class TEnumSet> extends AbstractSet implements Cloneable, Serializable { public static > TEnumSet noneOf(Class elementType) { @@ -28,9 +30,7 @@ public abstract class TEnumSet> extends AbstractSet impleme public static > TEnumSet allOf(Class elementType) { int count = TGenericEnumSet.getConstants(elementType).length; int[] bits = new int[((count - 1) / 32) + 1]; - for (int i = 0; i < bits.length; ++i) { - bits[i] = ~0; - } + Arrays.fill(bits, ~0); zeroHighBits(bits, count); return new TGenericEnumSet<>(elementType, bits); } @@ -49,7 +49,6 @@ public abstract class TEnumSet> extends AbstractSet impleme throw new IllegalArgumentException(); } E first = iter.next(); - @SuppressWarnings("unchecked") TEnumSet result = noneOf(first.getDeclaringClass()); result.add(first); while (iter.hasNext()) { @@ -125,7 +124,28 @@ public abstract class TEnumSet> extends AbstractSet impleme return copyOf(this); } - abstract void fastAdd(E t); + public static > TEnumSet range(E from, E to) { + Objects.requireNonNull(from); + Objects.requireNonNull(to); + + int fromIndex = from.ordinal(); + int toIndex = to.ordinal(); + if (fromIndex > toIndex) { + throw new IllegalArgumentException(); + } + + TEnumSet result = TEnumSet.noneOf(from.getDeclaringClass()); + for (int i = fromIndex; i <= toIndex; ++i) { + result.fastAdd(i); + } + return result; + } + + void fastAdd(E t) { + fastAdd(t.ordinal()); + } + + abstract void fastAdd(int n); private static void zeroHighBits(int[] bits, int count) { bits[bits.length - 1] &= (~0) >>> (32 - count % 32); diff --git a/classlib/src/main/java/org/teavm/classlib/java/util/TGenericEnumSet.java b/classlib/src/main/java/org/teavm/classlib/java/util/TGenericEnumSet.java index b0bfce473..0dbdee5a8 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/util/TGenericEnumSet.java +++ b/classlib/src/main/java/org/teavm/classlib/java/util/TGenericEnumSet.java @@ -143,8 +143,7 @@ class TGenericEnumSet> extends TEnumSet { } @Override - void fastAdd(E t) { - int n = t.ordinal(); + void fastAdd(int n) { int bitNumber = n / 32; bits[bitNumber] |= 1 << (n % 32); }