fs2 icon indicating copy to clipboard operation
fs2 copied to clipboard

Audit class tag comparisons in Chunk and fix unnecessary copying

Open mpilquist opened this issue 3 years ago • 1 comments

This should be true:

val arr = new Array[Byte](10)
arr eq Chunk.array(arr).toArraySlice.values

It's currently returning false because toArraySlice is incorrectly copying the underlying array. The issue is the guard on this pattern match: https://github.com/typelevel/fs2/blob/5ca9dbf460e0add23525f3e7e4ebd02a0fe1956a/core/shared/src/main/scala/fs2/Chunk.scala#L299-L300

The class tag comparison is wrong here. It should be comparing the class tag of the target type wrapped in to an array (ct.wrap.runtimeClass) with the type of the array used in the ArraySlice (as.values.getClass) but instead it is comparing to just as.getClass. Hence this check always fails and we always return a copy.

In the original failing example, O == O2 == Byte so ct.wrap.runtimeClass == classOf[Array[Byte]], as.getClass == classOf[ArraySlice[_]], as.value.getClass == classOf[Array[Byte]].

Let's add a test for this and then fix the class comparison.

There appear to be other nonsensical comparisons of class tags so let's audit all of these and ensure they are comparing the right things.

mpilquist avatar Mar 02 '22 23:03 mpilquist

This one is getting worked by a colleague of mine.

mpilquist avatar Mar 08 '22 02:03 mpilquist