All Downloads are FREE. Search and download functionalities are using the official Maven repository.

loggersoft.kotlin.utils.Integer.kt Maven / Gradle / Ivy

/*
 * Copyright (C) 2018 Alexander Kornilov ([email protected])
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

@file:Suppress("NOTHING_TO_INLINE")

package loggersoft.kotlin.utils

import java.math.BigInteger
import kotlin.math.absoluteValue

/**
 * Repeats [body] code block [this] times.
 */
inline fun Int.repeat(body: (index: Int) -> Unit) {
    for(index in 0 until this) body(index)
}

/**
 * Returns string representation of [Int] according to [format].
 * @see [IntegerFormatter] for format description.
 */
inline operator fun Int.get(format: String): String =
    IntegerFormatter(format).format(this < 0, this.absoluteValue) { radix, value ->
        if (value > 0) Pair(value / radix, value % radix) else null
    }

/**
 * Returns string representation of [Long] according to [format].
 * @see [IntegerFormatter] for format description.
 */
inline operator fun Long.get(format: String): String =
        IntegerFormatter(format).format(this < 0, this.absoluteValue) { radix, value ->
            if (value > 0) Pair(value / radix, (value % radix).toInt()) else null
        }

/**
 * Returns string representation of [BigInteger] according to [format].
 * @see [IntegerFormatter] for format description.
 */
inline operator fun BigInteger.get(format: String): String =
        IntegerFormatter(format).format(this.signum() < 0, this.abs()) { radix, value ->
            val bigIntRadix = radix.toBigInteger()
            if (value.signum() > 0) Pair(value / bigIntRadix, (value % bigIntRadix).toInt()) else null
        }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy