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

com.natpryce.krouton.primitive_path_elements.kt Maven / Gradle / Ivy

There is a newer version: 2.4.0.0
Show newest version
@file:JvmName("PathElementTypes")

package com.natpryce.krouton

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.util.Locale

val string by object : PathElementType {
    override fun parsePathElement(element: String) = element
}

val int by object : PathElementType {
    override fun parsePathElement(element: String) =
        parse(element, String::toInt)
}

val long by object : PathElementType {
    override fun parsePathElement(element: String) =
        parse(element, String::toLong)
}

val double by object : PathElementType {
    override fun parsePathElement(element: String) =
        parse(element, String::toDouble)
}

inline fun > enum() =
    VariablePathElement(
        name = E::class.simpleName ?: "enum",
        type = object : PathElementType {
            override fun parsePathElement(element: String) = try {
                java.lang.Enum.valueOf(E::class.java, element)
            }
            catch (e: IllegalArgumentException) {
                null
            }
        })

val isoLocalDate by object : PathElementType {
    private val format = DateTimeFormatter.ISO_LOCAL_DATE
    
    override fun parsePathElement(element: String) =
        parse(element) { LocalDate.parse(element, format) }
    
    override fun pathElementFrom(value: LocalDate) =
        value.format(format)
}

val locale by object : PathElementType {
    override fun parsePathElement(element: String) = Locale.forLanguageTag(element)
    override fun pathElementFrom(value: Locale) = value.toLanguageTag()
}

private inline fun  parse(s: String, parser: (String) -> T): T? =
    try {
        parser(s)
    } catch (e: Exception) {
        if (e is X) {
            null
        } else {
            throw e
        }
    }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy