Populate data/ hierarchy
[yangtools.git] / data / 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 org.opendaylight.yangtools.yang.model.api.SchemaNode;
16 import org.opendaylight.yangtools.yang.model.api.TypeAware;
17 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
18
19 /**
20  * Pre-computed thread-safe CodecCache. All possible codecs are created upfront at instantiation time, after which they
21  * are 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 public final class PrecomputedCodecCache<T> extends CodecCache<T> {
31     private final Map<TypeDefinition<?>, T> simpleCodecs;
32     private final Map<SchemaNode, T> complexCodecs;
33
34     PrecomputedCodecCache(final Map<TypeDefinition<?>, T> simpleCodecs, final Map<SchemaNode, T> complexCodecs) {
35         this.simpleCodecs = requireNonNull(simpleCodecs);
36         this.complexCodecs = requireNonNull(complexCodecs);
37     }
38
39     @Override
40     <S extends SchemaNode & TypeAware> T lookupComplex(final S schema) {
41         final T ret = complexCodecs.get(schema);
42         checkArgument(ret != null, "No codec available for schema %s", schema);
43         return ret;
44     }
45
46     @Override
47     T lookupSimple(final TypeDefinition<?> type) {
48         return simpleCodecs.get(type);
49     }
50
51     @Override
52     <S extends SchemaNode & TypeAware> T getComplex(final S schema, final T codec) {
53         throw new IllegalStateException("Uncached codec for " + schema);
54     }
55
56     @Override
57     T getSimple(final TypeDefinition<?> type, final T codec) {
58         throw new IllegalStateException("Uncached codec for " + type);
59     }
60
61     public int complexSize() {
62         return complexCodecs.size();
63     }
64
65     public int simpleSize() {
66         return simpleCodecs.size();
67     }
68 }