fix: Updates ArrayPool to STArrayPool for performance. (#968)

This commit is contained in:
Kamron Batman 2022-03-22 20:07:32 -07:00 • committed by GitHub
parent 76fddcbccd
commit 14b63ca48e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 3163 additions and 3165 deletions

View file

@ -11,7 +11,7 @@ namespace Server.Tests.Network
{ {
private async void DelayedExecute(Action action) private async void DelayedExecute(Action action)
{ {
await Task.Delay(5); await Task.Delay(1);
action(); action();
} }
@ -130,8 +130,12 @@ namespace Server.Tests.Network
continue; continue;
} }
result.CopyFrom(new[] { expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, result.CopyFrom(new[] {
expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value }); expected_value, expected_value, expected_value, expected_value,
expected_value, expected_value, expected_value, expected_value,
expected_value, expected_value, expected_value, expected_value,
expected_value, expected_value, expected_value, expected_value
});
writer.Advance(16); writer.Advance(16);
count += 16; count += 16;

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright 2019-2020 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: SpanWriter.cs * * File: SpanWriter.cs *
* * * *
@ -22,40 +22,41 @@ using System.Runtime.InteropServices;
using System.Text; using System.Text;
using Microsoft.Toolkit.HighPerformance; using Microsoft.Toolkit.HighPerformance;
using Server; using Server;
using Server.Buffers;
using Server.Text; using Server.Text;
namespace System.Buffers namespace System.Buffers;
public ref struct SpanWriter
{ {
public ref struct SpanWriter private readonly bool _resize;
private byte[] _arrayToReturnToPool;
private Span<byte> _buffer;
private int _position;
public int BytesWritten { get; private set; }
public int Position
{ {
private readonly bool _resize; get => _position;
private byte[] _arrayToReturnToPool; private set
private Span<byte> _buffer;
private int _position;
public int BytesWritten { get; private set; }
public int Position
{ {
get => _position; _position = value;
private set
{
_position = value;
if (value > BytesWritten) if (value > BytesWritten)
{ {
BytesWritten = value; BytesWritten = value;
}
} }
} }
}
public int Capacity => _buffer.Length; public int Capacity => _buffer.Length;
public ReadOnlySpan<byte> Span => _buffer[..Position]; public ReadOnlySpan<byte> Span => _buffer[..Position];
public Span<byte> RawBuffer => _buffer; public Span<byte> RawBuffer => _buffer;
/** /**
* Converts the writer to a Span<byte> using a SpanOwner. * Converts the writer to a Span<byte> using a SpanOwner.
* If the buffer was stackalloc, it will be copied to a rented buffer. * If the buffer was stackalloc, it will be copied to a rented buffer.
* Otherwise the existing rented buffer is used. * Otherwise the existing rented buffer is used.
@ -64,395 +65,394 @@ namespace System.Buffers
* Do not use the SpanWriter after calling this method. * Do not use the SpanWriter after calling this method.
* This method will effectively dispose of the SpanWriter and is therefore considered terminal. * This method will effectively dispose of the SpanWriter and is therefore considered terminal.
*/ */
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public SpanOwner ToSpan() public SpanOwner ToSpan()
{
var toReturn = _arrayToReturnToPool;
SpanOwner apo;
if (_position == 0)
{ {
var toReturn = _arrayToReturnToPool; apo = new SpanOwner(_position, Array.Empty<byte>());
SpanOwner apo;
if (_position == 0)
{
apo = new SpanOwner(_position, Array.Empty<byte>());
if (toReturn != null)
{
ArrayPool<byte>.Shared.Return(toReturn);
}
}
else if (toReturn != null)
{
apo = new SpanOwner(_position, toReturn);
}
else
{
var buffer = ArrayPool<byte>.Shared.Rent(_position);
_buffer.CopyTo(buffer);
apo = new SpanOwner(_position, buffer);
}
this = default; // Don't allow two references to the same buffer
return apo;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SpanWriter(Span<byte> initialBuffer, bool resize = false)
{
_resize = resize;
_buffer = initialBuffer;
_position = 0;
BytesWritten = 0;
_arrayToReturnToPool = null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SpanWriter(int initialCapacity, bool resize = false)
{
_resize = resize;
_arrayToReturnToPool = ArrayPool<byte>.Shared.Rent(initialCapacity);
_buffer = _arrayToReturnToPool;
_position = 0;
BytesWritten = 0;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacity)
{
var newSize = Math.Max(BytesWritten + additionalCapacity, _buffer.Length * 2);
byte[] poolArray = ArrayPool<byte>.Shared.Rent(newSize);
_buffer[..BytesWritten].CopyTo(poolArray);
byte[] toReturn = _arrayToReturnToPool;
_buffer = _arrayToReturnToPool = poolArray;
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
else if (toReturn != null)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void GrowIfNeeded(int count)
{ {
if (_position + count > _buffer.Length) apo = new SpanOwner(_position, toReturn);
}
else
{
var buffer = STArrayPool<byte>.Shared.Rent(_position);
_buffer.CopyTo(buffer);
apo = new SpanOwner(_position, buffer);
}
this = default; // Don't allow two references to the same buffer
return apo;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SpanWriter(Span<byte> initialBuffer, bool resize = false)
{
_resize = resize;
_buffer = initialBuffer;
_position = 0;
BytesWritten = 0;
_arrayToReturnToPool = null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SpanWriter(int initialCapacity, bool resize = false)
{
_resize = resize;
_arrayToReturnToPool = STArrayPool<byte>.Shared.Rent(initialCapacity);
_buffer = _arrayToReturnToPool;
_position = 0;
BytesWritten = 0;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacity)
{
var newSize = Math.Max(BytesWritten + additionalCapacity, _buffer.Length * 2);
byte[] poolArray = STArrayPool<byte>.Shared.Rent(newSize);
_buffer[..BytesWritten].CopyTo(poolArray);
byte[] toReturn = _arrayToReturnToPool;
_buffer = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
STArrayPool<byte>.Shared.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void GrowIfNeeded(int count)
{
if (_position + count > _buffer.Length)
{
if (!_resize)
{ {
if (!_resize) throw new OutOfMemoryException();
{
throw new OutOfMemoryException();
}
Grow(count);
}
}
public ref byte GetPinnableReference() => ref MemoryMarshal.GetReference(_buffer);
public void EnsureCapacity(int capacity)
{
if (capacity > _buffer.Length)
{
if (!_resize)
{
throw new OutOfMemoryException();
}
Grow(capacity - BytesWritten);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Write(bool value)
{
GrowIfNeeded(1);
_buffer[Position++] = *(byte*)&value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(byte value)
{
GrowIfNeeded(1);
_buffer[Position++] = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(sbyte value)
{
GrowIfNeeded(1);
_buffer[Position++] = (byte)value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(short value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteInt16BigEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(short value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteInt16LittleEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ushort value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteUInt16BigEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(ushort value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteUInt16LittleEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(int value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteInt32BigEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(int value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteInt32LittleEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(uint value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteUInt32BigEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(Serial serial) => Write(serial.Value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(uint value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteUInt32LittleEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(long value)
{
GrowIfNeeded(8);
BinaryPrimitives.WriteInt64BigEndian(_buffer[_position..], value);
Position += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ulong value)
{
GrowIfNeeded(8);
BinaryPrimitives.WriteUInt64BigEndian(_buffer[_position..], value);
Position += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ReadOnlySpan<byte> buffer)
{
var count = buffer.Length;
GrowIfNeeded(count);
buffer.CopyTo(_buffer[_position..]);
Position += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAscii(char chr) => Write((byte)chr);
public void WriteString<T>(string value, Encoding encoding, int fixedLength = -1) where T : struct, IEquatable<T>
{
int sizeT = Unsafe.SizeOf<T>();
if (sizeT > 2)
{
throw new InvalidConstraintException("WriteString only accepts byte, sbyte, char, short, and ushort as a constraint");
} }
value ??= string.Empty; Grow(count);
}
}
var charLength = Math.Min(fixedLength > -1 ? fixedLength : value.Length, value.Length); public ref byte GetPinnableReference() => ref MemoryMarshal.GetReference(_buffer);
var src = value.AsSpan(0, charLength);
var byteCount = fixedLength > -1 ? fixedLength * sizeT : encoding.GetByteCount(value); public void EnsureCapacity(int capacity)
if (byteCount == 0) {
if (capacity > _buffer.Length)
{
if (!_resize)
{ {
return; throw new OutOfMemoryException();
} }
GrowIfNeeded(byteCount); Grow(capacity - BytesWritten);
}
}
var bytesWritten = encoding.GetBytes(src, _buffer[_position..]); [MethodImpl(MethodImplOptions.AggressiveInlining)]
Position += bytesWritten; public unsafe void Write(bool value)
{
GrowIfNeeded(1);
_buffer[Position++] = *(byte*)&value;
}
if (fixedLength > -1) [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(byte value)
{
GrowIfNeeded(1);
_buffer[Position++] = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(sbyte value)
{
GrowIfNeeded(1);
_buffer[Position++] = (byte)value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(short value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteInt16BigEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(short value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteInt16LittleEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ushort value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteUInt16BigEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(ushort value)
{
GrowIfNeeded(2);
BinaryPrimitives.WriteUInt16LittleEndian(_buffer[_position..], value);
Position += 2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(int value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteInt32BigEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(int value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteInt32LittleEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(uint value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteUInt32BigEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(Serial serial) => Write(serial.Value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLE(uint value)
{
GrowIfNeeded(4);
BinaryPrimitives.WriteUInt32LittleEndian(_buffer[_position..], value);
Position += 4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(long value)
{
GrowIfNeeded(8);
BinaryPrimitives.WriteInt64BigEndian(_buffer[_position..], value);
Position += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ulong value)
{
GrowIfNeeded(8);
BinaryPrimitives.WriteUInt64BigEndian(_buffer[_position..], value);
Position += 8;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(ReadOnlySpan<byte> buffer)
{
var count = buffer.Length;
GrowIfNeeded(count);
buffer.CopyTo(_buffer[_position..]);
Position += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAscii(char chr) => Write((byte)chr);
public void WriteString<T>(string value, Encoding encoding, int fixedLength = -1) where T : struct, IEquatable<T>
{
int sizeT = Unsafe.SizeOf<T>();
if (sizeT > 2)
{
throw new InvalidConstraintException("WriteString only accepts byte, sbyte, char, short, and ushort as a constraint");
}
value ??= string.Empty;
var charLength = Math.Min(fixedLength > -1 ? fixedLength : value.Length, value.Length);
var src = value.AsSpan(0, charLength);
var byteCount = fixedLength > -1 ? fixedLength * sizeT : encoding.GetByteCount(value);
if (byteCount == 0)
{
return;
}
GrowIfNeeded(byteCount);
var bytesWritten = encoding.GetBytes(src, _buffer[_position..]);
Position += bytesWritten;
if (fixedLength > -1)
{
var extra = fixedLength * sizeT - bytesWritten;
if (extra > 0)
{ {
var extra = fixedLength * sizeT - bytesWritten; Clear(extra);
if (extra > 0)
{
Clear(extra);
}
} }
} }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLittleUni(string value) => WriteString<char>(value, TextEncoding.UnicodeLE); public void WriteLittleUni(string value) => WriteString<char>(value, TextEncoding.UnicodeLE);
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLittleUniNull(string value) public void WriteLittleUniNull(string value)
{
WriteString<char>(value, TextEncoding.UnicodeLE);
Write((ushort)0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteLittleUni(string value, int fixedLength) => WriteString<char>(value, TextEncoding.UnicodeLE, fixedLength);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBigUni(string value) => WriteString<char>(value, TextEncoding.Unicode);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBigUniNull(string value)
{
WriteString<char>(value, TextEncoding.Unicode);
Write((ushort)0); // '\0'
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBigUni(string value, int fixedLength) => WriteString<char>(value, TextEncoding.Unicode, fixedLength);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUTF8(string value) => WriteString<byte>(value, TextEncoding.UTF8);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUTF8Null(string value)
{
WriteString<byte>(value, TextEncoding.UTF8);
Write((byte)0); // '\0'
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAscii(string value) => WriteString<byte>(value, Encoding.ASCII);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAsciiNull(string value)
{
WriteString<byte>(value, Encoding.ASCII);
Write((byte)0); // '\0'
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAscii(string value, int fixedLength) => WriteString<byte>(value, Encoding.ASCII, fixedLength);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear(int count)
{
GrowIfNeeded(count);
_buffer.Slice(_position, count).Clear();
Position += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Seek(int offset, SeekOrigin origin)
{
Debug.Assert(
origin != SeekOrigin.End || _resize || offset <= 0,
"Attempting to seek to a position beyond capacity using SeekOrigin.End without resize"
);
Debug.Assert(
origin != SeekOrigin.End || offset >= -_buffer.Length,
"Attempting to seek to a negative position using SeekOrigin.End"
);
Debug.Assert(
origin != SeekOrigin.Begin || offset >= 0,
"Attempting to seek to a negative position using SeekOrigin.Begin"
);
Debug.Assert(
origin != SeekOrigin.Begin || _resize || offset <= _buffer.Length,
"Attempting to seek to a position beyond the capacity using SeekOrigin.Begin without resize"
);
Debug.Assert(
origin != SeekOrigin.Current || _position + offset >= 0,
"Attempting to seek to a negative position using SeekOrigin.Current"
);
Debug.Assert(
origin != SeekOrigin.Current || _resize || _position + offset <= _buffer.Length,
"Attempting to seek to a position beyond the capacity using SeekOrigin.Current without resize"
);
var newPosition = Math.Max(0, origin switch
{ {
WriteString<char>(value, TextEncoding.UnicodeLE); SeekOrigin.Current => _position + offset,
Write((ushort)0); SeekOrigin.End => BytesWritten + offset,
_ => offset // Begin
});
if (newPosition >= _buffer.Length)
{
Grow(newPosition - _buffer.Length + 1);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] return Position = newPosition;
public void WriteLittleUni(string value, int fixedLength) => WriteString<char>(value, TextEncoding.UnicodeLE, fixedLength); }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBigUni(string value) => WriteString<char>(value, TextEncoding.Unicode); public void Dispose()
{
[MethodImpl(MethodImplOptions.AggressiveInlining)] byte[] toReturn = _arrayToReturnToPool;
public void WriteBigUniNull(string value) this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null)
{ {
WriteString<char>(value, TextEncoding.Unicode); STArrayPool<byte>.Shared.Return(toReturn);
Write((ushort)0); // '\0' }
}
public struct SpanOwner : IDisposable
{
private readonly int _length;
private readonly byte[] _arrayToReturnToPool;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal SpanOwner(int length, byte[] buffer)
{
_length = length;
_arrayToReturnToPool = buffer;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<byte> Span
public void WriteBigUni(string value, int fixedLength) => WriteString<char>(value, TextEncoding.Unicode, fixedLength);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUTF8(string value) => WriteString<byte>(value, TextEncoding.UTF8);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUTF8Null(string value)
{ {
WriteString<byte>(value, TextEncoding.UTF8); [MethodImpl(MethodImplOptions.AggressiveInlining)]
Write((byte)0); // '\0' get => MemoryMarshal.CreateSpan(ref _arrayToReturnToPool.DangerousGetReference(), _length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAscii(string value) => WriteString<byte>(value, Encoding.ASCII);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAsciiNull(string value)
{
WriteString<byte>(value, Encoding.ASCII);
Write((byte)0); // '\0'
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteAscii(string value, int fixedLength) => WriteString<byte>(value, Encoding.ASCII, fixedLength);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear(int count)
{
GrowIfNeeded(count);
_buffer.Slice(_position, count).Clear();
Position += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Seek(int offset, SeekOrigin origin)
{
Debug.Assert(
origin != SeekOrigin.End || _resize || offset <= 0,
"Attempting to seek to a position beyond capacity using SeekOrigin.End without resize"
);
Debug.Assert(
origin != SeekOrigin.End || offset >= -_buffer.Length,
"Attempting to seek to a negative position using SeekOrigin.End"
);
Debug.Assert(
origin != SeekOrigin.Begin || offset >= 0,
"Attempting to seek to a negative position using SeekOrigin.Begin"
);
Debug.Assert(
origin != SeekOrigin.Begin || _resize || offset <= _buffer.Length,
"Attempting to seek to a position beyond the capacity using SeekOrigin.Begin without resize"
);
Debug.Assert(
origin != SeekOrigin.Current || _position + offset >= 0,
"Attempting to seek to a negative position using SeekOrigin.Current"
);
Debug.Assert(
origin != SeekOrigin.Current || _resize || _position + offset <= _buffer.Length,
"Attempting to seek to a position beyond the capacity using SeekOrigin.Current without resize"
);
var newPosition = Math.Max(0, origin switch
{
SeekOrigin.Current => _position + offset,
SeekOrigin.End => BytesWritten + offset,
_ => offset // Begin
});
if (newPosition >= _buffer.Length)
{
Grow(newPosition - _buffer.Length + 1);
}
return Position = newPosition;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose() public void Dispose()
{ {
byte[] toReturn = _arrayToReturnToPool; byte[] toReturn = _arrayToReturnToPool;
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again this = default;
if (toReturn != null) if (_length > 0)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
}
}
public struct SpanOwner : IDisposable
{
private readonly int _length;
private readonly byte[] _arrayToReturnToPool;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal SpanOwner(int length, byte[] buffer)
{
_length = length;
_arrayToReturnToPool = buffer;
}
public Span<byte> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => MemoryMarshal.CreateSpan(ref _arrayToReturnToPool.DangerousGetReference(), _length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
byte[] toReturn = _arrayToReturnToPool;
this = default;
if (_length > 0)
{
ArrayPool<byte>.Shared.Return(toReturn);
}
} }
} }
} }

View file

@ -2,473 +2,471 @@
// The .NET Foundation licenses this file to you under the MIT license. // The .NET Foundation licenses this file to you under the MIT license.
using System; using System;
using System.Buffers;
using System.Globalization; using System.Globalization;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Server.Buffers namespace Server.Buffers;
public ref struct ValueStringBuilder
{ {
public ref struct ValueStringBuilder private char[] _arrayToReturnToPool;
private Span<char> _chars;
private int _length;
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace.
public ValueStringBuilder(ReadOnlySpan<char> initialString) : this(initialString.Length)
{ {
private char[] _arrayToReturnToPool; Append(initialString);
private Span<char> _chars; }
private int _length;
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace. public ValueStringBuilder(ReadOnlySpan<char> initialString, Span<char> initialBuffer) : this(initialBuffer)
public ValueStringBuilder(ReadOnlySpan<char> initialString) : this(initialString.Length) {
Append(initialString);
}
public ValueStringBuilder(Span<char> initialBuffer)
{
_arrayToReturnToPool = null;
_chars = initialBuffer;
_length = 0;
}
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace.
public ValueStringBuilder(int initialCapacity)
{
_arrayToReturnToPool = STArrayPool<char>.Shared.Rent(initialCapacity);
_chars = _arrayToReturnToPool;
_length = 0;
}
public int Length => _length;
public int Capacity => _chars.Length;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_length = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnsureCapacity(int capacity)
{
if (capacity > _chars.Length)
{ {
Append(initialString); Grow(capacity - Length);
}
public ValueStringBuilder(ReadOnlySpan<char> initialString, Span<char> initialBuffer) : this(initialBuffer)
{
Append(initialString);
}
public ValueStringBuilder(Span<char> initialBuffer)
{
_arrayToReturnToPool = null;
_chars = initialBuffer;
_length = 0;
}
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace.
public ValueStringBuilder(int initialCapacity)
{
_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
_chars = _arrayToReturnToPool;
_length = 0;
}
public int Length => _length;
public int Capacity => _chars.Length;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_length = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnsureCapacity(int capacity)
{
if (capacity > _chars.Length)
{
Grow(capacity - Length);
}
}
/// <summary>
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// </summary>
public ref char GetPinnableReference() => ref MemoryMarshal.GetReference(_chars);
/// <summary>
/// Get a pinnable reference to the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ref char GetPinnableReference(bool terminate)
{
if (terminate)
{
EnsureCapacity(_length + 1);
_chars[_length] = '\0';
}
return ref MemoryMarshal.GetReference(_chars);
}
public ref char this[int index] => ref _chars[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() => _chars[.._length].ToString();
/// <summary>Returns the underlying storage of the builder.</summary>
public Span<char> RawChars => _chars;
/// <summary>
/// Returns a span around the contents of the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ReadOnlySpan<char> AsSpan(bool terminate)
{
if (terminate)
{
EnsureCapacity(_length + 1);
_chars[_length] = '\0';
}
return _chars[.._length];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan() => _chars[.._length];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan(int start) => _chars[start..];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryCopyTo(Span<char> destination, out int charsWritten)
{
if (_chars[.._length].TryCopyTo(destination))
{
charsWritten = _length;
return true;
}
charsWritten = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, char value, int count)
{
if (_length > _chars.Length - count)
{
Grow(count);
}
int remaining = _length - index;
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
_chars.Slice(index, count).Fill(value);
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, string s)
{
if (s == null)
{
return;
}
int count = s.Length;
if (_length > _chars.Length - count)
{
Grow(count);
}
int remaining = _length - index;
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
s.AsSpan().CopyTo(_chars[index..]);
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c)
{
int pos = _length;
if ((uint)pos < (uint)_chars.Length)
{
_chars[pos] = c;
_length = pos + 1;
}
else
{
GrowAndAppend(c);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(int value, NumberFormatInfo info = null)
{
if (value >= 0)
{
Append((uint)value);
return;
}
Append((info ?? NumberFormatInfo.CurrentInfo).NegativeSign);
Append((uint)-value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Append(uint value)
{
int bufferLength = value.CountDigits();
int pos = _length;
if ((uint)pos + (uint)bufferLength >= _chars.Length)
{
Grow(bufferLength);
}
if (bufferLength == 1)
{
_chars[pos] = (char)(value + '0');
_length = pos + 1;
return;
}
fixed (char* buffer = _chars[pos..])
{
char* p = buffer + bufferLength;
do
{
value = Utility.DivRem(value, 10, out uint remainder);
*--p = (char)(remainder + '0');
} while (value != 0);
}
_length = pos + bufferLength;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(string s)
{
if (s == null)
{
return;
}
int pos = _length;
if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
{
_chars[pos] = s[0];
_length = pos + 1;
}
else
{
AppendSlow(s);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AppendLine(string s)
{
if (s == null)
{
return;
}
// very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
if (s.Length == 1)
{
Append(s[0]);
}
else
{
AppendSlow(s);
}
Append(Environment.NewLine);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AppendSlow(string s)
{
int pos = _length;
if (pos > _chars.Length - s.Length)
{
Grow(s.Length);
}
s.AsSpan().CopyTo(_chars[pos..]);
_length += s.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c, int count)
{
if (_length > _chars.Length - count)
{
Grow(count);
}
Span<char> dst = _chars.Slice(_length, count);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = c;
}
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Append(char* value, int length)
{
int pos = _length;
if (pos > _chars.Length - length)
{
Grow(length);
}
Span<char> dst = _chars.Slice(_length, length);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = *value++;
}
_length += length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(ReadOnlySpan<char> value)
{
int pos = _length;
if (pos > _chars.Length - value.Length)
{
Grow(value.Length);
}
value.CopyTo(_chars[_length..]);
_length += value.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<char> AppendSpan(int length)
{
int origPos = _length;
if (origPos > _chars.Length - length)
{
Grow(length);
}
_length = origPos + length;
return _chars.Slice(origPos, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowAndAppend(char c)
{
Grow(1);
Append(c);
}
#nullable enable
/// <summary>
/// Resize the internal buffer either by doubling current buffer size or
/// by adding <paramref name="additionalCapacityBeyondPos"/> to
/// <see cref="Length"/> whichever is greater.
/// </summary>
/// <param name="additionalCapacityBeyondPos">
/// Number of chars requested beyond current position.
/// </param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacityBeyondPos)
{
char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_length + additionalCapacityBeyondPos, _chars.Length * 2));
_chars[.._length].CopyTo(poolArray);
char[] toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
char[] toReturn = _arrayToReturnToPool;
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
#nullable restore
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReplaceAny(ReadOnlySpan<char> oldChars, ReadOnlySpan<char> newChars, int startIndex, int count)
{
int currentLength = _length;
if ((uint)startIndex > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (count < 0 || startIndex > currentLength - count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var slice = _chars;
while (true)
{
var indexOf = slice.IndexOfAny(oldChars);
if (indexOf == -1)
{
break;
}
var chr = slice[indexOf];
slice[indexOf] = newChars[oldChars.IndexOf(chr)];
slice = slice[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Replace(char oldChar, char newChar, int startIndex, int count)
{
int currentLength = _length;
if ((uint)startIndex > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (count < 0 || startIndex > currentLength - count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var slice = _chars;
while (true)
{
var indexOf = slice.IndexOf(oldChar);
if (indexOf == -1)
{
break;
}
slice[indexOf] = newChar;
slice = slice[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Remove(int startIndex, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (length > _length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (startIndex == 0)
{
_chars = _chars[length..];
}
else if (startIndex + length == _length)
{
_chars = _chars[..startIndex];
}
else
{
// Somewhere in the middle, this will be slow
_chars[(startIndex + length)..].CopyTo(_chars[startIndex..]);
}
_length -= length;
} }
} }
/// <summary>
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// </summary>
public ref char GetPinnableReference() => ref MemoryMarshal.GetReference(_chars);
/// <summary>
/// Get a pinnable reference to the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ref char GetPinnableReference(bool terminate)
{
if (terminate)
{
EnsureCapacity(_length + 1);
_chars[_length] = '\0';
}
return ref MemoryMarshal.GetReference(_chars);
}
public ref char this[int index] => ref _chars[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() => _chars[.._length].ToString();
/// <summary>Returns the underlying storage of the builder.</summary>
public Span<char> RawChars => _chars;
/// <summary>
/// Returns a span around the contents of the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ReadOnlySpan<char> AsSpan(bool terminate)
{
if (terminate)
{
EnsureCapacity(_length + 1);
_chars[_length] = '\0';
}
return _chars[.._length];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan() => _chars[.._length];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan(int start) => _chars[start..];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryCopyTo(Span<char> destination, out int charsWritten)
{
if (_chars[.._length].TryCopyTo(destination))
{
charsWritten = _length;
return true;
}
charsWritten = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, char value, int count)
{
if (_length > _chars.Length - count)
{
Grow(count);
}
int remaining = _length - index;
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
_chars.Slice(index, count).Fill(value);
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, string s)
{
if (s == null)
{
return;
}
int count = s.Length;
if (_length > _chars.Length - count)
{
Grow(count);
}
int remaining = _length - index;
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
s.AsSpan().CopyTo(_chars[index..]);
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c)
{
int pos = _length;
if ((uint)pos < (uint)_chars.Length)
{
_chars[pos] = c;
_length = pos + 1;
}
else
{
GrowAndAppend(c);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(int value, NumberFormatInfo info = null)
{
if (value >= 0)
{
Append((uint)value);
return;
}
Append((info ?? NumberFormatInfo.CurrentInfo).NegativeSign);
Append((uint)-value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Append(uint value)
{
int bufferLength = value.CountDigits();
int pos = _length;
if ((uint)pos + (uint)bufferLength >= _chars.Length)
{
Grow(bufferLength);
}
if (bufferLength == 1)
{
_chars[pos] = (char)(value + '0');
_length = pos + 1;
return;
}
fixed (char* buffer = _chars[pos..])
{
char* p = buffer + bufferLength;
do
{
value = Utility.DivRem(value, 10, out uint remainder);
*--p = (char)(remainder + '0');
} while (value != 0);
}
_length = pos + bufferLength;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(string s)
{
if (s == null)
{
return;
}
int pos = _length;
if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
{
_chars[pos] = s[0];
_length = pos + 1;
}
else
{
AppendSlow(s);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AppendLine(string s)
{
if (s == null)
{
return;
}
// very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
if (s.Length == 1)
{
Append(s[0]);
}
else
{
AppendSlow(s);
}
Append(Environment.NewLine);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AppendSlow(string s)
{
int pos = _length;
if (pos > _chars.Length - s.Length)
{
Grow(s.Length);
}
s.AsSpan().CopyTo(_chars[pos..]);
_length += s.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c, int count)
{
if (_length > _chars.Length - count)
{
Grow(count);
}
Span<char> dst = _chars.Slice(_length, count);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = c;
}
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Append(char* value, int length)
{
int pos = _length;
if (pos > _chars.Length - length)
{
Grow(length);
}
Span<char> dst = _chars.Slice(_length, length);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = *value++;
}
_length += length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(ReadOnlySpan<char> value)
{
int pos = _length;
if (pos > _chars.Length - value.Length)
{
Grow(value.Length);
}
value.CopyTo(_chars[_length..]);
_length += value.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<char> AppendSpan(int length)
{
int origPos = _length;
if (origPos > _chars.Length - length)
{
Grow(length);
}
_length = origPos + length;
return _chars.Slice(origPos, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowAndAppend(char c)
{
Grow(1);
Append(c);
}
#nullable enable
/// <summary>
/// Resize the internal buffer either by doubling current buffer size or
/// by adding <paramref name="additionalCapacityBeyondPos"/> to
/// <see cref="Length"/> whichever is greater.
/// </summary>
/// <param name="additionalCapacityBeyondPos">
/// Number of chars requested beyond current position.
/// </param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacityBeyondPos)
{
char[] poolArray = STArrayPool<char>.Shared.Rent(Math.Max(_length + additionalCapacityBeyondPos, _chars.Length * 2));
_chars[.._length].CopyTo(poolArray);
char[] toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
STArrayPool<char>.Shared.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
char[] toReturn = _arrayToReturnToPool;
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null)
{
STArrayPool<char>.Shared.Return(toReturn);
}
}
#nullable restore
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReplaceAny(ReadOnlySpan<char> oldChars, ReadOnlySpan<char> newChars, int startIndex, int count)
{
int currentLength = _length;
if ((uint)startIndex > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (count < 0 || startIndex > currentLength - count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var slice = _chars;
while (true)
{
var indexOf = slice.IndexOfAny(oldChars);
if (indexOf == -1)
{
break;
}
var chr = slice[indexOf];
slice[indexOf] = newChars[oldChars.IndexOf(chr)];
slice = slice[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Replace(char oldChar, char newChar, int startIndex, int count)
{
int currentLength = _length;
if ((uint)startIndex > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (count < 0 || startIndex > currentLength - count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var slice = _chars;
while (true)
{
var indexOf = slice.IndexOf(oldChar);
if (indexOf == -1)
{
break;
}
slice[indexOf] = newChar;
slice = slice[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Remove(int startIndex, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (length > _length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (startIndex == 0)
{
_chars = _chars[length..];
}
else if (startIndex + length == _length)
{
_chars = _chars[..startIndex];
}
else
{
// Somewhere in the middle, this will be slow
_chars[(startIndex + length)..].CopyTo(_chars[startIndex..]);
}
_length -= length;
}
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: OutgoingGumpPackets.cs * * File: OutgoingGumpPackets.cs *
* * * *
@ -18,6 +18,7 @@ using System.Buffers;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Server.Buffers;
using Server.Collections; using Server.Collections;
using Server.Gumps; using Server.Gumps;
using Server.Logging; using Server.Logging;
@ -68,7 +69,7 @@ public static class OutgoingGumpPackets
if (wantLength > packBuffer.Length) if (wantLength > packBuffer.Length)
{ {
packBuffer = rentedBuffer = ArrayPool<byte>.Shared.Rent(wantLength); packBuffer = rentedBuffer = STArrayPool<byte>.Shared.Rent(wantLength);
} }
var packLength = wantLength; var packLength = wantLength;
@ -90,7 +91,7 @@ public static class OutgoingGumpPackets
if (rentedBuffer != null) if (rentedBuffer != null)
{ {
ArrayPool<byte>.Shared.Return(rentedBuffer); STArrayPool<byte>.Shared.Return(rentedBuffer);
} }
} }

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright (C) 2019-2021 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: PacketContainerBuilder.cs * * File: PacketContainerBuilder.cs *
* * * *
@ -14,9 +14,9 @@
*************************************************************************/ *************************************************************************/
using System; using System;
using System.Buffers;
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Server.Buffers;
namespace Server.Network; namespace Server.Network;
@ -89,7 +89,7 @@ public ref struct PacketContainerBuilder
private void Grow(int additionalCapacityBeyondPos) private void Grow(int additionalCapacityBeyondPos)
{ {
var newLength = Math.Max(Length + additionalCapacityBeyondPos, _bytes.Length * 2); var newLength = Math.Max(Length + additionalCapacityBeyondPos, _bytes.Length * 2);
byte[] poolArray = ArrayPool<byte>.Shared.Rent(newLength); byte[] poolArray = STArrayPool<byte>.Shared.Rent(newLength);
_bytes[..Length].CopyTo(poolArray); _bytes[..Length].CopyTo(poolArray);
@ -97,7 +97,7 @@ public ref struct PacketContainerBuilder
_bytes = _arrayToReturnToPool = poolArray; _bytes = _arrayToReturnToPool = poolArray;
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
@ -108,7 +108,7 @@ public ref struct PacketContainerBuilder
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
} }

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: StringHelpers.cs * * File: StringHelpers.cs *
* * * *
@ -14,276 +14,275 @@
*************************************************************************/ *************************************************************************/
using System; using System;
using System.Buffers;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Server.Buffers;
namespace Server namespace Server;
public static class StringHelpers
{ {
public static class StringHelpers [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string DefaultIfNullOrEmpty(this string value, string def) =>
string.IsNullOrWhiteSpace(value) ? def : value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Remove(
this ReadOnlySpan<char> a,
ReadOnlySpan<char> b,
StringComparison comparison,
Span<char> buffer,
out int size
)
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] size = 0;
public static string DefaultIfNullOrEmpty(this string value, string def) => if (a == null || a.Length == 0)
string.IsNullOrWhiteSpace(value) ? def : value;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Remove(
this ReadOnlySpan<char> a,
ReadOnlySpan<char> b,
StringComparison comparison,
Span<char> buffer,
out int size
)
{ {
size = 0; return;
if (a == null || a.Length == 0) }
var sliced = a;
while (true)
{
var indexOf = sliced.IndexOf(b, comparison);
if (indexOf == -1)
{ {
return; indexOf = sliced.Length;
} }
var sliced = a; if (size + indexOf > buffer.Length)
while (true)
{ {
var indexOf = sliced.IndexOf(b, comparison); throw new OutOfMemoryException(nameof(buffer));
if (indexOf == -1) }
{
indexOf = sliced.Length;
}
if (size + indexOf > buffer.Length) sliced[..indexOf].CopyTo(buffer[size..]);
{ size += indexOf;
throw new OutOfMemoryException(nameof(buffer));
}
sliced[..indexOf].CopyTo(buffer[size..]); if (indexOf == sliced.Length)
size += indexOf; {
break;
}
if (indexOf == sliced.Length) sliced = sliced[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Remove(this ReadOnlySpan<char> a, ReadOnlySpan<char> b, StringComparison comparison)
{
if (a == null)
{
return null;
}
if (a.Length == 0)
{
return "";
}
Span<char> span = a.Length < 1024 ? stackalloc char[a.Length] : null;
char[] chrs;
if (span == null)
{
chrs = STArrayPool<char>.Shared.Rent(a.Length);
span = chrs.AsSpan();
}
else
{
chrs = null;
}
a.Remove(b, comparison, span, out var size);
var str = span[..size].ToString();
if (chrs != null)
{
STArrayPool<char>.Shared.Return(chrs);
}
return str;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Capitalize(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
Span<char> span = value.Length < 1024 ? stackalloc char[value.Length] : null;
char[] chrs;
if (span == null)
{
chrs = STArrayPool<char>.Shared.Rent(value.Length);
span = chrs.AsSpan();
}
else
{
chrs = null;
}
var sliced = value.AsSpan();
// Copy over the previous span
sliced.CopyTo(span);
var index = 0;
while (true)
{
// Special case for titles - words that don't get capitalized
if (sliced.InsensitiveStartsWith("the "))
{
sliced = sliced[4..];
index += 4;
continue;
}
var indexOf = sliced.IndexOf(' ');
span[index] = char.ToUpperInvariant(sliced[0]);
if (indexOf == -1)
{
break;
}
if (indexOf == sliced.Length - 1)
{
break;
}
sliced = sliced[(indexOf + 1)..];
index += indexOf + 1;
}
var str = span.ToString();
if (chrs != null)
{
STArrayPool<char>.Shared.Return(chrs);
}
return str;
}
public static string TrimMultiline(this string str, string lineSeparator = "\n")
{
var parts = str.Split(lineSeparator);
for (var i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Trim();
}
return string.Join(lineSeparator, parts);
}
public static string IndentMultiline(this string str, string indent = "\t", string lineSeparator = "\n")
{
var parts = str.Split(lineSeparator);
for (var i = 0; i < parts.Length; i++)
{
parts[i] = $"{indent}{parts[i]}";
}
return string.Join(lineSeparator, parts);
}
public static List<string> Wrap(this string value, int perLine, int maxLines)
{
if ((value = value?.Trim() ?? "").Length <= 0)
{
return null;
}
var span = value.AsSpan();
var list = new List<string>(maxLines);
var lineLength = 0;
while (span.Length > 0)
{
var spaceIndex = span[lineLength..].IndexOf(' ');
if (spaceIndex == -1)
{
spaceIndex = span.Length - lineLength; // End of the string
}
var newLineLength = lineLength + spaceIndex;
// If the previous line is exactly perLine or not too long and we are at the end
if (newLineLength == perLine || newLineLength < perLine && newLineLength == span.Length)
{
list.Add(span[..newLineLength].ToString());
if (list.Count == maxLines || newLineLength == span.Length)
{ {
break; break;
} }
sliced = sliced[(indexOf + 1)..]; span = span[(newLineLength + 1)..];
lineLength = 0;
} }
} // We haven't hit perLine and are not sure if we can continue adding more words without going over
else if (newLineLength < perLine)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Remove(this ReadOnlySpan<char> a, ReadOnlySpan<char> b, StringComparison comparison)
{
if (a == null)
{ {
return null; lineLength = newLineLength + 1;
} }
// We already tried making the line longer, and it was too long, so fall back to the old line
if (a.Length == 0) else if (lineLength > 0 && lineLength <= perLine)
{ {
return ""; list.Add(span[..(lineLength - 1)].ToString());
} if (list.Count == maxLines)
{
break;
}
Span<char> span = a.Length < 1024 ? stackalloc char[a.Length] : null; span = span[lineLength..];
char[] chrs; lineLength = 0;
if (span == null)
{
chrs = ArrayPool<char>.Shared.Rent(a.Length);
span = chrs.AsSpan();
} }
// We have a really long single word with no spaces and have to forcibly break it up.
else else
{ {
chrs = null; lineLength = newLineLength;
} var index = 0;
a.Remove(b, comparison, span, out var size); while (index < lineLength)
var str = span[..size].ToString();
if (chrs != null)
{
ArrayPool<char>.Shared.Return(chrs);
}
return str;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Capitalize(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
Span<char> span = value.Length < 1024 ? stackalloc char[value.Length] : null;
char[] chrs;
if (span == null)
{
chrs = ArrayPool<char>.Shared.Rent(value.Length);
span = chrs.AsSpan();
}
else
{
chrs = null;
}
var sliced = value.AsSpan();
// Copy over the previous span
sliced.CopyTo(span);
var index = 0;
while (true)
{
// Special case for titles - words that don't get capitalized
if (sliced.InsensitiveStartsWith("the "))
{ {
sliced = sliced[4..]; lineLength -= perLine;
index += 4;
continue;
}
var indexOf = sliced.IndexOf(' '); var length = perLine - (span[index] == ' ' ? 1 : 0);
span[index] = char.ToUpperInvariant(sliced[0]); list.Add(span.Slice(index, length).ToString());
if (indexOf == -1)
{
break;
}
if (indexOf == sliced.Length - 1)
{
break;
}
sliced = sliced[(indexOf + 1)..];
index += indexOf + 1;
}
var str = span.ToString();
if (chrs != null)
{
ArrayPool<char>.Shared.Return(chrs);
}
return str;
}
public static string TrimMultiline(this string str, string lineSeparator = "\n")
{
var parts = str.Split(lineSeparator);
for (var i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Trim();
}
return string.Join(lineSeparator, parts);
}
public static string IndentMultiline(this string str, string indent = "\t", string lineSeparator = "\n")
{
var parts = str.Split(lineSeparator);
for (var i = 0; i < parts.Length; i++)
{
parts[i] = $"{indent}{parts[i]}";
}
return string.Join(lineSeparator, parts);
}
public static List<string> Wrap(this string value, int perLine, int maxLines)
{
if ((value = value?.Trim() ?? "").Length <= 0)
{
return null;
}
var span = value.AsSpan();
var list = new List<string>(maxLines);
var lineLength = 0;
while (span.Length > 0)
{
var spaceIndex = span[lineLength..].IndexOf(' ');
if (spaceIndex == -1)
{
spaceIndex = span.Length - lineLength; // End of the string
}
var newLineLength = lineLength + spaceIndex;
// If the previous line is exactly perLine or not too long and we are at the end
if (newLineLength == perLine || newLineLength < perLine && newLineLength == span.Length)
{
list.Add(span[..newLineLength].ToString());
if (list.Count == maxLines || newLineLength == span.Length)
{
break;
}
span = span[(newLineLength + 1)..];
lineLength = 0;
}
// We haven't hit perLine and are not sure if we can continue adding more words without going over
else if (newLineLength < perLine)
{
lineLength = newLineLength + 1;
}
// We already tried making the line longer, and it was too long, so fall back to the old line
else if (lineLength > 0 && lineLength <= perLine)
{
list.Add(span[..(lineLength - 1)].ToString());
if (list.Count == maxLines) if (list.Count == maxLines)
{ {
break; break;
} }
span = span[lineLength..]; index += perLine;
lineLength = 0;
} }
// We have a really long single word with no spaces and have to forcibly break it up.
else
{
lineLength = newLineLength;
var index = 0;
while (index < lineLength) span = span[(newLineLength - lineLength)..];
{
lineLength -= perLine;
var length = perLine - (span[index] == ' ' ? 1 : 0);
list.Add(span.Slice(index, length).ToString());
if (list.Count == maxLines)
{
break;
}
index += perLine;
}
span = span[(newLineLength - lineLength)..];
}
} }
return list;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] return list;
public static int IndexOfTerminator(this Span<byte> buffer, int sizeT) =>
sizeT switch
{
2 => MemoryMarshal.Cast<byte, char>(buffer).IndexOf((char)0) * 2,
4 => MemoryMarshal.Cast<byte, uint>(buffer).IndexOf((uint)0) * 4,
_ => buffer.IndexOf((byte)0)
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfTerminator(this ReadOnlySpan<byte> buffer, int sizeT) =>
sizeT switch
{
2 => MemoryMarshal.Cast<byte, char>(buffer).IndexOf((char)0) * 2,
4 => MemoryMarshal.Cast<byte, uint>(buffer).IndexOf((uint)0) * 4,
_ => buffer.IndexOf((byte)0)
};
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfTerminator(this Span<byte> buffer, int sizeT) =>
sizeT switch
{
2 => MemoryMarshal.Cast<byte, char>(buffer).IndexOf((char)0) * 2,
4 => MemoryMarshal.Cast<byte, uint>(buffer).IndexOf((uint)0) * 4,
_ => buffer.IndexOf((byte)0)
};
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfTerminator(this ReadOnlySpan<byte> buffer, int sizeT) =>
sizeT switch
{
2 => MemoryMarshal.Cast<byte, char>(buffer).IndexOf((char)0) * 2,
4 => MemoryMarshal.Cast<byte, uint>(buffer).IndexOf((uint)0) * 4,
_ => buffer.IndexOf((byte)0)
};
} }

View file

@ -1,118 +1,117 @@
using System; using System;
using System.Buffers; using Server.Buffers;
using Server.Collections; using Server.Collections;
namespace Server.Mobiles namespace Server.Mobiles;
public class BladeSpirits : BaseCreature
{ {
public class BladeSpirits : BaseCreature [Constructible]
public BladeSpirits() : base(AIType.AI_Melee)
{ {
[Constructible] Body = 574;
public BladeSpirits() : base(AIType.AI_Melee)
SetSpeed(0.5, 1.2);
SetStr(150);
SetDex(150);
SetInt(100);
SetHits(Core.SE ? 160 : 80);
SetStam(250);
SetMana(0);
SetDamage(10, 14);
SetDamageType(ResistanceType.Physical, 60);
SetDamageType(ResistanceType.Poison, 20);
SetDamageType(ResistanceType.Energy, 20);
SetResistance(ResistanceType.Physical, 30, 40);
SetResistance(ResistanceType.Fire, 40, 50);
SetResistance(ResistanceType.Cold, 30, 40);
SetResistance(ResistanceType.Poison, 100);
SetResistance(ResistanceType.Energy, 20, 30);
SetSkill(SkillName.MagicResist, 70.0);
SetSkill(SkillName.Tactics, 90.0);
SetSkill(SkillName.Wrestling, 90.0);
Fame = 0;
Karma = 0;
VirtualArmor = 40;
ControlSlots = Core.SE ? 2 : 1;
}
public BladeSpirits(Serial serial) : base(serial)
{
}
public override string CorpseName => "a blade spirit corpse";
public override bool DeleteCorpseOnDeath => Core.AOS;
public override bool IsHouseSummonable => true;
public override double DispelDifficulty => 0.0;
public override double DispelFocus => 20.0;
public override string DefaultName => "a blade spirit";
public override bool BleedImmune => true;
public override Poison PoisonImmune => Poison.Lethal;
public override double GetFightModeRanking(Mobile m, FightMode acqType, bool bPlayerOnly) =>
(m.Str + m.Skills.Tactics.Value) / Math.Max(GetDistanceToSqrt(m), 1.0);
public override int GetAngerSound() => 0x23A;
public override int GetAttackSound() => 0x3B8;
public override int GetHurtSound() => 0x23A;
public override void OnThink()
{
if (Core.SE && Summoned)
{ {
Body = 574; var eable = GetMobilesInRange(5);
using var queue = PooledRefQueue<Mobile>.Create();
SetSpeed(0.5, 1.2); foreach (var m in eable)
SetStr(150);
SetDex(150);
SetInt(100);
SetHits(Core.SE ? 160 : 80);
SetStam(250);
SetMana(0);
SetDamage(10, 14);
SetDamageType(ResistanceType.Physical, 60);
SetDamageType(ResistanceType.Poison, 20);
SetDamageType(ResistanceType.Energy, 20);
SetResistance(ResistanceType.Physical, 30, 40);
SetResistance(ResistanceType.Fire, 40, 50);
SetResistance(ResistanceType.Cold, 30, 40);
SetResistance(ResistanceType.Poison, 100);
SetResistance(ResistanceType.Energy, 20, 30);
SetSkill(SkillName.MagicResist, 70.0);
SetSkill(SkillName.Tactics, 90.0);
SetSkill(SkillName.Wrestling, 90.0);
Fame = 0;
Karma = 0;
VirtualArmor = 40;
ControlSlots = Core.SE ? 2 : 1;
}
public BladeSpirits(Serial serial) : base(serial)
{
}
public override string CorpseName => "a blade spirit corpse";
public override bool DeleteCorpseOnDeath => Core.AOS;
public override bool IsHouseSummonable => true;
public override double DispelDifficulty => 0.0;
public override double DispelFocus => 20.0;
public override string DefaultName => "a blade spirit";
public override bool BleedImmune => true;
public override Poison PoisonImmune => Poison.Lethal;
public override double GetFightModeRanking(Mobile m, FightMode acqType, bool bPlayerOnly) =>
(m.Str + m.Skills.Tactics.Value) / Math.Max(GetDistanceToSqrt(m), 1.0);
public override int GetAngerSound() => 0x23A;
public override int GetAttackSound() => 0x3B8;
public override int GetHurtSound() => 0x23A;
public override void OnThink()
{
if (Core.SE && Summoned)
{ {
var eable = GetMobilesInRange(5); if (m is EnergyVortex or BladeSpirits && ((BaseCreature)m).Summoned)
using var queue = PooledRefQueue<Mobile>.Create();
foreach (var m in eable)
{ {
if (m is EnergyVortex or BladeSpirits && ((BaseCreature)m).Summoned) queue.Enqueue(m);
{
queue.Enqueue(m);
}
}
eable.Free();
var amount = queue.Count - 6;
if (amount > 0)
{
var mobs = queue.ToPooledArray();
mobs.Shuffle();
while (amount > 0)
{
Dispel(mobs[amount--]);
}
ArrayPool<Mobile>.Shared.Return(mobs, true);
} }
} }
eable.Free();
base.OnThink(); var amount = queue.Count - 6;
if (amount > 0)
{
var mobs = queue.ToPooledArray();
mobs.Shuffle();
while (amount > 0)
{
Dispel(mobs[amount--]);
}
STArrayPool<Mobile>.Shared.Return(mobs, true);
}
} }
public override void Serialize(IGenericWriter writer) base.OnThink();
{ }
base.Serialize(writer);
writer.Write(0); // version public override void Serialize(IGenericWriter writer)
} {
base.Serialize(writer);
public override void Deserialize(IGenericReader reader) writer.Write(0); // version
{ }
base.Deserialize(reader);
var version = reader.ReadInt(); public override void Deserialize(IGenericReader reader)
} {
base.Deserialize(reader);
var version = reader.ReadInt();
} }
} }

View file

@ -1,129 +1,128 @@
using System; using System;
using System.Buffers; using Server.Buffers;
using Server.Collections; using Server.Collections;
namespace Server.Mobiles namespace Server.Mobiles;
public class EnergyVortex : BaseCreature
{ {
public class EnergyVortex : BaseCreature [Constructible]
public EnergyVortex() : base(AIType.AI_Melee)
{ {
[Constructible] if (Core.SE && Utility.Random(500) == 0) // Per OSI FoF, it's a 1/500 chance.
public EnergyVortex() : base(AIType.AI_Melee)
{ {
if (Core.SE && Utility.RandomDouble() < 0.002) // Per OSI FoF, it's a 1/500 chance. // Llama vortex!
{ Body = 0xDC;
// Llama vortex! Hue = 0x76;
Body = 0xDC; }
Hue = 0x76; else
} {
else Body = 164;
{
Body = 164;
}
SetStr(200);
SetDex(200);
SetInt(100);
SetHits(Core.SE ? 140 : 70);
SetStam(250);
SetMana(0);
SetDamage(14, 17);
SetDamageType(ResistanceType.Physical, 0);
SetDamageType(ResistanceType.Energy, 100);
SetResistance(ResistanceType.Physical, 60, 70);
SetResistance(ResistanceType.Fire, 40, 50);
SetResistance(ResistanceType.Cold, 40, 50);
SetResistance(ResistanceType.Poison, 40, 50);
SetResistance(ResistanceType.Energy, 90, 100);
SetSkill(SkillName.MagicResist, 99.9);
SetSkill(SkillName.Tactics, 100.0);
SetSkill(SkillName.Wrestling, 120.0);
Fame = 0;
Karma = 0;
VirtualArmor = 40;
ControlSlots = Core.SE ? 2 : 1;
} }
public EnergyVortex(Serial serial) SetStr(200);
: base(serial) SetDex(200);
SetInt(100);
SetHits(Core.SE ? 140 : 70);
SetStam(250);
SetMana(0);
SetDamage(14, 17);
SetDamageType(ResistanceType.Physical, 0);
SetDamageType(ResistanceType.Energy, 100);
SetResistance(ResistanceType.Physical, 60, 70);
SetResistance(ResistanceType.Fire, 40, 50);
SetResistance(ResistanceType.Cold, 40, 50);
SetResistance(ResistanceType.Poison, 40, 50);
SetResistance(ResistanceType.Energy, 90, 100);
SetSkill(SkillName.MagicResist, 99.9);
SetSkill(SkillName.Tactics, 100.0);
SetSkill(SkillName.Wrestling, 120.0);
Fame = 0;
Karma = 0;
VirtualArmor = 40;
ControlSlots = Core.SE ? 2 : 1;
}
public EnergyVortex(Serial serial)
: base(serial)
{
}
public override string CorpseName => "an energy vortex corpse";
public override bool DeleteCorpseOnDeath => Summoned;
public override bool AlwaysMurderer => true; // Or Llama vortices will appear gray.
public override double DispelDifficulty => 80.0;
public override double DispelFocus => 20.0;
public override string DefaultName => "an energy vortex";
public override bool BleedImmune => true;
public override Poison PoisonImmune => Poison.Lethal;
public override double GetFightModeRanking(Mobile m, FightMode acqType, bool bPlayerOnly) =>
(m.Int + m.Skills.Magery.Value) / Math.Max(GetDistanceToSqrt(m), 1.0);
public override int GetAngerSound() => 0x15;
public override int GetAttackSound() => 0x28;
public override void OnThink()
{
if (Core.SE && Summoned)
{ {
} var eable = GetMobilesInRange(5);
using var queue = PooledRefQueue<Mobile>.Create();
public override string CorpseName => "an energy vortex corpse"; foreach (var m in eable)
public override bool DeleteCorpseOnDeath => Summoned;
public override bool AlwaysMurderer => true; // Or Llama vortices will appear gray.
public override double DispelDifficulty => 80.0;
public override double DispelFocus => 20.0;
public override string DefaultName => "an energy vortex";
public override bool BleedImmune => true;
public override Poison PoisonImmune => Poison.Lethal;
public override double GetFightModeRanking(Mobile m, FightMode acqType, bool bPlayerOnly) =>
(m.Int + m.Skills.Magery.Value) / Math.Max(GetDistanceToSqrt(m), 1.0);
public override int GetAngerSound() => 0x15;
public override int GetAttackSound() => 0x28;
public override void OnThink()
{
if (Core.SE && Summoned)
{ {
var eable = GetMobilesInRange(5); if (m is EnergyVortex or BladeSpirits && ((BaseCreature)m).Summoned)
using var queue = PooledRefQueue<Mobile>.Create();
foreach (var m in eable)
{ {
if (m is EnergyVortex or BladeSpirits && ((BaseCreature)m).Summoned) queue.Enqueue(m);
{
queue.Enqueue(m);
}
}
eable.Free();
var amount = queue.Count - 6;
if (amount > 0)
{
var mobs = queue.ToPooledArray();
mobs.Shuffle();
while (amount > 0)
{
Dispel(mobs[amount--]);
}
ArrayPool<Mobile>.Shared.Return(mobs, true);
} }
} }
eable.Free();
base.OnThink(); var amount = queue.Count - 6;
} if (amount > 0)
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
if (BaseSoundID == 263)
{ {
BaseSoundID = 0; var mobs = queue.ToPooledArray();
mobs.Shuffle();
while (amount > 0)
{
Dispel(mobs[amount--]);
}
STArrayPool<Mobile>.Shared.Return(mobs, true);
} }
} }
base.OnThink();
}
public override void Serialize(IGenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(IGenericReader reader)
{
base.Deserialize(reader);
var version = reader.ReadInt();
if (BaseSoundID == 263)
{
BaseSoundID = 0;
}
} }
} }