Skip to content

Commit ba8325f

Browse files
authored
Merge pull request #10743 from mpilquist/topic/copy-to-array
Add copyToArray and toArray to IArray
2 parents ea1f70c + 52236a4 commit ba8325f

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

library/src/scala/IArray.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,18 @@ object opaques:
5252
// but we can use `exists` instead, which is how `ArrayOps#contains` itself is implemented:
5353
genericArrayOps(arr).exists(_ == elem)
5454

55+
/** Copy elements of this array to another array. */
56+
extension [T, U >: T](arr: IArray[T]) def copyToArray(xs: Array[U]): Int =
57+
genericArrayOps(arr).copyToArray(xs)
58+
59+
/** Copy elements of this array to another array. */
60+
extension [T, U >: T](arr: IArray[T]) def copyToArray(xs: Array[U], start: Int): Int =
61+
genericArrayOps(arr).copyToArray(xs, start)
62+
63+
/** Copy elements of this array to another array. */
64+
extension [T, U >: T](arr: IArray[T]) def copyToArray(xs: Array[U], start: Int, len: Int): Int =
65+
genericArrayOps(arr).copyToArray(xs, start, len)
66+
5567
/** Counts the number of elements in this array which satisfy a predicate */
5668
extension [T](arr: IArray[T]) def count(p: T => Boolean): Int =
5769
genericArrayOps(arr).count(p)
@@ -247,6 +259,10 @@ object opaques:
247259
extension [T](arr: IArray[T]) def takeWhile(p: T => Boolean): IArray[T] =
248260
genericArrayOps(arr).takeWhile(p)
249261

262+
/** Returns a mutable copy of this immutable array. */
263+
extension [T](arr: IArray[T]) def toArray: Array[T] =
264+
arr.clone.asInstanceOf[Array[T]]
265+
250266
/** Converts an array of pairs into an array of first elements and an array of second elements. */
251267
extension [U: ClassTag, V: ClassTag](arr: IArray[(U, V)]) def unzip: (IArray[U], IArray[V]) =
252268
genericArrayOps(arr).unzip

tests/run/iarrays.scala

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,17 @@ object Test extends App {
7070
val cs: Array[Double] = bs.asInstanceOf[Array[Double]]
7171
cs(1) = 3.0
7272
assert(bs(1) == 3.0)
73-
}
73+
74+
// Check copyToArray
75+
val ds: IArray[Int] = IArray(1, 2, 3)
76+
val es: Array[Int] = new Array[Int](10)
77+
ds.copyToArray(es, 5, 2)
78+
assert(es.toList == List(0, 0, 0, 0, 0, 1, 2, 0, 0, 0))
79+
val fs: Array[Any] = new Array[Any](10)
80+
ds.copyToArray(fs, 5, 2)
81+
assert(fs.toList == List(null, null, null, null, null, 1, 2, null, null, null))
82+
83+
// Check toArray
84+
ds.toArray(0) = 0
85+
assert(ds(0) == 1)
86+
}

0 commit comments

Comments
 (0)