1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.providers.media.util; 18 19 import java.util.Locale; 20 21 public final class Preconditions { 22 23 /** 24 * Ensures that that the argument numeric value is non-negative (greater than or equal to 0). 25 * 26 * @param value a numeric int value 27 * @return the validated numeric value 28 * @throws IllegalArgumentException if {@code value} was negative 29 */ checkArgumentNonnegative(final int value)30 public static int checkArgumentNonnegative(final int value) { 31 if (value < 0) { 32 throw new IllegalArgumentException(); 33 } 34 35 return value; 36 } 37 38 /** 39 * Ensures that the argument int value is within the inclusive range. 40 * 41 * @param value a int value 42 * @param lower the lower endpoint of the inclusive range 43 * @param upper the upper endpoint of the inclusive range 44 * @param valueName the name of the argument to use if the check fails 45 * 46 * @return the validated int value 47 * 48 * @throws IllegalArgumentException if {@code value} was not within the range 49 */ checkArgumentInRange(int value, int lower, int upper, String valueName)50 public static int checkArgumentInRange(int value, int lower, int upper, 51 String valueName) { 52 if (value < lower) { 53 throw new IllegalArgumentException( 54 String.format(Locale.ROOT, 55 "%s is out of range of [%d, %d] (too low)", valueName, lower, upper)); 56 } else if (value > upper) { 57 throw new IllegalArgumentException( 58 String.format(Locale.ROOT, 59 "%s is out of range of [%d, %d] (too high)", valueName, lower, upper)); 60 } 61 62 return value; 63 } 64 } 65