speed up ==, hash, <, >, <=, and >= for plain_data
[nmutil.git] / src / nmutil / clz.py
index cbf3397037e27a2e4c7c86d7dfa45bd4a7bdc266..70e0f513c45b52034c9aac5aac8d86dd55d76a38 100644 (file)
@@ -1,10 +1,25 @@
+# SPDX-License-Identifier: LGPL-3-or-later
 from nmigen import Module, Signal, Elaboratable, Cat, Repl
 import math
 """ This module is much more efficient than PriorityEncoder
     although it is functionally identical.
     see https://bugs.libre-soc.org/show_bug.cgi?id=326
+
+    This work is funded through NLnet under Grant 2019-02-012
+
+    License: LGPLv3+
+
 """
 
+
+def clz(v, width):
+    """count leading zeros."""
+    assert isinstance(width, int) and 0 <= width
+    max_v = (1 << width) - 1
+    assert isinstance(v, int) and 0 <= v <= max_v
+    return max_v.bit_length() - v.bit_length()
+
+
 class CLZ(Elaboratable):
     def __init__(self, width):
         self.width = width
@@ -81,4 +96,3 @@ class CLZ(Elaboratable):
         comb += self.lz.eq(pairs[0][0])
 
         return m
-