Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ public Serializer createSerializer(TypeResolver typeResolver, Class<?> clz) {
return new ScalaXlangCollectionSerializer(typeResolver, clz);
}
}
Serializer specific = SpecificCollectionSerializers.createSerializer(typeResolver, clz);
if (specific != null) {
return specific;
}
// Many map/seq/set types doesn't extends DefaultSerializable.
if (scala.collection.SortedMap.class.isAssignableFrom(clz)) {
return new ScalaSortedMapSerializer(typeResolver, clz);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,23 @@ class ScalaSeqSerializer[A, T <: scala.collection.Seq[A]](
new ListAdapter[Any](value)
}
}

/**
* Serializer for Scala collection kinds whose generic `iterableFactory` or
* `sortedIterableFactory` builds a different class, such as `BitSet` or a primitive `ArraySeq`.
* `factory` is the kind's own factory, chosen once per class by [[SpecificCollectionSerializers]].
*/
class ScalaSpecificCollectionSerializer[A, T <: Iterable[A]](
typeResolver: TypeResolver,
cls: Class[T],
factory: Factory[A, T])
extends AbstractScalaCollectionSerializer[A, T](typeResolver, cls) {
override def onCollectionWrite(
writeContext: WriteContext,
value: T): util.Collection[_] = {
val buffer = writeContext.getBuffer
buffer.writeVarUInt32Small7(value.size)
writeContext.writeRef(factory)
new CollectionAdapter[A, T](value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,23 @@ class ScalaSortedMapSerializer[K, V, T <: scala.collection.SortedMap[K, V]](
new MapAdapter[K, V](value)
}
}

/**
* Serializer for Scala map kinds whose generic `mapFactory` builds a different class, such as
* `IntMap` or `LongMap`. `factory` is the kind's own factory, chosen once per class by
* [[SpecificCollectionSerializers]].
*/
class ScalaSpecificMapSerializer[K, V, T <: scala.collection.Map[K, V]](
typeResolver: TypeResolver,
cls: Class[T],
factory: Factory[(K, V), T])
extends AbstractScalaMapSerializer[K, V, T](typeResolver, cls) {
override def onMapWrite(
writeContext: WriteContext,
value: T): util.Map[_, _] = {
val buffer = writeContext.getBuffer
buffer.writeVarUInt32Small7(value.size)
writeContext.writeRef(factory)
new MapAdapter[K, V](value)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.fory.serializer.scala

import org.apache.fory.context.{CopyContext, ReadContext, WriteContext}
import org.apache.fory.resolver.TypeResolver
import org.apache.fory.serializer.Serializer
import org.apache.fory.serializer.Serializers.StringBuilderSerializer
import org.apache.fory.serializer.collection.CollectionLikeSerializer
import org.apache.fory.serializer.GraphMemoryEstimates

import java.util
import scala.collection.{Factory, immutable, mutable}
import scala.reflect.ClassTag

/**
* Native-mode serializers for Scala collection kinds that the generic collection and map
* serializers would rebuild as a different class. Those serializers write the value's generic
* factory (`iterableFactory`, `sortedIterableFactory` or `mapFactory`), which builds, for example,
* a `Map` from an `IntMap` or a `TreeSet` from a `BitSet`.
*/
object SpecificCollectionSerializers {
private val immutableArraySeqTags: Map[Class[_], ClassTag[_]] = Map(
classOf[immutable.ArraySeq.ofByte] -> ClassTag.Byte,
classOf[immutable.ArraySeq.ofShort] -> ClassTag.Short,
classOf[immutable.ArraySeq.ofChar] -> ClassTag.Char,
classOf[immutable.ArraySeq.ofInt] -> ClassTag.Int,
classOf[immutable.ArraySeq.ofLong] -> ClassTag.Long,
classOf[immutable.ArraySeq.ofFloat] -> ClassTag.Float,
classOf[immutable.ArraySeq.ofDouble] -> ClassTag.Double,
classOf[immutable.ArraySeq.ofBoolean] -> ClassTag.Boolean)

private val mutableArraySeqTags: Map[Class[_], ClassTag[_]] = Map(
classOf[mutable.ArraySeq.ofByte] -> ClassTag.Byte,
classOf[mutable.ArraySeq.ofShort] -> ClassTag.Short,
classOf[mutable.ArraySeq.ofChar] -> ClassTag.Char,
classOf[mutable.ArraySeq.ofInt] -> ClassTag.Int,
classOf[mutable.ArraySeq.ofLong] -> ClassTag.Long,
classOf[mutable.ArraySeq.ofFloat] -> ClassTag.Float,
classOf[mutable.ArraySeq.ofDouble] -> ClassTag.Double,
classOf[mutable.ArraySeq.ofBoolean] -> ClassTag.Boolean)

/** Returns the serializer for `cls`, or null when the generic serializers handle it. */
def createSerializer(typeResolver: TypeResolver, cls: Class[_]): Serializer[_] = {
if (cls == classOf[mutable.StringBuilder]) {
new ScalaStringBuilderSerializer(typeResolver)
} else if (classOf[immutable.IntMap[_]].isAssignableFrom(cls)) {
mapSerializer(typeResolver, cls, immutable.IntMap.toFactory[Any](immutable.IntMap))
} else if (classOf[immutable.LongMap[_]].isAssignableFrom(cls)) {
mapSerializer(typeResolver, cls, immutable.LongMap.toFactory[Any](immutable.LongMap))
} else if (classOf[mutable.LongMap[_]].isAssignableFrom(cls)) {
mapSerializer(typeResolver, cls, mutable.LongMap.toFactory[Any](mutable.LongMap))
} else if (classOf[immutable.BitSet].isAssignableFrom(cls)) {
collectionSerializer(typeResolver, cls, immutable.BitSet)
} else if (classOf[mutable.BitSet].isAssignableFrom(cls)) {
collectionSerializer(typeResolver, cls, mutable.BitSet)
} else {
val immutableTag = immutableArraySeqTags.getOrElse(cls, null)
if (immutableTag != null) {
collectionSerializer(
typeResolver,
cls,
immutable.ArraySeq.evidenceIterableFactory(immutableTag.asInstanceOf[ClassTag[Any]]))
} else {
val mutableTag = mutableArraySeqTags.getOrElse(cls, null)
if (mutableTag != null) {
collectionSerializer(
typeResolver,
cls,
mutable.ArraySeq.evidenceIterableFactory(mutableTag.asInstanceOf[ClassTag[Any]]))
} else {
null
}
}
}
}

private def collectionSerializer(
typeResolver: TypeResolver,
cls: Class[_],
factory: Factory[_, _]): Serializer[_] = {
new ScalaSpecificCollectionSerializer[Any, Iterable[Any]](
typeResolver,
cls.asInstanceOf[Class[Iterable[Any]]],
factory.asInstanceOf[Factory[Any, Iterable[Any]]])
}

private def mapSerializer(
typeResolver: TypeResolver,
cls: Class[_],
factory: Factory[_, _]): Serializer[_] = {
new ScalaSpecificMapSerializer[Any, Any, scala.collection.Map[Any, Any]](
typeResolver,
cls.asInstanceOf[Class[scala.collection.Map[Any, Any]]],
factory.asInstanceOf[Factory[(Any, Any), scala.collection.Map[Any, Any]]])
}
}

/**
* Serializer for [[scala.collection.mutable.StringBuilder]]. It writes the wrapped
* `java.lang.StringBuilder` as a string, using the Java `StringBuilder` encoding, instead of
* writing the characters as a `Seq[Char]`. It extends [[CollectionLikeSerializer]] with the
* codegen hook disabled because struct fields route every Scala `Iterable` through the collection
* serializer path.
*/
class ScalaStringBuilderSerializer(typeResolver: TypeResolver)
extends CollectionLikeSerializer[mutable.StringBuilder](
typeResolver,
classOf[mutable.StringBuilder],
false) {
private val underlyingSerializer = new StringBuilderSerializer(typeResolver.getConfig)
private val graphMemoryBytes =
GraphMemoryEstimates.shallowObjectBytes(classOf[mutable.StringBuilder])

override def write(writeContext: WriteContext, value: mutable.StringBuilder): Unit =
underlyingSerializer.write(writeContext, value.underlying)

override def read(readContext: ReadContext): mutable.StringBuilder = {
readContext.reserveGraphMemory(graphMemoryBytes)
new mutable.StringBuilder(underlyingSerializer.read(readContext))
}

override def copy(
copyContext: CopyContext,
value: mutable.StringBuilder): mutable.StringBuilder =
new mutable.StringBuilder(new java.lang.StringBuilder(value.underlying))

override def onCollectionWrite(
writeContext: WriteContext,
value: mutable.StringBuilder): util.Collection[_] =
throw new IllegalStateException(s"supportCodegenHook is disabled for ${getType.getName}")

override def onCollectionRead(collection: util.Collection[_]): mutable.StringBuilder =
throw new IllegalStateException(s"supportCodegenHook is disabled for ${getType.getName}")
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ case class CollectionKindsHolder(
linkedHashSet: mutable.LinkedHashSet[String],
linkedHashMap: mutable.LinkedHashMap[String, Int])

case class SpecificKindsHolder(
intMap: immutable.IntMap[String],
longMap: immutable.LongMap[String],
bitSet: immutable.BitSet,
mutableBitSet: mutable.BitSet,
mutableLongMap: mutable.LongMap[String],
stringBuilder: mutable.StringBuilder,
intArraySeq: immutable.ArraySeq[Int],
doubleArraySeq: mutable.ArraySeq[Double])

class CollectionKindsTest extends AnyWordSpec with Matchers {
private def newFory(compatible: Boolean, requireClassRegistration: Boolean): Fory =
ForyScala.builder()
Expand Down Expand Up @@ -145,6 +155,55 @@ class CollectionKindsTest extends AnyWordSpec with Matchers {
(decoded + 4).toList shouldEqual List(4, 3, 2, 1)
}

"round trip kinds with a specific factory" in {
assertSameKind(fory, immutable.IntMap(3 -> "c", 1 -> "a"))
assertSameKind(fory, immutable.IntMap.empty[String])
assertSameKind(fory, immutable.LongMap(3L -> "c", 1L -> "a"))
assertSameKind(fory, mutable.LongMap(3L -> "c", 1L -> "a"))
assertSameKind(fory, immutable.BitSet(1, 70, 200))
assertSameKind(fory, immutable.BitSet(3))
assertSameKind(fory, mutable.BitSet(1, 70, 200))
assertOrdered(fory, immutable.ArraySeq(3, 1, 2))
assertOrdered(fory, immutable.ArraySeq(3L, 1L))
assertOrdered(fory, immutable.ArraySeq('b', 'a'))
assertOrdered(fory, mutable.ArraySeq(2.5, 1.5))
assertOrdered(fory, mutable.ArraySeq(true, false))
}

"round trip StringBuilder" in {
val decoded = roundTrip(fory, new mutable.StringBuilder("abc\u00e9\u4e2d"))
decoded.getClass shouldBe classOf[mutable.StringBuilder]
decoded.toString shouldEqual "abc\u00e9\u4e2d"
decoded.append('!').toString shouldEqual "abc\u00e9\u4e2d!"
val copied = fory.copy(new mutable.StringBuilder("xyz"))
copied.toString shouldEqual "xyz"
}

"round trip kinds with a specific factory as case class fields" in {
val fory = newFory(compatible, requireClassRegistration = false)
fory.register(classOf[SpecificKindsHolder])
val holder = SpecificKindsHolder(
immutable.IntMap(1 -> "a"),
immutable.LongMap(2L -> "b"),
immutable.BitSet(1, 2),
mutable.BitSet(3, 4),
mutable.LongMap(5L -> "e"),
new mutable.StringBuilder("sb"),
immutable.ArraySeq(1, 2),
mutable.ArraySeq(1.5, 2.5))
val decoded = roundTrip(fory, holder)
decoded.intMap shouldEqual holder.intMap
decoded.longMap shouldEqual holder.longMap
decoded.bitSet shouldEqual holder.bitSet
decoded.mutableBitSet shouldEqual holder.mutableBitSet
decoded.mutableLongMap shouldEqual holder.mutableLongMap
decoded.stringBuilder.toString shouldEqual "sb"
decoded.intArraySeq shouldEqual holder.intArraySeq
decoded.intArraySeq.getClass shouldBe holder.intArraySeq.getClass
decoded.doubleArraySeq shouldEqual holder.doubleArraySeq
decoded.doubleArraySeq.getClass shouldBe holder.doubleArraySeq.getClass
}

"round trip every declared kind as case class fields" in {
val fory = newFory(compatible, requireClassRegistration = false)
fory.register(classOf[CollectionKindsHolder])
Expand Down
Loading