Skip to content

Commit fc0f5f0

Browse files
committed
Move Long.toIntChecked() to extensions package
1 parent f86fff6 commit fc0f5f0

File tree

3 files changed

+31
-7
lines changed

3 files changed

+31
-7
lines changed

src/main/kotlin/de/ronny_h/aoc/extensions/numbers/IntegralNumbers.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,10 @@ fun String.isInt(): Boolean = try {
1818
}
1919

2020
fun sumOfFirstNaturalNumbers(n: Int): Long = (n * (n + 1).toLong()) / 2
21+
22+
fun Long.toIntChecked(): Int {
23+
if (this > Int.MAX_VALUE || this < Int.MIN_VALUE) {
24+
throw IllegalArgumentException("$this exceeds Int range")
25+
}
26+
return this.toInt()
27+
}

src/main/kotlin/de/ronny_h/aoc/year2024/day17/ChronospatialComputer.kt

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package de.ronny_h.aoc.year2024.day17
22

33
import de.ronny_h.aoc.AdventOfCode
44
import de.ronny_h.aoc.extensions.memoize
5+
import de.ronny_h.aoc.extensions.numbers.toIntChecked
56

67
fun main() = ChronospatialComputer().run("4,1,7,6,4,1,0,2,7", "164279024971453")
78

@@ -263,10 +264,3 @@ class ThreeBitComputer(input: List<String>) {
263264
val instructionPointer: Int,
264265
)
265266
}
266-
267-
private fun Long.toIntChecked(): Int {
268-
if (this > Int.MAX_VALUE) {
269-
throw IllegalArgumentException("$this exceeds Int range")
270-
}
271-
return this.toInt()
272-
}

src/test/kotlin/de/ronny_h/aoc/extensions/numbers/IntegralNumbersTest.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package de.ronny_h.aoc.extensions.numbers
22

3+
import io.kotest.assertions.throwables.shouldThrow
34
import io.kotest.core.spec.style.StringSpec
45
import io.kotest.data.forAll
56
import io.kotest.data.row
@@ -53,4 +54,26 @@ class IntegralNumbersTest : StringSpec({
5354
sumOfFirstNaturalNumbers(n) shouldBe sum
5455
}
5556
}
57+
58+
"Long values that are small enough can be converted to Int" {
59+
forAll(
60+
row(0L, 0),
61+
row(42L, 42),
62+
row(Int.MAX_VALUE.toLong(), Int.MAX_VALUE),
63+
row(Int.MIN_VALUE.toLong(), Int.MIN_VALUE),
64+
) { longValue, intValue ->
65+
longValue.toIntChecked() shouldBe intValue
66+
}
67+
}
68+
69+
"Long values that are too big cannot be converted to Int" {
70+
forAll(
71+
row(Int.MAX_VALUE.toLong() + 1),
72+
row(Int.MIN_VALUE.toLong() - 1),
73+
) { longValue ->
74+
shouldThrow<IllegalArgumentException> {
75+
longValue.toIntChecked()
76+
}
77+
}
78+
}
5679
})

0 commit comments

Comments
 (0)