Skip to content

Commit

Permalink
make assert_mode a parameter
Browse files Browse the repository at this point in the history
Signed-off-by: martinvuyk <[email protected]>
  • Loading branch information
martinvuyk committed Nov 19, 2024
1 parent 8ca410b commit a958314
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
6 changes: 4 additions & 2 deletions stdlib/src/collections/_index_normalization.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ fn normalize_index[
*,
ignore_zero_length: Bool = False,
cap_to_container_length: Bool = True,
assert_mode: StringLiteral = "warn",
](idx: Int, container: ContainerType) -> Int:
"""Normalize the given index value to a valid index value for the given
container length. If the provided value is negative, the `index +
Expand All @@ -31,6 +32,7 @@ fn normalize_index[
container_name: The name of the container. Used for the error message.
ignore_zero_length: Whether to ignore if the container is of length 0.
cap_to_container_length: Whether to cap the value to container length.
assert_mode: The mode in which to do the bounds check asserts.
Args:
idx: The index value to normalize.
Expand All @@ -49,13 +51,13 @@ fn normalize_index[

@parameter
if not ignore_zero_length:
debug_assert[assert_mode="none", cpu_only=True](
debug_assert[assert_mode=assert_mode, cpu_only=True](
c_len > 0,
"indexing into a ",
container_name,
" that has 0 elements",
)
debug_assert[assert_mode="none", cpu_only=True](
debug_assert[assert_mode=assert_mode, cpu_only=True](
-c_len <= idx < c_len,
container_name,
" has length: ",
Expand Down
6 changes: 3 additions & 3 deletions stdlib/test/collections/test_index_normalization.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ from testing import assert_equal
def test_out_of_bounds_message():
l = List[Int](1, 2)
# CHECK: index out of bounds: 2
_ = normalize_index["List"](2, l)
_ = normalize_index["List", assert_mode="safe"](2, l)
# CHECK: index out of bounds: -3
_ = normalize_index["List"](-3, l)
_ = normalize_index["List", assert_mode="safe"](-3, l)

l2 = List[Int]()
# CHECK: indexing into a List that has 0 elements
_ = normalize_index["List"](2, l2)
_ = normalize_index["List", assert_mode="safe"](2, l2)


def test_normalize_index():
Expand Down

0 comments on commit a958314

Please sign in to comment.