Fixup IOMv1
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / IOMv1.java
1 /*
2  * Copyright (c) 2022 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.util;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableList;
14 import java.io.Externalizable;
15 import java.io.IOException;
16 import java.io.ObjectInput;
17 import java.io.ObjectOutput;
18 import org.eclipse.jdt.annotation.NonNull;
19
20 /**
21  * Base class for {@link ImmutableOffsetMap} serialization proxies. Implements most of the serialization form at logic.
22  */
23 abstract class IOMv1<T extends ImmutableOffsetMap<?, ?>> implements Externalizable {
24     private static final long serialVersionUID = 1;
25
26     private ImmutableOffsetMap<?, ?> map;
27
28     IOMv1() {
29         // For Externalizable
30     }
31
32     IOMv1(final @NonNull T map) {
33         this.map = requireNonNull(map);
34     }
35
36     @Override
37     public final void writeExternal(final ObjectOutput out) throws IOException {
38         final var local = verifyNotNull(map);
39         out.writeInt(local.size());
40         for (var e : local.entrySet()) {
41             out.writeObject(e.getKey());
42             out.writeObject(e.getValue());
43         }
44     }
45
46     @Override
47     public final void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
48         // TODO: optimize for size == 1? what can we gain?
49         final int size = in.readInt();
50         final var keysBuilder = ImmutableList.builderWithExpectedSize(size);
51         final var values = new Object[size];
52         for (int i = 0; i < size; ++i) {
53             keysBuilder.add(in.readObject());
54             values[i] = in.readObject();
55         }
56
57         map = verifyNotNull(createInstance(keysBuilder.build(), values));
58     }
59
60     abstract @NonNull T createInstance(@NonNull ImmutableList<Object> keys, @NonNull Object[] values);
61
62     final Object readResolve() {
63         return verifyNotNull(map);
64     }
65 }