summaryrefslogtreecommitdiffstats
path: root/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/MemoryUtil.kt
blob: 59e9f8f873f57e5f7bf3470223262d03771cdd24 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

package org.yuzu.yuzu_emu.utils

import android.app.ActivityManager
import android.content.Context
import org.yuzu.yuzu_emu.R
import org.yuzu.yuzu_emu.YuzuApplication
import java.util.Locale

object MemoryUtil {
    private val context get() = YuzuApplication.appContext

    private val Long.floatForm: String
        get() = String.format(Locale.ROOT, "%.2f", this.toDouble())

    const val Kb: Long = 1024
    const val Mb = Kb * 1024
    const val Gb = Mb * 1024
    const val Tb = Gb * 1024
    const val Pb = Tb * 1024
    const val Eb = Pb * 1024

    private fun bytesToSizeUnit(size: Long): String {
        return when {
            size < Kb -> "${size.floatForm} ${context.getString(R.string.memory_byte)}"
            size < Mb -> "${(size / Kb).floatForm} ${context.getString(R.string.memory_kilobyte)}"
            size < Gb -> "${(size / Mb).floatForm} ${context.getString(R.string.memory_megabyte)}"
            size < Tb -> "${(size / Gb).floatForm} ${context.getString(R.string.memory_gigabyte)}"
            size < Pb -> "${(size / Tb).floatForm} ${context.getString(R.string.memory_terabyte)}"
            size < Eb -> "${(size / Pb).floatForm} ${context.getString(R.string.memory_petabyte)}"
            else -> "${(size / Eb).floatForm} ${context.getString(R.string.memory_exabyte)}"
        }
    }

    private val totalMemory =
        with(context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager) {
            val memInfo = ActivityManager.MemoryInfo()
            getMemoryInfo(memInfo)
            memInfo.totalMem
        }

    fun isLessThan(minimum: Int, size: Long): Boolean {
        return when (size) {
            Kb -> totalMemory < Mb && totalMemory < minimum
            Mb -> totalMemory < Gb && (totalMemory / Mb) < minimum
            Gb -> totalMemory < Tb && (totalMemory / Gb) < minimum
            Tb -> totalMemory < Pb && (totalMemory / Tb) < minimum
            Pb -> totalMemory < Eb && (totalMemory / Pb) < minimum
            Eb -> totalMemory / Eb < minimum
            else -> totalMemory < Kb && totalMemory < minimum
        }
    }

    fun getDeviceRAM(): String {
        return bytesToSizeUnit(totalMemory)
    }
}