2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.util;
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;
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>>() {
25 public Map<Object, Integer> load(final Collection<?> key) {
26 final Builder<Object, Integer> b = ImmutableMap.builder();
29 for (Object arg : key) {
37 private OffsetMapCache() {
38 throw new UnsupportedOperationException();
41 @SuppressWarnings("unchecked")
42 private static <T> Map<T, Integer> offsets(final Collection<T> args) {
43 return (Map<T, Integer>) CACHE.getUnchecked(args);
47 static void invalidateCache() {
48 CACHE.invalidateAll();
51 static <T> Map<T, Integer> orderedOffsets(final Collection<T> args) {
52 if (args.size() == 1) {
53 return unorderedOffsets(args);
56 return offsets(ImmutableList.copyOf(args));
59 static <T> Map<T, Integer> unorderedOffsets(final Collection<T> args) {
60 if (args instanceof SingletonSet) {
64 return offsets(ImmutableSet.copyOf(args));