From 5fd8ca4d6c5dbb66095d170c00bc321a2026666c Mon Sep 17 00:00:00 2001 From: Paul Backus Date: Thu, 18 Mar 2021 20:16:03 -0400 Subject: [PATCH 1/2] Add SumType.typeIndex --- src/sumtype.d | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/sumtype.d b/src/sumtype.d index ca4f626..ede4670 100644 --- a/src/sumtype.d +++ b/src/sumtype.d @@ -664,6 +664,15 @@ public: return this.match!hashOf; } } + + /** + * Returns the index of the type of the `SumType`'s current value in the + * `SumType`'s [Types]. + */ + size_t typeIndex() const + { + return tag; + } } // Construction @@ -1297,6 +1306,14 @@ version (D_BetterC) {} else assert(__traits(compiles, { MySum x; x = b; })); } +// Type index +@safe unittest { + alias MySum = SumType!(int, float); + + assert(MySum(42).typeIndex == IndexOf!(int, MySum.Types)); + assert(MySum(3.14).typeIndex == IndexOf!(float, MySum.Types)); +} + /// True if `T` is an instance of the `SumType` template, otherwise false. private enum bool isSumTypeInstance(T) = is(T == SumType!Args, Args...); From ee1b01ee59f32889e608939246373979510fc0b3 Mon Sep 17 00:00:00 2001 From: Paul Backus Date: Thu, 18 Mar 2021 20:59:07 -0400 Subject: [PATCH 2/2] Make typeIndex work correctly with qualifiers --- src/sumtype.d | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/sumtype.d b/src/sumtype.d index ede4670..c0101f0 100644 --- a/src/sumtype.d +++ b/src/sumtype.d @@ -668,10 +668,20 @@ public: /** * Returns the index of the type of the `SumType`'s current value in the * `SumType`'s [Types]. + * + * If the `SumType` is qualified, then its qualifiers are applied to + * [Types] before determining the index. */ - size_t typeIndex() const + size_t typeIndex(this This)() { - return tag; + import std.traits: CopyTypeQualifiers; + + alias Qualify(T) = CopyTypeQualifiers!(This, T); + alias QualifiedTypes = Map!(Qualify, Types); + + return this.match!((ref value) => + IndexOf!(typeof(value), QualifiedTypes) + ); } } @@ -1314,6 +1324,20 @@ version (D_BetterC) {} else assert(MySum(3.14).typeIndex == IndexOf!(float, MySum.Types)); } +// Type index for qualified SumTypes +// Disabled in BetterC due to use of dynamic arrays +version (D_BetterC) {} else +@safe unittest { + alias MySum = SumType!(const(int[]), int[]); + + int[] ma = [1, 2, 3]; + // Construct as mutable and convert to const to get mismatched type + tag + const x = MySum(ma); + + assert(MySum(ma).typeIndex == IndexOf!(int[], MySum.Types)); + assert(x.typeIndex == IndexOf!(const(int[]), Map!(ConstOf, MySum.Types))); +} + /// True if `T` is an instance of the `SumType` template, otherwise false. private enum bool isSumTypeInstance(T) = is(T == SumType!Args, Args...);