# permute.py
from myhdl import always_comb, intbv

def permute(a, x, mapping):
  """
    permutation: 
      a: input signal
      x: output signal
      mapping: specifies which bit of a drives each bit of x.
        that is: x[i] = a[mapping[i]]
      a and x must be the same width
      the length of mapping equals the signal width
  """

  @always_comb
  def logic():
    tmp = intbv(0, min=0, max=len(mapping))
    for i in range(len(mapping)):
      tmp[:] = mapping[i]
      x.next[i] = a[int(tmp)]

  return logic