4bf16141d1534cff194107f443dcea0f09c9f5b7
[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  * <p>
22  * Instantiation needs to occur through {@link LazyCodecCache#toPrecomputed()} after the lazy cache has been fully
23  * populated.
24  *
25  * @author Robert Varga
26  */
27 @Beta
28 @ThreadSafe
29 public final class PrecomputedCodecCache<T> extends CodecCache<T> {
30     private final Map<TypeDefinition<?>, T> simpleCodecs;
31     private final Map<TypedSchemaNode, T> complexCodecs;
32
33     PrecomputedCodecCache(final Map<TypeDefinition<?>, T> simpleCodecs, final Map<TypedSchemaNode, T> complexCodecs) {
34         this.simpleCodecs = Preconditions.checkNotNull(simpleCodecs);
35         this.complexCodecs = Preconditions.checkNotNull(complexCodecs);
36     }
37
38     @Override
39     T lookupComplex(final TypedSchemaNode schema) {
40         final T ret = complexCodecs.get(schema);
41         Preconditions.checkArgument(ret != null, "No codec available for schema %s", schema);
42         return ret;
43     }
44
45     @Override
46     T lookupSimple(final TypeDefinition<?> type) {
47         return simpleCodecs.get(type);
48     }
49
50     @Override
51     T getComplex(final TypedSchemaNode schema, final T codec) {
52         throw new IllegalStateException("Uncached codec for " + schema);
53     }
54
55     @Override
56     T getSimple(final TypeDefinition<?> type, final T codec) {
57         throw new IllegalStateException("Uncached codec for " + type);
58     }
59
60     public int complexSize() {
61         return complexCodecs.size();
62     }
63
64     public int simpleSize() {
65         return simpleCodecs.size();
66     }
67 }