Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chunk - Introduce a Constant Chunk subclass. #2995

Merged
merged 1 commit into from Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 25 additions & 0 deletions core/shared/src/main/scala/fs2/Chunk.scala
Expand Up @@ -550,6 +550,31 @@ object Chunk
override def map[O2](f: O => O2): Chunk[O2] = singleton(f(value))
}

def constant[A](value: A, size: Int): Chunk[A] =
if (size <= 0) empty
else if (size == 1) singleton(value)
else new Constant(value, size)

final class Constant[A](value: A, override val size: Int) extends Chunk[A] {

def apply(i: Int): A =
if (0 <= i && i < size) value else throw new IndexOutOfBoundsException()

def copyToArray[O2 >: A](xs: Array[O2], start: Int): Unit = {

@tailrec
def go(ix: Int): Unit =
if (ix < size) {
xs(start + ix) = value
go(ix + 1)
}
go(0)
}

protected def splitAtChunk_(n: Int): (Chunk[A], Chunk[A]) =
constant(value, n) -> constant(value, size - n)
}

/** Creates a chunk backed by a vector. */
def vector[O](v: Vector[O]): Chunk[O] = indexedSeq(v)

Expand Down
2 changes: 1 addition & 1 deletion core/shared/src/main/scala/fs2/Stream.scala
Expand Up @@ -3104,7 +3104,7 @@ object Stream extends StreamLowPriority {
* }}}
*/
def constant[F[x] >: Pure[x], O](o: O, chunkSize: Int = 256): Stream[F, O] =
chunk(Chunk.seq(List.fill(chunkSize)(o))).repeat
chunk(Chunk.constant(o, chunkSize)).repeat

/** A continuous stream of the elapsed time, computed using `System.nanoTime`.
* Note that the actual granularity of these elapsed times depends on the OS, for instance
Expand Down