Last active
March 25, 2020 21:40
-
-
Save E-K/7878861c540de8c10d995cf4a5e0e66d to your computer and use it in GitHub Desktop.
List<T>モドキ作る時用のヘルパクラス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Array.Resizeなどは勝手にやらないけど、ArrayPoolなど使い始めたら逆に邪魔になるので外でやってくれたほうが良かろうかと