test.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var Buffer = require('buffer').Buffer
  2. var test = require('tape')
  3. var toArrayBuffer = require('.')
  4. function elementsEqual (ab, buffer) {
  5. var view = new Uint8Array(ab)
  6. for (var i = 0; i < view.length; i++) {
  7. if (view[i] !== buffer[i]) {
  8. return false
  9. }
  10. }
  11. return true
  12. }
  13. test('Basic behavior', function (t) {
  14. var buf = new Buffer(10)
  15. for (var i = 0; i < 10; i++) {
  16. buf[i] = i
  17. }
  18. var ab = toArrayBuffer(buf)
  19. t.equals(ab.byteLength, 10, 'correct length')
  20. t.ok(elementsEqual(ab, buf), 'elements equal')
  21. t.end()
  22. })
  23. test('Behavior when input is a subarray 1', function (t) {
  24. var origBuf = new Buffer(10)
  25. for (var i = 0; i < 10; i++) {
  26. origBuf[i] = i
  27. }
  28. var buf = origBuf.slice(1)
  29. var ab = toArrayBuffer(buf)
  30. t.equals(ab.byteLength, 9, 'correct length')
  31. t.ok(elementsEqual(ab, buf), 'elements equal')
  32. t.notOk(ab === buf.buffer, 'the underlying ArrayBuffer is not returned when incorrect')
  33. t.end()
  34. })
  35. test('Behavior when input is a subarray 2', function (t) {
  36. var origBuf = new Buffer(10)
  37. for (var i = 0; i < 10; i++) {
  38. origBuf[i] = i
  39. }
  40. var buf = origBuf.slice(0, 9)
  41. var ab = toArrayBuffer(buf)
  42. t.equals(ab.byteLength, 9, 'correct length')
  43. t.ok(elementsEqual(ab, buf), 'elements equal')
  44. t.notOk(ab === buf.buffer, 'the underlying ArrayBuffer is not returned when incorrect')
  45. t.end()
  46. })