add eq32 helper
[nmutil.git] / src / nmutil / util.py
1 from collections.abc import Iterable
2
3 # XXX this already exists in nmigen._utils
4 # see https://bugs.libre-soc.org/show_bug.cgi?id=297
5 def flatten(v):
6 if isinstance(v, Iterable):
7 for i in v:
8 yield from flatten(i)
9 else:
10 yield v
11
12 # tree reduction function. operates recursively.
13 def treereduce(tree, op, fn):
14 """treereduce: apply a map-reduce to a list.
15 examples: OR-reduction of one member of a list of Records down to a
16 single data point:
17 treereduce(tree, operator.or_, lambda x: getattr(x, "data_o"))
18 """
19 #print ("treereduce", tree)
20 if not isinstance(tree, list):
21 return tree
22 if len(tree) == 1:
23 return fn(tree[0])
24 if len(tree) == 2:
25 return op(fn(tree[0]), fn(tree[1]))
26 s = len(tree) // 2 # splitpoint
27 return op(treereduce(tree[:s], op, fn),
28 treereduce(tree[s:], op, fn))
29
30 # chooses assignment of 32 bit or full 64 bit depending on is_32bit
31 def eq32(is_32bit, dest, src):
32 return [dest[0:32].eq(src[0:32]),
33 dest[32:64].eq(Mux(is_32bit, 0, src[32:64]))]
34
35