Skip to content

Commit

Permalink
Singleton implementation for Attributes.EMPTY
Browse files Browse the repository at this point in the history
  • Loading branch information
altavir committed Mar 27, 2024
1 parent ac851be commit 48b334a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ public interface Attributes {
override fun hashCode(): Int

public companion object {
public val EMPTY: Attributes = MapAttributes(emptyMap())
public val EMPTY: Attributes = object : Attributes {
override val content: Map<out Attribute<*>, Any?> get() = emptyMap()

override fun toString(): String = "Attributes.EMPTY"

override fun equals(other: Any?): Boolean = (other as? Attributes)?.isEmpty() ?: false

override fun hashCode(): Int = Unit.hashCode()
}

public fun equals(a1: Attributes, a2: Attributes): Boolean =
a1.keys == a2.keys && a1.keys.all { a1[it] == a2[it] }
Expand All @@ -43,7 +51,7 @@ internal class MapAttributes(override val content: Map<out Attribute<*>, Any?>)
override fun hashCode(): Int = content.hashCode()
}

public fun Attributes.isEmpty(): Boolean = content.isEmpty()
public fun Attributes.isEmpty(): Boolean = keys.isEmpty()

/**
* Get attribute value or default
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ public class AttributesBuilder<out O> internal constructor() : Attributes {

private val map = mutableMapOf<Attribute<*>, Any?>()

override fun toString(): String = "Attributes(value=${content.entries})"
override fun toString(): String = "Attributes(value=${map.entries})"
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
override fun hashCode(): Int = content.hashCode()
override fun hashCode(): Int = map.hashCode()

override val content: Map<out Attribute<*>, Any?> get() = map

Expand Down

0 comments on commit 48b334a

Please sign in to comment.