Refactor TypedSchemaNode
[yangtools.git] / yang / 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 javax.annotation.concurrent.NotThreadSafe;
14 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
15 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
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 @NotThreadSafe
25 public final class LazyCodecCache<T> extends CodecCache<T> {
26     private final Map<TypedDataSchemaNode, T> complexCodecs = new IdentityHashMap<>();
27     private final Map<TypeDefinition<?>, T> simpleCodecs = new IdentityHashMap<>();
28
29     @Override
30     T getComplex(final TypedDataSchemaNode schema, final T codec) {
31         return complexCodecs.computeIfAbsent(schema, any -> codec);
32     }
33
34     @Override
35     T lookupComplex(final TypedDataSchemaNode schema) {
36         return complexCodecs.get(schema);
37     }
38
39     @Override
40     T lookupSimple(final TypeDefinition<?> type) {
41         return simpleCodecs.get(type);
42     }
43
44     @Override
45     T getSimple(final TypeDefinition<?> type, final T codec) {
46         return simpleCodecs.computeIfAbsent(type, any -> codec);
47     }
48
49     public PrecomputedCodecCache<T> toPrecomputed() {
50         return new PrecomputedCodecCache<>(simpleCodecs, complexCodecs);
51     }
52 }