Cleanup MutableOffsetMap a bit
[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 java.io.Serial;
19 import org.eclipse.jdt.annotation.NonNull;
20
21 /**
22  * Base class for {@link ImmutableOffsetMap} serialization proxies. Implements most of the serialization form at logic.
23  */
24 abstract sealed class IOMv1<T extends ImmutableOffsetMap<?, ?>> implements Externalizable permits OIOMv1, UIOMv1 {
25     @Serial
26     private static final long serialVersionUID = 1;
27
28     private ImmutableOffsetMap<?, ?> map;
29
30     IOMv1() {
31         // For Externalizable
32     }
33
34     IOMv1(final @NonNull T map) {
35         this.map = requireNonNull(map);
36     }
37
38     @Override
39     public final void writeExternal(final ObjectOutput out) throws IOException {
40         final var local = verifyNotNull(map);
41         out.writeInt(local.size());
42         for (var e : local.entrySet()) {
43             out.writeObject(e.getKey());
44             out.writeObject(e.getValue());
45         }
46     }
47
48     @Override
49     public final void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
50         // TODO: optimize for size == 1? what can we gain?
51         final int size = in.readInt();
52         final var keysBuilder = ImmutableList.builderWithExpectedSize(size);
53         final var values = new Object[size];
54         for (int i = 0; i < size; ++i) {
55             keysBuilder.add(in.readObject());
56             values[i] = in.readObject();
57         }
58
59         map = verifyNotNull(createInstance(keysBuilder.build(), values));
60     }
61
62     abstract @NonNull T createInstance(@NonNull ImmutableList<Object> keys, @NonNull Object[] values);
63
64     @Serial
65     final Object readResolve() {
66         return verifyNotNull(map);
67     }
68 }