Advertisement
Cool_Dalek

Scala3 UByte

Jan 16th, 2023
1,763
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.00 KB | None | 0 0
  1. package smallui
  2.  
  3. import scala.util.FromDigits
  4. import scala.util.FromDigits.*
  5.  
  6. object UByte:
  7.   opaque type UByte = Byte
  8.  
  9.   // Code to support custom number literals for UByte.
  10.   // Unfortunately, custom number literals aren't working in Scala prior to 3.2.2 at the moment of writing
  11.   given FromDigits[UByte] = literal =>
  12.     if literal.isBlank || literal.length > 4
  13.     then throw MalformedNumber()
  14.  
  15.     val firstChar = literal.charAt(0)
  16.     val firstDigit = firstChar.isDigit
  17.  
  18.     if !(firstDigit || firstChar == '+') then throw MalformedNumber()
  19.     else if firstChar == '-' then throw NumberTooSmall()
  20.  
  21.     var int = if firstDigit then firstChar.toInt else 0
  22.     var i = 1
  23.     while i < literal.length do
  24.       val char = literal.charAt(i)
  25.       if char.isDigit
  26.       then int = int * 10 + char.toInt
  27.       else throw MalformedNumber()
  28.       i += 1
  29.     end while
  30.  
  31.     if int > 255 then throw NumberTooLarge()
  32.  
  33.     (int - 128).toByte
  34.   end given
  35.  
  36.   extension (self: UByte) {
  37.  
  38.     inline def -(other: UByte): UByte =
  39.       (self - other).toByte
  40.  
  41.     inline def +(other: UByte): UByte =
  42.       (self + other).toByte
  43.  
  44.     inline def /(other: UByte): UByte =
  45.       (self / other).toByte
  46.  
  47.     inline def *(other: UByte): UByte =
  48.       (self * other).toByte
  49.  
  50.     inline def toString: String =
  51.       (self + 128).toString
  52.  
  53.   }
  54.  
  55.   extension (self: String)
  56.     inline def toUByte: UByte = summon[FromDigits[UByte]].fromDigits(self)
  57.  
  58.   extension (self: Byte)
  59.     inline def toUByte: UByte = self
  60.  
  61.   extension (self: Char)
  62.     inline def toUByte: UByte = self.toByte
  63.  
  64.   extension (self: Short)
  65.     inline def toUByte: UByte = (self - 128).toByte
  66.  
  67.   extension (self: Int)
  68.     inline def toUByte: UByte = (self - 128).toByte
  69.  
  70.   extension (self: Long)
  71.     inline def toUByte: UByte = (self - 128).toByte
  72.  
  73.   extension (self: Float)
  74.     inline def toUByte: UByte = (self - 128).toByte
  75.  
  76.   extension (self: Double)
  77.     inline def toUByte: UByte = (self - 128).toByte
  78.  
  79. export UByte.UByte
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement