summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/util/ext/Math.kt
blob: 62ee22077bc5014bdc3fcd1c66819418fd339bf3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package io.dico.parcels2.util.ext

fun Double.floor(): Int {
    val down = toInt()
    if (down.toDouble() != this && (java.lang.Double.doubleToRawLongBits(this).ushr(63).toInt()) == 1) {
        return down - 1
    }
    return down
}

infix fun Int.umod(divisor: Int): Int {
    val out = this % divisor
    if (out < 0) {
        return out + divisor
    }
    return out
}

val Int.even: Boolean get() = and(1) == 0

fun IntRange.clamp(min: Int, max: Int): IntRange {
    if (first < min) {
        if (last > max) {
            return IntRange(min, max)
        }
        return IntRange(min, last)
    }
    if (last > max) {
        return IntRange(first, max)
    }
    return this
}

// the name coerceAtMost is bad
fun Int.clampMax(max: Int) = coerceAtMost(max)