From 5d7035b551e9dce0474c6d765c638e0d74468df0 Mon Sep 17 00:00:00 2001 From: Alexander Biryukov Date: Tue, 4 Oct 2022 04:22:16 +0300 Subject: [PATCH] Correct conversion between bytes and other units (#347) --- .../hoplite/decoder/SizeInBytesDecoder.kt | 2 +- .../hoplite/decoder/SizeInBytesDecoderTest.kt | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 hoplite-core/src/test/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoderTest.kt diff --git a/hoplite-core/src/main/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoder.kt b/hoplite-core/src/main/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoder.kt index 8cd02e47..b56a35d9 100644 --- a/hoplite-core/src/main/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoder.kt +++ b/hoplite-core/src/main/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoder.kt @@ -22,7 +22,7 @@ data class SizeInBytes(val size: Long) { fun gigabytes() = convert(InformationUnit.Gigabytes) fun gibibytes() = convert(InformationUnit.Gibibytes) - fun convert(unit: InformationUnit): Long = (unit.ratioToPrimary / size).toLong() + fun convert(unit: InformationUnit): Long = (size / unit.ratioToPrimary).toLong() companion object { fun parse(input: String): SizeInBytes? { diff --git a/hoplite-core/src/test/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoderTest.kt b/hoplite-core/src/test/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoderTest.kt new file mode 100644 index 00000000..1c521d6e --- /dev/null +++ b/hoplite-core/src/test/kotlin/com/sksamuel/hoplite/decoder/SizeInBytesDecoderTest.kt @@ -0,0 +1,24 @@ +package com.sksamuel.hoplite.decoder + +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe + +class SizeInBytesDecoderTest : FunSpec({ + val units = listOf( + InformationUnit.Kilobytes, + InformationUnit.Megabytes, + InformationUnit.Gigabytes, + + InformationUnit.Octets, + InformationUnit.Kibibytes, + InformationUnit.Mebibytes, + InformationUnit.Gibibytes + ) + + test("conversion between bytes and other units") { + val size = 8 + for (unit in units) { + SizeInBytes((size * unit.ratioToPrimary).toLong()).convert(unit) shouldBe size + } + } +})