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