0
function createUnsafeBuffer(size) {
  zeroFill[0] = 0;
  try {
    //直接返回new FastBuffer(size)
    return new FastBuffer(size);
  } finally {
    zeroFill[0] = 1;
  }
}
Buffer.alloc = function alloc(size, fill, encoding) {
  assertSize(size);
  if (fill !== undefined && fill !== 0 && size > 0) {
    const buf = createUnsafeBuffer(size);
    return _fill(buf, fill, 0, buf.length, encoding);
  }
  // fill未定义或为0的时候也是返回new FastBuffer(size)
  return new FastBuffer(size);
};

FastBuffer是继承自Uint8Array,Uint8Array数组类型创建时内容会被初始化为 0。
既然会被初始化为0,相当于填充了0那为什么createUnsafeBuffer是不安全的,FastBuffer同样操作却是安全的呢?

6月12日提问
1 个回答
0

已采纳

因为这句代码 zeroFill[0] = 0; 显示的关闭了 0 填充行为。 注释就在上一行写的

// A toggle used to access the zero fill setting of the array buffer allocator
// in C++.
// |zeroFill| can be undefined when running inside an isolate where we
// do not own the ArrayBuffer allocator.  Zero fill is always on in that case.
const zeroFill = bindingZeroFill || [0];

function createUnsafeBuffer(size) {
  zeroFill[0] = 0;
  try {
    return new FastBuffer(size);
  } finally {
    zeroFill[0] = 1;
  }
}

撰写答案

推广链接