Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created October 12, 2022 03:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/6ebb0eca3437f9f2510028dbf28c3608 to your computer and use it in GitHub Desktop.
Save ufcpp/6ebb0eca3437f9f2510028dbf28c3608 to your computer and use it in GitHub Desktop.
.NET 7 RC 2 でやっとまっとうに動いた
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.InteropServices;
var a2 = new Array2<int>();
for (int i = 0; i < 2; i++) a2[i] = i + 1;
Console.WriteLine(sum(a2.AsReadOnlySpan()));
var a3 = new Array3<int>();
for (int i = 0; i < 3; i++) a3[i] = i + 1;
Console.WriteLine(sum(a3.AsReadOnlySpan()));
var a4 = new Array4<int>();
for (int i = 0; i < 4; i++) a4[i] = i + 1;
Console.WriteLine(sum(a4.AsReadOnlySpan()));
static T sum<T>(ReadOnlySpan<T> items) where T : INumber<T>
{
var s = T.Zero;
foreach (var x in items) s += x;
return s;
}
public interface IFixedArray<T>
{
public static abstract int Length { get; }
Span<T> AsSpan();
public ReadOnlySpan<T> AsReadOnlySpan() => AsSpan();
public ref T this[int index] => ref AsSpan()[index];
}
#pragma warning disable IDE0044, IDE0051, IDE0052
struct Array2<T> : IFixedArray<T>
{
private T _0, _1;
public Array2(T x0, T x1) => (_0, _1) = (x0, x1);
public static int Length => 2;
[UnscopedRef] public Span<T> AsSpan() => MemoryMarshal.CreateSpan(ref _0, Length);
[UnscopedRef] public ReadOnlySpan<T> AsReadOnlySpan() => AsSpan();
[UnscopedRef] public ref T this[int index] => ref AsSpan()[index];
}
struct Array3<T> : IFixedArray<T>
{
private T _0, _1, _2;
public Array3(T x0, T x1, T x2) => (_0, _1, _2) = (x0, x1, x2);
public static int Length => 3;
[UnscopedRef] public Span<T> AsSpan() => MemoryMarshal.CreateSpan(ref _0, Length);
[UnscopedRef] public ReadOnlySpan<T> AsReadOnlySpan() => AsSpan();
[UnscopedRef] public ref T this[int index] => ref AsSpan()[index];
}
struct Array4<T> : IFixedArray<T>
{
private T _0, _1, _2, _3;
public Array4(T x0, T x1, T x2, T x3) => (_0, _1, _2, _3) = (x0, x1, x2, x3);
public static int Length => 4;
[UnscopedRef] public Span<T> AsSpan() => MemoryMarshal.CreateSpan(ref _0, Length);
[UnscopedRef] public ReadOnlySpan<T> AsReadOnlySpan() => AsSpan();
[UnscopedRef] public ref T this[int index] => ref AsSpan()[index];
}
class FixedArray
{
public static Array2<T> Create<T>(T x0, T x1) => new(x0, x1);
public static Array3<T> Create<T>(T x0, T x1, T x2) => new(x0, x1, x2);
public static Array4<T> Create<T>(T x0, T x1, T x2, T x3) => new(x0, x1, x2, x3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment