summaryrefslogtreecommitdiffstats
path: root/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/PreferenceUtil.kt
blob: a233ba25c720ee5f7a80ee0ef7b4578c0364341a (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
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

package org.yuzu.yuzu_emu.utils

import android.content.SharedPreferences

object PreferenceUtil {
    /**
     * Retrieves a shared preference value and then deletes the value in storage.
     * @param key Associated key for the value in this preferences instance
     * @return Typed value associated with [key]. Null if no such key exists.
     */
    inline fun <reified T> SharedPreferences.migratePreference(key: String): T? {
        if (!this.contains(key)) {
            return null
        }

        val value: Any = when (T::class) {
            String::class -> this.getString(key, "")!!

            Boolean::class -> this.getBoolean(key, false)

            Int::class -> this.getInt(key, 0)

            Float::class -> this.getFloat(key, 0f)

            Long::class -> this.getLong(key, 0)

            else -> throw IllegalStateException("Tried to migrate preference with invalid type!")
        }
        deletePreference(key)
        return value as T
    }

    fun SharedPreferences.deletePreference(key: String) = this.edit().remove(key).apply()
}