module BinData::BitField

def create_fixed_clamp_code(nbits, signed)

def create_fixed_clamp_code(nbits, signed)
  if nbits == 1 && signed == :signed
    raise "signed bitfield must have more than one bit"
  end
  if signed == :signed
    max = "(1 << (#{nbits} - 1)) - 1"
    min = "-((#{max}) + 1)"
  else
    min = "0"
    max = "(1 << #{nbits}) - 1"
  end
  clamp = "(val = val.clamp(#{min}, #{max}))"
  if nbits == 1
    # allow single bits to be used as booleans
    clamp = "(val == true) ? 1 : (not val) ? 0 : #{clamp}"
  end
  "val = #{clamp}"
end