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.base.Verify;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableMap.Builder;
18 import com.google.common.collect.ImmutableSet;
19 import java.lang.reflect.Array;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
25 final class OffsetMapCache {
26 private static final LoadingCache<Collection<?>, Map<Object, Integer>> CACHE =
27 CacheBuilder.newBuilder().weakValues().build(new CacheLoader<Collection<?>, Map<Object, Integer>>() {
29 public Map<Object, Integer> load(final Collection<?> key) {
30 final Builder<Object, Integer> b = ImmutableMap.builder();
33 for (Object arg : key) {
41 private OffsetMapCache() {
42 throw new UnsupportedOperationException();
45 @SuppressWarnings("unchecked")
46 private static <T> Map<T, Integer> offsets(final Collection<T> args) {
47 return (Map<T, Integer>) CACHE.getUnchecked(args);
51 static void invalidateCache() {
52 CACHE.invalidateAll();
55 static <T> Map<T, Integer> orderedOffsets(final Collection<T> args) {
56 if (args.size() == 1) {
57 return unorderedOffsets(args);
60 return offsets(ImmutableList.copyOf(args));
63 static <T> Map<T, Integer> unorderedOffsets(final Collection<T> args) {
64 if (args instanceof SingletonSet) {
68 return offsets(ImmutableSet.copyOf(args));
71 private static <K, V> V[] adjustArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
72 @SuppressWarnings("unchecked")
73 final V[] ret = (V[]) Array.newInstance(array.getClass().getComponentType(), array.length);
76 for (final K k : keys) {
77 final Integer o = Verify.verifyNotNull(offsets.get(k), "Key %s not present in offsets %s", k, offsets);
84 static <K, V> V[] adjustedArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
85 Verify.verify(offsets.size() == keys.size(), "Offsets %s do not match keys %s", offsets, keys);
87 // This relies on the fact that offsets has an ascending iterator
88 final Iterator<K> oi = offsets.keySet().iterator();
89 final Iterator<K> ki = keys.iterator();
91 while (oi.hasNext()) {
92 final K o = oi.next();
93 final K k = ki.next();
95 return adjustArray(offsets, keys, array);