001/**
002 * Copyright 2011-2015 John Ericksen
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *    http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.parceler;
017
018/**
019 * @author John Ericksen
020 */
021public final class MapsUtil {
022
023    public static final String INITIAL_HASH_MAP_CAPACITY_METHOD = "initialHashMapCapacity";
024
025    private static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
026
027    private MapsUtil() {
028        //
029    }
030
031    /**
032     * Copy of capacity method from Guava Maps utility.
033     *
034     * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
035     * larger than expectedSize and the load factor is ≥ its default (0.75).
036     *
037     * @param expectedSize
038     * @return HashMap capacity that avoids rehashing.
039     */
040    public static int initialHashMapCapacity(int expectedSize) {
041        if (expectedSize < 0) {
042            throw new ParcelerRuntimeException("Expected size must be non-negative");
043        }
044        if (expectedSize < 3) {
045            return expectedSize + 1;
046        }
047        if (expectedSize < MAX_POWER_OF_TWO) {
048            // This is the calculation used in JDK8 to resize when a putAll
049            // happens; it seems to be the most conservative calculation we
050            // can make.  0.75 is the default load factor.
051            return (int) ((float) expectedSize / 0.75F + 1.0F);
052        }
053        return Integer.MAX_VALUE; // any large value
054    }
055}