Skip to content

Commit d449f7b

Browse files
committed
lib.data: add .format() implementation.
1 parent 1fdd9bf commit d449f7b

File tree

2 files changed

+84
-4
lines changed

2 files changed

+84
-4
lines changed

amaranth/lib/data.py

+32-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from amaranth._utils import final
88
from amaranth.hdl import *
9-
from amaranth.hdl._repr import *
9+
from amaranth.hdl._repr import Repr, FormatInt, FormatEnum
1010
from amaranth import hdl
1111

1212

@@ -248,6 +248,20 @@ def from_bits(self, raw):
248248
"""
249249
return Const(self, raw)
250250

251+
def format(self, value, format_spec):
252+
if format_spec != "":
253+
raise ValueError(f"Format specifier {format_spec!r} is not supported for layouts")
254+
value = Value.cast(value)
255+
fields = {}
256+
for key, field in self:
257+
shape = Shape.cast(field.shape)
258+
field_value = value[field.offset:field.offset+shape.width]
259+
if isinstance(field.shape, ShapeCastable):
260+
fields[str(key)] = field.shape.format(field.shape(field_value), "")
261+
else:
262+
fields[str(key)] = Format("{}", field_value)
263+
return Format.Struct(value, fields)
264+
251265
def _value_repr(self, value):
252266
yield Repr(FormatInt(), value)
253267
for key, field in self:
@@ -539,6 +553,20 @@ def size(self):
539553
def __repr__(self):
540554
return f"ArrayLayout({self._elem_shape!r}, {self.length})"
541555

556+
def format(self, value, format_spec):
557+
if format_spec != "":
558+
raise ValueError(f"Format specifier {format_spec!r} is not supported for layouts")
559+
value = Value.cast(value)
560+
fields = []
561+
shape = Shape.cast(self._elem_shape)
562+
for index in range(self._length):
563+
field_value = value[shape.width * index:shape.width * (index + 1)]
564+
if isinstance(self._elem_shape, ShapeCastable):
565+
fields.append(self._elem_shape.format(self._elem_shape(field_value), ""))
566+
else:
567+
fields.append(Format("{}", field_value))
568+
return Format.Array(value, fields)
569+
542570

543571
class FlexibleLayout(Layout):
544572
"""Description of a flexible layout.
@@ -1163,6 +1191,9 @@ def const(cls, init):
11631191
def from_bits(cls, bits):
11641192
return cls.as_shape().from_bits(bits)
11651193

1194+
def format(cls, value, format_spec):
1195+
return cls.__layout.format(value, format_spec)
1196+
11661197
def _value_repr(cls, value):
11671198
return cls.__layout._value_repr(value)
11681199

tests/test_lib_data.py

+52-3
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def test_immutable(self):
7575
data.Field(1, 0).offset = 1
7676

7777

78-
class StructLayoutTestCase(TestCase):
78+
class StructLayoutTestCase(FHDLTestCase):
7979
def test_construct(self):
8080
sl = data.StructLayout({
8181
"a": unsigned(1),
@@ -126,8 +126,21 @@ def test_member_value_wrong(self):
126126
r"^Struct layout member shape must be a shape-castable object, not 1\.0$"):
127127
data.StructLayout({"a": 1.0})
128128

129+
def test_format(self):
130+
sl = data.StructLayout({
131+
"a": unsigned(1),
132+
"b": 2
133+
})
134+
sig = Signal(sl)
135+
self.assertRepr(sl.format(sig, ""), """
136+
(format-struct (sig sig)
137+
('a' (format '{}' (slice (sig sig) 0:1)))
138+
('b' (format '{}' (slice (sig sig) 1:3)))
139+
)
140+
""")
141+
129142

130-
class UnionLayoutTestCase(TestCase):
143+
class UnionLayoutTestCase(FHDLTestCase):
131144
def test_construct(self):
132145
ul = data.UnionLayout({
133146
"a": unsigned(1),
@@ -184,8 +197,21 @@ def test_const_two_members_wrong(self):
184197
r"\(specified: a, b\)$"):
185198
data.UnionLayout({"a": 1, "b": 2}).const(dict(a=1, b=2))
186199

200+
def test_format(self):
201+
ul = data.UnionLayout({
202+
"a": unsigned(1),
203+
"b": 2
204+
})
205+
sig = Signal(ul)
206+
self.assertRepr(ul.format(sig, ""), """
207+
(format-struct (sig sig)
208+
('a' (format '{}' (slice (sig sig) 0:1)))
209+
('b' (format '{}' (slice (sig sig) 0:2)))
210+
)
211+
""")
212+
187213

188-
class ArrayLayoutTestCase(TestCase):
214+
class ArrayLayoutTestCase(FHDLTestCase):
189215
def test_construct(self):
190216
al = data.ArrayLayout(unsigned(2), 3)
191217
self.assertEqual(al.elem_shape, unsigned(2))
@@ -243,6 +269,17 @@ def test_key_wrong_type(self):
243269
r"^Cannot index array layout with 'a'$"):
244270
al["a"]
245271

272+
def test_format(self):
273+
al = data.ArrayLayout(unsigned(2), 3)
274+
sig = Signal(al)
275+
self.assertRepr(al.format(sig, ""), """
276+
(format-array (sig sig)
277+
(format '{}' (slice (sig sig) 0:2))
278+
(format '{}' (slice (sig sig) 2:4))
279+
(format '{}' (slice (sig sig) 4:6))
280+
)
281+
""")
282+
246283

247284
class FlexibleLayoutTestCase(TestCase):
248285
def test_construct(self):
@@ -1012,6 +1049,18 @@ class S(data.Struct):
10121049
self.assertRepr(v.b.q.as_value(), "(slice (slice (sig v) 1:9) 4:8)")
10131050
self.assertRepr(v.b.q.r, "(s (slice (slice (slice (sig v) 1:9) 4:8) 0:2))")
10141051
self.assertRepr(v.b.q.s, "(s (slice (slice (slice (sig v) 1:9) 4:8) 2:4))")
1052+
self.assertRepr(S.format(v, ""), """
1053+
(format-struct (sig v)
1054+
('a' (format '{}' (slice (sig v) 0:1)))
1055+
('b' (format-struct (slice (sig v) 1:9)
1056+
('p' (format '{}' (slice (slice (sig v) 1:9) 0:4)))
1057+
('q' (format-struct (slice (slice (sig v) 1:9) 4:8)
1058+
('r' (format '{}' (slice (slice (slice (sig v) 1:9) 4:8) 0:2)))
1059+
('s' (format '{}' (slice (slice (slice (sig v) 1:9) 4:8) 2:4)))
1060+
))
1061+
))
1062+
)
1063+
""")
10151064

10161065
def test_construct_init(self):
10171066
class S(data.Struct):

0 commit comments

Comments
 (0)