package ru.dbotthepony.mc.otm.core.collect

import java.util.WeakHashMap

/**
 * Wrapper around [WeakHashMap] to behave like set
 */
class WeakHashSet<E : Any> : MutableSet<E> {
	private val backing = WeakHashMap<E, Unit>()

	override fun add(element: E): Boolean {
		return backing.put(element, Unit) == null
	}

	override fun addAll(elements: Collection<E>): Boolean {
		return elements.count(::add) > 0
	}

	override fun clear() {
		backing.clear()
	}

	override fun iterator(): MutableIterator<E> {
		return backing.keys.iterator()
	}

	override fun remove(element: E): Boolean {
		return backing.remove(element) != null
	}

	override fun removeAll(elements: Collection<E>): Boolean {
		return backing.keys.removeAll(elements)
	}

	override fun retainAll(elements: Collection<E>): Boolean {
		return backing.keys.retainAll(elements)
	}

	override val size: Int
		get() = backing.size

	override fun contains(element: E): Boolean {
		return backing.get(element) === Unit
	}

	override fun containsAll(elements: Collection<E>): Boolean {
		return elements.all(::contains)
	}

	override fun isEmpty(): Boolean {
		return backing.isEmpty()
	}
}
