Skip to content

Commit

Permalink
fixed generation of Sum<X, N0>, N0 is prohibited in Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
lostmsu committed Sep 9, 2021
1 parent f99f902 commit 876219b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/INumeral.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ public interface INumeral {
int Num { get; }
}

public interface INumeral<T> {
int Num { get; }
public interface INumeral<T>: INumeral {
}

public static class Numeral<T> where T : unmanaged {
Expand All @@ -18,7 +17,9 @@ public static Type GetNType(int n) {
while (n >= pwr) {
if ((n & pwr) == pwr) {
var powerOfTwo = PowersOfTwo<T>.Get(pwr);
result = typeof(Sum<,,>).MakeGenericType(typeof(T), powerOfTwo, result);
result = result == typeof(N0<T>)
? powerOfTwo
: typeof(Sum<,,>).MakeGenericType(typeof(T), powerOfTwo, result);
}

pwr <<= 1;
Expand Down
7 changes: 7 additions & 0 deletions src/Sum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ static Sum()
if (n1 <= n2)
throw new ArgumentException("Consistency: T1 must always be > T2. Swap them."
+ $"\n{typeof(Sum<T1, T2>).Name}: {typeof(T1).Name}={n1},{typeof(T2).Name}={n2}");
if (n1 == 0 || n2 == 0)
throw new ArgumentException("Consistency: T1 and T2 must always be > 0."
+ $"\n{typeof(Sum<T1, T2>).Name}: {typeof(T1).Name}={n1},{typeof(T2).Name}={n2}");
var t1 = typeof(T1);
var t2 = typeof(T2);
if (t2.IsConstructedGenericType && t2.GetGenericTypeDefinition() == typeof(Sum<,>))
Expand All @@ -41,5 +44,9 @@ public int Num {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.Item1.Num + this.Item2.Num;
}

static Sum() {
default(Sum<T1, T2>).Num.GetHashCode();
}
}
}
17 changes: 17 additions & 0 deletions tests/NumeralTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace TypeNum {
using System;

using Xunit;
public class NumeralTests {
[Fact]
public void GetNumeralType() {
var n5int = Numeral<int>.GetNType(5);
Assert.Equal(typeof(Sum<int, N4<int>, N1<int>>), n5int);
}

[Fact]
public void Sum0_Prohibited() {
Assert.Throws<TypeInitializationException>(() => default(Sum<int, N2<int>, N0<int>>).Num.GetHashCode());
}
}
}

0 comments on commit 876219b

Please sign in to comment.