import platform
import struct


def _ioc_encode(direction, number, structure):
  """
  ioctl command encoding helper function
  Calculates the appropriate spidev ioctl op argument given the direction,
  command number, and argument structure in python's struct.pack format.
  Returns a tuple of the calculated op and the struct.pack format
  See Linux kernel source file /include/uapi/asm/ioctl.h
  """
  ioc_magic = ord("k")
  ioc_nrbits = 8
  ioc_typebits = 8
  if platform.machine() == "mips":
    ioc_sizebits = 13
  else:
    ioc_sizebits = 14

  ioc_nrshift = 0
  ioc_typeshift = ioc_nrshift + ioc_nrbits
  ioc_sizeshift = ioc_typeshift + ioc_typebits
  ioc_dirshift = ioc_sizeshift + ioc_sizebits

  size = struct.calcsize(structure)

  operation = (
    (direction << ioc_dirshift)
    | (ioc_magic << ioc_typeshift)
    | (number << ioc_nrshift)
    | (size << ioc_sizeshift)
  )

  return direction, operation, structure