classlib: implement String.chars() (#872)

This commit is contained in:
J. Fronny 2023-12-05 13:26:39 +01:00 committed by GitHub
parent 067f7453fe
commit 9093ad2f8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 61 additions and 0 deletions

View File

@ -31,6 +31,8 @@ import org.teavm.classlib.java.util.TComparator;
import org.teavm.classlib.java.util.TFormatter;
import org.teavm.classlib.java.util.TLocale;
import org.teavm.classlib.java.util.regex.TPattern;
import org.teavm.classlib.java.util.stream.TIntStream;
import org.teavm.classlib.java.util.stream.intimpl.TStringCharsStream;
import org.teavm.dependency.PluggableDependency;
import org.teavm.interop.NoSideEffects;
@ -587,6 +589,10 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
return array;
}
public TIntStream chars() {
return new TStringCharsStream(this);
}
public static String valueOf(Object obj) {
return obj != null ? obj.toString() : "null";
}

View File

@ -0,0 +1,49 @@
/*
* Copyright 2023 JFronny.
*
* 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.util.stream.intimpl;
import java.util.Objects;
import java.util.function.IntPredicate;
import org.teavm.classlib.java.lang.TString;
public class TStringCharsStream extends TSimpleIntStreamImpl {
private final TString string;
private int index;
public TStringCharsStream(TString string) {
this.string = Objects.requireNonNull(string);
}
@Override
public boolean next(IntPredicate consumer) {
while (index < string.length()) {
if (!consumer.test(string.charAt(index++))) {
break;
}
}
return index < string.length();
}
@Override
protected int estimateSize() {
return string.length();
}
@Override
public long count() {
return string.length();
}
}

View File

@ -372,4 +372,10 @@ public class StringTest {
assertFalse(new String(new char[] { ' ', 'x', ' ' }).isBlank());
assertFalse(new String(new char[] { 'a', ' ' }).isBlank());
}
@Test
public void testChars() {
assertEquals(0, "".chars().toArray().length);
assertArrayEquals(new int[] {'A', 'B', 'C', '1', '2', '3'}, "ABC123".chars().toArray());
}
}