BUG-7983: extract codec caching from JSONCodecFactory
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / codec / PrecomputedCodecCache.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.yang.data.util.codec;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import java.util.Map;
13 import javax.annotation.concurrent.ThreadSafe;
14 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
15 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
16
17 /**
18  * Pre-computed CodecCache. All possible codecs are created upfront at instantiation time, after which they are
19  * available for the cost of a constant lookup.
20  *
21  * Instantiation needs to occur through {@link LazyCodecCache#toPrecomputed()} after the lazy cache has been fully
22  * populated.
23  *
24  * @author Robert Varga
25  */
26 @Beta
27 @ThreadSafe
28 public final class PrecomputedCodecCache<T> extends CodecCache<T> {
29     private final Map<TypeDefinition<?>, T> simpleCodecs;
30     private final Map<TypedSchemaNode, T> complexCodecs;
31
32     PrecomputedCodecCache(final Map<TypeDefinition<?>, T> simpleCodecs, final Map<TypedSchemaNode, T> complexCodecs) {
33         this.simpleCodecs = Preconditions.checkNotNull(simpleCodecs);
34         this.complexCodecs = Preconditions.checkNotNull(complexCodecs);
35     }
36
37     @Override
38     public T lookupComplex(final TypedSchemaNode schema) {
39         final T ret = complexCodecs.get(schema);
40         Preconditions.checkArgument(ret != null, "No codec available for schema %s", schema);
41         return ret;
42     }
43
44     @Override
45     public T lookupSimple(final TypeDefinition<?> type) {
46         return simpleCodecs.get(type);
47     }
48
49     @Override
50     public T getComplex(final TypedSchemaNode schema, final T codec) {
51         throw new IllegalStateException("Uncached codec for " + schema);
52     }
53
54     @Override
55     public T getSimple(final TypeDefinition<?> type, final T codec) {
56         throw new IllegalStateException("Uncached codec for " + type);
57     }
58
59     public int complexSize() {
60         return complexCodecs.size();
61     }
62
63     public int simpleSize() {
64         return simpleCodecs.size();
65     }
66 }