commonMain.buildCsv.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of csv Show documentation
Show all versions of csv Show documentation
Tiny Kotlin Multiplatform library for building and exporting CSV files
The newest version!
/** Copyright 2023 Halfbit GmbH, Sergej Shafarenka */
package de.halfbit.csv
import de.halfbit.csv.Csv.*
@DslMarker
public annotation class CsvDsl
public fun buildCsv(
block: CsvBuilder.() -> Unit
): Csv {
val header = mutableListOf()
val data = mutableListOf()
block(CsvBuilder(header, data))
return Csv(header.getOrNull(0), data)
}
@CsvDsl
public class CsvBuilder internal constructor(
private val header: MutableList,
private val data: MutableList,
) {
public fun row(block: CsvRowBuilder.() -> Unit) {
val row = mutableListOf()
val scope = CsvRowBuilder(row)
block(scope)
if (header.isEmpty()) {
header += HeaderRow(row)
} else {
data += DataRow(row, header[0])
}
}
}
@CsvDsl
public class CsvRowBuilder internal constructor(
private val row: MutableList,
) {
public fun value(value: String) {
row.add(value)
}
}
internal fun HeaderRow(row: List): HeaderRow =
object : HeaderRow, List by row {
private val indexOfColumn: MutableMap by lazy { mutableMapOf() }
override fun indexOfColumn(name: String): Int =
indexOfColumn[name] ?: run {
val index = indexOf(name)
indexOfColumn[name] = index
index
}
override fun toString(): String =
row.toString()
}
internal fun DataRow(row: List, header: HeaderRow): DataRow =
object : DataRow, List by row {
override fun value(columnName: String): String? =
row.getOrNull(header.indexOfColumn(columnName))
override fun toString(): String =
row.toString()
}