/* * 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 { public constructor() : this(mutableMapOf()) 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 fun from(attributes: Attributes) { map.putAll(attributes.content) } public fun SetAttribute.add( attrValue: V, ) { val currentSet: Set = get(this) ?: emptySet() map[this] = currentSet + attrValue } /** * Remove an element from [SetAttribute] */ public fun SetAttribute.remove( attrValue: V, ) { val currentSet: Set = get(this) ?: emptySet() map[this] = currentSet - attrValue } public fun build(): Attributes = AttributesImpl(map) } public inline fun Attributes(builder: AttributesBuilder.() -> Unit): Attributes = AttributesBuilder().apply(builder).build()