genlib/coding: gracefully handle flen(i) < 2
authorRobert Jordens <jordens@gmail.com>
Wed, 19 Mar 2014 23:47:26 +0000 (17:47 -0600)
committerSebastien Bourdeauducq <sb@m-labs.hk>
Thu, 20 Mar 2014 01:12:27 +0000 (18:12 -0700)
migen/genlib/coding.py
migen/test/test_coding.py

index ed0315576ecf5850a4ffa805176131bb1526e511..df89f6cc14ade048e235cfcb66df14306848beb1 100644 (file)
@@ -26,7 +26,7 @@ class Encoder(Module):
        """
        def __init__(self, width):
                self.i = Signal(width) # one-hot
-               self.o = Signal(max=width) # binary
+               self.o = Signal(max=max(2, width)) # binary
                self.n = Signal() # invalid: none or multiple
                act = dict((1<<j, self.o.eq(j)) for j in range(width))
                act["default"] = self.n.eq(1)
@@ -54,7 +54,7 @@ class PriorityEncoder(Module):
        """
        def __init__(self, width):
                self.i = Signal(width) # one-hot, lsb has priority
-               self.o = Signal(max=width) # binary
+               self.o = Signal(max=max(2, width)) # binary
                self.n = Signal() # none
                for j in range(width)[::-1]: # last has priority
                        self.comb += If(self.i[j], self.o.eq(j))
@@ -82,7 +82,7 @@ class Decoder(Module):
        """
 
        def __init__(self, width):
-               self.i = Signal(max=width) # binary
+               self.i = Signal(max=max(2, width)) # binary
                self.n = Signal() # none/invalid
                self.o = Signal(width) # one-hot
                act = dict((j, self.o.eq(1<<j)) for j in range(width))
index 1a61158a6b00f87df1d65380e4a2ab7e33b5c265..c21d726ff6362e15aabd0f3017f8676d4e6f4475 100644 (file)
@@ -75,3 +75,28 @@ class DecCase(SimCase, unittest.TestCase):
                        else:
                                self.assertEqual(o, 1<<i)
                self.run_with(cb, 256)
+
+class SmallPrioEncCase(SimCase, unittest.TestCase):
+       class TestBench(SimBench):
+               def __init__(self):
+                       self.submodules.dut = PriorityEncoder(1)
+
+       def test_sizes(self):
+               self.assertEqual(flen(self.tb.dut.i), 1)
+               self.assertEqual(flen(self.tb.dut.o), 1)
+               self.assertEqual(flen(self.tb.dut.n), 1)
+
+       def test_run_sequence(self):
+               seq = list(range(1))
+               def cb(tb, tbp):
+                       if seq:
+                               tbp.dut.i = seq.pop(0)
+                       i = tbp.dut.i
+                       if tbp.dut.n:
+                               self.assertEqual(i, 0)
+                       else:
+                               o = tbp.dut.o
+                               if o > 0:
+                                       self.assertEqual(i & 1<<(o - 1), 0)
+                               self.assertGreaterEqual(i, 1<<o)
+               self.run_with(cb, 5)