如何比较节点

时间:2016-07-09 19:42:31

标签: javascript node.js buffer memory-address

我想要一个能够测试一个缓冲区的起始地址是否包含在另一个缓冲区分配的内存中的函数。像这样:

function contains(parent, child) {...}

// allocate 44 bytes
let buffer1 = Buffer.alloc(44);
// copy 44 bytes to a new address
let buffer2 = Buffer.from(buffer1);
// make reference to 8th byte of buffer1
let buffer3 = buffer1.slice(8);
// make reference to last byte of buffer2
let buffer4 = buffer2.slice(buffer2.byteLength - 1);

console.log(contains(buffer1, buffer2)); // false
console.log(contains(buffer1, buffer3)); // true
console.log(contains(buffer1, buffer4)); // false
console.log(contains(buffer2, buffer3)); // false
console.log(contains(buffer2, buffer4)); // true
console.log(contains(buffer3, buffer1)); // false - buffer1 starts outside of buffer3
console.log(contains(buffer3, buffer4)); // false
console.log(contains(buffer4, buffer2)); // false - buffer2 starts outside of buffer4

我有一个可行的解决方案,但它需要我迭代整个父缓冲区,然后更改值以测试它们是否共享。我正在寻找一个O(1)或至多O(N)的解决方案,无需操作:

function contains(parent, child) {
  let index = 0;

  do {
    index = parent.indexOf(child[0], index);

    if (index < 0) {
      break;
    }

    parent[index]++;

    if (child[0] === parent[index]--) {
      return true;
    }
  } while (index++ < parent.byteLength - child.byteLength);

  return false;
}

0 个答案:

没有答案