b9776e3421bab45dffdcaa6f0066d73e5a9be261
[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.annotations.VisibleForTesting;
11 import com.google.common.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableMap.Builder;
17 import com.google.common.collect.ImmutableSet;
18 import java.util.Collection;
19 import java.util.Map;
20
21 final class OffsetMapCache {
22     private static final LoadingCache<Collection<?>, Map<Object, Integer>> CACHE =
23             CacheBuilder.newBuilder().weakValues().build(new CacheLoader<Collection<?>, Map<Object, Integer>>() {
24                 @Override
25                 public Map<Object, Integer> load(final Collection<?> key) {
26                     final Builder<Object, Integer> b = ImmutableMap.builder();
27                     int i = 0;
28
29                     for (Object arg : key) {
30                         b.put(arg, i++);
31                     }
32
33                     return b.build();
34                 }
35     });
36
37     private OffsetMapCache() {
38         throw new UnsupportedOperationException();
39     }
40
41     @SuppressWarnings("unchecked")
42     private static <T> Map<T, Integer> offsets(final Collection<T> args) {
43         return (Map<T, Integer>) CACHE.getUnchecked(args);
44     }
45
46     @VisibleForTesting
47     static void invalidateCache() {
48         CACHE.invalidateAll();
49     }
50
51     static <T> Map<T, Integer> orderedOffsets(final Collection<T> args) {
52         if (args.size() == 1) {
53             return unorderedOffsets(args);
54         }
55
56         return offsets(ImmutableList.copyOf(args));
57     }
58
59     static <T> Map<T, Integer> unorderedOffsets(final Collection<T> args) {
60         if (args instanceof SingletonSet) {
61             return offsets(args);
62         }
63
64         return offsets(ImmutableSet.copyOf(args));
65     }
66 }