diff --git a/src/main/kotlin/top/fatweb/api/util/ByteUtil.kt b/src/main/kotlin/top/fatweb/api/util/ByteUtil.kt new file mode 100644 index 0000000..d8dbfef --- /dev/null +++ b/src/main/kotlin/top/fatweb/api/util/ByteUtil.kt @@ -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 + } +} \ No newline at end of file diff --git a/src/test/kotlin/top/fatweb/api/FatWebApiApplicationTests.kt b/src/test/kotlin/top/fatweb/api/FatWebApiApplicationTests.kt index c73504e..5e4302b 100644 --- a/src/test/kotlin/top/fatweb/api/FatWebApiApplicationTests.kt +++ b/src/test/kotlin/top/fatweb/api/FatWebApiApplicationTests.kt @@ -7,6 +7,7 @@ import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.test.context.junit.jupiter.SpringExtension import top.fatweb.api.constant.SecurityConstants +import top.fatweb.api.util.ByteUtil import top.fatweb.api.util.JwtUtil @ExtendWith(SpringExtension::class) @@ -31,4 +32,11 @@ class FatWebApiApplicationTests { 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)) + } }