001/**
002 * Copyright The Apache Software Foundation
003 *
004 * Licensed to the Apache Software Foundation (ASF) under one or more
005 * contributor license agreements. See the NOTICE file distributed with this
006 * work for additional information regarding copyright ownership. The ASF
007 * licenses this file to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
015 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
016 * License for the specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.hadoop.hbase.io.hfile.bucket;
020
021import java.io.Serializable;
022import java.util.concurrent.ConcurrentHashMap;
023import java.util.concurrent.atomic.AtomicInteger;
024
025import org.apache.yetus.audience.InterfaceAudience;
026
027/**
028 * Map from type T to int and vice-versa. Used for reducing bit field item
029 * counts.
030 */
031@InterfaceAudience.Private
032public final class UniqueIndexMap<T> implements Serializable {
033  private static final long serialVersionUID = -1145635738654002342L;
034
035  ConcurrentHashMap<T, Integer> mForwardMap = new ConcurrentHashMap<>();
036  ConcurrentHashMap<Integer, T> mReverseMap = new ConcurrentHashMap<>();
037  AtomicInteger mIndex = new AtomicInteger(0);
038
039  // Map a length to an index. If we can't, allocate a new mapping. We might
040  // race here and get two entries with the same deserialiser. This is fine.
041  int map(T parameter) {
042    Integer ret = mForwardMap.get(parameter);
043    if (ret != null) return ret.intValue();
044    int nexti = mIndex.incrementAndGet();
045    assert (nexti < Short.MAX_VALUE);
046    mForwardMap.put(parameter, nexti);
047    mReverseMap.put(nexti, parameter);
048    return nexti;
049  }
050
051  T unmap(int leni) {
052    Integer len = Integer.valueOf(leni);
053    assert mReverseMap.containsKey(len);
054    return mReverseMap.get(len);
055  }
056}