Uuids.kt

  1. package com.hexagonkt.core

  2. import com.hexagonkt.core.text.decodeBase64
  3. import com.hexagonkt.core.text.encodeToBase64
  4. import java.nio.ByteBuffer
  5. import java.util.*

  6. // TODO UUIDv7: https://antonz.org/uuidv7/?ref=dailydev#kotlin
  7. /*
  8.     import java.security.SecureRandom
  9.     import java.time.Instant

  10.     object UUIDv7 {
  11.         private val random = SecureRandom()

  12.         fun generate(): ByteArray {
  13.             // random bytes
  14.             val value = ByteArray(16)
  15.             random.nextBytes(value)

  16.             // current timestamp in ms
  17.             val timestamp = Instant.now().toEpochMilli()

  18.             // timestamp
  19.             value[0] = ((timestamp shr 40) and 0xFF).toByte()
  20.             value[1] = ((timestamp shr 32) and 0xFF).toByte()
  21.             value[2] = ((timestamp shr 24) and 0xFF).toByte()
  22.             value[3] = ((timestamp shr 16) and 0xFF).toByte()
  23.             value[4] = ((timestamp shr 8) and 0xFF).toByte()
  24.             value[5] = (timestamp and 0xFF).toByte()

  25.             // version and variant
  26.             value[6] = (value[6].toInt() and 0x0F or 0x70).toByte()
  27.             value[8] = (value[8].toInt() and 0x3F or 0x80).toByte()

  28.             return value
  29.         }

  30.         @JvmStatic
  31.         fun main(args: Array<String>) {
  32.             val uuidVal = generate()
  33.             uuidVal.forEach { b -> print("%02x".format(b)) }
  34.             println()
  35.         }
  36.     }
  37.  */
  38. // TODO Rename to Ids.kt and support other algorithms (nanoid, ulid, snowflake, cuid)

  39. /**
  40.  * [TODO](https://github.com/hexagontk/hexagon/issues/271).
  41.  *
  42.  * @receiver .
  43.  * @return .
  44.  */
  45. fun UUID.bytes(): ByteArray =
  46.     ByteBuffer.wrap(ByteArray(16)).let {
  47.         it.putLong(this.mostSignificantBits)
  48.         it.putLong(this.leastSignificantBits)
  49.         it.array()
  50.     }

  51. /**
  52.  * [TODO](https://github.com/hexagontk/hexagon/issues/271).
  53.  *
  54.  * @receiver .
  55.  * @return .
  56.  */
  57. fun UUID.toBase64(): String =
  58.     bytes().encodeToBase64()

  59. /**
  60.  * [TODO](https://github.com/hexagontk/hexagon/issues/271).
  61.  *
  62.  * @param text .
  63.  * @return .
  64.  */
  65. fun uuid(text: String): UUID =
  66.     if (text[8] == '-') UUID.fromString(text)
  67.     else uuid(text.decodeBase64())

  68. /**
  69.  * [TODO](https://github.com/hexagontk/hexagon/issues/271).
  70.  *
  71.  * @param bytes .
  72.  * @return .
  73.  */
  74. fun uuid(bytes: ByteArray): UUID =
  75.     ByteBuffer.wrap(bytes).let { UUID(it.long, it.long) }