typelevel / typelevel/fs2

Audit class tag comparisons in Chunk and fix unnecessary copying

Open
#2,835 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Scala
Stars
2.5k
Forks
636
Avg merge
2d 4h
Merged PRs (30d)
7

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in core/shared/src/main/scala/fs2/Chunk.scala at the toArraySlice pattern-match guard around lines 299-300, then inspect the other class-tag comparisons in Chunk. Add a regression test for the Array[Byte] and Chunk.array example, audit the related comparisons, and run the relevant Chunk tests to confirm that unnecessary copying is avoided.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala
Domain
stream-processing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.