Populate data/ hierarchy
[yangtools.git] / data / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / codec / LazyCodecCache.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 java.util.IdentityHashMap;
12 import java.util.Map;
13 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
14 import org.opendaylight.yangtools.yang.model.api.TypeAware;
15 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
16
17 /**
18  * Lazily-populated CodecCache. This is a non-thread-safe factory, which performs caching of codecs. It is most
19  * appropriate for one-off encodings of repetitive data.
20  *
21  * @author Robert Varga
22  */
23 @Beta
24 public final class LazyCodecCache<T> extends CodecCache<T> {
25     private final Map<SchemaNode, T> complexCodecs = new IdentityHashMap<>();
26     private final Map<TypeDefinition<?>, T> simpleCodecs = new IdentityHashMap<>();
27
28     @Override
29     <S extends SchemaNode & TypeAware> T getComplex(final S schema, final T codec) {
30         return complexCodecs.computeIfAbsent(schema, any -> codec);
31     }
32
33     @Override
34     <S extends SchemaNode & TypeAware> T lookupComplex(final S schema) {
35         return complexCodecs.get(schema);
36     }
37
38     @Override
39     T lookupSimple(final TypeDefinition<?> type) {
40         return simpleCodecs.get(type);
41     }
42
43     @Override
44     T getSimple(final TypeDefinition<?> type, final T codec) {
45         return simpleCodecs.computeIfAbsent(type, any -> codec);
46     }
47
48     public PrecomputedCodecCache<T> toPrecomputed() {
49         return new PrecomputedCodecCache<>(simpleCodecs, complexCodecs);
50     }
51 }