mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-26 03:58:45 +00:00
base64 tools
This commit is contained in:
parent
6cccd5ff6c
commit
3174b84367
@ -2,6 +2,12 @@
|
|||||||
|
|
||||||
## 0.4.17
|
## 0.4.17
|
||||||
|
|
||||||
|
* `Common`
|
||||||
|
* Functionality for decode/encode base 64 to/from `ByteArray`/`String` have been added
|
||||||
|
* `Serialization`
|
||||||
|
* `Base 64`
|
||||||
|
* Project has been initiated
|
||||||
|
|
||||||
## 0.4.16
|
## 0.4.16
|
||||||
|
|
||||||
* `Coroutines`:
|
* `Coroutines`:
|
||||||
|
@ -1,2 +1,77 @@
|
|||||||
package dev.inmo.micro_utils.common
|
package dev.inmo.micro_utils.common
|
||||||
|
|
||||||
|
import kotlin.experimental.and
|
||||||
|
|
||||||
|
private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||||
|
private const val BASE64_MASK: Byte = 0x3f
|
||||||
|
private const val BASE64_PAD = '='
|
||||||
|
private val BASE64_INVERSE_ALPHABET = IntArray(256) {
|
||||||
|
BASE64_ALPHABET.indexOf(it.toChar())
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun Int.toBase64(): Char = BASE64_ALPHABET[this]
|
||||||
|
internal fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK
|
||||||
|
|
||||||
|
typealias EncodedBase64String = String
|
||||||
|
typealias EncodedByteArray = ByteArray
|
||||||
|
|
||||||
|
fun String.encodeBase64String(): EncodedBase64String = encodeToByteArray().encodeBase64String()
|
||||||
|
fun String.encodeBase64(): EncodedByteArray = encodeToByteArray().encodeBase64()
|
||||||
|
|
||||||
|
fun ByteArray.encodeBase64String(): EncodedBase64String = buildString {
|
||||||
|
var i = 0
|
||||||
|
while (this@encodeBase64String.size > i) {
|
||||||
|
val read = kotlin.math.min(3, this@encodeBase64String.size - i)
|
||||||
|
val data = ByteArray(3) {
|
||||||
|
if (it < read) {
|
||||||
|
this@encodeBase64String[it + i]
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val padSize = (data.size - read) * 8 / 6
|
||||||
|
val chunk = ((data[0].toInt() and 0xFF) shl 16) or
|
||||||
|
((data[1].toInt() and 0xFF) shl 8) or
|
||||||
|
(data[2].toInt() and 0xFF)
|
||||||
|
|
||||||
|
for (index in data.size downTo padSize) {
|
||||||
|
val char = (chunk shr (6 * index)) and BASE64_MASK.toInt()
|
||||||
|
append(char.toBase64())
|
||||||
|
}
|
||||||
|
|
||||||
|
repeat(padSize) { append(BASE64_PAD) }
|
||||||
|
|
||||||
|
i += read
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun ByteArray.encodeBase64(): EncodedByteArray = encodeBase64String().encodeToByteArray()
|
||||||
|
|
||||||
|
fun EncodedBase64String.decodeBase64() = dropLastWhile { it == BASE64_PAD }.encodeToByteArray().decodeBase64()
|
||||||
|
fun EncodedBase64String.decodeBase64String() = decodeBase64().decodeToString()
|
||||||
|
|
||||||
|
fun EncodedByteArray.decodeBase64(): ByteArray {
|
||||||
|
val result = mutableListOf<Byte>()
|
||||||
|
val data = ByteArray(4)
|
||||||
|
(0 until size step 4).forEach { i ->
|
||||||
|
var read = 0
|
||||||
|
for (j in 0 until 4) {
|
||||||
|
if (j + i < size) {
|
||||||
|
data[j] = get(j + i)
|
||||||
|
read++
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val chunk = data.foldIndexed(0) { index, result, current ->
|
||||||
|
result or (current.fromBase64().toInt() shl ((3 - index) * 6))
|
||||||
|
}
|
||||||
|
for (index in data.size - 2 downTo (data.size - read)) {
|
||||||
|
val origin = (chunk shr (8 * index)) and 0xff
|
||||||
|
result.add(origin.toByte())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.toByteArray()
|
||||||
|
}
|
||||||
|
fun EncodedByteArray.decodeBase64String() = decodeBase64().decodeToString()
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
package dev.inmo.micro_utils.common
|
||||||
|
|
||||||
|
import kotlin.random.Random
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class Base64Text {
|
||||||
|
|
||||||
|
val testText = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
|
||||||
|
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"""
|
||||||
|
val base64Text = """TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdm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BlaXVzIG1vZGkgdGVtcG9yYSBpbmNpZHVudCB1dCBsYWJvcmUgZXQgZG9sb3JlIG1hZ25hbSBhbGlxdWFtIHF1YWVyYXQgdm9sdXB0YXRlbS4gVXQgZW5pbSBhZCBtaW5pbWEgdmVuaWFtLCBxdWlzIG5vc3RydW0gZXhlcmNpdGF0aW9uZW0gdWxsYW0gY29ycG9yaXMgc3VzY2lwaXQgbGFib3Jpb3NhbSwgbmlzaSB1dCBhbGlxdWlkIGV4IGVhIGNvbW1vZGkgY29uc2VxdWF0dXI/IFF1aXMgYXV0ZW0gdmVsIGV1bSBpdXJlIHJlcHJlaGVuZGVyaXQgcXVpIGluIGVhIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIHF1YW0gbmloaWwgbW9sZXN0aWFlIGNvbnNlcXVhdHVyLCB2ZWwgaWxsdW0gcXVpIGRvbG9yZW0gZXVtIGZ1Z2lhdCBxdW8gdm9sdXB0YXMgbnVsbGEgcGFyaWF0dXI/"""
|
||||||
|
@Test
|
||||||
|
fun decodeEncode() {
|
||||||
|
val encoded = testText.encodeBase64String()
|
||||||
|
assertEquals(base64Text, encoded)
|
||||||
|
val decoded = encoded.decodeBase64String()
|
||||||
|
assertEquals(testText, decoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
val urlTestText = "https://example.com?isitexample=1"
|
||||||
|
val urlTestBase64Text = "aHR0cHM6Ly9leGFtcGxlLmNvbT9pc2l0ZXhhbXBsZT0x"
|
||||||
|
@Test
|
||||||
|
fun decodeEncodeUrl() {
|
||||||
|
val encoded = urlTestText.encodeBase64String()
|
||||||
|
assertEquals(urlTestBase64Text, encoded)
|
||||||
|
val decoded = encoded.decodeBase64String()
|
||||||
|
assertEquals(urlTestText, decoded)
|
||||||
|
}
|
||||||
|
}
|
@ -5,3 +5,13 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
apply from: "$mppProjectWithSerializationPresetPath"
|
apply from: "$mppProjectWithSerializationPresetPath"
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
sourceSets {
|
||||||
|
commonMain {
|
||||||
|
dependencies {
|
||||||
|
api project(":micro_utils.common")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,13 +1,21 @@
|
|||||||
package dev.inmo.micro_utils.serialization.base64
|
package dev.inmo.micro_utils.serialization.base64
|
||||||
|
|
||||||
|
import dev.inmo.micro_utils.common.*
|
||||||
import kotlinx.serialization.KSerializer
|
import kotlinx.serialization.KSerializer
|
||||||
|
import kotlinx.serialization.Serializer
|
||||||
import kotlinx.serialization.builtins.serializer
|
import kotlinx.serialization.builtins.serializer
|
||||||
import kotlinx.serialization.descriptors.SerialDescriptor
|
import kotlinx.serialization.descriptors.SerialDescriptor
|
||||||
import kotlinx.serialization.encoding.Decoder
|
import kotlinx.serialization.encoding.Decoder
|
||||||
|
import kotlinx.serialization.encoding.Encoder
|
||||||
|
|
||||||
class Base64Serializer<T>(private val typeSerializer: KSerializer<T>) : KSerializer<T> {
|
open class Base64Serializer<T>(
|
||||||
|
private val converterFrom: (T) -> String,
|
||||||
|
private val converterTo: (String) -> T,
|
||||||
|
) : KSerializer<T> {
|
||||||
override val descriptor: SerialDescriptor = String.serializer().descriptor
|
override val descriptor: SerialDescriptor = String.serializer().descriptor
|
||||||
override fun deserialize(decoder: Decoder): T {
|
override fun deserialize(decoder: Decoder): T = converterTo(decoder.decodeString().decodeBase64String())
|
||||||
TODO("Not yet implemented")
|
override fun serialize(encoder: Encoder, value: T) = encoder.encodeString(converterFrom(value).encodeBase64String())
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Serializer(String::class)
|
||||||
|
object Base64StringSerializer : Base64Serializer<String>({ it }, { it })
|
||||||
|
Loading…
Reference in New Issue
Block a user