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 authored and GitHub committed 2024-08-01 19:44:07 +08:00
1 parent 4b4c46e5ae
commit 7582f86482
1 file changed
+11 -23
@@ -9,15 +9,15 @@ import org.json.JSONObject
import java.net.URI import java.net.URI
import java.net.URLConnection import java.net.URLConnection
val Context.v2RayApplication: AngApplication val Context.v2RayApplication: AngApplication?
get() = applicationContext as AngApplication get() = applicationContext as? AngApplication
fun Context.toast(message: Int) { 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) { 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?>) { 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.toSpeedString(): String = this.toTrafficString() + "/s"
fun Long.toTrafficString(): String { fun Long.toTrafficString(): String {
if (this < THRESHOLD) { val units = arrayOf("B", "KB", "MB", "GB", "TB", "PB")
return "$this B" var size = this.toDouble()
var unitIndex = 0
while (size >= THRESHOLD && unitIndex < units.size - 1) {
size /= DIVISOR
unitIndex++
} }
val kb = this / DIVISOR return String.format("%.1f %s", size, units[unitIndex])
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 val URLConnection.responseLength: Long