Skip to content

Instantly share code, notes, and snippets.

@E-K
Last active March 25, 2020 21:40
Show Gist options
  • Save E-K/7878861c540de8c10d995cf4a5e0e66d to your computer and use it in GitHub Desktop.
Save E-K/7878861c540de8c10d995cf4a5e0e66d to your computer and use it in GitHub Desktop.
List<T>モドキ作る時用のヘルパクラス
using System;
using System.Runtime.CompilerServices;
namespace Nandemoii
{
public struct ListCore<T>
{
public Memory<T> Memory;
public int Count;
public bool IsFull => this.Memory.Length == this.Count;
public ListCore(Memory<T> memory, int count)
{
this.Memory = memory;
this.Count = count;
}
public void Add(T item)
{
ValidateFull();
this.Memory.Span[this.Count] = item;
this.Count++;
}
public void Insert(int index, T item)
{
ValidateFull();
if(index == this.Count)
{
Add(item);
return;
}
ValidateIndex(index);
var start = index;
var end = this.Count - 1;
var span = this.Memory.Span;
for(int i = end; i >= start; i--)
{
span[i + 1] = span[i];
}
span[index] = item;
this.Count++;
}
public void RemoveAt(int index)
{
ValidateIndex(index);
var start = index + 1;
var span = this.Memory.Span;
for (int i = start; i < this.Count; i++)
{
span[i - 1] = span[i];
}
span[this.Count - 1] = default;
this.Count--;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ValidateFull()
{
if (IsFull)
throw new InvalidOperationException("Full");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ValidateIndex(int index)
{
if (index < 0 || this.Count <= index)
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
@E-K
Copy link
Author

E-K commented Mar 25, 2020

Array.Resizeなどは勝手にやらないけど、ArrayPoolなど使い始めたら逆に邪魔になるので外でやってくれたほうが良かろうかと

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment