df6c35e3f649dd7baa5569c2ce2939fba1ea084c
[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.base.Verify;
12 import com.google.common.cache.Cache;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableMap.Builder;
19 import com.google.common.collect.ImmutableSet;
20 import java.lang.reflect.Array;
21 import java.util.Collection;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import javax.annotation.Nonnull;
27
28 final class OffsetMapCache {
29     /*
30      * Cache for offsets where order matters. The key is a List, which defines the iteration order. Since we want
31      * to retain this order, it is okay to use a simple LoadingCache.
32      */
33     private static final LoadingCache<List<?>, Map<?, Integer>> ORDERED_CACHE =
34             CacheBuilder.newBuilder().weakValues().build(new CacheLoader<List<?>, Map<?, Integer>>() {
35                 @Override
36                 public Map<?, Integer> load(@Nonnull final List<?> key) {
37                     return createMap(key);
38                 }
39             });
40     /*
41      * Cache for offsets where order does not mapper. The key is a Set of elements. We use manual two-stage loading
42      * because of the nature of the objects we store as values, which is ImmutableMaps. An ImmutableMap, when queried
43      * for keys (as is done in ImmutableOffsetMap.keySet()), will instantiate an ImmutableSet to hold these keys. It
44      * would be wasteful to use one Set for lookup only to have the map have an exact copy.
45      *
46      * We perform the first look up using a Set (which may come from the user, for example via
47      * ImmutableOffsetMap.unorderedCopyOf()), hence potentially saving a copy operation. If we fail to find an entry,
48      * we construct the map and put it conditionally with Map.keySet() as the key. This will detect concurrent loading
49      * and also lead to the cache and the map sharing the same Set.
50      */
51     private static final Cache<Set<?>, Map<?, Integer>> UNORDERED_CACHE =
52             CacheBuilder.newBuilder().weakValues().build();
53
54     private OffsetMapCache() {
55         throw new UnsupportedOperationException();
56     }
57
58     @VisibleForTesting
59     static void invalidateCache() {
60         ORDERED_CACHE.invalidateAll();
61         UNORDERED_CACHE.invalidateAll();
62     }
63
64     @SuppressWarnings("unchecked")
65     static <T> Map<T, Integer> orderedOffsets(final Collection<T> args) {
66         if (args.size() == 1) {
67             return unorderedOffsets(args);
68         }
69
70         return (Map<T, Integer>) ORDERED_CACHE.getUnchecked(ImmutableList.copyOf(args));
71     }
72
73     static <T> Map<T, Integer> unorderedOffsets(final Collection<T> args) {
74         return unorderedOffsets(args instanceof Set ? (Set<T>)args : ImmutableSet.copyOf(args));
75     }
76
77     @SuppressWarnings("unchecked")
78     private static <T> Map<T, Integer> unorderedOffsets(final Set<T> args) {
79         final Map<T, Integer> existing = (Map<T, Integer>) UNORDERED_CACHE.getIfPresent(args);
80         if (existing != null) {
81             return existing;
82         }
83
84         final Map<T, Integer> newMap = createMap(args);
85         final Map<?, Integer> raced = UNORDERED_CACHE.asMap().putIfAbsent(newMap.keySet(), newMap);
86         return raced == null ? newMap : (Map<T, Integer>)raced;
87     }
88
89     static <K, V> V[] adjustedArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
90         Verify.verify(offsets.size() == keys.size(), "Offsets %s do not match keys %s", offsets, keys);
91
92         // This relies on the fact that offsets has an ascending iterator
93         final Iterator<K> oi = offsets.keySet().iterator();
94         final Iterator<K> ki = keys.iterator();
95
96         while (oi.hasNext()) {
97             final K o = oi.next();
98             final K k = ki.next();
99             if (!k.equals(o)) {
100                 return adjustArray(offsets, keys, array);
101             }
102         }
103
104         return array;
105     }
106
107     private static <T> Map<T, Integer> createMap(final Collection<T> keys) {
108         final Builder<T, Integer> b = ImmutableMap.builder();
109         int counter = 0;
110
111         for (T arg : keys) {
112             b.put(arg, counter++);
113         }
114
115         return b.build();
116     }
117
118     private static <K, V> V[] adjustArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
119         @SuppressWarnings("unchecked")
120         final V[] ret = (V[]) Array.newInstance(array.getClass().getComponentType(), array.length);
121
122         int offset = 0;
123         for (final K k : keys) {
124             final Integer o = Verify.verifyNotNull(offsets.get(k), "Key %s not present in offsets %s", k, offsets);
125             ret[o] = array[offset++];
126         }
127
128         return ret;
129     }
130 }