Same as #format, but with a list instead of variadic args.
(
Printer printer, StarlarkSemantics semantics, String pattern, List<?> arguments)
| 306 | |
| 307 | /** Same as {@link #format}, but with a list instead of variadic args. */ |
| 308 | @SuppressWarnings("FormatString") // see b/178189609 |
| 309 | public static void formatWithList( |
| 310 | Printer printer, StarlarkSemantics semantics, String pattern, List<?> arguments) { |
| 311 | // N.B. MissingFormatWidthException is the only kind of IllegalFormatException |
| 312 | // whose constructor can take and display arbitrary error message, hence its use below. |
| 313 | // TODO(adonovan): this suggests we're using the wrong exception. Throw IAE? |
| 314 | |
| 315 | int length = pattern.length(); |
| 316 | int argLength = arguments.size(); |
| 317 | int i = 0; // index of next character in pattern |
| 318 | int a = 0; // index of next argument in arguments |
| 319 | |
| 320 | while (i < length) { |
| 321 | int p = pattern.indexOf('%', i); |
| 322 | if (p == -1) { |
| 323 | printer.append(pattern, i, length); |
| 324 | break; |
| 325 | } |
| 326 | if (p > i) { |
| 327 | printer.append(pattern, i, p); |
| 328 | } |
| 329 | if (p == length - 1) { |
| 330 | throw new MissingFormatWidthException( |
| 331 | "incomplete format pattern ends with %: " + Starlark.repr(pattern)); |
| 332 | } |
| 333 | char conv = pattern.charAt(p + 1); |
| 334 | i = p + 2; |
| 335 | |
| 336 | // %%: literal % |
| 337 | if (conv == '%') { |
| 338 | printer.append('%'); |
| 339 | continue; |
| 340 | } |
| 341 | |
| 342 | // get argument |
| 343 | if (a >= argLength) { |
| 344 | throw new MissingFormatWidthException( |
| 345 | "not enough arguments for format pattern " |
| 346 | + Starlark.repr(pattern) |
| 347 | + ": " |
| 348 | + Starlark.repr(Tuple.copyOf(arguments))); |
| 349 | } |
| 350 | Object arg = arguments.get(a++); |
| 351 | |
| 352 | switch (conv) { |
| 353 | case 'd': |
| 354 | case 'o': |
| 355 | case 'x': |
| 356 | case 'X': |
| 357 | { |
| 358 | Number n; |
| 359 | if (arg instanceof StarlarkInt) { |
| 360 | n = ((StarlarkInt) arg).toNumber(); |
| 361 | } else if (arg instanceof Integer) { |
| 362 | n = (Number) arg; |
| 363 | } else if (arg instanceof StarlarkFloat) { |
| 364 | double d = ((StarlarkFloat) arg).toDouble(); |
| 365 | try { |