Debian Codegraph @

src/main/org/h2/util/StringUtils.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util;
7
8 import java.io.ByteArrayOutputStream;
9 import java.lang.ref.SoftReference;
10 import java.net.URLEncoder;
11 import java.nio.charset.StandardCharsets;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.HashSet;
15 import java.util.Locale;
16 import java.util.concurrent.TimeUnit;
17 import java.util.function.IntPredicate;
18
19 import org.h2.api.ErrorCode;
20 import org.h2.engine.SysProperties;
21 import org.h2.message.DbException;
22
23 /**
24 * A few String utility functions.
25 */
26 public class StringUtils {
27
28 private static SoftReference<String[]> softCache;
29 private static long softCacheCreatedNs;
30
31 private static final char[] HEX = "0123456789abcdef".toCharArray();
32 private static final int[] HEX_DECODE = new int['f' + 1];
33
34 // memory used by this cache:
35 // 4 * 1024 * 2 (strings per pair) * 64 * 2 (bytes per char) = 0.5 MB
36 private static final int TO_UPPER_CACHE_LENGTH = 2 * 1024;
37 private static final int TO_UPPER_CACHE_MAX_ENTRY_LENGTH = 64;
38 private static final String[][] TO_UPPER_CACHE = new String[TO_UPPER_CACHE_LENGTH][];
39
40 static {
41 for (int i = 0; i < HEX_DECODE.length; i++) {
42 HEX_DECODE[i] = -1;
43 }
44 for (int i = 0; i <= 9; i++) {
45 HEX_DECODE[i + '0'] = i;
46 }
47 for (int i = 0; i <= 5; i++) {
48 HEX_DECODE[i + 'a'] = HEX_DECODE[i + 'A'] = i + 10;
49 }
50 }
51
52 private StringUtils() {
53 // utility class
54 }
55
56 private static String[] getCache() {
57 String[] cache;
58 if (softCache != null) {
59 cache = softCache.get();
60 if (cache != null) {
61 return cache;
62 }
63 }
64 // create a new cache at most every 5 seconds
65 // so that out of memory exceptions are not delayed
66 long time = System.nanoTime();
67 if (softCacheCreatedNs != 0 && time - softCacheCreatedNs < TimeUnit.SECONDS.toNanos(5)) {
68 return null;
69 }
70 try {
71 cache = new String[SysProperties.OBJECT_CACHE_SIZE];
72 softCache = new SoftReference<>(cache);
73 return cache;
74 } finally {
75 softCacheCreatedNs = System.nanoTime();
76 }
77 }
78
79 /**
80 * Convert a string to uppercase using the English locale.
81 *
82 * @param s the test to convert
83 * @return the uppercase text
84 */
85 public static String toUpperEnglish(String s) {
86 if (s.length() > TO_UPPER_CACHE_MAX_ENTRY_LENGTH) {
87 return s.toUpperCase(Locale.ENGLISH);
88 }
89 int index = s.hashCode() & (TO_UPPER_CACHE_LENGTH - 1);
90 String[] e = TO_UPPER_CACHE[index];
91 if (e != null) {
92 if (e[0].equals(s)) {
93 return e[1];
94 }
95 }
96 String s2 = s.toUpperCase(Locale.ENGLISH);
97 e = new String[] { s, s2 };
98 TO_UPPER_CACHE[index] = e;
99 return s2;
100 }
101
102 /**
103 * Convert a string to lowercase using the English locale.
104 *
105 * @param s the text to convert
106 * @return the lowercase text
107 */
108 public static String toLowerEnglish(String s) {
109 return s.toLowerCase(Locale.ENGLISH);
110 }
111
112 /**
113 * Convert a string to a SQL literal. Null is converted to NULL. The text is
114 * enclosed in single quotes. If there are any special characters, the
115 * Unicode character string literal is used.
116 *
117 * @param s the text to convert.
118 * @return the SQL literal
119 */
120 public static String quoteStringSQL(String s) {
121 if (s == null) {
122 return "NULL";
123 }
124 return quoteStringSQL(new StringBuilder(s.length() + 2), s).toString();
125 }
126
127 /**
128 * Convert a string to a SQL character string literal. Null is converted to
129 * NULL. If there are any special characters, the Unicode character string
130 * literal is used.
131 *
132 * @param builder
133 * string builder to append result to
134 * @param s the text to convert
135 * @return the specified string builder
136 */
137 public static StringBuilder quoteStringSQL(StringBuilder builder, String s) {
138 if (s == null) {
139 return builder.append("NULL");
140 }
141 return quoteIdentifierOrLiteral(builder, s, '\'');
142 }
143
144 /**
145 * Decodes a Unicode SQL string.
146 *
147 * @param s
148 * the string to decode
149 * @param uencode
150 * the code point of UENCODE character, or '\\'
151 * @return the decoded string
152 * @throws DbException
153 * on format exception
154 */
155 public static String decodeUnicodeStringSQL(String s, int uencode) {
156 int l = s.length();
157 StringBuilder builder = new StringBuilder(l);
158 for (int i = 0; i < l;) {
159 int cp = s.codePointAt(i);
160 i += Character.charCount(cp);
161 if (cp == uencode) {
162 if (i >= l) {
163 throw getFormatException(s, i);
164 }
165 cp = s.codePointAt(i);
166 if (cp == uencode) {
167 i += Character.charCount(cp);
168 } else {
169 if (i + 4 > l) {
170 throw getFormatException(s, i);
171 }
172 char ch = s.charAt(i);
173 try {
174 if (ch == '+') {
175 if (i + 7 > l) {
176 throw getFormatException(s, i);
177 }
178 cp = Integer.parseUnsignedInt(s.substring(i + 1, i += 7), 16);
179 } else {
180 cp = Integer.parseUnsignedInt(s.substring(i, i += 4), 16);
181 }
182 } catch (NumberFormatException e) {
183 throw getFormatException(s, i);
184 }
185 }
186 }
187 builder.appendCodePoint(cp);
188 }
189 return builder.toString();
190 }
191
192 /**
193 * Convert a string to a Java literal using the correct escape sequences.
194 * The literal is not enclosed in double quotes. The result can be used in
195 * properties files or in Java source code.
196 *
197 * @param s the text to convert
198 * @return the Java representation
199 */
200 public static String javaEncode(String s) {
201 StringBuilder buff = new StringBuilder(s.length());
202 javaEncode(s, buff, false);
203 return buff.toString();
204 }
205
206 /**
207 * Convert a string to a Java literal using the correct escape sequences.
208 * The literal is not enclosed in double quotes. The result can be used in
209 * properties files or in Java source code.
210 *
211 * @param s the text to convert
212 * @param buff the Java representation to return
213 * @param forSQL true if we embedding this inside a STRINGDECODE SQL command
214 */
215 public static void javaEncode(String s, StringBuilder buff, boolean forSQL) {
216 int length = s.length();
217 for (int i = 0; i < length; i++) {
218 char c = s.charAt(i);
219 switch (c) {
220 // case '\b':
221 // // BS backspace
222 // // not supported in properties files
223 // buff.append("\\b");
224 // break;
225 case '\t':
226 // HT horizontal tab
227 buff.append("\\t");
228 break;
229 case '\n':
230 // LF linefeed
231 buff.append("\\n");
232 break;
233 case '\f':
234 // FF form feed
235 buff.append("\\f");
236 break;
237 case '\r':
238 // CR carriage return
239 buff.append("\\r");
240 break;
241 case '"':
242 // double quote
243 buff.append("\\\"");
244 break;
245 case '\'':
246 // quote:
247 if (forSQL) {
248 buff.append('\'');
249 }
250 buff.append('\'');
251 break;
252 case '\\':
253 // backslash
254 buff.append("\\\\");
255 break;
256 default:
257 if (c >= ' ' && (c < 0x80)) {
258 buff.append(c);
259 // not supported in properties files
260 // } else if (c < 0xff) {
261 // buff.append("\\");
262 // // make sure it's three characters (0x200 is octal 1000)
263 // buff.append(Integer.toOctalString(0x200 | c).substring(1));
264 } else {
265 buff.append("\\u")
266 .append(HEX[c >>> 12])
267 .append(HEX[c >>> 8 & 0xf])
268 .append(HEX[c >>> 4 & 0xf])
269 .append(HEX[c & 0xf]);
270 }
271 }
272 }
273 }
274
275 /**
276 * Add an asterisk ('[*]') at the given position. This format is used to
277 * show where parsing failed in a statement.
278 *
279 * @param s the text
280 * @param index the position
281 * @return the text with asterisk
282 */
283 public static String addAsterisk(String s, int index) {
284 if (s != null) {
285 int len = s.length();
286 index = Math.min(index, len);
287 s = new StringBuilder(len + 3).append(s, 0, index).append("[*]").append(s, index, len).toString();
288 }
289 return s;
290 }
291
292 private static DbException getFormatException(String s, int i) {
293 return DbException.get(ErrorCode.STRING_FORMAT_ERROR_1, addAsterisk(s, i));
294 }
295
296 /**
297 * Decode a text that is encoded as a Java string literal. The Java
298 * properties file format and Java source code format is supported.
299 *
300 * @param s the encoded string
301 * @return the string
302 */
303 public static String javaDecode(String s) {
304 int length = s.length();
305 StringBuilder buff = new StringBuilder(length);
306 for (int i = 0; i < length; i++) {
307 char c = s.charAt(i);
308 if (c == '\\') {
309 if (i + 1 >= s.length()) {
310 throw getFormatException(s, i);
311 }
312 c = s.charAt(++i);
313 switch (c) {
314 case 't':
315 buff.append('\t');
316 break;
317 case 'r':
318 buff.append('\r');
319 break;
320 case 'n':
321 buff.append('\n');
322 break;
323 case 'b':
324 buff.append('\b');
325 break;
326 case 'f':
327 buff.append('\f');
328 break;
329 case '#':
330 // for properties files
331 buff.append('#');
332 break;
333 case '=':
334 // for properties files
335 buff.append('=');
336 break;
337 case ':':
338 // for properties files
339 buff.append(':');
340 break;
341 case '"':
342 buff.append('"');
343 break;
344 case '\\':
345 buff.append('\\');
346 break;
347 case 'u': {
348 if (i + 4 >= length) {
349 throw getFormatException(s, i);
350 }
351 try {
352 c = (char) Integer.parseInt(s.substring(i + 1, i + 5), 16);
353 } catch (NumberFormatException e) {
354 throw getFormatException(s, i);
355 }
356 i += 4;
357 buff.append(c);
358 break;
359 }
360 default:
361 if (c >= '0' && c <= '9' && i + 2 < length) {
362 try {
363 c = (char) Integer.parseInt(s.substring(i, i + 3), 8);
364 } catch (NumberFormatException e) {
365 throw getFormatException(s, i);
366 }
367 i += 2;
368 buff.append(c);
369 } else {
370 throw getFormatException(s, i);
371 }
372 }
373 } else {
374 buff.append(c);
375 }
376 }
377 return buff.toString();
378 }
379
380 /**
381 * Convert a string to the Java literal and enclose it with double quotes.
382 * Null will result in "null" (without double quotes).
383 *
384 * @param s the text to convert
385 * @return the Java representation
386 */
387 public static String quoteJavaString(String s) {
388 if (s == null) {
389 return "null";
390 }
391 StringBuilder builder = new StringBuilder(s.length() + 2).append('"');
392 javaEncode(s, builder, false);
393 return builder.append('"').toString();
394 }
395
396 /**
397 * Convert a string array to the Java source code that represents this
398 * array. Null will be converted to 'null'.
399 *
400 * @param array the string array
401 * @return the Java source code (including new String[]{})
402 */
403 public static String quoteJavaStringArray(String[] array) {
404 if (array == null) {
405 return "null";
406 }
407 StringBuilder buff = new StringBuilder("new String[]{");
408 for (int i = 0; i < array.length; i++) {
409 if (i > 0) {
410 buff.append(", ");
411 }
412 buff.append(quoteJavaString(array[i]));
413 }
414 return buff.append('}').toString();
415 }
416
417 /**
418 * Convert an int array to the Java source code that represents this array.
419 * Null will be converted to 'null'.
420 *
421 * @param array the int array
422 * @return the Java source code (including new int[]{})
423 */
424 public static String quoteJavaIntArray(int[] array) {
425 if (array == null) {
426 return "null";
427 }
428 StringBuilder builder = new StringBuilder("new int[]{");
429 for (int i = 0; i < array.length; i++) {
430 if (i > 0) {
431 builder.append(", ");
432 }
433 builder.append(array[i]);
434 }
435 return builder.append('}').toString();
436 }
437
438 /**
439 * Encode the string as a URL.
440 *
441 * @param s the string to encode
442 * @return the encoded string
443 */
444 public static String urlEncode(String s) {
445 try {
446 return URLEncoder.encode(s, "UTF-8");
447 } catch (Exception e) {
448 // UnsupportedEncodingException
449 throw DbException.convert(e);
450 }
451 }
452
453 /**
454 * Decode the URL to a string.
455 *
456 * @param encoded the encoded URL
457 * @return the decoded string
458 */
459 public static String urlDecode(String encoded) {
460 int length = encoded.length();
461 byte[] buff = new byte[length];
462 int j = 0;
463 for (int i = 0; i < length; i++) {
464 char ch = encoded.charAt(i);
465 if (ch == '+') {
466 buff[j++] = ' ';
467 } else if (ch == '%') {
468 buff[j++] = (byte) Integer.parseInt(encoded.substring(i + 1, i + 3), 16);
469 i += 2;
470 } else if (ch <= 127 && ch >= ' ') {
471 buff[j++] = (byte) ch;
472 } else {
473 throw new IllegalArgumentException("Unexpected char " + (int) ch + " decoding " + encoded);
474 }
475 }
476 return new String(buff, 0, j, StandardCharsets.UTF_8);
477 }
478
479 /**
480 * Split a string into an array of strings using the given separator. A null
481 * string will result in a null array, and an empty string in a zero element
482 * array.
483 *
484 * @param s the string to split
485 * @param separatorChar the separator character
486 * @param trim whether each element should be trimmed
487 * @return the array list
488 */
489 public static String[] arraySplit(String s, char separatorChar, boolean trim) {
490 if (s == null) {
491 return null;
492 }
493 int length = s.length();
494 if (length == 0) {
495 return new String[0];
496 }
497 ArrayList<String> list = Utils.newSmallArrayList();
498 StringBuilder buff = new StringBuilder(length);
499 for (int i = 0; i < length; i++) {
500 char c = s.charAt(i);
501 if (c == separatorChar) {
502 String e = buff.toString();
503 list.add(trim ? e.trim() : e);
504 buff.setLength(0);
505 } else if (c == '\\' && i < length - 1) {
506 buff.append(s.charAt(++i));
507 } else {
508 buff.append(c);
509 }
510 }
511 String e = buff.toString();
512 list.add(trim ? e.trim() : e);
513 return list.toArray(new String[0]);
514 }
515
516 /**
517 * Combine an array of strings to one array using the given separator
518 * character. A backslash and the separator character and escaped using a
519 * backslash.
520 *
521 * @param list the string array
522 * @param separatorChar the separator character
523 * @return the combined string
524 */
525 public static String arrayCombine(String[] list, char separatorChar) {
526 StringBuilder builder = new StringBuilder();
527 for (int i = 0; i < list.length; i++) {
528 if (i > 0) {
529 builder.append(separatorChar);
530 }
531 String s = list[i];
532 if (s == null) {
533 continue;
534 }
535 for (int j = 0, length = s.length(); j < length; j++) {
536 char c = s.charAt(j);
537 if (c == '\\' || c == separatorChar) {
538 builder.append('\\');
539 }
540 builder.append(c);
541 }
542 }
543 return builder.toString();
544 }
545
546 /**
547 * Creates an XML attribute of the form name="value".
548 * A single space is prepended to the name,
549 * so that multiple attributes can be concatenated.
550 * @param name the attribute name
551 * @param value the attribute value
552 * @return the attribute
553 */
554 public static String xmlAttr(String name, String value) {
555 return " " + name + "=\"" + xmlText(value) + "\"";
556 }
557
558 /**
559 * Create an XML node with optional attributes and content.
560 * The data is indented with 4 spaces if it contains a newline character.
561 *
562 * @param name the element name
563 * @param attributes the attributes (may be null)
564 * @param content the content (may be null)
565 * @return the node
566 */
567 public static String xmlNode(String name, String attributes, String content) {
568 return xmlNode(name, attributes, content, true);
569 }
570
571 /**
572 * Create an XML node with optional attributes and content. The data is
573 * indented with 4 spaces if it contains a newline character and the indent
574 * parameter is set to true.
575 *
576 * @param name the element name
577 * @param attributes the attributes (may be null)
578 * @param content the content (may be null)
579 * @param indent whether to indent the content if it contains a newline
580 * @return the node
581 */
582 public static String xmlNode(String name, String attributes,
583 String content, boolean indent) {
584 StringBuilder builder = new StringBuilder();
585 builder.append('<').append(name);
586 if (attributes != null) {
587 builder.append(attributes);
588 }
589 if (content == null) {
590 builder.append("/>\n");
591 return builder.toString();
592 }
593 builder.append('>');
594 if (indent && content.indexOf('\n') >= 0) {
595 builder.append('\n');
596 indent(builder, content, 4, true);
597 } else {
598 builder.append(content);
599 }
600 builder.append("</").append(name).append(">\n");
601 return builder.toString();
602 }
603
604 /**
605 * Indents a string with spaces and appends it to a specified builder.
606 *
607 * @param builder string builder to append to
608 * @param s the string
609 * @param spaces the number of spaces
610 * @param newline append a newline if there is none
611 * @return the specified string builder
612 */
613 public static StringBuilder indent(StringBuilder builder, String s, int spaces, boolean newline) {
614 for (int i = 0, length = s.length(); i < length;) {
615 for (int j = 0; j < spaces; j++) {
616 builder.append(' ');
617 }
618 int n = s.indexOf('\n', i);
619 n = n < 0 ? length : n + 1;
620 builder.append(s, i, n);
621 i = n;
622 }
623 if (newline && !s.endsWith("\n")) {
624 builder.append('\n');
625 }
626 return builder;
627 }
628
629 /**
630 * Escapes a comment.
631 * If the data contains '--', it is converted to '- -'.
632 * The data is indented with 4 spaces if it contains a newline character.
633 *
634 * @param data the comment text
635 * @return &lt;!-- data --&gt;
636 */
637 public static String xmlComment(String data) {
638 int idx = 0;
639 while (true) {
640 idx = data.indexOf("--", idx);
641 if (idx < 0) {
642 break;
643 }
644 data = data.substring(0, idx + 1) + " " + data.substring(idx + 1);
645 }
646 // must have a space at the beginning and at the end,
647 // otherwise the data must not contain '-' as the first/last character
648 if (data.indexOf('\n') >= 0) {
649 StringBuilder builder = new StringBuilder(data.length() + 18).append("<!--\n");
650 return indent(builder, data, 4, true).append("-->\n").toString();
651 }
652 return "<!-- " + data + " -->\n";
653 }
654
655 /**
656 * Converts the data to a CDATA element.
657 * If the data contains ']]&gt;', it is escaped as a text element.
658 *
659 * @param data the text data
660 * @return &lt;![CDATA[data]]&gt;
661 */
662 public static String xmlCData(String data) {
663 if (data.contains("]]>")) {
664 return xmlText(data);
665 }
666 boolean newline = data.endsWith("\n");
667 data = "<![CDATA[" + data + "]]>";
668 return newline ? data + "\n" : data;
669 }
670
671 /**
672 * Returns &lt;?xml version="1.0"?&gt;
673 * @return &lt;?xml version="1.0"?&gt;
674 */
675 public static String xmlStartDoc() {
676 return "<?xml version=\"1.0\"?>\n";
677 }
678
679 /**
680 * Escapes an XML text element.
681 *
682 * @param text the text data
683 * @return the escaped text
684 */
685 public static String xmlText(String text) {
686 return xmlText(text, false);
687 }
688
689 /**
690 * Escapes an XML text element.
691 *
692 * @param text the text data
693 * @param escapeNewline whether to escape newlines
694 * @return the escaped text
695 */
696 public static String xmlText(String text, boolean escapeNewline) {
697 int length = text.length();
698 StringBuilder buff = new StringBuilder(length);
699 for (int i = 0; i < length; i++) {
700 char ch = text.charAt(i);
701 switch (ch) {
702 case '<':
703 buff.append("&lt;");
704 break;
705 case '>':
706 buff.append("&gt;");
707 break;
708 case '&':
709 buff.append("&amp;");
710 break;
711 case '\'':
712 // &apos; is not valid in HTML
713 buff.append("&#39;");
714 break;
715 case '\"':
716 buff.append("&quot;");
717 break;
718 case '\r':
719 case '\n':
720 if (escapeNewline) {
721 buff.append("&#x").
722 append(Integer.toHexString(ch)).
723 append(';');
724 } else {
725 buff.append(ch);
726 }
727 break;
728 case '\t':
729 buff.append(ch);
730 break;
731 default:
732 if (ch < ' ' || ch > 127) {
733 buff.append("&#x").
734 append(Integer.toHexString(ch)).
735 append(';');
736 } else {
737 buff.append(ch);
738 }
739 }
740 }
741 return buff.toString();
742 }
743
744 /**
745 * Replace all occurrences of the before string with the after string. Unlike
746 * {@link String#replaceAll(String, String)} this method reads {@code before}
747 * and {@code after} arguments as plain strings and if {@code before} argument
748 * is an empty string this method returns original string {@code s}.
749 *
750 * @param s the string
751 * @param before the old text
752 * @param after the new text
753 * @return the string with the before string replaced
754 */
755 public static String replaceAll(String s, String before, String after) {
756 int next = s.indexOf(before);
757 if (next < 0 || before.isEmpty()) {
758 return s;
759 }
760 StringBuilder buff = new StringBuilder(
761 s.length() - before.length() + after.length());
762 int index = 0;
763 while (true) {
764 buff.append(s, index, next).append(after);
765 index = next + before.length();
766 next = s.indexOf(before, index);
767 if (next < 0) {
768 buff.append(s, index, s.length());
769 break;
770 }
771 }
772 return buff.toString();
773 }
774
775 /**
776 * Enclose a string with double quotes. A double quote inside the string is
777 * escaped using a double quote.
778 *
779 * @param s the text
780 * @return the double quoted text
781 */
782 public static String quoteIdentifier(String s) {
783 return quoteIdentifierOrLiteral(new StringBuilder(s.length() + 2), s, '"').toString();
784 }
785
786 /**
787 * Enclose a string with double quotes and append it to the specified
788 * string builder. A double quote inside the string is escaped using a
789 * double quote.
790 *
791 * @param builder string builder to append to
792 * @param s the text
793 * @return the specified builder
794 */
795 public static StringBuilder quoteIdentifier(StringBuilder builder, String s) {
796 return quoteIdentifierOrLiteral(builder, s, '"');
797 }
798
799 private static StringBuilder quoteIdentifierOrLiteral(StringBuilder builder, String s, char q) {
800 int builderLength = builder.length();
801 builder.append(q);
802 for (int i = 0, l = s.length(); i < l;) {
803 int cp = s.codePointAt(i);
804 i += Character.charCount(cp);
805 if (cp < ' ' || cp > 127) {
806 // need to start from the beginning
807 builder.setLength(builderLength);
808 builder.append("U&").append(q);
809 for (i = 0; i < l;) {
810 cp = s.codePointAt(i);
811 i += Character.charCount(cp);
812 if (cp >= ' ' && cp < 127) {
813 char ch = (char) cp;
814 if (ch == q || ch == '\\') {
815 builder.append(ch);
816 }
817 builder.append(ch);
818 } else if (cp <= 0xffff) {
819 appendHex(builder.append('\\'), cp, 2);
820 } else {
821 appendHex(builder.append("\\+"), cp, 3);
822 }
823 }
824 break;
825 }
826 if (cp == q) {
827 builder.append(q);
828 }
829 builder.append((char) cp);
830 }
831 return builder.append(q);
832 }
833
834 /**
835 * Check if a String is null or empty (the length is null).
836 *
837 * @param s the string to check
838 * @return true if it is null or empty
839 */
840 public static boolean isNullOrEmpty(String s) {
841 return s == null || s.isEmpty();
842 }
843
844 /**
845 * Pad a string. This method is used for the SQL function RPAD and LPAD.
846 *
847 * @param string the original string
848 * @param n the target length
849 * @param padding the padding string
850 * @param right true if the padding should be appended at the end
851 * @return the padded string
852 */
853 public static String pad(String string, int n, String padding, boolean right) {
854 if (n < 0) {
855 n = 0;
856 }
857 if (n < string.length()) {
858 return string.substring(0, n);
859 } else if (n == string.length()) {
860 return string;
861 }
862 int paddingChar;
863 if (padding == null || padding.isEmpty()) {
864 paddingChar = ' ';
865 } else {
866 paddingChar = padding.codePointAt(0);
867 }
868 StringBuilder buff = new StringBuilder(n);
869 n -= string.length();
870 if (Character.isSupplementaryCodePoint(paddingChar)) {
871 n >>= 1;
872 }
873 if (right) {
874 buff.append(string);
875 }
876 for (int i = 0; i < n; i++) {
877 buff.appendCodePoint(paddingChar);
878 }
879 if (!right) {
880 buff.append(string);
881 }
882 return buff.toString();
883 }
884
885 /**
886 * Create a new char array and copy all the data. If the size of the byte
887 * array is zero, the same array is returned.
888 *
889 * @param chars the char array (may be null)
890 * @return a new char array
891 */
892 public static char[] cloneCharArray(char[] chars) {
893 if (chars == null) {
894 return null;
895 }
896 int len = chars.length;
897 if (len == 0) {
898 return chars;
899 }
900 return Arrays.copyOf(chars, len);
901 }
902
903 /**
904 * Trim a character from a string.
905 *
906 * @param s the string
907 * @param leading if leading characters should be removed
908 * @param trailing if trailing characters should be removed
909 * @param characters what to remove or {@code null} for a space
910 * @return the trimmed string
911 */
912 public static String trim(String s, boolean leading, boolean trailing, String characters) {
913 if (characters == null || characters.isEmpty()) {
914 return trim(s, leading, trailing, ' ');
915 }
916 int length = characters.length();
917 if (length == 1) {
918 return trim(s, leading, trailing, characters.charAt(0));
919 }
920 IntPredicate test;
921 int count = characters.codePointCount(0, length);
922 check: if (count <= 2) {
923 int cp = characters.codePointAt(0);
924 if (count > 1) {
925 int cp2 = characters.codePointAt(Character.charCount(cp));
926 if (cp != cp2) {
927 test = value -> value == cp || value == cp2;
928 break check;
929 }
930 }
931 test = value -> value == cp;
932 } else {
933 HashSet<Integer> set = new HashSet<>();
934 characters.codePoints().forEach(set::add);
935 test = set::contains;
936 }
937 return trim(s, leading, trailing, test);
938 }
939
940 private static String trim(String s, boolean leading, boolean trailing, IntPredicate test) {
941 int begin = 0, end = s.length();
942 if (leading) {
943 int cp;
944 while (begin < end && test.test(cp = s.codePointAt(begin))) {
945 begin += Character.charCount(cp);
946 }
947 }
948 if (trailing) {
949 int cp;
950 while (end > begin && test.test(cp = s.codePointBefore(end))) {
951 end -= Character.charCount(cp);
952 }
953 }
954 // substring() returns self if start == 0 && end == length()
955 return s.substring(begin, end);
956 }
957
958 /**
959 * Trim a character from a string.
960 *
961 * @param s the string
962 * @param leading if leading characters should be removed
963 * @param trailing if trailing characters should be removed
964 * @param character what to remove
965 * @return the trimmed string
966 */
967 public static String trim(String s, boolean leading, boolean trailing, char character) {
968 int begin = 0, end = s.length();
969 if (leading) {
970 while (begin < end && s.charAt(begin) == character) {
971 begin++;
972 }
973 }
974 if (trailing) {
975 while (end > begin && s.charAt(end - 1) == character) {
976 end--;
977 }
978 }
979 // substring() returns self if start == 0 && end == length()
980 return s.substring(begin, end);
981 }
982
983 /**
984 * Trim a whitespace from a substring. Equivalent of
985 * {@code substring(beginIndex).trim()}.
986 *
987 * @param s the string
988 * @param beginIndex start index of substring (inclusive)
989 * @return trimmed substring
990 */
991 public static String trimSubstring(String s, int beginIndex) {
992 return trimSubstring(s, beginIndex, s.length());
993 }
994
995 /**
996 * Trim a whitespace from a substring. Equivalent of
997 * {@code substring(beginIndex, endIndex).trim()}.
998 *
999 * @param s the string
1000 * @param beginIndex start index of substring (inclusive)
1001 * @param endIndex end index of substring (exclusive)
1002 * @return trimmed substring
1003 */
1004 public static String trimSubstring(String s, int beginIndex, int endIndex) {
1005 while (beginIndex < endIndex && s.charAt(beginIndex) <= ' ') {
1006 beginIndex++;
1007 }
1008 while (beginIndex < endIndex && s.charAt(endIndex - 1) <= ' ') {
1009 endIndex--;
1010 }
1011 return s.substring(beginIndex, endIndex);
1012 }
1013
1014 /**
1015 * Trim a whitespace from a substring and append it to a specified string
1016 * builder. Equivalent of
1017 * {@code builder.append(substring(beginIndex, endIndex).trim())}.
1018 *
1019 * @param builder string builder to append to
1020 * @param s the string
1021 * @param beginIndex start index of substring (inclusive)
1022 * @param endIndex end index of substring (exclusive)
1023 * @return the specified builder
1024 */
1025 public static StringBuilder trimSubstring(StringBuilder builder, String s, int beginIndex, int endIndex) {
1026 while (beginIndex < endIndex && s.charAt(beginIndex) <= ' ') {
1027 beginIndex++;
1028 }
1029 while (beginIndex < endIndex && s.charAt(endIndex - 1) <= ' ') {
1030 endIndex--;
1031 }
1032 return builder.append(s, beginIndex, endIndex);
1033 }
1034
1035 /**
1036 * Truncates the specified string to the specified length. This method,
1037 * unlike {@link String#substring(int, int)}, doesn't break Unicode code
1038 * points. If the specified length in characters breaks a valid pair of
1039 * surrogates, the whole pair is not included into result.
1040 *
1041 * @param s
1042 * the string to truncate
1043 * @param maximumLength
1044 * the maximum length in characters
1045 * @return the specified string if it isn't longer than the specified
1046 * maximum length, and the truncated string otherwise
1047 */
1048 public static String truncateString(String s, int maximumLength) {
1049 if (s.length() > maximumLength) {
1050 s = maximumLength > 0 ? s.substring(0,
1051 Character.isSurrogatePair(s.charAt(maximumLength - 1), s.charAt(maximumLength)) ? maximumLength - 1
1052 : maximumLength)
1053 : "";
1054 }
1055 return s;
1056 }
1057
1058 /**
1059 * Get the string from the cache if possible. If the string has not been
1060 * found, it is added to the cache. If there is such a string in the cache,
1061 * that one is returned.
1062 *
1063 * @param s the original string
1064 * @return a string with the same content, if possible from the cache
1065 */
1066 public static String cache(String s) {
1067 if (!SysProperties.OBJECT_CACHE) {
1068 return s;
1069 }
1070 if (s == null) {
1071 return s;
1072 } else if (s.isEmpty()) {
1073 return "";
1074 }
1075 String[] cache = getCache();
1076 if (cache != null) {
1077 int hash = s.hashCode();
1078 int index = hash & (SysProperties.OBJECT_CACHE_SIZE - 1);
1079 String cached = cache[index];
1080 if (s.equals(cached)) {
1081 return cached;
1082 }
1083 cache[index] = s;
1084 }
1085 return s;
1086 }
1087
1088 /**
1089 * Clear the cache. This method is used for testing.
1090 */
1091 public static void clearCache() {
1092 softCache = null;
1093 }
1094
1095 /**
1096 * Parses an unsigned 31-bit integer. Neither - nor + signs are allowed.
1097 *
1098 * @param s string to parse
1099 * @param start the beginning index, inclusive
1100 * @param end the ending index, exclusive
1101 * @return the unsigned {@code int} not greater than {@link Integer#MAX_VALUE}.
1102 */
1103 public static int parseUInt31(String s, int start, int end) {
1104 if (end > s.length() || start < 0 || start > end) {
1105 throw new IndexOutOfBoundsException();
1106 }
1107 if (start == end) {
1108 throw new NumberFormatException("");
1109 }
1110 int result = 0;
1111 for (int i = start; i < end; i++) {
1112 char ch = s.charAt(i);
1113 // Ensure that character is valid and that multiplication by 10 will
1114 // be performed without overflow
1115 if (ch < '0' || ch > '9' || result > 214_748_364) {
1116 throw new NumberFormatException(s.substring(start, end));
1117 }
1118 result = result * 10 + ch - '0';
1119 if (result < 0) {
1120 // Overflow
1121 throw new NumberFormatException(s.substring(start, end));
1122 }
1123 }
1124 return result;
1125 }
1126
1127 /**
1128 * Convert a hex encoded string to a byte array.
1129 *
1130 * @param s the hex encoded string
1131 * @return the byte array
1132 */
1133 public static byte[] convertHexToBytes(String s) {
1134 int len = s.length();
1135 if (len % 2 != 0) {
1136 throw DbException.get(ErrorCode.HEX_STRING_ODD_1, s);
1137 }
1138 len /= 2;
1139 byte[] buff = new byte[len];
1140 int mask = 0;
1141 int[] hex = HEX_DECODE;
1142 try {
1143 for (int i = 0; i < len; i++) {
1144 int d = hex[s.charAt(i + i)] << 4 | hex[s.charAt(i + i + 1)];
1145 mask |= d;
1146 buff[i] = (byte) d;
1147 }
1148 } catch (ArrayIndexOutOfBoundsException e) {
1149 throw DbException.get(ErrorCode.HEX_STRING_WRONG_1, s);
1150 }
1151 if ((mask & ~255) != 0) {
1152 throw DbException.get(ErrorCode.HEX_STRING_WRONG_1, s);
1153 }
1154 return buff;
1155 }
1156
1157 /**
1158 * Parses a hex encoded string with possible space separators and appends
1159 * the decoded binary string to the specified output stream.
1160 *
1161 * @param baos the output stream, or {@code null}
1162 * @param s the hex encoded string
1163 * @param start the start index
1164 * @param end the end index, exclusive
1165 * @return the specified output stream or a new output stream
1166 */
1167 public static ByteArrayOutputStream convertHexWithSpacesToBytes(ByteArrayOutputStream baos, String s, int start,
1168 int end) {
1169 if (baos == null) {
1170 baos = new ByteArrayOutputStream((end - start) >>> 1);
1171 }
1172 int mask = 0;
1173 int[] hex = HEX_DECODE;
1174 try {
1175 loop: for (int i = start;;) {
1176 char c1, c2;
1177 do {
1178 if (i >= end) {
1179 break loop;
1180 }
1181 c1 = s.charAt(i++);
1182 } while (c1 == ' ');
1183 do {
1184 if (i >= end) {
1185 if (((mask | hex[c1]) & ~255) != 0) {
1186 throw getHexStringException(ErrorCode.HEX_STRING_WRONG_1, s, start, end);
1187 }
1188 throw getHexStringException(ErrorCode.HEX_STRING_ODD_1, s, start, end);
1189 }
1190 c2 = s.charAt(i++);
1191 } while (c2 == ' ');
1192 int d = hex[c1] << 4 | hex[c2];
1193 mask |= d;
1194 baos.write(d);
1195 }
1196 } catch (ArrayIndexOutOfBoundsException e) {
1197 throw getHexStringException(ErrorCode.HEX_STRING_WRONG_1, s, start, end);
1198 }
1199 if ((mask & ~255) != 0) {
1200 throw getHexStringException(ErrorCode.HEX_STRING_WRONG_1, s, start, end);
1201 }
1202 return baos;
1203 }
1204
1205 private static DbException getHexStringException(int code, String s, int start, int end) {
1206 return DbException.get(code, s.substring(start, end));
1207 }
1208
1209 /**
1210 * Convert a byte array to a hex encoded string.
1211 *
1212 * @param value the byte array
1213 * @return the hex encoded string
1214 */
1215 public static String convertBytesToHex(byte[] value) {
1216 return convertBytesToHex(value, value.length);
1217 }
1218
1219 /**
1220 * Convert a byte array to a hex encoded string.
1221 *
1222 * @param value the byte array
1223 * @param len the number of bytes to encode
1224 * @return the hex encoded string
1225 */
1226 public static String convertBytesToHex(byte[] value, int len) {
1227 byte[] bytes = new byte[len * 2];
1228 char[] hex = HEX;
1229 for (int i = 0, j = 0; i < len; i++) {
1230 int c = value[i] & 0xff;
1231 bytes[j++] = (byte) hex[c >> 4];
1232 bytes[j++] = (byte) hex[c & 0xf];
1233 }
1234 return new String(bytes, StandardCharsets.ISO_8859_1);
1235 }
1236
1237 /**
1238 * Convert a byte array to a hex encoded string and appends it to a specified string builder.
1239 *
1240 * @param builder string builder to append to
1241 * @param value the byte array
1242 * @return the hex encoded string
1243 */
1244 public static StringBuilder convertBytesToHex(StringBuilder builder, byte[] value) {
1245 return convertBytesToHex(builder, value, value.length);
1246 }
1247
1248 /**
1249 * Convert a byte array to a hex encoded string and appends it to a specified string builder.
1250 *
1251 * @param builder string builder to append to
1252 * @param value the byte array
1253 * @param len the number of bytes to encode
1254 * @return the hex encoded string
1255 */
1256 public static StringBuilder convertBytesToHex(StringBuilder builder, byte[] value, int len) {
1257 char[] hex = HEX;
1258 for (int i = 0; i < len; i++) {
1259 int c = value[i] & 0xff;
1260 builder.append(hex[c >>> 4]).append(hex[c & 0xf]);
1261 }
1262 return builder;
1263 }
1264
1265 /**
1266 * Appends specified number of trailing bytes from unsigned long value to a
1267 * specified string builder.
1268 *
1269 * @param builder
1270 * string builder to append to
1271 * @param x
1272 * value to append
1273 * @param bytes
1274 * number of bytes to append
1275 * @return the specified string builder
1276 */
1277 public static StringBuilder appendHex(StringBuilder builder, long x, int bytes) {
1278 char[] hex = HEX;
1279 for (int i = bytes * 8; i > 0;) {
1280 builder.append(hex[(int) (x >> (i -= 4)) & 0xf]).append(hex[(int) (x >> (i -= 4)) & 0xf]);
1281 }
1282 return builder;
1283 }
1284
1285 /**
1286 * Check if this string is a decimal number.
1287 *
1288 * @param s the string
1289 * @return true if it is
1290 */
1291 public static boolean isNumber(String s) {
1292 int l = s.length();
1293 if (l == 0) {
1294 return false;
1295 }
1296 for (int i = 0; i < l; i++) {
1297 if (!Character.isDigit(s.charAt(i))) {
1298 return false;
1299 }
1300 }
1301 return true;
1302 }
1303
1304 /**
1305 * Check if the specified string is empty or contains only whitespace.
1306 *
1307 * @param s
1308 * the string
1309 * @return whether the specified string is empty or contains only whitespace
1310 */
1311 public static boolean isWhitespaceOrEmpty(String s) {
1312 for (int i = 0, l = s.length(); i < l; i++) {
1313 if (s.charAt(i) > ' ') {
1314 return false;
1315 }
1316 }
1317 return true;
1318 }
1319
1320 /**
1321 * Append a zero-padded number from 00 to 99 to a string builder.
1322 *
1323 * @param builder the string builder
1324 * @param positiveValue the number to append
1325 * @return the specified string builder
1326 */
1327 public static StringBuilder appendTwoDigits(StringBuilder builder, int positiveValue) {
1328 if (positiveValue < 10) {
1329 builder.append('0');
1330 }
1331 return builder.append(positiveValue);
1332 }
1333
1334 /**
1335 * Append a zero-padded number to a string builder.
1336 *
1337 * @param builder the string builder
1338 * @param length the number of characters to append
1339 * @param positiveValue the number to append
1340 * @return the specified string builder
1341 */
1342 public static StringBuilder appendZeroPadded(StringBuilder builder, int length, int positiveValue) {
1343 String s = Integer.toString(positiveValue);
1344 length -= s.length();
1345 for (; length > 0; length--) {
1346 builder.append('0');
1347 }
1348 return builder.append(s);
1349 }
1350
1351 /**
1352 * Appends the specified string or its part to the specified builder with
1353 * maximum builder length limit.
1354 *
1355 * @param builder the string builder
1356 * @param s the string to append
1357 * @param length the length limit
1358 * @return the specified string builder
1359 */
1360 public static StringBuilder appendToLength(StringBuilder builder, String s, int length) {
1361 int builderLength = builder.length();
1362 if (builderLength < length) {
1363 int need = length - builderLength;
1364 if (need >= s.length()) {
1365 builder.append(s);
1366 } else {
1367 builder.append(s, 0, need);
1368 }
1369 }
1370 return builder;
1371 }
1372
1373 /**
1374 * Escape table or schema patterns used for DatabaseMetaData functions.
1375 *
1376 * @param pattern the pattern
1377 * @return the escaped pattern
1378 */
1379 public static String escapeMetaDataPattern(String pattern) {
1380 if (pattern == null || pattern.isEmpty()) {
1381 return pattern;
1382 }
1383 return replaceAll(pattern, "\\", "\\\\");
1384 }
1385
1386 }