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

ru.astrainteractive.astralibs.serialization.StringFormatExt.kt Maven / Gradle / Ivy

There is a newer version: 3.16.1
Show newest version
package ru.astrainteractive.astralibs.serialization

import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.StringFormat
import kotlinx.serialization.encodeToString
import kotlinx.serialization.serializer
import java.io.File

object StringFormatExt {
    /**
     * Attempts to parse content of [file] and return [T] as kotlin's result
     */
    fun  StringFormat.parse(deserializer: DeserializationStrategy, file: File) = kotlin.runCatching {
        if (!file.exists()) error("Could not find file ${file.absolutePath}")
        decodeFromString(deserializer, file.readText())
    }

    inline fun  StringFormat.parse(file: File): Result {
        return parse(serializer(), file)
    }

    /**
     * Parse value or return null if not parsed
     */
    fun  StringFormat.parseOrNull(deserializer: DeserializationStrategy, file: File): T? {
        return parse(deserializer, file).getOrNull()
    }

    inline fun  StringFormat.parseOrNull(file: File): T? {
        return parseOrNull(serializer(), file)
    }

    /**
     * Attempt to parse. Returns default [factory] value on failure
     */
    fun  StringFormat.parseOrDefault(deserializer: DeserializationStrategy, file: File, factory: () -> T): T {
        return parse(deserializer, file).getOrElse { factory.invoke() }
    }

    inline fun  StringFormat.parseOrDefault(file: File, noinline factory: () -> T): T {
        return parseOrDefault(serializer(), file, factory)
    }

    /**
     * Converts [value] into string by [encodeToString] and write text into file [file]
     */
    fun  StringFormat.writeIntoFile(serializer: SerializationStrategy, value: T, file: File) {
        val string = encodeToString(serializer, value)
        if (file.parentFile.exists()) file.parentFile.mkdirs()
        if (!file.exists()) file.createNewFile()
        file.writeText(string)
    }

    inline fun  StringFormat.writeIntoFile(value: T, file: File) {
        writeIntoFile(serializer(), value, file)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy