/* * Copyright 2018-2023 KMath contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package space.kscience.attributes /** * A safe builder for [Attributes] * * @param O type marker of an owner object, for which these attributes are made */ public class AttributesBuilder internal constructor( private val map: MutableMap, Any?>, ) : Attributes { override fun toString(): String = "Attributes(value=${content.entries})" override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other) override fun hashCode(): Int = content.hashCode() override val content: Map, Any?> get() = map public operator fun set(attribute: Attribute, value: T?) { if (value == null) { map.remove(attribute) } else { map[attribute] = value } } public operator fun Attribute.invoke(value: V?) { set(this, value) } public infix fun Attribute.put(value: V?) { set(this, value) } /** * Put all attributes for given [attributes] */ public fun putAll(attributes: Attributes) { map.putAll(attributes.content) } public infix fun SetAttribute.add(attrValue: V) { val currentSet: Set = get(this) ?: emptySet() map[this] = currentSet + attrValue } /** * Remove an element from [SetAttribute] */ public infix fun SetAttribute.remove(attrValue: V) { val currentSet: Set = get(this) ?: emptySet() map[this] = currentSet - attrValue } public fun build(): Attributes = AttributesImpl(map) } /** * Create [Attributes] with a given [builder] * @param O the type for which attributes are built. The type is used only during compilation phase for static extension dispatch */ public fun Attributes(builder: AttributesBuilder.() -> Unit): Attributes = AttributesBuilder(mutableMapOf()).apply(builder).build()