Skip to content

lib.data: make views of ArrayLayout iterable. #1410

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

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 6 additions & 0 deletions amaranth/lib/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,12 @@ def __len__(self):
f"`len()` can only be used on views of array layout, not {self.__layout!r}")
return self.__layout.length

def __iter__(self):
if not isinstance(self.__layout, ArrayLayout):
raise TypeError(
f"Only views of array layout can be iterated, not {self.__layout!r}")
return (self[i] for i in range(self.__layout.length))

def __eq__(self, other):
if isinstance(other, View) and self.__layout == other.__layout:
return self.__target == other.__target
Expand Down
8 changes: 8 additions & 0 deletions tests/test_lib_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,14 @@ def test_len(self):
s2 = Signal(data.ArrayLayout(2, 3))
self.assertEqual(len(s2), 3)

def test_iter(self):
s1 = Signal(data.StructLayout({"a": unsigned(2)}))
with self.assertRaisesRegex(TypeError,
r"^Only views of array layout can be iterated, not StructLayout.*$"):
iter(s1)
s2 = Signal(data.ArrayLayout(2, 3))
self.assertRepr(tuple(s2), "((slice (sig s2) 0:2), (slice (sig s2) 2:4), (slice (sig s2) 4:6))")

def test_operator(self):
s1 = Signal(data.StructLayout({"a": unsigned(2)}))
s2 = Signal(unsigned(2))
Expand Down
Loading