Skip to content

Commit 94acdf8

Browse files
committed
Add java.lang.Utils.roundUpToPowerOfTwo utility function
The use-case of this function is for ensuring the size of internal buffers (e.g. internal Array of `ju.ArrayList`).
1 parent 1501c94 commit 94acdf8

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

javalib/src/main/scala/java/lang/Utils.scala

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,4 +187,9 @@ private[java] object Utils {
187187
false
188188
// scalastyle:on return
189189
}
190+
191+
/** Round up to a power of 2; if overflow, returns the given number. */
192+
@inline def roundUpToPowerOfTwo(i: Int): Int =
193+
if (i > (1 << 30)) i
194+
else ((1 << 31) >>> (Integer.numberOfLeadingZeros(i - 1)) - 1)
190195
}

javalib/src/main/scala/java/util/ArrayList.scala

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,8 @@ class ArrayList[E] private (innerInit: AnyRef, private var _size: Int)
6666

6767
def ensureCapacity(minCapacity: Int): Unit = {
6868
if (isWebAssembly) {
69-
if (innerWasm.length < minCapacity) {
70-
if (minCapacity > (1 << 30))
71-
resizeTo(minCapacity)
72-
else
73-
resizeTo(((1 << 31) >>> (Integer.numberOfLeadingZeros(minCapacity - 1)) - 1))
74-
}
69+
if (innerWasm.length < minCapacity)
70+
resizeTo(roundUpToPowerOfTwo(minCapacity))
7571
}
7672
// We ignore this in JS as js.Array doesn't support explicit pre-allocation
7773
}

0 commit comments

Comments
 (0)