Improve serialization defensiveness of Revision
[yangtools.git] / common / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / MountPointLabel.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech 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.common;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.Interner;
13 import com.google.common.collect.Interners;
14 import java.io.DataInput;
15 import java.io.DataOutput;
16 import java.io.IOException;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.opendaylight.yangtools.concepts.Identifier;
19 import org.opendaylight.yangtools.concepts.WritableObject;
20
21 /**
22  * The name (label) of a YANG schema mount instance, as defined in
23  * <a href="https://www.rfc-editor.org/rfc/rfc8528">RFC8528</a>.
24  */
25 @NonNullByDefault
26 public record MountPointLabel(QName qname) implements Identifier, WritableObject {
27     @java.io.Serial
28     private static final long serialVersionUID = 1L;
29     private static final Interner<MountPointLabel> INTERNER = Interners.newWeakInterner();
30
31     public MountPointLabel {
32         requireNonNull(qname);
33     }
34
35     public MountPointLabel intern() {
36         final var cacheQName = qname.intern();
37
38         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname'. It is
39         // important that it does not hold user-supplied reference (such a String instance from parsing of an XML
40         // document).
41         final var template = cacheQName == qname ? this : new MountPointLabel(cacheQName);
42
43         return INTERNER.intern(template);
44     }
45
46     public static MountPointLabel readFrom(final DataInput in) throws IOException {
47         return new MountPointLabel(QName.readFrom(in));
48     }
49
50     @Override
51     public void writeTo(final DataOutput out) throws IOException {
52         qname.writeTo(out);
53     }
54 }