Refactor extension functions for better performance and clarity (#3394)

Refactor Kotlin extension functions for clarity and performance

- Updated `v2RayApplication` extension to handle potential ClassCastException.
- Simplified `toast` functions for better readability.
- Refactored `toTrafficString` function to reduce redundancy and improve performance.
- Minor improvements to JSON and URL connection handling.
This commit is contained in:
Tamim Hossain
2024-08-01 17:44:07 +06:00
committed by GitHub
parent 4b4c46e5ae
commit 7582f86482

View File

@@ -9,15 +9,15 @@ import org.json.JSONObject
import java.net.URI
import java.net.URLConnection
val Context.v2RayApplication: AngApplication
get() = applicationContext as AngApplication
val Context.v2RayApplication: AngApplication?
get() = applicationContext as? AngApplication
fun Context.toast(message: Int) {
ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).apply { show() }
ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun Context.toast(message: CharSequence) {
ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).apply { show() }
ToastCompat.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun JSONObject.putOpt(pair: Pair<String, Any?>) {
@@ -34,26 +34,14 @@ const val DIVISOR = 1024.0
fun Long.toSpeedString(): String = this.toTrafficString() + "/s"
fun Long.toTrafficString(): String {
if (this < THRESHOLD) {
return "$this B"
val units = arrayOf("B", "KB", "MB", "GB", "TB", "PB")
var size = this.toDouble()
var unitIndex = 0
while (size >= THRESHOLD && unitIndex < units.size - 1) {
size /= DIVISOR
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)
return String.format("%.1f %s", size, units[unitIndex])
}
val URLConnection.responseLength: Long