001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.core.util; 018 019import org.apache.logging.log4j.util.Strings; 020 021/** 022 * Helps deal with integers. 023 */ 024public final class Integers { 025 026 private static final int BITS_PER_INT = 32; 027 028 private Integers() { 029 } 030 031 /** 032 * Parses the string argument as a signed decimal integer. 033 * 034 * @param s a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""} 035 * @param defaultValue the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""} 036 * @return the integer value represented by the argument in decimal. 037 * @throws NumberFormatException if the string does not contain a parsable integer. 038 */ 039 public static int parseInt(final String s, final int defaultValue) { 040 return Strings.isEmpty(s) ? defaultValue : Integer.parseInt(s); 041 } 042 043 /** 044 * Parses the string argument as a signed decimal integer. 045 * 046 * @param s a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""} 047 * @return the integer value represented by the argument in decimal. 048 * @throws NumberFormatException if the string does not contain a parsable integer. 049 */ 050 public static int parseInt(final String s) { 051 return parseInt(s, 0); 052 } 053 054 /** 055 * Calculate the next power of 2, greater than or equal to x. 056 * <p> 057 * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. 058 * 059 * @param x Value to round up 060 * @return The next power of 2 from x inclusive 061 */ 062 public static int ceilingNextPowerOfTwo(final int x) { 063 return 1 << (BITS_PER_INT - Integer.numberOfLeadingZeros(x - 1)); 064 } 065}