JoshGlazebrook / smart-buffer

smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.
https://www.npmjs.com/package/smart-buffer
MIT License
102 stars 18 forks source link

Fix writing zero-terminated buffer #5

Closed Fr0sT-Brutal closed 7 years ago

Fr0sT-Brutal commented 7 years ago

writeBufferNT doesn't allocate a space for null byte; moreover it duplicates code. Code to check the bug:

var smb = new smbuf(1);
console.log(smb);
smb.writeBufferNT(Buffer.from('aaa'));
console.log(smb);
>arr.njs
SmartBuffer { buff: <Buffer 00>, length: 0, _readOffset: 0, _writeOffset: 0 }
SmartBuffer {
  buff: <Buffer 61 61 61>,
  length: 3,
  _readOffset: 0,
  _writeOffset: 4 }
coveralls commented 7 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling f12c8a4e35d8951fd697bf9eba0d29c0f328b082 on Fr0sT-Brutal:patch-1 into 56ded6259a34f213aa1b49338c1057d1ac79836e on JoshGlazebrook:master.

coveralls commented 7 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling f12c8a4e35d8951fd697bf9eba0d29c0f328b082 on Fr0sT-Brutal:patch-1 into 56ded6259a34f213aa1b49338c1057d1ac79836e on JoshGlazebrook:master.

Fr0sT-Brutal commented 7 years ago

Regarding test fail: terminator is written over instead of replace. But that's how writeStringNT works. So now they both work in the same way.

JoshGlazebrook commented 7 years ago

Okay so the issue with the test seems to be something else that also affects writeStringNT when using an offset.

var smb = new smbuf(1);
smb.writeString('hello');
smb.writeStringNT('aaa', 0);

SmartBuffer {
  buff: <Buffer 61 61 61 68 65 6c 6c 6f 00 00 00 00 00>,
  length: 9,
  _readOffset: 0,
  _writeOffset: 9 }

The problem is with:

this.writeString(value, offset, encoding);
this.writeUInt8(0x00);

When writing with an offset, the writeOffset is not updated to after where the string was inserted (which is correct). However, the writeUInt8 is writing at the current writeOffset and not right after where the string was written.

So a solution would be:

this.writeString(value, offset, encoding);
this.writeUInt8(0x00, (typeof offset === 'number' ? offset + value.length : this._writeOffset));
SmartBuffer {
  buff: <Buffer 61 61 61 00 68 65 6c 6c 6f a0 7e 80 03>,
  length: 9,
  _readOffset: 0,
  _writeOffset: 9 }

And the same with writeBufferNT.

I'll work on this later tonight when I get home.

JoshGlazebrook commented 7 years ago

Fixed on #5