basic.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
  2. var B = require('../').Buffer
  3. var test = require('tape')
  4. test('instanceof Buffer', function (t) {
  5. var buf = new B([1, 2])
  6. t.ok(buf instanceof B)
  7. t.end()
  8. })
  9. test('convert to Uint8Array in modern browsers', function (t) {
  10. if (B.TYPED_ARRAY_SUPPORT) {
  11. var buf = new B([1, 2])
  12. var uint8array = new Uint8Array(buf.buffer)
  13. t.ok(uint8array instanceof Uint8Array)
  14. t.equal(uint8array[0], 1)
  15. t.equal(uint8array[1], 2)
  16. } else {
  17. t.pass('object impl: skipping test')
  18. }
  19. t.end()
  20. })
  21. test('indexes from a string', function (t) {
  22. var buf = new B('abc')
  23. t.equal(buf[0], 97)
  24. t.equal(buf[1], 98)
  25. t.equal(buf[2], 99)
  26. t.end()
  27. })
  28. test('indexes from an array', function (t) {
  29. var buf = new B([ 97, 98, 99 ])
  30. t.equal(buf[0], 97)
  31. t.equal(buf[1], 98)
  32. t.equal(buf[2], 99)
  33. t.end()
  34. })
  35. test('setting index value should modify buffer contents', function (t) {
  36. var buf = new B([ 97, 98, 99 ])
  37. t.equal(buf[2], 99)
  38. t.equal(buf.toString(), 'abc')
  39. buf[2] += 10
  40. t.equal(buf[2], 109)
  41. t.equal(buf.toString(), 'abm')
  42. t.end()
  43. })
  44. test('storing negative number should cast to unsigned', function (t) {
  45. var buf = new B(1)
  46. if (B.TYPED_ARRAY_SUPPORT) {
  47. // This does not work with the object implementation -- nothing we can do!
  48. buf[0] = -3
  49. t.equal(buf[0], 253)
  50. }
  51. buf = new B(1)
  52. buf.writeInt8(-3, 0)
  53. t.equal(buf[0], 253)
  54. t.end()
  55. })
  56. test('test that memory is copied from array-like', function (t) {
  57. if (B.TYPED_ARRAY_SUPPORT) {
  58. var u = new Uint8Array(4)
  59. var b = new B(u)
  60. b[0] = 1
  61. b[1] = 2
  62. b[2] = 3
  63. b[3] = 4
  64. t.equal(u[0], 0)
  65. t.equal(u[1], 0)
  66. t.equal(u[2], 0)
  67. t.equal(u[3], 0)
  68. } else {
  69. t.pass('object impl: skipping test')
  70. }
  71. t.end()
  72. })