-
Notifications
You must be signed in to change notification settings - Fork 154
/
RefinedTypeOps.scala
54 lines (45 loc) · 1.37 KB
/
RefinedTypeOps.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package eu.timepit.refined.api
import eu.timepit.refined.macros.RefineMacro
/**
* Provides functions to create values of the refined type `FTP` from
* values of the base type `T`. It is intended to simplify the definition
* of a refined type's companion object.
*
* Example: {{{
* scala> import eu.timepit.refined.api.{ Refined, RefinedTypeOps }
* | import eu.timepit.refined.numeric.Positive
*
* scala> type PosInt = Int Refined Positive
*
* scala> object PosInt extends RefinedTypeOps[PosInt, Int]
*
* scala> PosInt(1)
* res0: PosInt = 1
*
* scala> PosInt.from(2)
* res1: Either[String, PosInt] = Right(2)
* }}}
*/
class RefinedTypeOps[FTP, T](implicit rt: RefinedType.AuxT[FTP, T]) extends Serializable {
def apply[F[_, _], P](t: T)(
implicit ev: F[T, P] =:= FTP,
rt: RefType[F],
v: Validate[T, P]
): FTP =
macro RefineMacro.implApplyRef[FTP, F, T, P]
def from(t: T): Either[String, FTP] =
rt.refine(t)
def unapply(t: T): Option[FTP] =
from(t).right.toOption
def unsafeFrom(t: T): FTP =
rt.unsafeRefine(t)
}
object RefinedTypeOps {
class Numeric[FTP: Min: Max, T](implicit rt: RefinedType.AuxT[FTP, T])
extends RefinedTypeOps[FTP, T] {
/** The smallest valid value of this type */
val MinValue: FTP = Min[FTP].min
/** The largest valid value of this type */
val MaxValue: FTP = Max[FTP].max
}
}