Update _Ext.kt

This commit is contained in:
Το μοχθηρό ^_^
2024-02-25 19:05:48 +08:00
committed by GitHub
parent c7efcde868
commit 802f2cf3eb
@@ -1,6 +1,7 @@
package com.v2ray.ang.extension
import android.content.Context
import android.os.Build
import android.widget.Toast
import com.v2ray.ang.AngApplication
import me.drakeet.support.toast.ToastCompat
@@ -9,47 +10,60 @@ import java.net.URI
import java.net.URLConnection
val Context.v2RayApplication: AngApplication
get() = applicationContext as? AngApplication ?: throw IllegalStateException("Not an AngApplication")
get() = applicationContext as AngApplication
fun Context.toast(message: Int) = showToast(message)
fun Context.toast(message: CharSequence) = showToast(message)
private fun Context.showToast(message: Any) {
ToastCompat.makeText(this, message.toString(), Toast.LENGTH_SHORT).apply { show() }
fun Context.toast(message: Int) {
ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).apply { show() }
}
fun JSONObject.putOpt(pair: Pair<String, Any>) {
pair.second?.let {
put(pair.first, it)
}
fun Context.toast(message: CharSequence) {
ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).apply { show() }
}
fun JSONObject.putOpt(pairs: Map<String, Any>) {
pairs.forEach { (key, value) ->
putOpt(key to value)
}
fun JSONObject.putOpt(pair: Pair<String, Any?>) {
put(pair.first, pair.second)
}
private const val KILOBYTE = 1024.0
private const val THRESHOLD = 1024
fun JSONObject.putOpt(pairs: Map<String, Any?>) {
pairs.forEach { put(it.key, it.value) }
}
const val THRESHOLD = 1000L
const val DIVISOR = 1024.0
fun Long.toSpeedString(): String = this.toTrafficString() + "/s"
fun Long.toTrafficString(): String {
var value = this.toDouble()
val units = listOf("B", "KB", "MB", "GB", "TB", "PB")
var unitIndex = 0
while (value >= THRESHOLD && unitIndex < units.lastIndex) {
value /= KILOBYTE
unitIndex++
if (this < THRESHOLD) {
return "$this B"
}
return String.format("%.2f %s", value, units[unitIndex])
val kb = this / DIVISOR
if (kb < THRESHOLD) {
return "${String.format("%.1f KB", kb)}"
}
val mb = kb / DIVISOR
if (mb < THRESHOLD) {
return "${String.format("%.1f MB", mb)}"
}
val gb = mb / DIVISOR
if (gb < THRESHOLD) {
return "${String.format("%.1f GB", gb)}"
}
val tb = gb / DIVISOR
if (tb < THRESHOLD) {
return "${String.format("%.1f TB", tb)}"
}
return String.format("%.1f PB", tb / DIVISOR)
}
val URLConnection.responseLength: Long
get() = if (Build.VERSION.SDK_INT >= 23) contentLengthLong else contentLength.toLong()
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
contentLengthLong
} else {
contentLength.toLong()
}
val URI.idnHost: String
get() = host?.replace("[", "")?.replace("]", "") ?: ""
fun String.removeWhiteSpace() = replace("\\s+".toRegex(), "")
fun String.removeWhiteSpace(): String = replace("\\s+".toRegex(), "")