From 81bc4c2407b7485677f35caab530a932894c4b7e Mon Sep 17 00:00:00 2001 From: PJ Fanning Date: Tue, 10 Nov 2026 12:49:30 +0100 Subject: [PATCH] fix(scala): rebuild specialized Scala collections as their own class The native Scala collection and map serializers write the value's generic factory (iterableFactory, sortedIterableFactory or mapFactory). For some kinds that factory builds a different class, so IntMap and LongMap came back as Map, BitSet as TreeSet, mutable.LongMap as HashMap, StringBuilder as ArrayBuffer[Char], and primitive ArraySeq as a boxed ArraySeq.ofRef. Declared case class fields of these types failed with ClassCastException. ScalaSerializerFactory now picks, once per class, a serializer that writes the kind's own stdlib factory: the IntMap/LongMap ToFactory objects, the BitSet companions, and a ClassTag factory for primitive ArraySeq variants. Scala StringBuilder gets a dedicated serializer that reuses the java.lang.StringBuilder string encoding. Closes #4102 Co-Authored-By: Claude Opus 5.5 --- .../scala/ScalaSerializerFactory.java | 4 + .../scala/CollectionSerializer.scala | 20 +++ .../fory/serializer/scala/MapSerializer.scala | 20 +++ .../scala/SpecificCollectionSerializers.scala | 152 ++++++++++++++++++ .../scala/CollectionKindsTest.scala | 59 +++++++ 5 files changed, 255 insertions(+) create mode 100644 scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/SpecificCollectionSerializers.scala diff --git a/scala/fory-scala/src/main/java/org/apache/fory/serializer/scala/ScalaSerializerFactory.java b/scala/fory-scala/src/main/java/org/apache/fory/serializer/scala/ScalaSerializerFactory.java index db8f3fe689..5053ae288d 100644 --- a/scala/fory-scala/src/main/java/org/apache/fory/serializer/scala/ScalaSerializerFactory.java +++ b/scala/fory-scala/src/main/java/org/apache/fory/serializer/scala/ScalaSerializerFactory.java @@ -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); diff --git a/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/CollectionSerializer.scala b/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/CollectionSerializer.scala index 3b18d757ca..f1420a5a85 100644 --- a/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/CollectionSerializer.scala +++ b/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/CollectionSerializer.scala @@ -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) + } +} diff --git a/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/MapSerializer.scala b/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/MapSerializer.scala index 7b95bde2e5..814f8a2234 100644 --- a/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/MapSerializer.scala +++ b/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/MapSerializer.scala @@ -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) + } +} diff --git a/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/SpecificCollectionSerializers.scala b/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/SpecificCollectionSerializers.scala new file mode 100644 index 0000000000..fc56acab23 --- /dev/null +++ b/scala/fory-scala/src/main/scala/org/apache/fory/serializer/scala/SpecificCollectionSerializers.scala @@ -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}") +} diff --git a/scala/fory-scala/src/test/scala/org/apache/fory/serializer/scala/CollectionKindsTest.scala b/scala/fory-scala/src/test/scala/org/apache/fory/serializer/scala/CollectionKindsTest.scala index 8157919f12..66aa2e138d 100644 --- a/scala/fory-scala/src/test/scala/org/apache/fory/serializer/scala/CollectionKindsTest.scala +++ b/scala/fory-scala/src/test/scala/org/apache/fory/serializer/scala/CollectionKindsTest.scala @@ -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() @@ -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])