/*
 * JavaScript code written by Robert Mars (rmars@cisco.com) based on
 * Java code written by Jeremy Allison (jra@cygnus.com) based on
 * C code from Eric Young (eay@mincom.oz.au).
 */


//class Int32Manipulator
/**
 * Int32Manipulator class.
 * Provides byte manipulation functions used by the Des and
 * TripleDes code.
 *
 * JavaScript code written by Robert Mars (rmars@cisco.com) based on
 * Java code written by Jeremy Allison (jra@cygnus.com) based on
 * C code from Eric Young (eay@mincom.oz.au).
 */
function Int32Manipulator() {
  /**
   *
   * Convert 4 bytes from a byte array to a 32-bit int 
   * (read from the array as little-endian format).
   * Returns the 32 bit int.
   * @param b             Byte array to convert from.
   * @param start         offset in byte array to begin.
   *
   */
  Int32Manipulator.prototype.bytes_to_int=function(b, start) {
    return (b[start] & 0xff)|
      ((b[start+1] & 0xff) << 8) |
      ((b[start+2] & 0xff) << 16) |
      ((b[start+3] & 0xff) << 24);
  }

  /**
   *
   * Write a 32-bit int into 4 bytes of a byte array 
   * (write into the array as little-endian format).
   * @param bytes        Byte aray to write into.
   * @param offset       Offset into array to begin.
   * @param val          32-bit int to write.
   *
   */
  Int32Manipulator.prototype.set_int=function(bytes, offset, val) {
    bytes[offset++] = val & 0xff;
    bytes[offset++] = (val >>> 8) & 0xff;
    bytes[offset++] = (val >>> 16) & 0xff;
    bytes[offset++] = (val >>> 24) & 0xff;
  }


  /**
   * PERM_OP. Internal routine used by Des code.
   *
   */
  Int32Manipulator.prototype.PERM_OP=function(ref_to_a, ref_to_b, tmp, n, m) {
    var a = ref_to_a[0];
    var b = ref_to_b[0];
    tmp = ((a>>>n)^b)&m;
    b ^= tmp;
    a ^= tmp<<n;
    ref_to_a[0] = a;
    ref_to_b[0] = b;
  }

  /**
   * HPERM_OP. Internal routine used by Des code.
   *
   */
  Int32Manipulator.prototype.HPERM_OP=function(ref_to_a, tmp, n, m) {
    var a = ref_to_a[0];
    tmp = ((a<<(16-n))^a)&m;
    a = a^tmp^(tmp>>>(16-n));
    ref_to_a[0] = a;
  }
}
