Skip to content

Commit 7a58b62

Browse files
wanda-phiwhitequark
authored andcommitted
lib.data: make len() work on views of array layout.
Fixes #1403.
1 parent 0915b9a commit 7a58b62

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

amaranth/lib/data.py

+6
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,12 @@ def __getattr__(self, name):
850850
f"may only be accessed by indexing")
851851
return item
852852

853+
def __len__(self):
854+
if not isinstance(self.__layout, ArrayLayout):
855+
raise TypeError(
856+
f"`len()` can only be used on views of array layout, not {self.__layout!r}")
857+
return self.__layout.length
858+
853859
def __eq__(self, other):
854860
if isinstance(other, View) and self.__layout == other.__layout:
855861
return self.__target == other.__target

tests/test_lib_data.py

+8
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,14 @@ def test_eq(self):
763763
r"with the same layout, not .*$"):
764764
s1 != Const(0, 2)
765765

766+
def test_len(self):
767+
s1 = Signal(data.StructLayout({"a": unsigned(2)}))
768+
with self.assertRaisesRegex(TypeError,
769+
r"^`len\(\)` can only be used on views of array layout, not StructLayout.*$"):
770+
len(s1)
771+
s2 = Signal(data.ArrayLayout(2, 3))
772+
self.assertEqual(len(s2), 3)
773+
766774
def test_operator(self):
767775
s1 = Signal(data.StructLayout({"a": unsigned(2)}))
768776
s2 = Signal(unsigned(2))

0 commit comments

Comments
 (0)