Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package smallui
- import scala.util.FromDigits
- import scala.util.FromDigits.*
- object UByte:
- opaque type UByte = Byte
- // Code to support custom number literals for UByte.
- // Unfortunately, custom number literals aren't working in Scala prior to 3.2.2 at the moment of writing
- given FromDigits[UByte] = literal =>
- if literal.isBlank || literal.length > 4
- then throw MalformedNumber()
- val firstChar = literal.charAt(0)
- val firstDigit = firstChar.isDigit
- if !(firstDigit || firstChar == '+') then throw MalformedNumber()
- else if firstChar == '-' then throw NumberTooSmall()
- var int = if firstDigit then firstChar.toInt else 0
- var i = 1
- while i < literal.length do
- val char = literal.charAt(i)
- if char.isDigit
- then int = int * 10 + char.toInt
- else throw MalformedNumber()
- i += 1
- end while
- if int > 255 then throw NumberTooLarge()
- (int - 128).toByte
- end given
- extension (self: UByte) {
- inline def -(other: UByte): UByte =
- (self - other).toByte
- inline def +(other: UByte): UByte =
- (self + other).toByte
- inline def /(other: UByte): UByte =
- (self / other).toByte
- inline def *(other: UByte): UByte =
- (self * other).toByte
- inline def toString: String =
- (self + 128).toString
- }
- extension (self: String)
- inline def toUByte: UByte = summon[FromDigits[UByte]].fromDigits(self)
- extension (self: Byte)
- inline def toUByte: UByte = self
- extension (self: Char)
- inline def toUByte: UByte = self.toByte
- extension (self: Short)
- inline def toUByte: UByte = (self - 128).toByte
- extension (self: Int)
- inline def toUByte: UByte = (self - 128).toByte
- extension (self: Long)
- inline def toUByte: UByte = (self - 128).toByte
- extension (self: Float)
- inline def toUByte: UByte = (self - 128).toByte
- extension (self: Double)
- inline def toUByte: UByte = (self - 128).toByte
- export UByte.UByte
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement