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.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;
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>>() {
24 public Map<Object, Integer> load(final Collection<?> key) {
25 final Builder<Object, Integer> b = ImmutableMap.builder();
28 for (Object arg : key) {
36 private OffsetMapCache() {
37 throw new UnsupportedOperationException();
40 @SuppressWarnings("unchecked")
41 private static <T> Map<T, Integer> offsets(final Collection<T> args) {
42 return (Map<T, Integer>) CACHE.getUnchecked(args);
45 static <T> Map<T, Integer> orderedOffsets(final Collection<T> args) {
46 if (args.size() == 1) {
47 return unorderedOffsets(args);
50 return offsets(ImmutableList.copyOf(args));
53 static <T> Map<T, Integer> unorderedOffsets(final Collection<T> args) {
54 if (args instanceof SingletonSet) {
58 return offsets(ImmutableSet.copyOf(args));