Add RevisionUnion
[yangtools.git] / common / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / RUv1.java
1 /*
2  * Copyright (c) 2024 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 java.io.Externalizable;
11 import java.io.IOException;
12 import java.io.ObjectInput;
13 import java.io.ObjectOutput;
14 import java.nio.charset.StandardCharsets;
15
16 /**
17  * Serialization proxy for {@link RevisionUnion}.
18  */
19 final class RUv1 implements Externalizable {
20     @java.io.Serial
21     private static final long serialVersionUID = 1L;
22     private static final int LENGTH = Revision.MAX_VALUE.unionString().length();
23
24     private String dateString;
25
26     @SuppressWarnings("checkstyle:redundantModifier")
27     public RUv1() {
28         // For Externalizable
29     }
30
31     RUv1(final String dateString) {
32         final int length = dateString.length();
33         if (length != 0 && length != LENGTH) {
34             throw new IllegalArgumentException("Unexpected string length " + length);
35         }
36         this.dateString = dateString;
37     }
38
39     @Override
40     public void writeExternal(final ObjectOutput out) throws IOException {
41         final var length = dateString.length();
42         out.writeByte(length);
43         if (length != 0) {
44             out.write(dateString.getBytes(StandardCharsets.US_ASCII));
45         }
46     }
47
48     @Override
49     public void readExternal(final ObjectInput in) throws IOException {
50         final int length = in.readByte();
51         if (length == LENGTH) {
52             final var bytes = new byte[length];
53             in.readFully(bytes);
54             dateString = new String(bytes, StandardCharsets.US_ASCII);
55         } else if (length == 0) {
56             dateString = "";
57         } else {
58             throw new IOException("Unexpected byte length " + length);
59         }
60     }
61
62     @java.io.Serial
63     private Object readResolve() {
64         return RevisionUnion.of(dateString);
65     }
66 }