Skip to content

lib.data: make len() work on views of array layout. #1406

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

Merged
merged 1 commit into from
Jun 17, 2024
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
6 changes: 6 additions & 0 deletions amaranth/lib/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,12 @@ def __getattr__(self, name):
f"may only be accessed by indexing")
return item

def __len__(self):
if not isinstance(self.__layout, ArrayLayout):
raise TypeError(
f"`len()` can only be used on views of array layout, not {self.__layout!r}")
return 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 @@ -763,6 +763,14 @@ def test_eq(self):
r"with the same layout, not .*$"):
s1 != Const(0, 2)

def test_len(self):
s1 = Signal(data.StructLayout({"a": unsigned(2)}))
with self.assertRaisesRegex(TypeError,
r"^`len\(\)` can only be used on views of array layout, not StructLayout.*$"):
len(s1)
s2 = Signal(data.ArrayLayout(2, 3))
self.assertEqual(len(s2), 3)

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