When lengths are different, smaller should be zero-padded from the left

Open
#14 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
50/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
javascript
Domain
tooling

Research direction

Start by reproducing the shown xor(Buffer.from(...)) call and inspect the module's buffer-alignment logic for unequal lengths. Done means the call returns the stated expected hex value, with equal-length inputs continuing to work as before.

Written by the indexing model from the issue text.

Description

xor(Buffer.from('7f5022b7e361a9ef34f2792b045bf413a985f8caf7978e67027dbb01b137b67d', 'hex'),
Buffer.from('C8834C1FcF0Df6623Fc8C8eD25064A4148D99388', 'hex'))

gives the wrong value. The answer should be
7f5022b7e361a9ef34f2792bccd8b80c66880ea8c85f468a277bf140f9ee25f5, but it gives b7d36ea82c6c5f8d0b3ab1c6215dbe52e15c6b42f7978e67027dbb01b137b67d

The reason is that it doesn't zero pad it from the left. It only indirectly zero-pads it to the right when sizes mismatch, because it will be comparing with NaNs which are treated as zeroes when the index exceeds the smaller buffer's length.

I fixed this by adding zero-padding:

var Buffer = require('safe-buffer').Buffer

module.exports = function xor (a, b) {
  // pad the shorter buffer with 0s
  let padded
  let a_
  let b_
  if(a.length > b.length){
    padded = Buffer.alloc(a.length)
    a_ = a
    b.copy(padded, padded.length-b.length)
    b_ = padded

  } else if(a.length < b.length){
    padded = Buffer.alloc(b.length)
    a_ = a.copy(padded, padded.length-a.length)
    a_ = padded
    b_ = b
  } else {
    a_ = a;
    b_ = b;
  }

  var length = a_.length
  var buffer = Buffer.allocUnsafe(length)

  for (var i = 0; i < length; ++i) {
    buffer[i] = a_[i] ^ b_[i]
  }
  return buffer
}

It is far longer than your original code and perhaps there's a more elegant solution. If you'd like, I can submit this as a PR, or feel free to copy if you want to add it.

Dominant language
JavaScript
Stars
32
Forks
5
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from browserify/buffer-xor

All issues in browserify/buffer-xor

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.