modernuo/Projects/Server/Collections/OrderedSet.cs
Kamron Batman 4ea1d79cad
fix: Removes broken OrderedHashSet and adds a simple OrderedSet (#1756)
> [!CAUTION]
> **BREAKING CHANGE**
> Removed `OrderdHashSet` and `PooledOrderedHashSet` due to bugs.

> [!NOTE]
> **Developer Note**
> The OrderedSet is not a full data structure. It is not particularly efficient. Pull Requests are welcome for a better implementation, especially if it ends up supporting `ISet<T>` and `IReadOnlySet<T>`

## Summary

The ordered hash set was buggy. It's kind of painful to implement, so for now, I added a simple `OrderedSet` to suffice for gumps. Please reach out if this causes disruption!
2024-05-03 18:03:26 -07:00

62 lines
2.3 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2024 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: OrderedSet.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Server.Collections;
/// <summary>
/// A data structure designed for scenarios where the order of insertion is important.
/// Note: This is not particularly effecient.
/// </summary>
/// <typeparam name="T">The type of elements in the set.</typeparam>
public class OrderedSet<T>
{
private readonly Dictionary<T, int> _dictionary;
private readonly List<T> _list;
public OrderedSet(IEqualityComparer<T> comparer = null)
{
_dictionary = new Dictionary<T, int>(comparer);
_list = [];
}
public int Count => _dictionary.Count;
public int Add(T value)
{
ref var order = ref CollectionsMarshal.GetValueRefOrAddDefault(_dictionary, value, out var exists);
if (exists)
{
return order;
}
_list.Add(value);
return order = _list.Count - 1;
}
public bool Contains(T value) => _dictionary.ContainsKey(value);
public void Clear()
{
_dictionary.Clear();
_list.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public List<T>.Enumerator GetEnumerator() => _list.GetEnumerator();
}