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

commonMain.buildCsv.kt Maven / Gradle / Ivy

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()
    }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy