From 96de1fdaa152dc854122b1e3aee98acbedfee463 Mon Sep 17 00:00:00 2001 From: Kamron Batman <3953314+kamronbatman@users.noreply.github.com> Date: Sun, 7 Jul 2024 12:09:13 -0700 Subject: [PATCH] fix: Fixes NPE in PooledRefList sort (#1864) --- Projects/Server/Collections/PooledRefList.cs | 32 ++++++++------------ 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/Projects/Server/Collections/PooledRefList.cs b/Projects/Server/Collections/PooledRefList.cs index 27eba2be1..8aff2f7b3 100644 --- a/Projects/Server/Collections/PooledRefList.cs +++ b/Projects/Server/Collections/PooledRefList.cs @@ -6,6 +6,7 @@ using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using Server.Buffers; namespace Server.Collections; @@ -946,13 +947,16 @@ public ref struct PooledRefList _version++; } - // Sorts the elements in this list. Uses the default comparer and - // Array.Sort. - public void Sort() => Sort(0, Count, null); - // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. - public void Sort(IComparer? comparer) => Sort(0, Count, comparer); + public void Sort(IComparer? comparer = null) + { + if (_size > 1) + { + Array.Sort(_items, 0, _size, comparer); + } + _version++; + } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If @@ -964,15 +968,8 @@ public ref struct PooledRefList // public void Sort(int index, int count, IComparer? comparer) { - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_size - index < count) { @@ -988,14 +985,11 @@ public ref struct PooledRefList public void Sort(Comparison comparison) { - if (comparison == null) - { - throw new ArgumentNullException(nameof(comparison)); - } + ArgumentNullException.ThrowIfNull(comparison); if (_size > 1) { - Array.Sort(_items, comparison); + _items.AsSpan(0, _size).Sort(comparison); } _version++; }