diff --git a/dataforge-data/src/jvmMain/kotlin/hep/dataforge/data/select.kt b/dataforge-data/src/jvmMain/kotlin/hep/dataforge/data/select.kt index 9df89f84..02672c37 100644 --- a/dataforge-data/src/jvmMain/kotlin/hep/dataforge/data/select.kt +++ b/dataforge-data/src/jvmMain/kotlin/hep/dataforge/data/select.kt @@ -12,44 +12,15 @@ import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.typeOf -/** - * Check if data could be safely cast to given class - */ -private fun Data<*>.canCast(type: KType): Boolean = this.type.isSubtypeOf(type) - /** * Cast the node to given type if the cast is possible or return null */ @Suppress("UNCHECKED_CAST") private fun Data<*>.castOrNull(type: KType): Data? = - if (!canCast(type)) null else object : Data by (this as Data) { + if (!this.type.isSubtypeOf(type)) null else object : Data by (this as Data) { override val type: KType = type } -/** - * Unsafe cast of data node - */ -private fun Data<*>.cast(type: KType): Data = - castOrNull(type) ?: error("Can't cast ${this.type} to $type") - -private inline fun Data<*>.cast(): Data = cast(typeOf()) - -@Suppress("UNCHECKED_CAST") -private fun DataSet<*>.castOrNull(type: KType): DataSet? = - if (!canCast(type)) null else object : DataSet by (this as DataSet) { - override val dataType: KType = type - } - - -private fun DataSet<*>.cast(type: KType): DataSet = - castOrNull(type) ?: error("Can't cast ${this.dataType} to $type") - -/** - * Check that node is compatible with given type meaning that each element could be cast to the type - */ -private fun DataSet<*>.canCast(type: KType): Boolean = - type.isSubtypeOf(this.dataType) - /** * Select all data matching given type and filters. Does not modify paths */ @@ -61,10 +32,11 @@ internal fun DataSet<*>.select( ): ActiveDataSet = object : ActiveDataSet { override val dataType = type - @Suppress("UNCHECKED_CAST") - override fun flow(): Flow> = this@select.flow().filter { - it.type.isSubtypeOf(type) && (namePattern == null || it.name.matches(namePattern)) + + override fun flow(): Flow> = this@select.flow().filter { datum -> + datum.type.isSubtypeOf(type) && (namePattern == null || datum.name.matches(namePattern)) }.map { + @Suppress("UNCHECKED_CAST") it as NamedData } @@ -72,7 +44,7 @@ internal fun DataSet<*>.select( override val updates: Flow = this@select.updates.filter { val datum = this@select.getData(it) - datum?.canCast(type) ?: false + datum?.type?.isSubtypeOf(type) ?: false } }