MemInfo.kt 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. package eu.mjdev.desktop.helpers.system
  2. import eu.mjdev.desktop.extensions.Custom.lines
  3. import java.io.File
  4. @Suppress("MemberVisibilityCanBePrivate")
  5. class MemInfo(
  6. private val info: List<String> = File("/proc/meminfo").lines,
  7. val free: Double = info.parseLine("MemAvailable").times(KB),
  8. val total: Double = info.parseLine("MemTotal").times(KB),
  9. val used: Double = total - free,
  10. ) {
  11. companion object {
  12. const val KB = 1024
  13. fun List<String>.parseLine(
  14. filter: String
  15. ): Double = firstOrNull { l -> l.startsWith(filter) }?.filter { it.isDigit() }?.toDouble() ?: 0.0
  16. fun Double.toReadable(): String {
  17. val bytes = toLong()
  18. return when {
  19. bytes == Long.MIN_VALUE || bytes < 0 -> "-"
  20. bytes < 1024L -> "$bytes B"
  21. bytes <= 0xfffccccccccccccL shr 40 -> "%.1f KB".format(bytes.toDouble() / (0x1 shl 10))
  22. bytes <= 0xfffccccccccccccL shr 30 -> "%.1f MB".format(bytes.toDouble() / (0x1 shl 20))
  23. bytes <= 0xfffccccccccccccL shr 20 -> "%.1f GB".format(bytes.toDouble() / (0x1 shl 30))
  24. bytes <= 0xfffccccccccccccL shr 10 -> "%.1f TB".format(bytes.toDouble() / (0x1 shl 40))
  25. bytes <= 0xfffccccccccccccL -> "%.1f PB".format((bytes shr 10).toDouble() / (0x1 shl 40))
  26. else -> "%.1f EB".format((bytes shr 20).toDouble() / (0x1 shl 40))
  27. }
  28. }
  29. }
  30. }