Skip to content

Commit 95b1fa7

Browse files
committedMay 27, 2021
8267529: StringJoiner can create a String that breaks String::equals
Reviewed-by: naoto
1 parent 7f52c50 commit 95b1fa7

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed
 

‎src/java.base/share/classes/java/lang/String.java

+6-2
Original file line numberDiff line numberDiff line change
@@ -3239,8 +3239,12 @@ public static String join(CharSequence delimiter, CharSequence... elements) {
32393239
*/
32403240
@ForceInline
32413241
static String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
3242-
int icoder = prefix.coder() | suffix.coder() | delimiter.coder();
3243-
long len = (long) prefix.length() + suffix.length() + (long) Math.max(0, size - 1) * delimiter.length();
3242+
int icoder = prefix.coder() | suffix.coder();
3243+
long len = (long) prefix.length() + suffix.length();
3244+
if (size > 1) { // when there are more than one element, size - 1 delimiters will be emitted
3245+
len += (long) (size - 1) * delimiter.length();
3246+
icoder |= delimiter.coder();
3247+
}
32443248
// assert len > 0L; // max: (long) Integer.MAX_VALUE << 32
32453249
// following loop wil add max: (long) Integer.MAX_VALUE * Integer.MAX_VALUE to len
32463250
// so len can overflow at most once

‎test/jdk/java/lang/String/StringJoinTest.java

+14-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -21,13 +21,15 @@
2121
* questions.
2222
*/
2323
/**
24-
* @test @bug 5015163
24+
* @test
25+
* @bug 5015163 8267529
2526
* @summary test String merge/join that is the inverse of String.split()
2627
* @run testng StringJoinTest
2728
* @author Jim Gish
2829
*/
2930
import java.util.ArrayList;
3031
import java.util.List;
32+
import java.util.StringJoiner;
3133
import org.testng.annotations.Test;
3234

3335
import static org.testng.Assert.*;
@@ -111,4 +113,14 @@ public void testJoinNullStringList() {
111113
public void testJoinNullDelimiter() {
112114
String.join(null, JIM, JOHN);
113115
}
116+
117+
public void testIgnoreDelimiterCoderJoin() {
118+
// 8267529: Ensure that joining zero or one latin-1 Strings with a UTF-16
119+
// delimiter produce a String with a latin-1 coder, since the delimiter
120+
// is not added.
121+
assertEquals("", new StringJoiner("\u2013").toString());
122+
assertEquals("foo", new StringJoiner("\u2013").add("foo").toString());
123+
assertEquals("", String.join("\u2013"));
124+
assertEquals("foo", String.join("\u2013", "foo"));
125+
}
114126
}

1 commit comments

Comments
 (1)

openjdk-notifier[bot] commented on May 27, 2021

@openjdk-notifier[bot]
Please sign in to comment.