Fix javadoc warnings in ImmutableOffsetMap
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / ImmutableOffsetMap.java
index 019722b509af3e0bbff16386effc121389de3287..66b20fbdf1ec9be8cdb47ef557bc897be1b08d38 100644 (file)
@@ -7,41 +7,89 @@
  */
 package org.opendaylight.yangtools.util;
 
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+
 import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.UnmodifiableIterator;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.lang.reflect.Field;
+import java.util.AbstractMap.SimpleImmutableEntry;
 import java.util.AbstractSet;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
 import java.util.Set;
-import javax.annotation.Nonnull;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 
 /**
  * Implementation of the {@link Map} interface which stores a set of immutable mappings using a key-to-offset map and
  * a backing array. This is useful for situations where the same key set is shared across a multitude of maps, as this
  * class uses a global cache to share the key-to-offset mapping.
  *
- * This map supports creation of value objects on the fly. To achieve that, subclasses should override {@link #valueToObject(Object)},
- * {@link #objectToValue(Object, Object)}, {@link #clone()} and {@link #toModifiableMap()} methods.
+ * <p>
+ * In case the set of keys is statically known, you can use {@link ImmutableOffsetMapTemplate} to efficiently create
+ * {@link ImmutableOffsetMap} instances.
  *
  * @param <K> the type of keys maintained by this map
  * @param <V> the type of mapped values
  */
 @Beta
-public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> implements Cloneable, UnmodifiableMapPhase<K, V>, Serializable {
+public abstract class ImmutableOffsetMap<K, V> implements UnmodifiableMapPhase<K, V>, Serializable {
+    static final class Ordered<K, V> extends ImmutableOffsetMap<K, V> {
+        private static final long serialVersionUID = 1L;
+
+        Ordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
+            super(offsets, objects);
+        }
+
+        @Override
+        public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
+            return MutableOffsetMap.orderedCopyOf(this);
+        }
+
+        @Override
+        void setFields(final List<K> keys, final V[] values) throws IOException {
+            setField(this, OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys));
+            setField(this, ARRAY_FIELD, values);
+        }
+    }
+
+    static final class Unordered<K, V> extends ImmutableOffsetMap<K, V> {
+        private static final long serialVersionUID = 1L;
+
+        Unordered(final ImmutableMap<K, Integer> offsets, final V[] objects) {
+            super(offsets, objects);
+        }
+
+        @Override
+        public @NonNull MutableOffsetMap<K, V> toModifiableMap() {
+            return MutableOffsetMap.unorderedCopyOf(this);
+        }
+
+        @Override
+        void setFields(final List<K> keys, final V[] values) throws IOException {
+            final Map<K, Integer> newOffsets = OffsetMapCache.unorderedOffsets(keys);
+
+            setField(this, OFFSETS_FIELD, newOffsets);
+            setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(newOffsets, keys, values));
+        }
+    }
+
     private static final long serialVersionUID = 1L;
 
-    private final Map<K, Integer> offsets;
-    private final Object[] objects;
+    private final transient @NonNull ImmutableMap<K, Integer> offsets;
+    private final transient @NonNull V[] objects;
+    private transient int hashCode;
 
     /**
      * Construct a new instance backed by specified key-to-offset map and array of objects.
@@ -50,61 +98,107 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
      * @param objects Array of value object, may not be null. The array is stored as is, the caller
      *              is responsible for ensuring its contents remain unmodified.
      */
