Add ByteUtil

This commit is contained in:
2023-10-18 01:47:05 +08:00
parent 047178d70d
commit 0efbdde2a7
2 changed files with 84 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
package top.fatweb.api.util
import kotlin.math.floor
object ByteUtil {
private const val BASE = 1024
enum class ByteUnit {
B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB
}
fun formatByteSize(byteSize: Long): String {
if (byteSize <= -1) {
return byteSize.toString()
}
var size = byteSize.toDouble()
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.B)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.KiB)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.MiB)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.GiB)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.TiB)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.PiB)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.EiB)
}
size /= BASE
if (floor(size / BASE) <= 0) {
return format(size, ByteUnit.ZiB)
}
size /= BASE
return format(size, ByteUnit.YiB)
}
fun format(size: Double, unit: ByteUnit): String {
val precision = if (size * 1000 % 10 > 0) {
3
} else if (size * 100 % 10 > 0) {
2
} else if (size * 10 % 10 > 0) {
1
} else {
0
}
val formatStr = "%.${precision}f"
return String.format(formatStr, size) + unit.name
}
}

View File

@@ -7,6 +7,7 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.context.junit.jupiter.SpringExtension
import top.fatweb.api.constant.SecurityConstants import top.fatweb.api.constant.SecurityConstants
import top.fatweb.api.util.ByteUtil
import top.fatweb.api.util.JwtUtil import top.fatweb.api.util.JwtUtil
@ExtendWith(SpringExtension::class) @ExtendWith(SpringExtension::class)
@@ -31,4 +32,11 @@ class FatWebApiApplicationTests {
logger.info(passwordEncoder.encode("admin@dev")) logger.info(passwordEncoder.encode("admin@dev"))
} }
*/ */
@Test
fun byteUtilTest() {
assertEquals("512B", ByteUtil.formatByteSize(512))
assertEquals("512KiB", ByteUtil.formatByteSize(512 * 1024))
assertEquals("1.5MiB", ByteUtil.formatByteSize(1 * 1024 * 1024 + 512 * 1024))
}
} }