1 /**
2 * Copyright The Apache Software Foundation
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with this
6 * work for additional information regarding copyright ownership. The ASF
7 * licenses this file to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 * License for the specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.hadoop.hbase.io.hfile.bucket;
20
21 import java.io.Serializable;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.atomic.AtomicInteger;
24
25 import org.apache.hadoop.hbase.classification.InterfaceAudience;
26
27 /**
28 * Map from type T to int and vice-versa. Used for reducing bit field item
29 * counts.
30 */
31 @InterfaceAudience.Private
32 public final class UniqueIndexMap<T> implements Serializable {
33 private static final long serialVersionUID = -1145635738654002342L;
34
35 ConcurrentHashMap<T, Integer> mForwardMap = new ConcurrentHashMap<T, Integer>();
36 ConcurrentHashMap<Integer, T> mReverseMap = new ConcurrentHashMap<Integer, T>();
37 AtomicInteger mIndex = new AtomicInteger(0);
38
39 // Map a length to an index. If we can't, allocate a new mapping. We might
40 // race here and get two entries with the same deserialiser. This is fine.
41 int map(T parameter) {
42 Integer ret = mForwardMap.get(parameter);
43 if (ret != null) return ret.intValue();
44 int nexti = mIndex.incrementAndGet();
45 assert (nexti < Short.MAX_VALUE);
46 mForwardMap.put(parameter, nexti);
47 mReverseMap.put(nexti, parameter);
48 return nexti;
49 }
50
51 T unmap(int leni) {
52 Integer len = Integer.valueOf(leni);
53 assert mReverseMap.containsKey(len);
54 return mReverseMap.get(len);
55 }
56 }