Skip to content

Commit

Permalink
Fix repeating Strings which use non UTF encoding
Browse files Browse the repository at this point in the history
Request: MO
Change-Id: Ief69b233f2fba538f9e2f36268a244771eb27072
  • Loading branch information
mduft committed Sep 11, 2020
1 parent 1a0e5a8 commit 095b447
Showing 1 changed file with 9 additions and 17 deletions.
26 changes: 9 additions & 17 deletions common/src/main/java/io/bdeploy/common/util/StringHelper.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package io.bdeploy.common.util;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
* Helper for {@link java.lang.String}
*/
Expand Down Expand Up @@ -54,7 +51,8 @@ public static boolean isAllLowerCase(String s) {
* If this string is empty or count is zero then the empty
* string is returned.
* <p>
* NOTE: Borrowed from the Java 11 implementation in {@link String}.
* This is less efficient than the Java 11 implementation as we
* cannot reuse the original Strings encoding to fill arrays.
*
* @param count number of times to repeat
* @return A string composed of this string repeated
Expand All @@ -75,24 +73,18 @@ public static String repeat(String string, int count) {
if (len == 0 || count == 0) {
return "";
}
if (len == 1) {
final byte[] single = new byte[count];
Arrays.fill(single, value[0]);
return new String(single, StandardCharsets.UTF_8);
}
if (Integer.MAX_VALUE / count < len) {
throw new OutOfMemoryError(
"Repeating " + len + " bytes String " + count + " times will produce a String exceeding maximum size.");
}
final int limit = len * count;
final byte[] multiple = new byte[limit];
System.arraycopy(value, 0, multiple, 0, len);
int copied = len;
for (; copied < limit - copied; copied <<= 1) {
System.arraycopy(multiple, 0, multiple, copied, copied);

StringBuilder builder = new StringBuilder(string.length() * count);

while (count-- > 0) {
builder.append(string);
}
System.arraycopy(multiple, 0, multiple, copied, limit - copied);
return new String(multiple, StandardCharsets.UTF_8);

return builder.toString();
}

}

0 comments on commit 095b447

Please sign in to comment.