Skip to content

Add copyToArray and toArray to IArray #10743

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

Merged
merged 2 commits into from
Dec 11, 2020
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions library/src/scala/IArray.scala
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,18 @@ object opaques:
// but we can use `exists` instead, which is how `ArrayOps#contains` itself is implemented:
genericArrayOps(arr).exists(_ == elem)

/** Copy elements of this array to another array. */
extension [T, U >: T](arr: IArray[T]) def copyToArray(xs: Array[U]): Int =
genericArrayOps(arr).copyToArray(xs)

/** Copy elements of this array to another array. */
extension [T, U >: T](arr: IArray[T]) def copyToArray(xs: Array[U], start: Int): Int =
genericArrayOps(arr).copyToArray(xs, start)

/** Copy elements of this array to another array. */
extension [T, U >: T](arr: IArray[T]) def copyToArray(xs: Array[U], start: Int, len: Int): Int =
genericArrayOps(arr).copyToArray(xs, start, len)

/** Counts the number of elements in this array which satisfy a predicate */
extension [T](arr: IArray[T]) def count(p: T => Boolean): Int =
genericArrayOps(arr).count(p)
Expand Down Expand Up @@ -247,6 +259,10 @@ object opaques:
extension [T](arr: IArray[T]) def takeWhile(p: T => Boolean): IArray[T] =
genericArrayOps(arr).takeWhile(p)

/** Returns a mutable copy of this immutable array. */
extension [T](arr: IArray[T]) def toArray: Array[T] =
arr.clone.asInstanceOf[Array[T]]

/** Converts an array of pairs into an array of first elements and an array of second elements. */
extension [U: ClassTag, V: ClassTag](arr: IArray[(U, V)]) def unzip: (IArray[U], IArray[V]) =
genericArrayOps(arr).unzip
Expand Down
15 changes: 14 additions & 1 deletion tests/run/iarrays.scala
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,17 @@ object Test extends App {
val cs: Array[Double] = bs.asInstanceOf[Array[Double]]
cs(1) = 3.0
assert(bs(1) == 3.0)
}

// Check copyToArray
val ds: IArray[Int] = IArray(1, 2, 3)
val es: Array[Int] = new Array[Int](10)
ds.copyToArray(es, 5, 2)
assert(es.toList == List(0, 0, 0, 0, 0, 1, 2, 0, 0, 0))
val fs: Array[Any] = new Array[Any](10)
ds.copyToArray(fs, 5, 2)
assert(fs.toList == List(null, null, null, null, null, 1, 2, null, null, null))

// Check toArray
ds.toArray(0) = 0
assert(ds(0) == 1)
}