Generate toString implementation for unsigned types

This commit is contained in:
Ilya Gorbunov
2018-05-08 17:50:41 +03:00
parent e988ea5a1c
commit 0eee258fce
6 changed files with 42 additions and 1 deletions
@@ -123,6 +123,8 @@ public inline class UByte internal constructor(private val data: Byte) : Compara
public fun toUInt(): UInt = data.toUInt()
public fun toULong(): ULong = data.toULong()
public override fun toString(): String = toInt().toString()
}
public fun Byte.toUByte(): UByte = UByte(this)
@@ -127,6 +127,8 @@ public inline class UInt internal constructor(private val data: Int) : Comparabl
public fun toUInt(): UInt = this
public fun toULong(): ULong = data.toULong()
public override fun toString(): String = toLong().toString()
}
public fun Byte.toUInt(): UInt = UInt(this.toInt() and 0xFF)
@@ -127,6 +127,8 @@ public inline class ULong internal constructor(private val data: Long) : Compara
public fun toUInt(): UInt = data.toUInt()
public fun toULong(): ULong = this
public override fun toString(): String = ulongToString(data)
}
public fun Byte.toULong(): ULong = ULong(this.toLong() and 0xFF)
@@ -123,6 +123,8 @@ public inline class UShort internal constructor(private val data: Short) : Compa
public fun toUInt(): UInt = data.toUInt()
public fun toULong(): ULong = data.toULong()
public override fun toString(): String = toInt().toString()
}
public fun Byte.toUShort(): UShort = UShort(this.toShort() and 0xFF)
@@ -51,4 +51,21 @@ internal fun ulongRemainder(v1: ULong, v2: ULong): ULong {
val quotient = ((dividend ushr 1) / divisor) shl 1
val rem = dividend - quotient * divisor
return ULong(rem - if (ULong(rem) >= ULong(divisor)) divisor else 0)
}
}
internal fun ulongToString(v: Long): String = ulongToString(v, 10)
internal fun ulongToString(v: Long, base: Int): String {
require(base == 10) // TODO: toString(base) support in common
if (v >= 0) return v.toString(/* base */)
var quotient = ((v ushr 1) / base) shl 1
var rem = v - quotient * base
if (rem >= base) {
rem -= base
quotient += 1
}
return quotient.toString(/* base */) + rem.toString(/* base */)
}