From 7582f86482fccab4fe48e6d7235ef6ebc08b44f0 Mon Sep 17 00:00:00 2001 From: Tamim Hossain <132823494+CodeWithTamim@users.noreply.github.com> Date: Thu, 1 Aug 2024 17:44:07 +0600 Subject: [PATCH] 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. --- .../kotlin/com/v2ray/ang/extension/_Ext.kt | 34 ++++++------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt index 9b764c0d..71837467 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt @@ -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) { @@ -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