...
 
Commits (4)
......@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](semver.md).
### Added
- `string` extension for Random
- Directory as Directory2 alias
- `luhn10` extension for String
- `mod97` extension for String
### Changed
### Deprecated
- Queue (`klib.queue.Queue`)
......
kotlin.code.style=official
# kLib Version
klib_version=5.1.0-dev.1
klib_version=5.1.0-dev.2
# Versions
gradle_version=6.4
......
......@@ -4,6 +4,7 @@ import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.math.BigInteger
import java.util.Base64
import klib.annotations.Experimental
import klib.encoding.base.Base58e
......@@ -455,3 +456,64 @@ fun String.splitBy(num: Int = 1): List<String> {
fun String.trimSpace(): String {
return this.replace(" ", "")
}
/**
* Check a String if it is Luhn valid
*
* @since 5.1.0
* @author Thomas Obernosterer
*/
fun String.luhn10(): Boolean {
var sum = 0
var alternate = false
for (i in length - 1 downTo 0) {
var n = substring(i, i + 1).toInt()
if (alternate) {
n *= 2
if (n > 9) {
n = n % 10 + 1
}
}
sum += n
alternate = !alternate
}
return sum % 10 == 0
}
/**
* Check if a String is Mod97 Valid
*
* @since 5.1.0
* @author Thomas Obernosterer
*/
fun String.mod97(): Boolean {
fun transform(src: CharSequence, srcPos: Int, srcLen: Int, dest: CharArray, destPos: Int): Int {
var offset = destPos
for (i in srcPos until srcLen) {
when (val c = src[i]) {
in '0'..'9' -> {
dest[offset++] = c
}
in 'A'..'Z' -> {
val tmp = 10 + (c - 'A')
dest[offset++] = ('0'.toInt() + tmp / 10).toChar()
dest[offset++] = ('0'.toInt() + tmp % 10).toChar()
}
in 'a'..'z' -> {
val tmp = 10 + (c - 'a')
dest[offset++] = ('0'.toInt() + tmp / 10).toChar()
dest[offset++] = ('0'.toInt() + tmp % 10).toChar()
}
else -> require(c == ' ') { "Invalid character '$c'." }
}
}
return offset
}
val buffer = CharArray(length * 2)
var offset: Int = transform(this, 4, length, buffer, 0)
offset = transform(this, 0, 4, buffer, offset)
val sum = BigInteger(String(buffer, 0, offset))
val remainder = sum.remainder(BigInteger("97"))
return remainder.toInt() == 1
}