reinterpretUntilZeros.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var fs = require('fs')
  2. var assert = require('assert')
  3. var weak = require('weak')
  4. var ref = require('../')
  5. describe('reinterpretUntilZeros()', function () {
  6. beforeEach(gc)
  7. it('should return a new Buffer instance up until the first 0', function () {
  8. var buf = new Buffer('hello\0world')
  9. var buf2 = buf.reinterpretUntilZeros(1)
  10. assert.equal(buf2.length, 'hello'.length)
  11. assert.equal(buf2.toString(), 'hello')
  12. })
  13. it('should return a new Buffer instance up until the first 0 starting from offset', function () {
  14. var buf = new Buffer('hello\0world')
  15. var buf2 = buf.reinterpretUntilZeros(1, 3)
  16. assert.equal(buf2.length, 'lo'.length)
  17. assert.equal(buf2.toString(), 'lo')
  18. })
  19. it('should return a new Buffer instance up until the first 2-byte sequence of 0s', function () {
  20. var str = 'hello world'
  21. var buf = new Buffer(50)
  22. var len = buf.write(str, 'ucs2')
  23. buf.writeInt16LE(0, len) // NULL terminate the string
  24. var buf2 = buf.reinterpretUntilZeros(2)
  25. assert.equal(str.length, buf2.length / 2)
  26. assert.equal(buf2.toString('ucs2'), str)
  27. })
  28. it('should return a large Buffer instance > 10,000 bytes with UTF16-LE char bytes', function () {
  29. var data = fs.readFileSync(__dirname + '/utf16le.bin');
  30. var strBuf = ref.reinterpretUntilZeros(data, 2);
  31. assert(strBuf.length > 10000);
  32. var str = strBuf.toString('ucs2');
  33. // the data in `utf16le.bin` should be a JSON parsable string
  34. assert(JSON.parse(str));
  35. })
  36. })