pointer.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var assert = require('assert')
  2. var weak = require('weak')
  3. var ref = require('../')
  4. describe('pointer', function () {
  5. var test = new Buffer('hello world')
  6. beforeEach(gc)
  7. it('should write and read back a pointer (Buffer) in a Buffer', function () {
  8. var buf = new Buffer(ref.sizeof.pointer)
  9. ref.writePointer(buf, 0, test)
  10. var out = ref.readPointer(buf, 0, test.length)
  11. assert.strictEqual(out.length, test.length)
  12. for (var i = 0, l = out.length; i < l; i++) {
  13. assert.strictEqual(out[i], test[i])
  14. }
  15. assert.strictEqual(ref.address(out), ref.address(test))
  16. })
  17. it('should retain references to a written pointer in a Buffer', function (done) {
  18. var child_gc = false
  19. var parent_gc = false
  20. var child = new Buffer('a pointer holding some data...')
  21. var parent = new Buffer(ref.sizeof.pointer)
  22. weak(child, function () { child_gc = true })
  23. weak(parent, function () { parent_gc = true })
  24. ref.writePointer(parent, 0, child)
  25. assert(!child_gc, '"child" has been garbage collected too soon')
  26. assert(!parent_gc, '"parent" has been garbage collected too soon')
  27. // try to GC `child`
  28. child = null
  29. gc()
  30. assert(!child_gc, '"child" has been garbage collected too soon')
  31. assert(!parent_gc, '"parent" has been garbage collected too soon')
  32. // now GC `parent`
  33. parent = null
  34. setImmediate(function () {
  35. gc()
  36. assert(parent_gc, '"parent" has not been garbage collected')
  37. assert(child_gc, '"child" has not been garbage collected')
  38. done()
  39. });
  40. })
  41. it('should throw an Error when reading from the NULL pointer', function () {
  42. assert.throws(function () {
  43. ref.NULL.readPointer()
  44. })
  45. })
  46. it('should return a 0-length Buffer when reading a NULL pointer', function () {
  47. var buf = new Buffer(ref.sizeof.pointer)
  48. ref.writePointer(buf, 0, ref.NULL)
  49. var out = ref.readPointer(buf, 0, 100)
  50. assert.strictEqual(out.length, 0)
  51. })
  52. describe('offset', function () {
  53. it('should read two pointers next to each other in memory', function () {
  54. var buf = new Buffer(ref.sizeof.pointer * 2)
  55. var a = new Buffer('hello')
  56. var b = new Buffer('world')
  57. buf.writePointer(a, 0 * ref.sizeof.pointer)
  58. buf.writePointer(b, 1 * ref.sizeof.pointer)
  59. var _a = buf.readPointer(0 * ref.sizeof.pointer)
  60. var _b = buf.readPointer(1 * ref.sizeof.pointer)
  61. assert.equal(a.address(), _a.address())
  62. assert.equal(b.address(), _b.address())
  63. })
  64. })
  65. })