Add IOMv1 proxy
[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 ImmutableOffsetMap<?, ?> map;
25
26     IOMv1() {
27         // For Externalizable
28     }
29
30     IOMv1(final @NonNull T map) {
31         this.map = requireNonNull(map);
32     }
33
34     @Override
35     public final void writeExternal(final ObjectOutput out) throws IOException {
36         final var local = verifyNotNull(map);
37         out.writeInt(local.size());
38         for (var e : local.entrySet()) {
39             out.writeObject(e.getKey());
40             out.writeObject(e.getValue());
41         }
42     }
43
44     @Override
45     public final void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
46         // TODO: optimize for size == 1? what can we gain?
47         final int size = in.readInt();
48         final var keysBuilder = ImmutableList.builderWithExpectedSize(size);
49         final var values = new Object[size];
50         for (int i = 0; i < size; ++i) {
51             keysBuilder.add(in.readObject());
52             values[i] = in.readObject();
53         }
54
55         map = verifyNotNull(readReplace(keysBuilder.build(), values));
56     }
57
58     final Object readReplace() {
59         return verifyNotNull(map);
60     }
61
62     abstract @NonNull T readReplace(@NonNull ImmutableList<Object> keys, @NonNull Object[] values);
63 }