export const is_big_endian_system =
  new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x12;

export const is_little_endian_system =
  new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x78;

export const i8_to_ui8_array = (num) => {
  if (typeof num === 'string' || num instanceof String) {
    num = parseInt(num, 10);
  }

  const buffer = Buffer.alloc(1);
  buffer.writeInt8(num);
  return new Uint8Array(buffer);
};

export const ui8_array_to_i8 = (ar, offset) => {
  const buffer = Buffer.alloc(1);
  buffer[0] = ar[offset];

  return buffer.readInt8(0);
};

export const ui8_to_ui8_array = (num) => {
  if (typeof num === 'string' || num instanceof String) {
    num = parseInt(num, 10);
  }

  const buffer = Buffer.alloc(1);
  buffer.writeUInt8(num);
  return new Uint8Array(buffer);
};

export const ui8_array_to_ui8 = (ar, offset) => {
  const buffer = Buffer.alloc(1);
  buffer[0] = ar[offset];

  return buffer.readUInt8(0);
};

export const i16_to_be_ui8_array = (num) => {
  if (typeof num === 'string' || num instanceof String) {
    num = parseInt(num, 10);
  }

  const buffer = Buffer.alloc(2);
  buffer.writeInt16BE(num);
  return new Uint8Array(buffer);
};

export const be_ui8_array_to_i16 = (ar, offset) => {
  const buffer = Buffer.alloc(2);
  for (let i = offset; i < buffer.length + offset; i++) {
    buffer[i - offset] = ar[i];
  }
  return buffer.readInt16BE(0);
};

export const ui16_to_be_ui8_array = (num) => {
  if (typeof num === 'string' || num instanceof String) {
    num = parseInt(num, 10);
  }

  const buffer = Buffer.alloc(2);
  buffer.writeUInt16BE(num);
  return new Uint8Array(buffer);
};

export const be_ui8_array_to_ui16 = (ar, offset) => {
  const buffer = Buffer.alloc(2);
  for (let i = offset; i < buffer.length + offset; i++) {
    buffer[i - offset] = ar[i];
  }
  return buffer.readUInt16BE(0);
};

export const i32_to_be_ui8_array = (num) => {
  if (typeof num === 'string' || num instanceof String) {
    num = parseInt(num, 10);
  }

  const buffer = Buffer.alloc(4);
  buffer.writeInt32BE(num);
  return new Uint8Array(buffer);
};

export const be_ui8_array_to_i32 = (ar, offset) => {
  const buffer = Buffer.alloc(4);
  for (let i = offset; i < buffer.length + offset; i++) {
    buffer[i - offset] = ar[i];
  }
  return buffer.readInt32BE(0);
};

export const ui32_to_be_ui8_array = (num) => {
  if (typeof num === 'string' || num instanceof String) {
    num = parseInt(num, 10);
  }

  const buffer = Buffer.alloc(4);
  buffer.writeUInt32BE(num);
  return new Uint8Array(buffer);
};

export const be_ui8_array_to_ui32 = (ar, offset) => {
  const buffer = Buffer.alloc(4);
  for (let i = offset; i < buffer.length + offset; i++) {
    buffer[i - offset] = ar[i];
  }

  return buffer.readUInt32BE(0);
};
