hdl.rec: implement Record.like.
authorwhitequark <cz@m-labs.hk>
Tue, 2 Jul 2019 17:35:00 +0000 (17:35 +0000)
committerwhitequark <cz@m-labs.hk>
Tue, 2 Jul 2019 17:46:53 +0000 (17:46 +0000)
Fixes #120.

nmigen/hdl/rec.py
nmigen/test/test_hdl_rec.py

index 26b26f7ca451acc1431e138defbb50efaeb7536f..2c6694c8d9588f8a2fd0610b6500aab7d5c6c13e 100644 (file)
@@ -69,6 +69,16 @@ class Layout:
 
 # Unlike most Values, Record *can* be subclassed.
 class Record(Value):
+    @classmethod
+    def like(cls, other, name=None, name_suffix=None, src_loc_at=0):
+        if name is not None:
+            new_name = str(name)
+        elif name_suffix is not None:
+            new_name = other.name + str(name_suffix)
+        else:
+            new_name = tracer.get_var_name(depth=2 + src_loc_at, default=None)
+        return cls(other.layout, new_name)
+
     def __init__(self, layout, name=None, *, fields=None):
         if name is None:
             name = tracer.get_var_name(default=None)
index fc1959fc1d913109c480442fb9f01a641cd877cf..9c72a16eddb88548f3ae87e19a438f7caecf759c 100644 (file)
@@ -129,6 +129,16 @@ class RecordTestCase(FHDLTestCase):
         self.assertIs(r.stb, ns)
         self.assertIs(r.info, nr)
 
+    def test_like(self):
+        r1 = Record([("a", 1), ("b", 2)])
+        r2 = Record.like(r1)
+        self.assertEqual(r1.layout, r2.layout)
+        self.assertEqual(r2.name, "r2")
+        r3 = Record.like(r1, name="foo")
+        self.assertEqual(r3.name, "foo")
+        r4 = Record.like(r1, name_suffix="foo")
+        self.assertEqual(r4.name, "r1foo")
+
 
 class ConnectTestCase(FHDLTestCase):
     def setUp_flat(self):