Advertisement
Guest User

Inline Classes

a guest
Oct 18th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.22 KB | None | 0 0
  1. @file:Suppress("EXPERIMENTAL_FEATURE_WARNING")
  2.  
  3. package de.icks.led.shared
  4.  
  5. import androidx.annotation.ColorInt
  6. import de.icks.led.util.currentMillisFromMidnight
  7.  
  8. private const val COMMAND_TYPE_MASK      = 0xF000000_00000000
  9. private const val COMMAND_TYPE_INDEX     = 0x1000000_00000000
  10. private const val COMMAND_TYPE_FILL      = 0x2000000_00000000
  11. private const val COMMAND_TYPE_COLOR     = 0x3000000_00000000
  12.  
  13. private const val TIMESTAMP_MASK = 0x0FFFFFF_00000000 // Note: 279 minutes as millis is the maximum timestamp
  14. private const val PAYLOAD_MASK   = 0x0000000_FFFFFFFF
  15.  
  16. private val millisFromMidNight = currentMillisFromMidnight()
  17. private fun maskedTimestamp() = ((System.currentTimeMillis() - millisFromMidNight) shl 32) and TIMESTAMP_MASK
  18.  
  19. interface LedCommand {
  20.     val encodedCommand: Long
  21. }
  22.  
  23. interface TimestampCommand: LedCommand {
  24.     /**
  25.      * Millis from midnight
  26.      */
  27.     val timestampMillis get() = (encodedCommand and TIMESTAMP_MASK) shr 32
  28. }
  29.  
  30. inline class LedIndexCommand(override val encodedCommand: Long) : TimestampCommand {
  31.     constructor( index: Int) : this(COMMAND_TYPE_INDEX or maskedTimestamp() or (PAYLOAD_MASK and index.toLong()))
  32.     val index get() =  (encodedCommand and PAYLOAD_MASK).toInt()
  33. }
  34.  
  35. inline class LedColorCommand(override val encodedCommand: Long): TimestampCommand {
  36.     constructor(@ColorInt color: Int) : this(COMMAND_TYPE_COLOR or maskedTimestamp() or (PAYLOAD_MASK and color.toLong()))
  37.     val color @ColorInt get() =  (encodedCommand and PAYLOAD_MASK).toInt()
  38. }
  39.  
  40. inline class LedFillCommand(override val encodedCommand: Long): TimestampCommand {
  41.     constructor() : this(COMMAND_TYPE_FILL or maskedTimestamp())
  42. }
  43.  
  44. interface LedCommandResolver {
  45.     fun resolveCommand(encodedCommand: Long) {
  46.         when(encodedCommand and COMMAND_TYPE_MASK) {
  47.             COMMAND_TYPE_INDEX -> onIndexCommand(LedIndexCommand(encodedCommand))
  48.             COMMAND_TYPE_FILL -> onFillCommand(LedFillCommand(encodedCommand))
  49.             COMMAND_TYPE_COLOR -> onColorCommand(LedColorCommand(encodedCommand))
  50.         }
  51.     }
  52.  
  53.     fun onIndexCommand(command: LedIndexCommand) {}
  54.     fun onFillCommand(command: LedFillCommand) {}
  55.     fun onColorCommand(command: LedColorCommand) {}
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement