Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Tuple#to_static_array #12930

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions spec/std/tuple_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,19 @@ describe "Tuple" do
ary = Tuple.new.to_a
ary.size.should eq(0)
end

it "#to_static_array" do
HertzDevil marked this conversation as resolved.
Show resolved Hide resolved
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)

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
18 changes: 18 additions & 0 deletions src/tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
HertzDevil marked this conversation as resolved.
Show resolved Hide resolved
{% end %}
end

# Appends a string representation of this tuple to the given `IO`.
#
# ```
Expand Down