const test = require('tape')
const toBuffer = require('../')

test('convert to buffer from Uint8Array', function (t) {
  let arr = new Uint8Array([1, 2, 3])
  arr = toBuffer(arr)

  t.deepEqual(arr, Buffer.from([1, 2, 3]), 'contents equal')
  t.equal(arr.readUInt8(0), 1)
  t.equal(arr.readUInt8(1), 2)
  t.equal(arr.readUInt8(2), 3)

  t.ok(Buffer.isBuffer(arr), 'is buffer')
  t.ok(arr instanceof Uint8Array, 'is Uint8Array')
  t.end()
})

test('convert to buffer from Uint8Array with larger underlying ArrayBuffer', function (t) {
  let arr = new Uint8Array([1, 2, 3]).subarray(1, 2)
  arr = toBuffer(arr)

  t.deepEqual(arr, Buffer.from([2]), 'contents equal')
  t.equal(arr.readUInt8(0), 2)

  t.ok(Buffer.isBuffer(arr), 'is buffer')
  t.ok(arr instanceof Uint8Array, 'is Uint8Array')
  t.end()
})

test('convert to buffer from Uint32Array', function (t) {
  let arr = new Uint32Array([1, 2, 3])
  arr = toBuffer(arr)

  t.deepEqual(arr, Buffer.from([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]), 'contents equal')
  t.equal(arr.readUInt32LE(0), 1)
  t.equal(arr.readUInt32LE(4), 2)
  t.equal(arr.readUInt32LE(8), 3)

  t.ok(Buffer.isBuffer(arr), 'is buffer')
  t.ok(arr instanceof Uint8Array, 'is Uint8Array')
  t.end()
})

test('convert to buffer from Uint32Array with larger underlying ArrayBuffer', function (t) {
  let arr = new Uint32Array([1, 2, 3]).subarray(1, 2)
  arr = toBuffer(arr)

  t.deepEqual(arr, Buffer.from([2, 0, 0, 0]), 'contents equal')
  t.equal(arr.readUInt32LE(0), 2)

  t.ok(Buffer.isBuffer(arr), 'is buffer')
  t.ok(arr instanceof Uint8Array, 'is Uint8Array')
  t.end()
})
