+ @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> 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 to copy
+ if (m instanceof MutableOffsetMap) {
+ return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
+ }
+
+ final int size = m.size();
+ if (size == 0) {
+ // Shares a single object
+ return ImmutableMap.of();
+ }
+ if (size == 1) {
+ // Efficient single-entry implementation
+ final Entry<K, V> e = m.entrySet().iterator().next();
+ return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
+ }
+
+ final Map<K, Integer> offsets = OffsetMapCache.orderedOffsets(m.keySet());
+ @SuppressWarnings("unchecked")
+ final V[] array = (V[]) new Object[offsets.size()];
+ for (Entry<K, V> 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 <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> m) {