Advertisement
bobmarley12345

java optimised MessageFormat.format()

Dec 7th, 2022
759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.47 KB | None | 0 0
  1. // format("Hello {0}!", this.username);
  2. // format("You have chosen {0} as your {1} account name. Are you sure you want {0}?", this.username, this.accountName);
  3.  
  4. /**
  5.  * Similar to {@link java.text.MessageFormat#format(String, Object...)}, only more efficient, and
  6.  * escaping a bracket char is done with the '\' char, instead of the ' char
  7.  * <p>
  8.  *     Uses a number between {@code {}'s} to index an object in the given arguments. Null objects are handled by the StringBuilder
  9.  * </p>
  10.  * <p>
  11.  *     Escaping an open bracket ('{') is supported, however escaping a closing bracket ('}') after an
  12.  *     opened bracket is not supported... and there would be little to no reason to do so anyway
  13.  * </p>
  14.  * @param value The value to be formatted
  15.  * @param args   The values to splice in
  16.  * @return A string where all of the {...} cases have been replaced with the given arguments
  17.  * @throws BadFormatException Malformed index supplier (Missing a closing '}' char or there was nothing between '{' and '}')
  18.  * @throws IndexOutOfBoundsException The index is out of range of args
  19.  * @throws NumberFormatException The index is not a valid integer number
  20.  */
  21. public static String format(@Nullable String value, Object... args) {
  22.     if (StringUtils.isEmpty(value)) {
  23.         return value;
  24.     }
  25.     int firstIndex = value.indexOf('{');
  26.     if (firstIndex == -1) {
  27.         return value;
  28.     }
  29.     char[] chars = value.toCharArray();
  30.     int lastCloseIndex = StringUtils.lastIndexOf(chars, '}', firstIndex);
  31.     if (lastCloseIndex == -1) {
  32.         if (firstIndex == 0 || chars[firstIndex - 1] != '\\') { // check if the value is escaped using \\{
  33.             throw new BadFormatException("Initial value check - missing closing '}' after the first opening bracket '{' at index " + firstIndex + ":\n" + value);
  34.         }
  35.         return value;
  36.     }
  37.     StringBuilder string = new StringBuilder(value.length() * 2).append(value, 0, firstIndex);
  38.     for (int i = firstIndex, end = chars.length, endIndex = end - 1; i < end; ++i) {
  39.         char c = chars[i];
  40.         if (c != '{' || i == endIndex) { // last character
  41.             string.append(c);
  42.         }
  43.         else if (i > 0 && chars[i - 1] == '\\') { // escape
  44.             string.setCharAt(i - 1, '{'); // charAt(i - 1) == '\', so replace with '{'
  45.         }
  46.         else {
  47.             int closeIndex = StringUtils.indexOf(chars, '}', i + 1);
  48.             if (closeIndex == -1) {
  49.                 throw new BadFormatException("Missing a closing '}' after an opening bracket '{' at index " + i + ":\n" + value);
  50.             }
  51.             int startIndex = i + 1;
  52.             if (startIndex == closeIndex) {
  53.                 throw new BadFormatException("Value between '{' and '}' was empty! At index " + startIndex + ":\n" + value);
  54.             }
  55.             if (Parsing.parseInt(chars, startIndex, closeIndex)) {
  56.                 int index = Parsing.getInt();
  57.                 if (index < args.length && index >= 0) {
  58.                     string.append(args[index]); // let the sb handle null objects :)
  59.                 }
  60.                 else {
  61.                     string.append("{").append(index).append("}");
  62.                 }
  63.                 i = closeIndex;
  64.             }
  65.             else {
  66.                 throw new NumberFormatException("Value between '{' and '}' (" + StringUtils.toString(chars, startIndex, closeIndex) + ") was not an integer! At index " + startIndex + ":\n" + value);
  67.             }
  68.         }
  69.     }
  70.     return string.toString();
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement