From 01a5686fb46080290623eb372eb411789476f6dc Mon Sep 17 00:00:00 2001 From: Wanda Date: Tue, 18 Jun 2024 01:27:07 +0200 Subject: [PATCH] lib.data: make `len()` work on views of array layout. Fixes #1403. --- amaranth/lib/data.py | 6 ++++++ tests/test_lib_data.py | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/amaranth/lib/data.py b/amaranth/lib/data.py index 6135bb054..8c77cc2cf 100644 --- a/amaranth/lib/data.py +++ b/amaranth/lib/data.py @@ -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 diff --git a/tests/test_lib_data.py b/tests/test_lib_data.py index 697f36650..ceafd638b 100644 --- a/tests/test_lib_data.py +++ b/tests/test_lib_data.py @@ -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))