Skip to content

Commit fae97cf

Browse files
committed
lib.data.{Field, Layout, Const}: add __hash__
1 parent 5689b6b commit fae97cf

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

amaranth/lib/data.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ def width(self):
6565
"""
6666
return Shape.cast(self.shape).width
6767

68+
def __hash__(self):
69+
return hash((self.shape, self.offset))
70+
6871
def __eq__(self, other):
6972
"""Compare fields.
7073
@@ -166,6 +169,9 @@ def as_shape(self):
166169
"""
167170
return unsigned(self.size)
168171

172+
def __hash__(self):
173+
return hash(self.size)
174+
169175
def __eq__(self, other):
170176
"""Compare layouts.
171177
@@ -1123,6 +1129,9 @@ def __len__(self):
11231129
f"`len()` can only be used on constants of array layout, not {self.__layout!r}")
11241130
return self.__layout.length
11251131

1132+
def __hash__(self):
1133+
return hash((self.__target, self.__layout))
1134+
11261135
def __eq__(self, other):
11271136
if isinstance(other, View) and self.__layout == other._View__layout:
11281137
return self.as_value() == other._View__target

tests/test_lib_data.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ def test_immutable(self):
7474
with self.assertRaises(AttributeError):
7575
data.Field(1, 0).offset = 1
7676

77+
def test_hash(self):
78+
hash(data.Field(unsigned(2), 1))
79+
7780

7881
class StructLayoutTestCase(FHDLTestCase):
7982
def test_construct(self):
@@ -520,6 +523,9 @@ def test_signal_init(self):
520523
self.assertEqual(Signal(sl).as_value().init, 0)
521524
self.assertEqual(Signal(sl, init={"a": 0b1, "b": 0b10}).as_value().init, 5)
522525

526+
def test_hash(self):
527+
hash(data.StructLayout({}))
528+
523529

524530
class ViewTestCase(FHDLTestCase):
525531
def test_construct(self):
@@ -1167,6 +1173,9 @@ def test_repr(self):
11671173
s1 = data.Const(data.StructLayout({"a": unsigned(2)}), 2)
11681174
self.assertRepr(s1, "Const(StructLayout({'a': unsigned(2)}), 2)")
11691175

1176+
def test_hash(self):
1177+
hash(data.Const(data.StructLayout({"a": unsigned(2)}), 2))
1178+
11701179

11711180
class StructTestCase(FHDLTestCase):
11721181
def test_construct(self):

0 commit comments

Comments
 (0)