aboutsummaryrefslogtreecommitdiffstats
path: root/utils/Collections/ConcurrentSet.cs
blob: 3fec14f2acf434f421bcee828c5f7e892b369fd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/***************************************************************************************************
 Copyright (C) 2025 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

using System.Collections;
using System.Collections.Concurrent;

namespace Qt.DotNet.Utils.Collections.Concurrent
{
    public class ConcurrentSet<T> : IReadOnlyCollection<T>
    {
        private ConcurrentDictionary<T, bool> Items { get; }
        public ConcurrentSet(IEqualityComparer<T> comparer = null)
        {
            Items = new ConcurrentDictionary<T, bool>(comparer ?? EqualityComparer<T>.Default);
        }
        public bool Add(T item) => Items.TryAdd(item, true);
        public bool Remove(T item) => Items.TryRemove(item, out _);
        public void Clear() => Items.Clear();

        public int Count => Items.Count;
        public bool Contains(T item) => Items.ContainsKey(item);

        public IEnumerator<T> GetEnumerator() => Items.Keys.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => Items.Keys.GetEnumerator();
    }
}