e99a4f8a0692ee853ba80e952ab27fcd8a62e83e
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / OffsetMapCache.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util;
9
10 import com.google.common.cache.CacheBuilder;
11 import com.google.common.cache.CacheLoader;
12 import com.google.common.cache.LoadingCache;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableMap.Builder;
16 import com.google.common.collect.ImmutableSet;
17 import java.util.Collection;
18 import java.util.Map;
19
20 final class OffsetMapCache {
21     private static final LoadingCache<Collection<?>, Map<Object, Integer>> CACHE =
22             CacheBuilder.newBuilder().weakValues().build(new CacheLoader<Collection<?>, Map<Object, Integer>>() {
23                 @Override
24                 public Map<Object, Integer> load(final Collection<?> key) {
25                     final Builder<Object, Integer> b = ImmutableMap.builder();
26                     int i = 0;
27
28                     for (Object arg : key) {
29                         b.put(arg, i++);
30                     }
31
32                     return b.build();
33                 }
34     });
35
36     private OffsetMapCache() {
37         throw new UnsupportedOperationException();
38     }
39
40     @SuppressWarnings("unchecked")
41     private static <T> Map<T, Integer> offsets(final Collection<T> args) {
42         return (Map<T, Integer>) CACHE.getUnchecked(args);
43     }
44
45     static <T> Map<T, Integer> orderedOffsets(final Collection<T> args) {
46         if (args.size() == 1) {
47             return unorderedOffsets(args);
48         }
49
50         return offsets(ImmutableList.copyOf(args));
51     }
52
53     static <T> Map<T, Integer> unorderedOffsets(final Collection<T> args) {
54         if (args instanceof SingletonSet) {
55             return offsets(args);
56         }
57
58         return offsets(ImmutableSet.copyOf(args));
59     }
60 }