From 5b5c26cf99ec70e85abbe5f2868ac5ffc896c0aa Mon Sep 17 00:00:00 2001 From: Ivan Hetman Date: Tue, 31 Oct 2023 10:45:23 +0200 Subject: [PATCH] classlib: minor improvements (#843) * String.substring performance * More argument validation in String methods * Object.checkFromIndexSize corner case for large indexes * ByteBuffer.wrap argument validation --- .../org/teavm/classlib/java/lang/TString.java | 45 +++++++++++-------- .../teavm/classlib/java/nio/TByteBuffer.java | 2 + .../teavm/classlib/java/util/TObjects.java | 4 +- 3 files changed, 31 insertions(+), 20 deletions(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java b/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java index 1c5b5e195..bc3c258d5 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java +++ b/classlib/src/main/java/org/teavm/classlib/java/lang/TString.java @@ -15,7 +15,10 @@ */ package org.teavm.classlib.java.lang; +import java.nio.charset.IllegalCharsetNameException; +import java.nio.charset.UnsupportedCharsetException; import java.util.Locale; +import java.util.Objects; import org.teavm.classlib.PlatformDetector; import org.teavm.classlib.java.io.TSerializable; import org.teavm.classlib.java.io.TUnsupportedEncodingException; @@ -52,7 +55,7 @@ public class TString extends TObject implements TSerializable, TComparable value.length) { - throw new IndexOutOfBoundsException(); - } + Objects.checkFromIndexSize(offset, count, value.length); initWithCharArray(value, offset, count); } @@ -80,7 +81,7 @@ public class TString extends TObject implements TSerializable, TComparable endIndex) { - throw new TIndexOutOfBoundsException(); - } + int length = charactersLength(); if (beginIndex == endIndex) { return EMPTY; } - if (PlatformDetector.isJavaScript()) { - var nativeSubstring = substringJS(nativeString(), beginIndex, endIndex); - return nativeSubstring != nativeString() ? new TString(nativeSubstring) : this; + if (beginIndex == 0 && endIndex == length) { + return this; } - if (beginIndex == 0 && endIndex == length()) { - return this; + if (PlatformDetector.isJavaScript()) { + if (beginIndex < 0 || beginIndex > endIndex || endIndex > length) { + throw new TStringIndexOutOfBoundsException(); + } + return new TString(substringJS(nativeString(), beginIndex, endIndex)); } return new TString(fastCharArray(), beginIndex, endIndex - beginIndex); } @@ -669,7 +674,11 @@ public class TString extends TObject implements TSerializable, TComparable { @@ -45,6 +46,7 @@ public abstract class TByteBuffer extends TBuffer implements TComparable length) { + if (fromIndex < 0 || size < 0 || size > length - fromIndex) { throw new IndexOutOfBoundsException(); } return fromIndex; } public static long checkFromIndexSize(long fromIndex, long size, long length) { - if (fromIndex < 0 || size < 0 || fromIndex + size > length) { + if (fromIndex < 0 || size < 0 || size > length - fromIndex) { throw new IndexOutOfBoundsException(); } return fromIndex;