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

[stdlib] Add comp time SIMD range constructor #3114

Open
wants to merge 7 commits into
base: nightly
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
36 changes: 36 additions & 0 deletions stdlib/src/builtin/simd.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,42 @@ struct SIMD[type: DType, size: Int = simdwidthof[type]()](
)
)

@staticmethod
fn from_range[start: Int, end: Int, step: Int = 1]() -> Self:
"""Construct from a compile time range using the index as value.

Parameters:
start: The start of the range.
end: The end of the range.
step: The step of the range.

Returns:
The new SIMD vector.

Constraints:
The range must be equal to or less than SIMD size.

Examples:
```mojo
print(SIMD[DType.uint8, 4].from_range[0, 4]()) # [0, 1, 2, 3]
print(SIMD[DType.uint8, 4].from_range[3, -1, -1]()) # [3, 2, 1, 0]
```
.
"""

constrained[
abs((start - end) // step) <= size,
martinvuyk marked this conversation as resolved.
Show resolved Hide resolved
"The range must be equal to or less than SIMD size.",
]()
var vec = Self()
var idx = 0

@parameter
for i in range(start, end, step):
vec[idx] = i
idx += 1
return vec

# ===-------------------------------------------------------------------===#
# Operator dunders
# ===-------------------------------------------------------------------===#
Expand Down
10 changes: 10 additions & 0 deletions stdlib/test/builtin/test_simd.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -1531,6 +1531,15 @@ def test_split():
assert_equal(tup[1], SIMD[DType.index, 4](5, 6, 7, 8))


def test_range_constructor():
alias INum = SIMD[DType.uint8, 4]
assert_equal(INum.from_range[0, 4](), INum(0, 1, 2, 3))
assert_equal(INum.from_range[3, -1, -1](), INum(3, 2, 1, 0))
alias FNum = SIMD[DType.float16, 4]
assert_equal(FNum.from_range[0, 4](), FNum(0, 1, 2, 3))
assert_equal(FNum.from_range[3, -1, -1](), FNum(3, 2, 1, 0))


def main():
test_abs()
test_add()
Expand Down Expand Up @@ -1579,4 +1588,5 @@ def main():
test_truthy()
test_modf()
test_split()
test_range_constructor()
# TODO: add tests for __and__, __or__, anc comparison operators