-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6399e82
commit 437a241
Showing
3 changed files
with
93 additions
and
10 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
shared/src/main/scala/io/estatico/newtype/arrays/AsArray.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package io.estatico.newtype.arrays | ||
|
||
import scala.reflect.ClassTag | ||
|
||
trait AsArray[N] { | ||
type Repr | ||
def clsTag: ClassTag[Repr] | ||
|
||
final def empty: Array[N] = Array.empty(clsTag).asInstanceOf[Array[N]] | ||
|
||
final def apply(xs: N*): Array[N] = | ||
Array(xs.asInstanceOf[Seq[Repr]]: _*)(clsTag).asInstanceOf[Array[N]] | ||
|
||
final def upcast[R](array: Array[R]): Array[N] = array.asInstanceOf[Array[N]] | ||
|
||
final def downcast(array: Array[N]): Array[Repr] = array.asInstanceOf[Array[Repr]] | ||
} | ||
|
||
object AsArray { | ||
|
||
type Aux[N, R] = AsArray[N] { type Repr = R } | ||
|
||
def unsafeDerive[N, R](implicit ct: ClassTag[R]): Aux[N, R] = | ||
new AsArray[N] { | ||
type Repr = R | ||
override def clsTag: ClassTag[Repr] = ct | ||
} | ||
|
||
def empty[N](implicit ev: AsArray[N]): Array[N] = ev.empty | ||
|
||
def apply[N](xs: N*)(implicit ev: AsArray[N]): Array[N] = ev(xs: _*) | ||
|
||
def upcast[R, N](array: Array[R])(implicit ev: Aux[N, R]): Array[N] = ev.upcast(array) | ||
|
||
def upcast[N]: UpcastPartiallyApplied[N] = _upcast.asInstanceOf[UpcastPartiallyApplied[N]] | ||
|
||
def downcast[N](array: Array[N])(implicit ev: AsArray[N]): Array[ev.Repr] = ev.downcast(array) | ||
|
||
final class UpcastPartiallyApplied[N] private[AsArray] { | ||
def apply[R](array: Array[R])(implicit ev: Aux[N, R]): Array[N] = upcast[R, N](array) | ||
} | ||
|
||
private val _upcast = new UpcastPartiallyApplied[Nothing] | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters