From 80e95c9a18962c1e41805d7754f9bc2253356656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Tue, 10 Jan 2023 16:43:44 +0100 Subject: [PATCH 1/2] Add `Tuple#to_static_array` --- spec/std/tuple_spec.cr | 11 +++++++++++ src/tuple.cr | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/spec/std/tuple_spec.cr b/spec/std/tuple_spec.cr index 22d8d40933d0..a5a589f193d0 100644 --- a/spec/std/tuple_spec.cr +++ b/spec/std/tuple_spec.cr @@ -341,4 +341,15 @@ describe "Tuple" do ary = Tuple.new.to_a ary.size.should eq(0) end + + it "#to_static_array" do + ary = {1, 'a', true}.to_static_array + ary.should be_a(StaticArray(Int32 | Char | Bool, 3)) + ary.should eq(StaticArray[1, 'a', true]) + ary.size.should eq(3) + + ary = Tuple.new.to_static_array + ary.should be_a(StaticArray(NoReturn, 0)) + ary.size.should eq(0) + end end diff --git a/src/tuple.cr b/src/tuple.cr index 16d2675243c8..a3815c856278 100644 --- a/src/tuple.cr +++ b/src/tuple.cr @@ -548,6 +548,24 @@ struct Tuple end end + # Returns a `StaticArray` with the same elements. + # + # The element type is `Union(*T)`. + # + # ``` + # {1, 'a', true}.to_static_array # => StaticArray[1, 'a', true] + # ``` + @[AlwaysInline] + def to_static_array : StaticArray + {% begin %} + ary = uninitialized StaticArray(Union(*T), {{ T.size }}) + each_with_index do |value, i| + ary.to_unsafe[i] = value + end + ary + {% end %} + end + # Appends a string representation of this tuple to the given `IO`. # # ``` From 7cf2bd16271231f2d029125b761320b9914880fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Wed, 11 Jan 2023 15:43:43 +0100 Subject: [PATCH 2/2] Add test case for downcast type --- spec/std/tuple_spec.cr | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spec/std/tuple_spec.cr b/spec/std/tuple_spec.cr index a5a589f193d0..c6ead7b1ccf6 100644 --- a/spec/std/tuple_spec.cr +++ b/spec/std/tuple_spec.cr @@ -351,5 +351,9 @@ describe "Tuple" do ary = Tuple.new.to_static_array ary.should be_a(StaticArray(NoReturn, 0)) ary.size.should eq(0) + + ary = Tuple(String | Int32).new(1).to_static_array + ary.should be_a(StaticArray(String | Int32, 1)) + ary.should eq StaticArray[1.as(String | Int32)] end end