@@ -22,6 +22,73 @@ import scala.collection.mutable.{Builder, ListBuffer}
22
22
import scala .util .Try
23
23
24
24
class LazyListTest {
25
+
26
+ @ Test
27
+ def serialization (): Unit = if (scala.util.Properties .releaseVersion.exists(_.startsWith(" 2.12" ))) {
28
+ import java .io ._
29
+
30
+ def serialize (obj : AnyRef ): Array [Byte ] = {
31
+ val buffer = new ByteArrayOutputStream
32
+ val out = new ObjectOutputStream (buffer)
33
+ out.writeObject(obj)
34
+ buffer.toByteArray
35
+ }
36
+
37
+ def deserialize (a : Array [Byte ]): AnyRef = {
38
+ val in = new ObjectInputStream (new ByteArrayInputStream (a))
39
+ in.readObject
40
+ }
41
+
42
+ def serializeDeserialize [T <: AnyRef ](obj : T ) = deserialize(serialize(obj)).asInstanceOf [T ]
43
+
44
+ val l = LazyList .from(10 )
45
+
46
+ val ld1 = serializeDeserialize(l)
47
+ assertEquals(l.take(10 ).toList, ld1.take(10 ).toList)
48
+
49
+ l.tail.head
50
+ val ld2 = serializeDeserialize(l)
51
+ assertEquals(l.take(10 ).toList, ld2.take(10 ).toList)
52
+
53
+ LazyListTest .serializationForceCount = 0
54
+ val u = LazyList .from(10 ).map(x => { LazyListTest .serializationForceCount += 1 ; x })
55
+
56
+ def printDiff (): Unit = {
57
+ val a = serialize(u)
58
+ classOf [LazyList [_]].getDeclaredField(" scala$collection$compat$immutable$LazyList$$stateEvaluated" ).setBoolean(u, true )
59
+ val b = serialize(u)
60
+ val i = a.zip(b).indexWhere(p => p._1 != p._2)
61
+ println(" difference: " )
62
+ println(s " val from = ${a.slice(i - 10 , i + 10 ).mkString(" List[Byte](" , " , " , " )" )}" )
63
+ println(s " val to = ${b.slice(i - 10 , i + 10 ).mkString(" List[Byte](" , " , " , " )" )}" )
64
+ }
65
+
66
+ // to update this test, comment-out `LazyList.writeReplace` and run `printDiff`
67
+ // printDiff()
68
+
69
+ val from = List [Byte ](83 , 116 , 97 , 116 , 101 , 59 , 120 , 112 , 0 , 0 , 0 , 115 , 114 , 0 , 33 , 106 , 97 , 118 , 97 , 46 )
70
+ val to = List [Byte ](83 , 116 , 97 , 116 , 101 , 59 , 120 , 112 , 0 , 0 , 1 , 115 , 114 , 0 , 33 , 106 , 97 , 118 , 97 , 46 )
71
+
72
+ assertEquals(LazyListTest .serializationForceCount, 0 )
73
+
74
+ u.head
75
+ assertEquals(LazyListTest .serializationForceCount, 1 )
76
+
77
+ val data = serialize(u)
78
+ var i = data.indexOfSlice(from)
79
+ to.foreach(x => {data(i) = x; i += 1 })
80
+
81
+ val ud1 = deserialize(data).asInstanceOf [LazyList [Int ]]
82
+
83
+ // this check failed before scala/scala#10118, deserialization triggered evaluation
84
+ assertEquals(LazyListTest .serializationForceCount, 1 )
85
+
86
+ ud1.tail.head
87
+ assertEquals(LazyListTest .serializationForceCount, 2 )
88
+
89
+ u.tail.head
90
+ assertEquals(LazyListTest .serializationForceCount, 3 )
91
+ }
25
92
26
93
@ Test
27
94
def t6727_and_t6440_and_8627 (): Unit = {
@@ -403,3 +470,7 @@ class LazyListTest {
403
470
assertEquals(1 , count)
404
471
}
405
472
}
473
+
474
+ object LazyListTest {
475
+ var serializationForceCount = 0
476
+ }
0 commit comments