@@ -14,6 +14,8 @@ package scala
14
14
package collection
15
15
package immutable
16
16
17
+ import java .io .IOException
18
+
17
19
import generic ._
18
20
import immutable .{RedBlackTree => RB }
19
21
import mutable .Builder
@@ -88,6 +90,41 @@ object TreeMap extends ImmutableSortedMapFactory[TreeMap] {
88
90
89
91
override def result (): TreeMap [A , B ] = new TreeMap (tree)(ordering)
90
92
}
93
+ private val legacySerialisation = System .getProperty(" scala.collection.immutable.TreeMap.newSerialisation" , " false" ) != " false"
94
+
95
+ private class TreeMapProxy [A , B ](
96
+ @ transient private [this ] var tree : RedBlackTree .Tree [A , B ],
97
+ @ transient private [this ] var ordering : Ordering [A ]) extends Serializable {
98
+
99
+ @ throws[IOException ]
100
+ private [this ] def writeObject (out : java.io.ObjectOutputStream ) = {
101
+ out.writeInt(RB .count(tree))
102
+ out.writeObject(ordering)
103
+ RB .foreachEntry(tree, {
104
+ (k : A , v : B ) =>
105
+ out.writeObject(k)
106
+ out.writeObject(v)
107
+ })
108
+ }
109
+ @ throws[IOException ]
110
+ private [this ] def readObject (in : java.io.ObjectInputStream ) = {
111
+ val size = in.readInt()
112
+ ordering = in.readObject().asInstanceOf [Ordering [A ]]
113
+ implicit val ord = ordering
114
+
115
+ val data = Array .newBuilder[(A , B )]
116
+ data.sizeHint(size)
117
+ for (i <- 0 until size) {
118
+ val key = in.readObject().asInstanceOf [A ]
119
+ val value = in.readObject().asInstanceOf [B ]
120
+ data += ((key, value))
121
+ }
122
+ tree = RB .fromOrderedEntries(data.result.iterator, size)
123
+ }
124
+ @ throws[IOException ]
125
+ private [this ] def readResolve (): AnyRef =
126
+ new TreeMap (tree)(ordering)
127
+ }
91
128
}
92
129
93
130
/** This class implements immutable maps using a tree.
@@ -346,4 +383,8 @@ final class TreeMap[A, +B] private (tree: RB.Tree[A, B])(implicit val ordering:
346
383
newMapOrSelf(RB .transform[A , B , W ](tree, f)).asInstanceOf [That ]
347
384
else super .transform(f)
348
385
}
386
+
387
+ @ throws[IOException ]
388
+ private [this ] def writeReplace (out : java.io.ObjectOutputStream ): AnyRef =
389
+ if (TreeMap .legacySerialisation) this else new TreeMap .TreeMapProxy (tree, ordering)
349
390
}
0 commit comments