Skip to content

Commit abd9171

Browse files
committed
Added support for converting hex literals to ByteVector instances
1 parent 44ef04d commit abd9171

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed
-12 KB
Binary file not shown.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package scodec.bits
2+
3+
import scala.quoted._
4+
import scala.quoted.matching._
5+
import scala.util.FromDigits
6+
7+
trait ByteVectorPlatform {
8+
9+
class FromDigits extends FromDigits.WithRadix[ByteVector] {
10+
def fromDigits(digits: String, radix: Int): ByteVector =
11+
if (radix == 16) ByteVector.fromValidHex(digits.tail)
12+
else throw FromDigits.MalformedNumber("unsupported radix")
13+
}
14+
15+
given FromDigits {
16+
override inline def fromDigits(digits: String): ByteVector =
17+
${ByteVectorFromDigits('digits, Expr(10))}
18+
override inline def fromDigits(digits: String, radix: Int): ByteVector =
19+
${ByteVectorFromDigits('digits, 'radix)}
20+
}
21+
}
22+
23+
24+
object ByteVectorFromDigits {
25+
26+
def apply(digits: Expr[String], radix: Expr[Int])(given qctx: QuoteContext): Expr[ByteVector] =
27+
(digits, radix) match {
28+
case (Const(ds), Const(r)) =>
29+
if (r == 16) {
30+
'{ByteVector.fromValidHex($digits.tail)}
31+
} else {
32+
qctx.error(s"unsupported radix $r", radix)
33+
'{ByteVector.empty}
34+
}
35+
case other =>
36+
'{
37+
if ($radix == 16) ByteVector.fromValidHex($digits.tail)
38+
else throw FromDigits.MalformedNumber("unsupported radix")
39+
}
40+
}
41+
}

core/shared/src/main/scala/scodec/bits/ByteVector.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1323,7 +1323,7 @@ sealed abstract class ByteVector extends BitwiseOperations[ByteVector, Long] wit
13231323
* @groupname base Base Conversions
13241324
* @groupprio base 3
13251325
*/
1326-
object ByteVector {
1326+
object ByteVector extends ByteVectorPlatform {
13271327

13281328
// various specialized function types
13291329

0 commit comments

Comments
 (0)