Skip to content

Commit

Permalink
dev: Add BigInt support
Browse files Browse the repository at this point in the history
  • Loading branch information
Iltotore committed Sep 11, 2024
1 parent 3ac1310 commit 081c5e0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 12 additions & 1 deletion main/src/io/github/iltotore/iron/constraint/numeric.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ package io.github.iltotore.iron.constraint
import io.github.iltotore.iron.constraint.any.*
import io.github.iltotore.iron.compileTime.*
import io.github.iltotore.iron.{==>, Constraint, Implication}
import io.github.iltotore.iron.macros.reflectUtil

import scala.compiletime.summonInline
import scala.quoted.*
import scala.util.NotGiven

/**
Expand Down Expand Up @@ -170,8 +173,16 @@ object numeric:
override inline def test(inline value: BigDecimal): Boolean = value > BigDecimal(longValue[V])

inline given [V <: Int | Long]: GreaterConstraint[BigInt, V] with
override inline def test(inline value: BigInt): Boolean = value > BigInt(longValue[V])
override inline def test(inline value: BigInt): Boolean = ${checkBigInt('value, '{longValue[V]})}

private def checkBigInt(expr: Expr[BigInt], thanExpr: Expr[Long])(using Quotes): Expr[Boolean] =
val rflUtil = reflectUtil
import rflUtil.*

(expr.decode, thanExpr.decode) match
case (Right(value), Right(than)) => Expr(value > BigInt(than))
case _ => '{$expr > BigInt($thanExpr)}

given [V1, V2](using V1 > V2 =:= true): (Greater[V1] ==> Greater[V2]) = Implication()

given [V1, V2](using V1 > V2 =:= true): (StrictEqual[V1] ==> Greater[V2]) = Implication()
Expand Down
11 changes: 10 additions & 1 deletion main/src/io/github/iltotore/iron/macros/ReflectUtil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ class ReflectUtil[Q <: Quotes & Singleton](using val _quotes: Q):

private val enhancedDecoders: Map[TypeRepr, (Term, Map[String, ?]) => Either[DecodingFailure, ?]] = Map(
TypeRepr.of[Boolean] -> decodeBoolean,
TypeRepr.of[String] -> decodeString
TypeRepr.of[BigInt] -> decodeBigInt,
TypeRepr.of[String] -> decodeString
)

/**
Expand Down Expand Up @@ -325,3 +326,11 @@ class ReflectUtil[Q <: Quotes & Singleton](using val _quotes: Q):
case (leftResult, rightResult) => Left(DecodingFailure.StringPartsNotInlined(List(leftResult, rightResult)))

case _ => Left(DecodingFailure.Unknown)

def decodeBigInt(term: Term, definitions: Map[String, ?]): Either[DecodingFailure, BigInt] =
term match
case Apply(Select(Ident("BigInt"), "apply"), List(value)) =>
if value.tpe <:< TypeRepr.of[Int] then decodeTerm[Int](value, definitions).map(BigInt.apply)
else if value.tpe <:< TypeRepr.of[Long] then decodeTerm[Long](value, definitions).map(BigInt.apply)
else Left(DecodingFailure.Unknown)
case _ => Left(DecodingFailure.Unknown)

0 comments on commit 081c5e0

Please sign in to comment.