reinterpret.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var assert = require('assert')
  2. var weak = require('weak')
  3. var ref = require('../')
  4. describe('reinterpret()', function () {
  5. beforeEach(gc)
  6. it('should return a new Buffer instance at the same address', function () {
  7. var buf = new Buffer('hello world')
  8. var small = buf.slice(0, 0)
  9. assert.strictEqual(0, small.length)
  10. assert.strictEqual(buf.address(), small.address())
  11. var reinterpreted = small.reinterpret(buf.length)
  12. assert.strictEqual(buf.address(), reinterpreted.address())
  13. assert.strictEqual(buf.length, reinterpreted.length)
  14. assert.strictEqual(buf.toString(), reinterpreted.toString())
  15. })
  16. it('should return a new Buffer instance starting at the offset address', function () {
  17. var buf = new Buffer('hello world')
  18. var offset = 3
  19. var small = buf.slice(offset, buf.length)
  20. assert.strictEqual(buf.length - offset, small.length)
  21. assert.strictEqual(buf.address() + offset, small.address())
  22. var reinterpreted = buf.reinterpret(small.length, offset)
  23. assert.strictEqual(small.address(), reinterpreted.address())
  24. assert.strictEqual(small.length, reinterpreted.length)
  25. assert.strictEqual(small.toString(), reinterpreted.toString())
  26. })
  27. it('should retain a reference to the original Buffer when reinterpreted', function () {
  28. var origGCd = false
  29. var otherGCd = false
  30. var buf = new Buffer(1)
  31. weak(buf, function () { origGCd = true })
  32. var other = buf.reinterpret(0)
  33. weak(other, function () { otherGCd = true })
  34. assert(!origGCd, '"buf" has been garbage collected too soon')
  35. assert(!otherGCd, '"other" has been garbage collected too soon')
  36. // try to GC `buf`
  37. buf = null
  38. gc()
  39. assert(!origGCd, '"buf" has been garbage collected too soon')
  40. assert(!otherGCd, '"other" has been garbage collected too soon')
  41. // now GC `other`
  42. other = null
  43. gc()
  44. assert(otherGCd, '"other" has not been garbage collected')
  45. assert(origGCd, '"buf" has not been garbage collected')
  46. })
  47. })