-
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 4fdb89c
Showing
3 changed files
with
84 additions
and
8 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
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,38 @@ | ||
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 } | ||
|
||
/** Summon the AsArray instance for the given newtype N. */ | ||
def apply[N](implicit ev: AsArray[N]): Aux[N, ev.Repr] = ev | ||
|
||
/** Construct a new array of newtype N from varargs. */ | ||
def apply[N](xs: N*)(implicit ev: AsArray[N]): Array[N] = ev(xs: _*) | ||
|
||
/** Construct an empty array of newtype N. */ | ||
def empty[N](implicit ev: AsArray[N]): Array[N] = ev.empty | ||
|
||
def unsafeDerive[N, R](implicit ct: ClassTag[R]): Aux[N, R] = | ||
new AsArray[N] { | ||
type Repr = R | ||
override def clsTag: ClassTag[Repr] = ct | ||
} | ||
} | ||
|
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