All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.implementations.immutableSet.PersistentHashSet.kt Maven / Gradle / Ivy

There is a newer version: 0.3.8
Show newest version
/*
 * Copyright 2016-2019 JetBrains s.r.o.
 * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
 */

package kotlinx.collections.immutable.implementations.immutableSet

import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.mutate

internal class PersistentHashSet(internal val node: TrieNode,
                                    override val size: Int): AbstractSet(), PersistentSet {
    override fun contains(element: E): Boolean {
        return node.contains(element.hashCode(), element, 0)
    }

    override fun add(element: E): PersistentSet {
        val newNode = node.add(element.hashCode(), element, 0)
        if (node === newNode) { return this }
        return PersistentHashSet(newNode, size + 1)
    }

    override fun addAll(elements: Collection): PersistentSet {
        return this.mutate { it.addAll(elements) }
    }

    override fun remove(element: E): PersistentSet {
        val newNode = node.remove(element.hashCode(), element, 0)
        if (node === newNode) { return this }
        return PersistentHashSet(newNode, size - 1)
    }

    override fun removeAll(elements: Collection): PersistentSet {
        return mutate { it.removeAll(elements) }
    }

    override fun removeAll(predicate: (E) -> Boolean): PersistentSet {
        return mutate { it.removeAll(predicate) }
    }

    override fun retainAll(elements: Collection): PersistentSet {
        return mutate { it.retainAll(elements) }
    }

    override fun containsAll(elements: Collection): Boolean {
        if (elements is PersistentHashSet) {
            return node.containsAll(elements.node, 0)
        }
        if (elements is PersistentHashSetBuilder) {
            return node.containsAll(elements.node, 0)
        }
        return super.containsAll(elements)
    }

    override fun clear(): PersistentSet {
        return PersistentHashSet.emptyOf()
    }

    override fun iterator(): Iterator {
        return PersistentHashSetIterator(node)
    }

    override fun builder(): PersistentSet.Builder {
        return PersistentHashSetBuilder(this)
    }

    internal companion object {
        private val EMPTY = PersistentHashSet(TrieNode.EMPTY, 0)
        internal fun  emptyOf(): PersistentSet = PersistentHashSet.EMPTY
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy