summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/text/Text.java
diff options
context:
space:
mode:
authorjonmv <venstad@gmail.com>2023-10-20 17:09:20 +0200
committerjonmv <venstad@gmail.com>2023-10-20 17:09:20 +0200
commite228115788634d77f5b6354c12c1718252044860 (patch)
tree2317d7a3ebb49ff5328ed289a3fd646b2fffbd97 /vespajlib/src/main/java/com/yahoo/text/Text.java
parent2ecc9af04be2dbebedbf0032990cd3b699aa35d5 (diff)
Use code point count for truncate as well
Diffstat (limited to 'vespajlib/src/main/java/com/yahoo/text/Text.java')
-rw-r--r--vespajlib/src/main/java/com/yahoo/text/Text.java17
1 files changed, 4 insertions, 13 deletions
diff --git a/vespajlib/src/main/java/com/yahoo/text/Text.java b/vespajlib/src/main/java/com/yahoo/text/Text.java
index e133407a967..fe931ef34a3 100644
--- a/vespajlib/src/main/java/com/yahoo/text/Text.java
+++ b/vespajlib/src/main/java/com/yahoo/text/Text.java
@@ -170,15 +170,15 @@ public final class Text {
}
/**
- * Returns a string which is never larger than the given number of characters.
+ * Returns a string which is never larger than the given number of code points.
* If the string is longer than the given length it will be truncated.
* If length is 4 or less the string will be truncated to length.
* If length is longer than 4, it will be truncated at length-4 with " ..." added at the end.
*/
public static String truncate(String s, int length) {
- if (s.length() <= length) return s;
- if (length <= 4) return safeSubstring(s, length);
- return safeSubstring(s, length - 4) + " ...";
+ if (s.codePointCount(0, s.length()) <= length) return s;
+ if (length <= 4) return substringByCodepoints(s, 0, length);
+ return substringByCodepoints(s, 0, length - 4) + " ...";
}
public static String substringByCodepoints(String s, int fromCP, int toCP) {
@@ -209,13 +209,4 @@ public final class Text {
return String.format(Locale.US, format, args);
}
- /** Like {@link String#substring(int)}, but if this would split a surrogate pair at the end, the leading high surrogate is also cut. */
- public static String safeSubstring(String s, int length) {
- boolean pairCut = 0 < length
- && length < s.length()
- && Character.isHighSurrogate(s.charAt(length - 1))
- && Character.isLowSurrogate(s.charAt(length));
- return s.substring(0, length - (pairCut ? 1 : 0));
- }
-
}