-    ImmutableOffsetMap(@Nonnull final Map<K, Integer> offsets, @Nonnull final Object[] objects) {
-        this.offsets = Preconditions.checkNotNull(offsets);
-        this.objects = Preconditions.checkNotNull(objects);
-        Preconditions.checkArgument(offsets.size() == objects.length);
+    ImmutableOffsetMap(final ImmutableMap<K, Integer> offsets, final V[] objects) {
+        this.offsets = requireNonNull(offsets);
+        this.objects = requireNonNull(objects);
+        checkArgument(offsets.size() == objects.length);
     }
 
+    @Override
+    public abstract @NonNull MutableOffsetMap<K, V> toModifiableMap();
+
+    abstract void setFields(List<K> keys, V[] values) throws IOException;
+
     /**
-     * Construct a new instance based on some other instance.
+     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
+     * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
+     * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
+     * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
+     * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
+     * {@link ImmutableOffsetMap} with the same iteration order as input.
      *
-     * @param m Instance to share data with, may not be null.
+     * @param <K> the type of keys maintained by the map
+     * @param <V> the type of mapped values
+     * @param map Input map, may not be null.
+     * @return An isolated, immutable copy of the input map
+     * @throws NullPointerException if {@code map} or any of its elements is null.
      */
-    protected ImmutableOffsetMap(@Nonnull final ImmutableOffsetMap<K, V> m) {
-        this.offsets = m.offsets;
-        this.objects = m.objects;
+    public static <K, V> @NonNull Map<K, V> orderedCopyOf(final @NonNull Map<K, V> map) {
+        final Map<K, V> common = commonCopy(map);
+        if (common != null) {
+            return common;
+        }
+
+        final int size = map.size();
+        if (size == 1) {
+            // Efficient single-entry implementation
+            final Entry<K, V> e = map.entrySet().iterator().next();
+            return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
+        }
+
+        final ImmutableMap<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
+        @SuppressWarnings("unchecked")
+        final V[] array = (V[]) new Object[offsets.size()];
+        for (Entry<K, V> e : map.entrySet()) {
+            array[offsets.get(e.getKey())] = e.getValue();
+        }
+
+        return new Ordered<>(offsets, array);
     }
 
     /**
-     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true,
-     * as this method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient.
-     * This method also recognizes {@link ImmutableOffsetMap} on input, and returns it back without doing anything else.
-     * It also recognizes {@link MutableOffsetMap} (as returned by {@link #toModifiableMap()}) and makes an efficient
-     * copy of its contents. All other maps are converted to an {@link ImmutableOffsetMap} with the same iteration
-     * order as input.
+     * Create an {@link ImmutableOffsetMap} as a copy of an existing map. This is actually not completely true, as this
+     * method returns an {@link ImmutableMap} for empty and singleton inputs, as those are more memory-efficient. This
+     * method also recognizes {@link ImmutableOffsetMap} and {@link SharedSingletonMap} on input, and returns it back
+     * without doing anything else. It also recognizes {@link MutableOffsetMap} (as returned by
+     * {@link #toModifiableMap()}) and makes an efficient copy of its contents. All other maps are converted to an
+     * {@link ImmutableOffsetMap}. Iterator order is not guaranteed to be retained.
      *
-     * @param m Input map, may not be null.
+     * @param <K> the type of keys maintained by the map
+     * @param <V> the type of mapped values
+     * @param map Input map, may not be null.
      * @return An isolated, immutable copy of the input map
+     * @throws NullPointerException if {@code map} or any of its elements is null.
      */
-    @Nonnull public static <K, V> Map<K, V> copyOf(@Nonnull final Map<K, V> m) {
-        // Prevent a copy
-        if (m instanceof ImmutableOffsetMap) {
-            return m;
+    public static <K, V> @NonNull Map<K, V> unorderedCopyOf(final @NonNull Map<K, V> map) {
+        final Map<K, V> common = commonCopy(map);
+        if (common != null) {
+            return common;
         }
 
-        // Better-packed
-        final int size = m.size();
-        if (size == 0) {
-            return ImmutableMap.of();
-        }
-        if (size == 1) {
-            return ImmutableMap.copyOf(m);
+        if (map.size() == 1) {
+            // Efficient single-entry implementation
+            final Entry<K, V> e = map.entrySet().iterator().next();
+            return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
         }
 
-        // Familiar and efficient
-        if (m instanceof MutableOffsetMap) {
-            return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
-        }
-
-        final Map<K, Integer> offsets = OffsetMapCache.offsetsFor(m.keySet());
+        final ImmutableMap<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
         @SuppressWarnings("unchecked")
         final V[] array = (V[]) new Object[offsets.size()];
-        for (Entry<K, V> e : m.entrySet()) {
+        for (Entry<K, V> e : map.entrySet()) {
             array[offsets.get(e.getKey())] = e.getValue();
         }
 
-        return new ImmutableOffsetMap<>(offsets, array);
+        return new Unordered<>(offsets, array);
+    }
+
+    private static <K, V> @Nullable Map<K, V> commonCopy(final @NonNull Map<K, V> map) {
+        // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
+        if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
+            return map;
+        }
+
+        // Familiar and efficient to copy
+        if (map instanceof MutableOffsetMap) {
+            return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
+        }
+
+        if (map.isEmpty()) {
+            // Shares a single object
+            return ImmutableMap.of();
+        }
+
+        return null;
     }
 
     @Override
@@ -117,6 +211,64 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
         return offsets.isEmpty();
     }
 
+    @Override
+    public final int hashCode() {
+        if (hashCode != 0) {
+            return hashCode;
+        }
+
+        int result = 0;
+        for (Entry<K, Integer> e : offsets.entrySet()) {
+            result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode();
+        }
+
+        hashCode = result;
+        return result;
+    }
+
+    @Override
+    public final boolean equals(final Object obj) {
+        if (obj == this) {
+            return true;
+        }
+        if (!(obj instanceof Map)) {
+            return false;
+        }
+
+        if (obj instanceof ImmutableOffsetMap) {
+            final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
+
+            // If the offset match, the arrays have to match, too
+            if (offsets.equals(om.offsets)) {
+                return Arrays.deepEquals(objects, om.objects);
+            }
+        } else if (obj instanceof MutableOffsetMap) {
+            // Let MutableOffsetMap do the actual work.
+            return obj.equals(this);
+        }
+
+        final Map<?, ?> other = (Map<?, ?>)obj;
+
+        // Size and key sets have to match
+        if (size() != other.size() || !keySet().equals(other.keySet())) {
+            return false;
+        }
+
+        try {
+            // Ensure all objects are present
+            for (Entry<K, Integer> e : offsets.entrySet()) {
+                if (!objects[e.getValue()].equals(other.get(e.getKey()))) {
+                    return false;
+                }
+            }
+        } catch (ClassCastException e) {
+            // Can be thrown by other.get() indicating we have incompatible key types
+            return false;
+        }
+
+        return true;
+    }
+
     @Override
     public final boolean containsKey(final Object key) {
         return offsets.containsKey(key);
@@ -124,25 +276,18 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
 
     @Override
     public final boolean containsValue(final Object value) {
-        @SuppressWarnings("unchecked")
-        final Object obj = valueToObject((V)value);
         for (Object o : objects) {
-            if (Objects.equals(obj, o)) {
+            if (value.equals(o)) {
                 return true;
             }
         }
         return false;
     }
 
-    @SuppressWarnings("unchecked")
     @Override
     public final V get(final Object key) {
-        final Integer offset = offsets.get(key);
-        if (offset == null) {
-            return null;
-        }
-
-        return objectToValue((K) key, objects[offset]);
+        Integer offset;
+        return (offset = offsets.get(key)) == null ? null : objects[offset];
     }
 
     @Override
@@ -151,6 +296,12 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
     }
 
     @Override
+    public final V put(final K key, final V value) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    @SuppressWarnings("checkstyle:parameterName")
     public final void putAll(final Map<? extends K, ? extends V> m) {
         throw new UnsupportedOperationException();
     }
@@ -166,34 +317,44 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
     }
 
     @Override
-    public final Set<Entry<K, V>> entrySet() {
-        return new EntrySet();
+    public final @NonNull Collection<V> values() {
+        return new ConstantArrayCollection<>(objects);
     }
 
     @Override
-    public MutableOffsetMap<K, V> toModifiableMap() {
-        return new MutableOffsetMap<>(this);
+    public final @NonNull Set<Entry<K, V>> entrySet() {
+        return new EntrySet();
     }
 
     @Override
-    public ImmutableOffsetMap<K, V> clone() throws CloneNotSupportedException {
-        return new ImmutableOffsetMap<>(this);
+    public final String toString() {
+        final StringBuilder sb = new StringBuilder("{");
+        final Iterator<K> it = offsets.keySet().iterator();
+        int offset = 0;
+        while (it.hasNext()) {
+            sb.append(it.next()).append('=').append(objects[offset++]);
+
+            if (it.hasNext()) {
+                sb.append(", ");
+            }
+        }
+
+        return sb.append('}').toString();
     }
 
-    Map<K, Integer> offsets() {
+    final @NonNull ImmutableMap<K, Integer> offsets() {
         return offsets;
     }
 
-    Object[] objects() {
+    final @NonNull V[] objects() {
         return objects;
     }
 
     private final class EntrySet extends AbstractSet<Entry<K, V>> {
         @Override
-        public Iterator<Entry<K, V>> iterator() {
+        public @NonNull Iterator<Entry<K, V>> iterator() {
             final Iterator<Entry<K, Integer>> it = offsets.entrySet().iterator();
-
-            return new UnmodifiableIterator<Entry<K, V>>() {
+            return new UnmodifiableIterator<>() {
                 @Override
                 public boolean hasNext() {
                     return it.hasNext();
@@ -202,7 +363,7 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
                 @Override
                 public Entry<K, V> next() {
                     final Entry<K, Integer> e = it.next();
-                    return new SimpleEntry<>(e.getKey(), objectToValue(e.getKey(), objects[e.getValue()]));
+                    return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]);
                 }
             };
         }
@@ -224,7 +385,7 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
     private static final Field OFFSETS_FIELD = fieldFor("offsets");
     private static final Field ARRAY_FIELD = fieldFor("objects");
 
-    private static Field fieldFor(final String name) {
+    private static @NonNull Field fieldFor(final @NonNull String name) {
         final Field f;
         try {
             f = ImmutableOffsetMap.class.getDeclaredField(name);
@@ -236,16 +397,19 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
         return f;
     }
 
-    private void setField(final Field field, final Object value) throws IOException {
+    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
+            justification = "https://github.com/spotbugs/spotbugs/issues/811")
+    private static void setField(final @NonNull ImmutableOffsetMap<?, ?> map, final @NonNull Field field,
+            final Object value) throws IOException {
         try {
-            field.set(this, value);
+            field.set(map, value);
         } catch (IllegalArgumentException | IllegalAccessException e) {
             throw new IOException("Failed to set field " + field, e);
         }
     }
 
     @SuppressWarnings("unchecked")
-    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
+    private void readObject(final @NonNull ObjectInputStream in) throws IOException, ClassNotFoundException {
         final int s = in.readInt();
 
         final List<K> keys = new ArrayList<>(s);
@@ -256,7 +420,6 @@ public class ImmutableOffsetMap<K, V> extends AbstractLazyValueMap<K, V> impleme
             values[i] = (V)in.readObject();
         }
 
-        setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys));
-        setField(ARRAY_FIELD, values);
+        setFields(keys, values);
     }
 }