001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import com.google.common.annotations.GwtCompatible;
018import com.google.errorprone.annotations.CanIgnoreReturnValue;
019import org.checkerframework.checker.nullness.compatqual.NullableDecl;
020
021/**
022 * Static convenience methods that help a method or constructor check whether it was invoked
023 * correctly (that is, whether its <i>preconditions</i> were met).
024 *
025 * <p>If the precondition is not met, the {@code Preconditions} method throws an unchecked exception
026 * of a specified type, which helps the method in which the exception was thrown communicate that
027 * its caller has made a mistake. This allows constructs such as
028 *
029 * <pre>{@code
030 * public static double sqrt(double value) {
031 *   if (value < 0) {
032 *     throw new IllegalArgumentException("input is negative: " + value);
033 *   }
034 *   // calculate square root
035 * }
036 * }</pre>
037 *
038 * <p>to be replaced with the more compact
039 *
040 * <pre>{@code
041 * public static double sqrt(double value) {
042 *   checkArgument(value >= 0, "input is negative: %s", value);
043 *   // calculate square root
044 * }
045 * }</pre>
046 *
047 * <p>so that a hypothetical bad caller of this method, such as:
048 *
049 * <pre>{@code
050 *   void exampleBadCaller() {
051 *     double d = sqrt(-1.0);
052 * }
053 * }</pre>
054 *
055 * <p>would be flagged as having called {@code sqrt()} with an illegal argument.
056 *
057 * <h3>Performance</h3>
058 *
059 * <p>Avoid passing message arguments that are expensive to compute; your code will always compute
060 * them, even though they usually won't be needed. If you have such arguments, use the conventional
061 * if/throw idiom instead.
062 *
063 * <p>Depending on your message arguments, memory may be allocated for boxing and varargs array
064 * creation. However, the methods of this class have a large number of overloads that prevent such
065 * allocations in many common cases.
066 *
067 * <p>The message string is not formatted unless the exception will be thrown, so the cost of the
068 * string formatting itself should not be a concern.
069 *
070 * <p>As with any performance concerns, you should consider profiling your code (in a production
071 * environment if possible) before spending a lot of effort on tweaking a particular element.
072 *
073 * <h3>Other types of preconditions</h3>
074 *
075 * <p>Not every type of precondition failure is supported by these methods. Continue to throw
076 * standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link
077 * UnsupportedOperationException} in the situations they are intended for.
078 *
079 * <h3>Non-preconditions</h3>
080 *
081 * <p>It is of course possible to use the methods of this class to check for invalid conditions
082 * which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is
083 * misleading to future readers of the code and of stack traces. See <a
084 * href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional failures
085 * explained</a> in the Guava User Guide for more advice. Notably, {@link Verify} offers assertions
086 * similar to those in this class for non-precondition checks.
087 *
088 * <h3>{@code java.util.Objects.requireNonNull()}</h3>
089 *
090 * <p>Projects which use {@code com.google.common} should generally avoid the use of {@link
091 * java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link
092 * #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation.
093 * (The same goes for the message-accepting overloads.)
094 *
095 * <h3>Only {@code %s} is supported</h3>
096 *
097 * <p>In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is
098 * supported, not the full range of {@link java.util.Formatter} specifiers.
099 *
100 * <h3>More information</h3>
101 *
102 * <p>See the Guava User Guide on <a
103 * href="https://github.com/google/guava/wiki/PreconditionsExplained">using {@code
104 * Preconditions}</a>.
105 *
106 * @author Kevin Bourrillion
107 * @since 2.0
108 */
109@GwtCompatible
110public final class Preconditions {
111  private Preconditions() {}
112
113  /**
114   * Ensures the truth of an expression involving one or more parameters to the calling method.
115   *
116   * @param expression a boolean expression
117   * @throws IllegalArgumentException if {@code expression} is false
118   */
119  public static void checkArgument(boolean expression) {
120    if (!expression) {
121      throw new IllegalArgumentException();
122    }
123  }
124
125  /**
126   * Ensures the truth of an expression involving one or more parameters to the calling method.
127   *
128   * @param expression a boolean expression
129   * @param errorMessage the exception message to use if the check fails; will be converted to a
130   *     string using {@link String#valueOf(Object)}
131   * @throws IllegalArgumentException if {@code expression} is false
132   */
133  public static void checkArgument(boolean expression, @NullableDecl Object errorMessage) {
134    if (!expression) {
135      throw new IllegalArgumentException(String.valueOf(errorMessage));
136    }
137  }
138
139  /**
140   * Ensures the truth of an expression involving one or more parameters to the calling method.
141   *
142   * @param expression a boolean expression
143   * @param errorMessageTemplate a template for the exception message should the check fail. The
144   *     message is formed by replacing each {@code %s} placeholder in the template with an
145   *     argument. These are matched by position - the first {@code %s} gets {@code
146   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
147   *     square braces. Unmatched placeholders will be left as-is.
148   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
149   *     are converted to strings using {@link String#valueOf(Object)}.
150   * @throws IllegalArgumentException if {@code expression} is false
151   */
152  public static void checkArgument(
153      boolean expression,
154      @NullableDecl String errorMessageTemplate,
155      @NullableDecl Object... errorMessageArgs) {
156    if (!expression) {
157      throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
158    }
159  }
160
161  /**
162   * Ensures the truth of an expression involving one or more parameters to the calling method.
163   *
164   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
165   *
166   * @since 20.0 (varargs overload since 2.0)
167   */
168  public static void checkArgument(boolean b, @NullableDecl String errorMessageTemplate, char p1) {
169    if (!b) {
170      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
171    }
172  }
173
174  /**
175   * Ensures the truth of an expression involving one or more parameters to the calling method.
176   *
177   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
178   *
179   * @since 20.0 (varargs overload since 2.0)
180   */
181  public static void checkArgument(boolean b, @NullableDecl String errorMessageTemplate, int p1) {
182    if (!b) {
183      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
184    }
185  }
186
187  /**
188   * Ensures the truth of an expression involving one or more parameters to the calling method.
189   *
190   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
191   *
192   * @since 20.0 (varargs overload since 2.0)
193   */
194  public static void checkArgument(boolean b, @NullableDecl String errorMessageTemplate, long p1) {
195    if (!b) {
196      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
197    }
198  }
199
200  /**
201   * Ensures the truth of an expression involving one or more parameters to the calling method.
202   *
203   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
204   *
205   * @since 20.0 (varargs overload since 2.0)
206   */
207  public static void checkArgument(
208      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1) {
209    if (!b) {
210      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
211    }
212  }
213
214  /**
215   * Ensures the truth of an expression involving one or more parameters to the calling method.
216   *
217   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
218   *
219   * @since 20.0 (varargs overload since 2.0)
220   */
221  public static void checkArgument(
222      boolean b, @NullableDecl String errorMessageTemplate, char p1, char p2) {
223    if (!b) {
224      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
225    }
226  }
227
228  /**
229   * Ensures the truth of an expression involving one or more parameters to the calling method.
230   *
231   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
232   *
233   * @since 20.0 (varargs overload since 2.0)
234   */
235  public static void checkArgument(
236      boolean b, @NullableDecl String errorMessageTemplate, char p1, int p2) {
237    if (!b) {
238      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
239    }
240  }
241
242  /**
243   * Ensures the truth of an expression involving one or more parameters to the calling method.
244   *
245   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
246   *
247   * @since 20.0 (varargs overload since 2.0)
248   */
249  public static void checkArgument(
250      boolean b, @NullableDecl String errorMessageTemplate, char p1, long p2) {
251    if (!b) {
252      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
253    }
254  }
255
256  /**
257   * Ensures the truth of an expression involving one or more parameters to the calling method.
258   *
259   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
260   *
261   * @since 20.0 (varargs overload since 2.0)
262   */
263  public static void checkArgument(
264      boolean b, @NullableDecl String errorMessageTemplate, char p1, @NullableDecl Object p2) {
265    if (!b) {
266      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
267    }
268  }
269
270  /**
271   * Ensures the truth of an expression involving one or more parameters to the calling method.
272   *
273   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
274   *
275   * @since 20.0 (varargs overload since 2.0)
276   */
277  public static void checkArgument(
278      boolean b, @NullableDecl String errorMessageTemplate, int p1, char p2) {
279    if (!b) {
280      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
281    }
282  }
283
284  /**
285   * Ensures the truth of an expression involving one or more parameters to the calling method.
286   *
287   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
288   *
289   * @since 20.0 (varargs overload since 2.0)
290   */
291  public static void checkArgument(
292      boolean b, @NullableDecl String errorMessageTemplate, int p1, int p2) {
293    if (!b) {
294      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
295    }
296  }
297
298  /**
299   * Ensures the truth of an expression involving one or more parameters to the calling method.
300   *
301   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
302   *
303   * @since 20.0 (varargs overload since 2.0)
304   */
305  public static void checkArgument(
306      boolean b, @NullableDecl String errorMessageTemplate, int p1, long p2) {
307    if (!b) {
308      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
309    }
310  }
311
312  /**
313   * Ensures the truth of an expression involving one or more parameters to the calling method.
314   *
315   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
316   *
317   * @since 20.0 (varargs overload since 2.0)
318   */
319  public static void checkArgument(
320      boolean b, @NullableDecl String errorMessageTemplate, int p1, @NullableDecl Object p2) {
321    if (!b) {
322      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
323    }
324  }
325
326  /**
327   * Ensures the truth of an expression involving one or more parameters to the calling method.
328   *
329   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
330   *
331   * @since 20.0 (varargs overload since 2.0)
332   */
333  public static void checkArgument(
334      boolean b, @NullableDecl String errorMessageTemplate, long p1, char p2) {
335    if (!b) {
336      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
337    }
338  }
339
340  /**
341   * Ensures the truth of an expression involving one or more parameters to the calling method.
342   *
343   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
344   *
345   * @since 20.0 (varargs overload since 2.0)
346   */
347  public static void checkArgument(
348      boolean b, @NullableDecl String errorMessageTemplate, long p1, int p2) {
349    if (!b) {
350      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
351    }
352  }
353
354  /**
355   * Ensures the truth of an expression involving one or more parameters to the calling method.
356   *
357   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
358   *
359   * @since 20.0 (varargs overload since 2.0)
360   */
361  public static void checkArgument(
362      boolean b, @NullableDecl String errorMessageTemplate, long p1, long p2) {
363    if (!b) {
364      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
365    }
366  }
367
368  /**
369   * Ensures the truth of an expression involving one or more parameters to the calling method.
370   *
371   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
372   *
373   * @since 20.0 (varargs overload since 2.0)
374   */
375  public static void checkArgument(
376      boolean b, @NullableDecl String errorMessageTemplate, long p1, @NullableDecl Object p2) {
377    if (!b) {
378      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
379    }
380  }
381
382  /**
383   * Ensures the truth of an expression involving one or more parameters to the calling method.
384   *
385   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
386   *
387   * @since 20.0 (varargs overload since 2.0)
388   */
389  public static void checkArgument(
390      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, char p2) {
391    if (!b) {
392      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
393    }
394  }
395
396  /**
397   * Ensures the truth of an expression involving one or more parameters to the calling method.
398   *
399   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
400   *
401   * @since 20.0 (varargs overload since 2.0)
402   */
403  public static void checkArgument(
404      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, int p2) {
405    if (!b) {
406      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
407    }
408  }
409
410  /**
411   * Ensures the truth of an expression involving one or more parameters to the calling method.
412   *
413   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
414   *
415   * @since 20.0 (varargs overload since 2.0)
416   */
417  public static void checkArgument(
418      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, long p2) {
419    if (!b) {
420      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
421    }
422  }
423
424  /**
425   * Ensures the truth of an expression involving one or more parameters to the calling method.
426   *
427   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
428   *
429   * @since 20.0 (varargs overload since 2.0)
430   */
431  public static void checkArgument(
432      boolean b,
433      @NullableDecl String errorMessageTemplate,
434      @NullableDecl Object p1,
435      @NullableDecl Object p2) {
436    if (!b) {
437      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
438    }
439  }
440
441  /**
442   * Ensures the truth of an expression involving one or more parameters to the calling method.
443   *
444   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
445   *
446   * @since 20.0 (varargs overload since 2.0)
447   */
448  public static void checkArgument(
449      boolean b,
450      @NullableDecl String errorMessageTemplate,
451      @NullableDecl Object p1,
452      @NullableDecl Object p2,
453      @NullableDecl Object p3) {
454    if (!b) {
455      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2, p3));
456    }
457  }
458
459  /**
460   * Ensures the truth of an expression involving one or more parameters to the calling method.
461   *
462   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
463   *
464   * @since 20.0 (varargs overload since 2.0)
465   */
466  public static void checkArgument(
467      boolean b,
468      @NullableDecl String errorMessageTemplate,
469      @NullableDecl Object p1,
470      @NullableDecl Object p2,
471      @NullableDecl Object p3,
472      @NullableDecl Object p4) {
473    if (!b) {
474      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2, p3, p4));
475    }
476  }
477
478  /**
479   * Ensures the truth of an expression involving the state of the calling instance, but not
480   * involving any parameters to the calling method.
481   *
482   * @param expression a boolean expression
483   * @throws IllegalStateException if {@code expression} is false
484   * @see Verify#verify Verify.verify()
485   */
486  public static void checkState(boolean expression) {
487    if (!expression) {
488      throw new IllegalStateException();
489    }
490  }
491
492  /**
493   * Ensures the truth of an expression involving the state of the calling instance, but not
494   * involving any parameters to the calling method.
495   *
496   * @param expression a boolean expression
497   * @param errorMessage the exception message to use if the check fails; will be converted to a
498   *     string using {@link String#valueOf(Object)}
499   * @throws IllegalStateException if {@code expression} is false
500   * @see Verify#verify Verify.verify()
501   */
502  public static void checkState(boolean expression, @NullableDecl Object errorMessage) {
503    if (!expression) {
504      throw new IllegalStateException(String.valueOf(errorMessage));
505    }
506  }
507
508  /**
509   * Ensures the truth of an expression involving the state of the calling instance, but not
510   * involving any parameters to the calling method.
511   *
512   * @param expression a boolean expression
513   * @param errorMessageTemplate a template for the exception message should the check fail. The
514   *     message is formed by replacing each {@code %s} placeholder in the template with an
515   *     argument. These are matched by position - the first {@code %s} gets {@code
516   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
517   *     square braces. Unmatched placeholders will be left as-is.
518   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
519   *     are converted to strings using {@link String#valueOf(Object)}.
520   * @throws IllegalStateException if {@code expression} is false
521   * @see Verify#verify Verify.verify()
522   */
523  public static void checkState(
524      boolean expression,
525      @NullableDecl String errorMessageTemplate,
526      @NullableDecl Object... errorMessageArgs) {
527    if (!expression) {
528      throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
529    }
530  }
531
532  /**
533   * Ensures the truth of an expression involving the state of the calling instance, but not
534   * involving any parameters to the calling method.
535   *
536   * <p>See {@link #checkState(boolean, String, Object...)} for details.
537   *
538   * @since 20.0 (varargs overload since 2.0)
539   */
540  public static void checkState(boolean b, @NullableDecl String errorMessageTemplate, char p1) {
541    if (!b) {
542      throw new IllegalStateException(format(errorMessageTemplate, p1));
543    }
544  }
545
546  /**
547   * Ensures the truth of an expression involving the state of the calling instance, but not
548   * involving any parameters to the calling method.
549   *
550   * <p>See {@link #checkState(boolean, String, Object...)} for details.
551   *
552   * @since 20.0 (varargs overload since 2.0)
553   */
554  public static void checkState(boolean b, @NullableDecl String errorMessageTemplate, int p1) {
555    if (!b) {
556      throw new IllegalStateException(format(errorMessageTemplate, p1));
557    }
558  }
559
560  /**
561   * Ensures the truth of an expression involving the state of the calling instance, but not
562   * involving any parameters to the calling method.
563   *
564   * <p>See {@link #checkState(boolean, String, Object...)} for details.
565   *
566   * @since 20.0 (varargs overload since 2.0)
567   */
568  public static void checkState(boolean b, @NullableDecl String errorMessageTemplate, long p1) {
569    if (!b) {
570      throw new IllegalStateException(format(errorMessageTemplate, p1));
571    }
572  }
573
574  /**
575   * Ensures the truth of an expression involving the state of the calling instance, but not
576   * involving any parameters to the calling method.
577   *
578   * <p>See {@link #checkState(boolean, String, Object...)} for details.
579   *
580   * @since 20.0 (varargs overload since 2.0)
581   */
582  public static void checkState(
583      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1) {
584    if (!b) {
585      throw new IllegalStateException(format(errorMessageTemplate, p1));
586    }
587  }
588
589  /**
590   * Ensures the truth of an expression involving the state of the calling instance, but not
591   * involving any parameters to the calling method.
592   *
593   * <p>See {@link #checkState(boolean, String, Object...)} for details.
594   *
595   * @since 20.0 (varargs overload since 2.0)
596   */
597  public static void checkState(
598      boolean b, @NullableDecl String errorMessageTemplate, char p1, char p2) {
599    if (!b) {
600      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
601    }
602  }
603
604  /**
605   * Ensures the truth of an expression involving the state of the calling instance, but not
606   * involving any parameters to the calling method.
607   *
608   * <p>See {@link #checkState(boolean, String, Object...)} for details.
609   *
610   * @since 20.0 (varargs overload since 2.0)
611   */
612  public static void checkState(
613      boolean b, @NullableDecl String errorMessageTemplate, char p1, int p2) {
614    if (!b) {
615      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
616    }
617  }
618
619  /**
620   * Ensures the truth of an expression involving the state of the calling instance, but not
621   * involving any parameters to the calling method.
622   *
623   * <p>See {@link #checkState(boolean, String, Object...)} for details.
624   *
625   * @since 20.0 (varargs overload since 2.0)
626   */
627  public static void checkState(
628      boolean b, @NullableDecl String errorMessageTemplate, char p1, long p2) {
629    if (!b) {
630      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
631    }
632  }
633
634  /**
635   * Ensures the truth of an expression involving the state of the calling instance, but not
636   * involving any parameters to the calling method.
637   *
638   * <p>See {@link #checkState(boolean, String, Object...)} for details.
639   *
640   * @since 20.0 (varargs overload since 2.0)
641   */
642  public static void checkState(
643      boolean b, @NullableDecl String errorMessageTemplate, char p1, @NullableDecl Object p2) {
644    if (!b) {
645      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
646    }
647  }
648
649  /**
650   * Ensures the truth of an expression involving the state of the calling instance, but not
651   * involving any parameters to the calling method.
652   *
653   * <p>See {@link #checkState(boolean, String, Object...)} for details.
654   *
655   * @since 20.0 (varargs overload since 2.0)
656   */
657  public static void checkState(
658      boolean b, @NullableDecl String errorMessageTemplate, int p1, char p2) {
659    if (!b) {
660      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
661    }
662  }
663
664  /**
665   * Ensures the truth of an expression involving the state of the calling instance, but not
666   * involving any parameters to the calling method.
667   *
668   * <p>See {@link #checkState(boolean, String, Object...)} for details.
669   *
670   * @since 20.0 (varargs overload since 2.0)
671   */
672  public static void checkState(
673      boolean b, @NullableDecl String errorMessageTemplate, int p1, int p2) {
674    if (!b) {
675      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
676    }
677  }
678
679  /**
680   * Ensures the truth of an expression involving the state of the calling instance, but not
681   * involving any parameters to the calling method.
682   *
683   * <p>See {@link #checkState(boolean, String, Object...)} for details.
684   *
685   * @since 20.0 (varargs overload since 2.0)
686   */
687  public static void checkState(
688      boolean b, @NullableDecl String errorMessageTemplate, int p1, long p2) {
689    if (!b) {
690      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
691    }
692  }
693
694  /**
695   * Ensures the truth of an expression involving the state of the calling instance, but not
696   * involving any parameters to the calling method.
697   *
698   * <p>See {@link #checkState(boolean, String, Object...)} for details.
699   *
700   * @since 20.0 (varargs overload since 2.0)
701   */
702  public static void checkState(
703      boolean b, @NullableDecl String errorMessageTemplate, int p1, @NullableDecl Object p2) {
704    if (!b) {
705      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
706    }
707  }
708
709  /**
710   * Ensures the truth of an expression involving the state of the calling instance, but not
711   * involving any parameters to the calling method.
712   *
713   * <p>See {@link #checkState(boolean, String, Object...)} for details.
714   *
715   * @since 20.0 (varargs overload since 2.0)
716   */
717  public static void checkState(
718      boolean b, @NullableDecl String errorMessageTemplate, long p1, char p2) {
719    if (!b) {
720      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
721    }
722  }
723
724  /**
725   * Ensures the truth of an expression involving the state of the calling instance, but not
726   * involving any parameters to the calling method.
727   *
728   * <p>See {@link #checkState(boolean, String, Object...)} for details.
729   *
730   * @since 20.0 (varargs overload since 2.0)
731   */
732  public static void checkState(
733      boolean b, @NullableDecl String errorMessageTemplate, long p1, int p2) {
734    if (!b) {
735      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
736    }
737  }
738
739  /**
740   * Ensures the truth of an expression involving the state of the calling instance, but not
741   * involving any parameters to the calling method.
742   *
743   * <p>See {@link #checkState(boolean, String, Object...)} for details.
744   *
745   * @since 20.0 (varargs overload since 2.0)
746   */
747  public static void checkState(
748      boolean b, @NullableDecl String errorMessageTemplate, long p1, long p2) {
749    if (!b) {
750      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
751    }
752  }
753
754  /**
755   * Ensures the truth of an expression involving the state of the calling instance, but not
756   * involving any parameters to the calling method.
757   *
758   * <p>See {@link #checkState(boolean, String, Object...)} for details.
759   *
760   * @since 20.0 (varargs overload since 2.0)
761   */
762  public static void checkState(
763      boolean b, @NullableDecl String errorMessageTemplate, long p1, @NullableDecl Object p2) {
764    if (!b) {
765      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
766    }
767  }
768
769  /**
770   * Ensures the truth of an expression involving the state of the calling instance, but not
771   * involving any parameters to the calling method.
772   *
773   * <p>See {@link #checkState(boolean, String, Object...)} for details.
774   *
775   * @since 20.0 (varargs overload since 2.0)
776   */
777  public static void checkState(
778      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, char p2) {
779    if (!b) {
780      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
781    }
782  }
783
784  /**
785   * Ensures the truth of an expression involving the state of the calling instance, but not
786   * involving any parameters to the calling method.
787   *
788   * <p>See {@link #checkState(boolean, String, Object...)} for details.
789   *
790   * @since 20.0 (varargs overload since 2.0)
791   */
792  public static void checkState(
793      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, int p2) {
794    if (!b) {
795      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
796    }
797  }
798
799  /**
800   * Ensures the truth of an expression involving the state of the calling instance, but not
801   * involving any parameters to the calling method.
802   *
803   * <p>See {@link #checkState(boolean, String, Object...)} for details.
804   *
805   * @since 20.0 (varargs overload since 2.0)
806   */
807  public static void checkState(
808      boolean b, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, long p2) {
809    if (!b) {
810      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
811    }
812  }
813
814  /**
815   * Ensures the truth of an expression involving the state of the calling instance, but not
816   * involving any parameters to the calling method.
817   *
818   * <p>See {@link #checkState(boolean, String, Object...)} for details.
819   *
820   * @since 20.0 (varargs overload since 2.0)
821   */
822  public static void checkState(
823      boolean b,
824      @NullableDecl String errorMessageTemplate,
825      @NullableDecl Object p1,
826      @NullableDecl Object p2) {
827    if (!b) {
828      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
829    }
830  }
831
832  /**
833   * Ensures the truth of an expression involving the state of the calling instance, but not
834   * involving any parameters to the calling method.
835   *
836   * <p>See {@link #checkState(boolean, String, Object...)} for details.
837   *
838   * @since 20.0 (varargs overload since 2.0)
839   */
840  public static void checkState(
841      boolean b,
842      @NullableDecl String errorMessageTemplate,
843      @NullableDecl Object p1,
844      @NullableDecl Object p2,
845      @NullableDecl Object p3) {
846    if (!b) {
847      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
848    }
849  }
850
851  /**
852   * Ensures the truth of an expression involving the state of the calling instance, but not
853   * involving any parameters to the calling method.
854   *
855   * <p>See {@link #checkState(boolean, String, Object...)} for details.
856   *
857   * @since 20.0 (varargs overload since 2.0)
858   */
859  public static void checkState(
860      boolean b,
861      @NullableDecl String errorMessageTemplate,
862      @NullableDecl Object p1,
863      @NullableDecl Object p2,
864      @NullableDecl Object p3,
865      @NullableDecl Object p4) {
866    if (!b) {
867      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3, p4));
868    }
869  }
870
871  /**
872   * Ensures that an object reference passed as a parameter to the calling method is not null.
873   *
874   * @param reference an object reference
875   * @return the non-null reference that was validated
876   * @throws NullPointerException if {@code reference} is null
877   * @see Verify#verifyNotNull Verify.verifyNotNull()
878   */
879  @CanIgnoreReturnValue
880  public static <T> T checkNotNull(T reference) {
881    if (reference == null) {
882      throw new NullPointerException();
883    }
884    return reference;
885  }
886
887  /**
888   * Ensures that an object reference passed as a parameter to the calling method is not null.
889   *
890   * @param reference an object reference
891   * @param errorMessage the exception message to use if the check fails; will be converted to a
892   *     string using {@link String#valueOf(Object)}
893   * @return the non-null reference that was validated
894   * @throws NullPointerException if {@code reference} is null
895   * @see Verify#verifyNotNull Verify.verifyNotNull()
896   */
897  @CanIgnoreReturnValue
898  public static <T> T checkNotNull(T reference, @NullableDecl Object errorMessage) {
899    if (reference == null) {
900      throw new NullPointerException(String.valueOf(errorMessage));
901    }
902    return reference;
903  }
904
905  /**
906   * Ensures that an object reference passed as a parameter to the calling method is not null.
907   *
908   * @param reference an object reference
909   * @param errorMessageTemplate a template for the exception message should the check fail. The
910   *     message is formed by replacing each {@code %s} placeholder in the template with an
911   *     argument. These are matched by position - the first {@code %s} gets {@code
912   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
913   *     square braces. Unmatched placeholders will be left as-is.
914   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
915   *     are converted to strings using {@link String#valueOf(Object)}.
916   * @return the non-null reference that was validated
917   * @throws NullPointerException if {@code reference} is null
918   * @see Verify#verifyNotNull Verify.verifyNotNull()
919   */
920  @CanIgnoreReturnValue
921  public static <T> T checkNotNull(
922      T reference,
923      @NullableDecl String errorMessageTemplate,
924      @NullableDecl Object... errorMessageArgs) {
925    if (reference == null) {
926      throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
927    }
928    return reference;
929  }
930
931  /**
932   * Ensures that an object reference passed as a parameter to the calling method is not null.
933   *
934   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
935   *
936   * @since 20.0 (varargs overload since 2.0)
937   */
938  @CanIgnoreReturnValue
939  public static <T> T checkNotNull(T obj, @NullableDecl String errorMessageTemplate, char p1) {
940    if (obj == null) {
941      throw new NullPointerException(format(errorMessageTemplate, p1));
942    }
943    return obj;
944  }
945
946  /**
947   * Ensures that an object reference passed as a parameter to the calling method is not null.
948   *
949   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
950   *
951   * @since 20.0 (varargs overload since 2.0)
952   */
953  @CanIgnoreReturnValue
954  public static <T> T checkNotNull(T obj, @NullableDecl String errorMessageTemplate, int p1) {
955    if (obj == null) {
956      throw new NullPointerException(format(errorMessageTemplate, p1));
957    }
958    return obj;
959  }
960
961  /**
962   * Ensures that an object reference passed as a parameter to the calling method is not null.
963   *
964   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
965   *
966   * @since 20.0 (varargs overload since 2.0)
967   */
968  @CanIgnoreReturnValue
969  public static <T> T checkNotNull(T obj, @NullableDecl String errorMessageTemplate, long p1) {
970    if (obj == null) {
971      throw new NullPointerException(format(errorMessageTemplate, p1));
972    }
973    return obj;
974  }
975
976  /**
977   * Ensures that an object reference passed as a parameter to the calling method is not null.
978   *
979   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
980   *
981   * @since 20.0 (varargs overload since 2.0)
982   */
983  @CanIgnoreReturnValue
984  public static <T> T checkNotNull(
985      T obj, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1) {
986    if (obj == null) {
987      throw new NullPointerException(format(errorMessageTemplate, p1));
988    }
989    return obj;
990  }
991
992  /**
993   * Ensures that an object reference passed as a parameter to the calling method is not null.
994   *
995   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
996   *
997   * @since 20.0 (varargs overload since 2.0)
998   */
999  @CanIgnoreReturnValue
1000  public static <T> T checkNotNull(
1001      T obj, @NullableDecl String errorMessageTemplate, char p1, char p2) {
1002    if (obj == null) {
1003      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1004    }
1005    return obj;
1006  }
1007
1008  /**
1009   * Ensures that an object reference passed as a parameter to the calling method is not null.
1010   *
1011   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1012   *
1013   * @since 20.0 (varargs overload since 2.0)
1014   */
1015  @CanIgnoreReturnValue
1016  public static <T> T checkNotNull(
1017      T obj, @NullableDecl String errorMessageTemplate, char p1, int p2) {
1018    if (obj == null) {
1019      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1020    }
1021    return obj;
1022  }
1023
1024  /**
1025   * Ensures that an object reference passed as a parameter to the calling method is not null.
1026   *
1027   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1028   *
1029   * @since 20.0 (varargs overload since 2.0)
1030   */
1031  @CanIgnoreReturnValue
1032  public static <T> T checkNotNull(
1033      T obj, @NullableDecl String errorMessageTemplate, char p1, long p2) {
1034    if (obj == null) {
1035      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1036    }
1037    return obj;
1038  }
1039
1040  /**
1041   * Ensures that an object reference passed as a parameter to the calling method is not null.
1042   *
1043   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1044   *
1045   * @since 20.0 (varargs overload since 2.0)
1046   */
1047  @CanIgnoreReturnValue
1048  public static <T> T checkNotNull(
1049      T obj, @NullableDecl String errorMessageTemplate, char p1, @NullableDecl Object p2) {
1050    if (obj == null) {
1051      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1052    }
1053    return obj;
1054  }
1055
1056  /**
1057   * Ensures that an object reference passed as a parameter to the calling method is not null.
1058   *
1059   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1060   *
1061   * @since 20.0 (varargs overload since 2.0)
1062   */
1063  @CanIgnoreReturnValue
1064  public static <T> T checkNotNull(
1065      T obj, @NullableDecl String errorMessageTemplate, int p1, char p2) {
1066    if (obj == null) {
1067      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1068    }
1069    return obj;
1070  }
1071
1072  /**
1073   * Ensures that an object reference passed as a parameter to the calling method is not null.
1074   *
1075   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1076   *
1077   * @since 20.0 (varargs overload since 2.0)
1078   */
1079  @CanIgnoreReturnValue
1080  public static <T> T checkNotNull(
1081      T obj, @NullableDecl String errorMessageTemplate, int p1, int p2) {
1082    if (obj == null) {
1083      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1084    }
1085    return obj;
1086  }
1087
1088  /**
1089   * Ensures that an object reference passed as a parameter to the calling method is not null.
1090   *
1091   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1092   *
1093   * @since 20.0 (varargs overload since 2.0)
1094   */
1095  @CanIgnoreReturnValue
1096  public static <T> T checkNotNull(
1097      T obj, @NullableDecl String errorMessageTemplate, int p1, long p2) {
1098    if (obj == null) {
1099      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1100    }
1101    return obj;
1102  }
1103
1104  /**
1105   * Ensures that an object reference passed as a parameter to the calling method is not null.
1106   *
1107   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1108   *
1109   * @since 20.0 (varargs overload since 2.0)
1110   */
1111  @CanIgnoreReturnValue
1112  public static <T> T checkNotNull(
1113      T obj, @NullableDecl String errorMessageTemplate, int p1, @NullableDecl Object p2) {
1114    if (obj == null) {
1115      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1116    }
1117    return obj;
1118  }
1119
1120  /**
1121   * Ensures that an object reference passed as a parameter to the calling method is not null.
1122   *
1123   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1124   *
1125   * @since 20.0 (varargs overload since 2.0)
1126   */
1127  @CanIgnoreReturnValue
1128  public static <T> T checkNotNull(
1129      T obj, @NullableDecl String errorMessageTemplate, long p1, char p2) {
1130    if (obj == null) {
1131      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1132    }
1133    return obj;
1134  }
1135
1136  /**
1137   * Ensures that an object reference passed as a parameter to the calling method is not null.
1138   *
1139   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1140   *
1141   * @since 20.0 (varargs overload since 2.0)
1142   */
1143  @CanIgnoreReturnValue
1144  public static <T> T checkNotNull(
1145      T obj, @NullableDecl String errorMessageTemplate, long p1, int p2) {
1146    if (obj == null) {
1147      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1148    }
1149    return obj;
1150  }
1151
1152  /**
1153   * Ensures that an object reference passed as a parameter to the calling method is not null.
1154   *
1155   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1156   *
1157   * @since 20.0 (varargs overload since 2.0)
1158   */
1159  @CanIgnoreReturnValue
1160  public static <T> T checkNotNull(
1161      T obj, @NullableDecl String errorMessageTemplate, long p1, long p2) {
1162    if (obj == null) {
1163      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1164    }
1165    return obj;
1166  }
1167
1168  /**
1169   * Ensures that an object reference passed as a parameter to the calling method is not null.
1170   *
1171   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1172   *
1173   * @since 20.0 (varargs overload since 2.0)
1174   */
1175  @CanIgnoreReturnValue
1176  public static <T> T checkNotNull(
1177      T obj, @NullableDecl String errorMessageTemplate, long p1, @NullableDecl Object p2) {
1178    if (obj == null) {
1179      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1180    }
1181    return obj;
1182  }
1183
1184  /**
1185   * Ensures that an object reference passed as a parameter to the calling method is not null.
1186   *
1187   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1188   *
1189   * @since 20.0 (varargs overload since 2.0)
1190   */
1191  @CanIgnoreReturnValue
1192  public static <T> T checkNotNull(
1193      T obj, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, char p2) {
1194    if (obj == null) {
1195      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1196    }
1197    return obj;
1198  }
1199
1200  /**
1201   * Ensures that an object reference passed as a parameter to the calling method is not null.
1202   *
1203   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1204   *
1205   * @since 20.0 (varargs overload since 2.0)
1206   */
1207  @CanIgnoreReturnValue
1208  public static <T> T checkNotNull(
1209      T obj, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, int p2) {
1210    if (obj == null) {
1211      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1212    }
1213    return obj;
1214  }
1215
1216  /**
1217   * Ensures that an object reference passed as a parameter to the calling method is not null.
1218   *
1219   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1220   *
1221   * @since 20.0 (varargs overload since 2.0)
1222   */
1223  @CanIgnoreReturnValue
1224  public static <T> T checkNotNull(
1225      T obj, @NullableDecl String errorMessageTemplate, @NullableDecl Object p1, long p2) {
1226    if (obj == null) {
1227      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1228    }
1229    return obj;
1230  }
1231
1232  /**
1233   * Ensures that an object reference passed as a parameter to the calling method is not null.
1234   *
1235   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1236   *
1237   * @since 20.0 (varargs overload since 2.0)
1238   */
1239  @CanIgnoreReturnValue
1240  public static <T> T checkNotNull(
1241      T obj,
1242      @NullableDecl String errorMessageTemplate,
1243      @NullableDecl Object p1,
1244      @NullableDecl Object p2) {
1245    if (obj == null) {
1246      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1247    }
1248    return obj;
1249  }
1250
1251  /**
1252   * Ensures that an object reference passed as a parameter to the calling method is not null.
1253   *
1254   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1255   *
1256   * @since 20.0 (varargs overload since 2.0)
1257   */
1258  @CanIgnoreReturnValue
1259  public static <T> T checkNotNull(
1260      T obj,
1261      @NullableDecl String errorMessageTemplate,
1262      @NullableDecl Object p1,
1263      @NullableDecl Object p2,
1264      @NullableDecl Object p3) {
1265    if (obj == null) {
1266      throw new NullPointerException(format(errorMessageTemplate, p1, p2, p3));
1267    }
1268    return obj;
1269  }
1270
1271  /**
1272   * Ensures that an object reference passed as a parameter to the calling method is not null.
1273   *
1274   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1275   *
1276   * @since 20.0 (varargs overload since 2.0)
1277   */
1278  @CanIgnoreReturnValue
1279  public static <T> T checkNotNull(
1280      T obj,
1281      @NullableDecl String errorMessageTemplate,
1282      @NullableDecl Object p1,
1283      @NullableDecl Object p2,
1284      @NullableDecl Object p3,
1285      @NullableDecl Object p4) {
1286    if (obj == null) {
1287      throw new NullPointerException(format(errorMessageTemplate, p1, p2, p3, p4));
1288    }
1289    return obj;
1290  }
1291
1292  /*
1293   * All recent hotspots (as of 2009) *really* like to have the natural code
1294   *
1295   * if (guardExpression) {
1296   *    throw new BadException(messageExpression);
1297   * }
1298   *
1299   * refactored so that messageExpression is moved to a separate String-returning method.
1300   *
1301   * if (guardExpression) {
1302   *    throw new BadException(badMsg(...));
1303   * }
1304   *
1305   * The alternative natural refactorings into void or Exception-returning methods are much slower.
1306   * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is
1307   * a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
1308   *
1309   * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
1310   * RangeCheckMicroBenchmark in the JDK that was used to test this.
1311   *
1312   * But the methods in this class want to throw different exceptions, depending on the args, so it
1313   * appears that this pattern is not directly applicable. But we can use the ridiculous, devious
1314   * trick of throwing an exception in the middle of the construction of another exception. Hotspot
1315   * is fine with that.
1316   */
1317
1318  /**
1319   * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
1320   * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
1321   *
1322   * @param index a user-supplied index identifying an element of an array, list or string
1323   * @param size the size of that array, list or string
1324   * @return the value of {@code index}
1325   * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
1326   * @throws IllegalArgumentException if {@code size} is negative
1327   */
1328  @CanIgnoreReturnValue
1329  public static int checkElementIndex(int index, int size) {
1330    return checkElementIndex(index, size, "index");
1331  }
1332
1333  /**
1334   * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
1335   * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
1336   *
1337   * @param index a user-supplied index identifying an element of an array, list or string
1338   * @param size the size of that array, list or string
1339   * @param desc the text to use to describe this index in an error message
1340   * @return the value of {@code index}
1341   * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
1342   * @throws IllegalArgumentException if {@code size} is negative
1343   */
1344  @CanIgnoreReturnValue
1345  public static int checkElementIndex(int index, int size, @NullableDecl String desc) {
1346    // Carefully optimized for execution by hotspot (explanatory comment above)
1347    if (index < 0 || index >= size) {
1348      throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
1349    }
1350    return index;
1351  }
1352
1353  private static String badElementIndex(int index, int size, @NullableDecl String desc) {
1354    if (index < 0) {
1355      return format("%s (%s) must not be negative", desc, index);
1356    } else if (size < 0) {
1357      throw new IllegalArgumentException("negative size: " + size);
1358    } else { // index >= size
1359      return format("%s (%s) must be less than size (%s)", desc, index, size);
1360    }
1361  }
1362
1363  /**
1364   * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
1365   * size {@code size}. A position index may range from zero to {@code size}, inclusive.
1366   *
1367   * @param index a user-supplied index identifying a position in an array, list or string
1368   * @param size the size of that array, list or string
1369   * @return the value of {@code index}
1370   * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
1371   * @throws IllegalArgumentException if {@code size} is negative
1372   */
1373  @CanIgnoreReturnValue
1374  public static int checkPositionIndex(int index, int size) {
1375    return checkPositionIndex(index, size, "index");
1376  }
1377
1378  /**
1379   * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
1380   * size {@code size}. A position index may range from zero to {@code size}, inclusive.
1381   *
1382   * @param index a user-supplied index identifying a position in an array, list or string
1383   * @param size the size of that array, list or string
1384   * @param desc the text to use to describe this index in an error message
1385   * @return the value of {@code index}
1386   * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
1387   * @throws IllegalArgumentException if {@code size} is negative
1388   */
1389  @CanIgnoreReturnValue
1390  public static int checkPositionIndex(int index, int size, @NullableDecl String desc) {
1391    // Carefully optimized for execution by hotspot (explanatory comment above)
1392    if (index < 0 || index > size) {
1393      throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
1394    }
1395    return index;
1396  }
1397
1398  private static String badPositionIndex(int index, int size, @NullableDecl String desc) {
1399    if (index < 0) {
1400      return format("%s (%s) must not be negative", desc, index);
1401    } else if (size < 0) {
1402      throw new IllegalArgumentException("negative size: " + size);
1403    } else { // index > size
1404      return format("%s (%s) must not be greater than size (%s)", desc, index, size);
1405    }
1406  }
1407
1408  /**
1409   * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list
1410   * or string of size {@code size}, and are in order. A position index may range from zero to
1411   * {@code size}, inclusive.
1412   *
1413   * @param start a user-supplied index identifying a starting position in an array, list or string
1414   * @param end a user-supplied index identifying a ending position in an array, list or string
1415   * @param size the size of that array, list or string
1416   * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size},
1417   *     or if {@code end} is less than {@code start}
1418   * @throws IllegalArgumentException if {@code size} is negative
1419   */
1420  public static void checkPositionIndexes(int start, int end, int size) {
1421    // Carefully optimized for execution by hotspot (explanatory comment above)
1422    if (start < 0 || end < start || end > size) {
1423      throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
1424    }
1425  }
1426
1427  private static String badPositionIndexes(int start, int end, int size) {
1428    if (start < 0 || start > size) {
1429      return badPositionIndex(start, size, "start index");
1430    }
1431    if (end < 0 || end > size) {
1432      return badPositionIndex(end, size, "end index");
1433    }
1434    // end < start
1435    return format("end index (%s) must not be less than start index (%s)", end, start);
1436  }
1437
1438  /**
1439   * Substitutes each {@code %s} in {@code template} with an argument. These are matched by
1440   * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
1441   * placeholders, the unmatched arguments will be appended to the end of the formatted message in
1442   * square braces.
1443   *
1444   * @param template a string containing 0 or more {@code %s} placeholders. null is treated as
1445   *     "null".
1446   * @param args the arguments to be substituted into the message template. Arguments are converted
1447   *     to strings using {@link String#valueOf(Object)}. Arguments can be null.
1448   */
1449  // Note that this is somewhat-improperly used from Verify.java as well.
1450  static String format(@NullableDecl String template, @NullableDecl Object... args) {
1451    template = String.valueOf(template); // null -> "null"
1452
1453    args = args == null ? new Object[] {"(Object[])null"} : args;
1454
1455    // start substituting the arguments into the '%s' placeholders
1456    StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
1457    int templateStart = 0;
1458    int i = 0;
1459    while (i < args.length) {
1460      int placeholderStart = template.indexOf("%s", templateStart);
1461      if (placeholderStart == -1) {
1462        break;
1463      }
1464      builder.append(template, templateStart, placeholderStart);
1465      builder.append(args[i++]);
1466      templateStart = placeholderStart + 2;
1467    }
1468    builder.append(template, templateStart, template.length());
1469
1470    // if we run out of placeholders, append the extra args in square braces
1471    if (i < args.length) {
1472      builder.append(" [");
1473      builder.append(args[i++]);
1474      while (i < args.length) {
1475        builder.append(", ");
1476        builder.append(args[i++]);
1477      }
1478      builder.append(']');
1479    }
1480
1481    return builder.toString();
1482  }
1483}