test-buffer-badhex.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var Buffer = require('../../').Buffer;
  3. var assert = require('assert');
  4. var Buffer = require('../../').Buffer;
  5. // Test hex strings and bad hex strings
  6. {
  7. var buf1 = Buffer.alloc(4);
  8. assert.strictEqual(buf1.length, 4);
  9. assert.deepStrictEqual(buf1, new Buffer([0, 0, 0, 0]));
  10. assert.strictEqual(buf1.write('abcdxx', 0, 'hex'), 2);
  11. assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0x00, 0x00]));
  12. assert.strictEqual(buf1.toString('hex'), 'abcd0000');
  13. assert.strictEqual(buf1.write('abcdef01', 0, 'hex'), 4);
  14. assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0xef, 0x01]));
  15. assert.strictEqual(buf1.toString('hex'), 'abcdef01');
  16. var buf2 = Buffer.from(buf1.toString('hex'), 'hex');
  17. assert.strictEqual(buf1.toString('hex'), buf2.toString('hex'));
  18. var buf3 = Buffer.alloc(5);
  19. assert.strictEqual(buf3.write('abcdxx', 1, 'hex'), 2);
  20. assert.strictEqual(buf3.toString('hex'), '00abcd0000');
  21. var buf4 = Buffer.alloc(4);
  22. assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0]));
  23. assert.strictEqual(buf4.write('xxabcd', 0, 'hex'), 0);
  24. assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0]));
  25. assert.strictEqual(buf4.write('xxab', 1, 'hex'), 0);
  26. assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0]));
  27. assert.strictEqual(buf4.write('cdxxab', 0, 'hex'), 1);
  28. assert.deepStrictEqual(buf4, new Buffer([0xcd, 0, 0, 0]));
  29. var buf5 = Buffer.alloc(256);
  30. for (var i = 0; i < 256; i++)
  31. buf5[i] = i;
  32. var hex = buf5.toString('hex');
  33. assert.deepStrictEqual(Buffer.from(hex, 'hex'), buf5);
  34. var badHex = hex.slice(0, 256) + 'xx' + hex.slice(256, 510);
  35. assert.deepStrictEqual(Buffer.from(badHex, 'hex'), buf5.slice(0, 128));
  36. }