buffer_xor.ts 786 B

123456789101112131415161718
  1. import {Buffer} from "buffer";
  2. // Often in the code, when we want to calculate a content-based ID, where the content is an unordered set, we compute the XOR of the content-based IDs of the set elements. This is because XOR is insensitive to order.
  3. // Precondition that is NOT CHECKED: buffers must be of equal length
  4. // Returns new buffer that is bitwise XOR of inputs.
  5. export function bufferXOR(a: Buffer, b: Buffer): Buffer {
  6. const result = Buffer.allocUnsafe(a.length);
  7. for (let i=0; i<a.length; i+=4) {
  8. // Little endian is fastest, because native to Intel CPUs
  9. result.writeInt32LE(a.readInt32LE(i) ^ b.readInt32LE(i), i);
  10. }
  11. return result;
  12. }
  13. export function buffersXOR(...args: Buffer[]): Buffer {
  14. return args.reduce((a,b) => bufferXOR(a,b), Buffer.alloc(32));
  15. }