X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=blobdiff_plain;f=common%2Futil%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fyangtools%2Futil%2FImmutableOffsetMap.java;h=7e5dd349ff0b268886c966792a3134e4446feef8;hb=24d06767f3a0ead8152a745fb05eda1d4a37ba77;hp=b9c374fbdf67592c7044e5a3a2cf621839c5c7eb;hpb=47be99e64e3f1b33834220289a6875935e12b5e6;p=yangtools.git diff --git a/common/util/src/main/java/org/opendaylight/yangtools/util/ImmutableOffsetMap.java b/common/util/src/main/java/org/opendaylight/yangtools/util/ImmutableOffsetMap.java index b9c374fbdf..7e5dd349ff 100644 --- a/common/util/src/main/java/org/opendaylight/yangtools/util/ImmutableOffsetMap.java +++ b/common/util/src/main/java/org/opendaylight/yangtools/util/ImmutableOffsetMap.java @@ -16,13 +16,14 @@ 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; @@ -31,19 +32,56 @@ import javax.annotation.Nonnull; * 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. - * * @param the type of keys maintained by this map * @param the type of mapped values */ @Beta -public class ImmutableOffsetMap extends AbstractLazyValueMap implements UnmodifiableMapPhase, Serializable { +public abstract class ImmutableOffsetMap implements UnmodifiableMapPhase, Serializable { + static final class Ordered extends ImmutableOffsetMap { + private static final long serialVersionUID = 1L; + + Ordered(final Map offsets, final V[] objects) { + super(offsets, objects); + } + + @Override + public MutableOffsetMap toModifiableMap() { + return MutableOffsetMap.orderedCopyOf(this); + } + + @Override + void setFields(final List keys, final V[] values) throws IOException { + setField(this, OFFSETS_FIELD, OffsetMapCache.orderedOffsets(keys)); + setField(this, ARRAY_FIELD, values); + } + } + + static final class Unordered extends ImmutableOffsetMap { + private static final long serialVersionUID = 1L; + + Unordered(final Map offsets, final V[] objects) { + super(offsets, objects); + } + + @Override + public MutableOffsetMap toModifiableMap() { + return MutableOffsetMap.unorderedCopyOf(this); + } + + @Override + void setFields(final List keys, final V[] values) throws IOException { + final Map offsets = OffsetMapCache.unorderedOffsets(keys); + + setField(this, OFFSETS_FIELD, offsets); + setField(this, ARRAY_FIELD, OffsetMapCache.adjustedArray(offsets, keys, values)); + } + } + private static final long serialVersionUID = 1L; - private final Map offsets; - private final Object[] objects; - private int hashCode; + private transient final Map offsets; + private transient final V[] objects; + private transient int hashCode; /** * Construct a new instance backed by specified key-to-offset map and array of objects. @@ -52,20 +90,32 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap 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 offsets, @Nonnull final Object[] objects) { + ImmutableOffsetMap(@Nonnull final Map offsets, @Nonnull final V[] objects) { this.offsets = Preconditions.checkNotNull(offsets); this.objects = Preconditions.checkNotNull(objects); Preconditions.checkArgument(offsets.size() == objects.length); } + @Override + public abstract MutableOffsetMap toModifiableMap(); + + abstract void setFields(List 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} 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 m Input map, may not be null. + * @return An isolated, immutable copy of the input map + * @deprecated Use {@link #orderedCopyOf(Map)} or {@link #unorderedCopyOf(Map)} instead. */ - protected ImmutableOffsetMap(@Nonnull final ImmutableOffsetMap m) { - this.offsets = m.offsets; - this.objects = m.objects; + @Deprecated + @Nonnull public static Map copyOf(@Nonnull final Map m) { + return orderedCopyOf(m); } /** @@ -79,34 +129,79 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme * @param m Input map, may not be null. * @return An isolated, immutable copy of the input map */ - @Nonnull public static Map copyOf(@Nonnull final Map m) { - // Prevent a copy - if (m instanceof ImmutableOffsetMap) { + @Nonnull public static Map orderedCopyOf(@Nonnull final Map m) { + // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead. + if (m instanceof ImmutableOffsetMap || m instanceof SharedSingletonMap) { return m; } - // Better-packed + // Familiar and efficient to copy + if (m instanceof MutableOffsetMap) { + return ((MutableOffsetMap) m).toUnmodifiableMap(); + } + final int size = m.size(); if (size == 0) { + // Shares a single object return ImmutableMap.of(); } if (size == 1) { - return ImmutableMap.copyOf(m); + // Efficient single-entry implementation + final Entry e = m.entrySet().iterator().next(); + return SharedSingletonMap.orderedOf(e.getKey(), e.getValue()); + } + + final Map offsets = OffsetMapCache.orderedOffsets(m.keySet()); + @SuppressWarnings("unchecked") + final V[] array = (V[]) new Object[offsets.size()]; + for (Entry e : m.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}. Iterator order is not + * guaranteed to be retained. + * + * @param m Input map, may not be null. + * @return An isolated, immutable copy of the input map + */ + @Nonnull public static Map unorderedCopyOf(@Nonnull final Map m) { + // Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead. + if (m instanceof ImmutableOffsetMap || m instanceof SharedSingletonMap) { + return m; } - // Familiar and efficient + // Familiar and efficient to copy if (m instanceof MutableOffsetMap) { return ((MutableOffsetMap) m).toUnmodifiableMap(); } - final Map offsets = OffsetMapCache.offsetsFor(m.keySet()); + final int size = m.size(); + if (size == 0) { + // Shares a single object + return ImmutableMap.of(); + } + if (size == 1) { + // Efficient single-entry implementation + final Entry e = m.entrySet().iterator().next(); + return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue()); + } + + final Map offsets = OffsetMapCache.unorderedOffsets(m.keySet()); @SuppressWarnings("unchecked") final V[] array = (V[]) new Object[offsets.size()]; for (Entry e : m.entrySet()) { array[offsets.get(e.getKey())] = e.getValue(); } - return new ImmutableOffsetMap<>(offsets, array); + return new Unordered<>(offsets, array); } @Override @@ -120,15 +215,14 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme } @Override - public int hashCode() { + public final int hashCode() { if (hashCode != 0) { return hashCode; } int result = 0; for (Entry e : offsets.entrySet()) { - final Object v = objects[e.getValue()]; - result += e.getKey().hashCode() ^ objectToValue(e.getKey(), v).hashCode(); + result += e.getKey().hashCode() ^ objects[e.getValue()].hashCode(); } hashCode = result; @@ -136,47 +230,46 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme } @Override - public boolean equals(final Object o) { + public final boolean equals(final Object o) { if (o == this) { return true; } - if (o == null) { + if (!(o instanceof Map)) { return false; } if (o instanceof ImmutableOffsetMap) { final ImmutableOffsetMap om = (ImmutableOffsetMap) o; - if (offsets.equals(om.offsets) && Arrays.deepEquals(objects, om.objects)) { - return true; + + // If the offset match, the arrays have to match, too + if (offsets.equals(om.offsets)) { + return Arrays.deepEquals(objects, om.objects); } } else if (o instanceof MutableOffsetMap) { // Let MutableOffsetMap do the actual work. return o.equals(this); - } else if (o instanceof Map) { - final Map om = (Map)o; + } - // Size and key sets have to match - if (size() != om.size() || !keySet().equals(om.keySet())) { - return false; - } + final Map other = (Map)o; + + // 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 e : offsets.entrySet()) { - final V v = objectToValue(e.getKey(), objects[e.getValue()]); - if (!v.equals(om.get(e.getKey()))) { - return false; - } + try { + // Ensure all objects are present + for (Entry e : offsets.entrySet()) { + if (!objects[e.getValue()].equals(other.get(e.getKey()))) { + return false; } - } catch (ClassCastException e) { - // Can be thrown by om.get() and indicate we have incompatible key types - return false; } - - return true; + } catch (ClassCastException e) { + // Can be thrown by other.get() indicating we have incompatible key types + return false; } - return false; + return true; } @Override @@ -186,25 +279,18 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap 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]); + return offset == null ? null : objects[offset]; } @Override @@ -212,6 +298,11 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme throw new UnsupportedOperationException(); } + @Override + public final V put(final K key, final V value) { + throw new UnsupportedOperationException(); + } + @Override public final void putAll(final Map m) { throw new UnsupportedOperationException(); @@ -227,21 +318,39 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme return offsets.keySet(); } + @Override + public final Collection values() { + return new ConstantArrayCollection<>(objects); + } + @Override public final Set> entrySet() { return new EntrySet(); } @Override - public MutableOffsetMap toModifiableMap() { - return new MutableOffsetMap<>(this); + public final String toString() { + final StringBuilder sb = new StringBuilder("{"); + final Iterator it = offsets.keySet().iterator(); + int i = 0; + while (it.hasNext()) { + sb.append(it.next()); + sb.append('='); + sb.append(objects[i++]); + + if (it.hasNext()) { + sb.append(", "); + } + } + + return sb.append('}').toString(); } - Map offsets() { + final Map offsets() { return offsets; } - Object[] objects() { + final V[] objects() { return objects; } @@ -259,7 +368,7 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme @Override public Entry next() { final Entry e = it.next(); - return new SimpleImmutableEntry<>(e.getKey(), objectToValue(e.getKey(), objects[e.getValue()])); + return new SimpleImmutableEntry<>(e.getKey(), objects[e.getValue()]); } }; } @@ -293,9 +402,9 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme return f; } - private void setField(final Field field, final Object value) throws IOException { + private static void setField(final ImmutableOffsetMap map, final 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); } @@ -313,7 +422,6 @@ public class ImmutableOffsetMap extends AbstractLazyValueMap impleme values[i] = (V)in.readObject(); } - setField(OFFSETS_FIELD, OffsetMapCache.offsetsFor(keys)); - setField(ARRAY_FIELD, values); + setFields(keys, values); } }