Пример #1
0
function packFrame(item) {
  var length = item.body.length;

  // write TYPE_AND_BASE128_SIZE
  var head = [(typeToNum[item.type] << 4) | (length & 0xf)];
  var i = 0;
  length >>= 4;
  while (length) {
    head[i++] |= 0x80;
    head[i] = length & 0x7f;
    length >>= 7;
  }

  if (typeof item.ref === "number") {
    // write BIG_ENDIAN_MODIFIED_BASE_128_NUMBER
    var offset = item.ref;
    // Calculate how many digits we need in base 128 and move the pointer
    i += Math.floor(Math.log(offset) / Math.log(0x80)) + 1;
    // Write the last digit
    head[i] = offset & 0x7f;
    // Then write the rest
    while (offset >>= 7) {
      head[--i] = 0x80 | (--offset & 0x7f);
    }
  }

  var parts = [bodec.fromArray(head)];
  if (typeof item.ref === "string") {
    parts.push(bodec.fromHex(item.ref));
  }
  parts.push(deflate(item.body));
  return bodec.join(parts);
}
Пример #2
0
  return function (item) {
    if (item === undefined) {
      if (left !== 0) throw new Error("Some items were missing");
      return emit();
    }
    if (typeof item.num === "number") {
      if (left !== undefined) throw new Error("Header already sent");
      left = item.num;
      write(packHeader(item.num));
    }
    else if (typeof item.type === "string" && bodec.isBinary(item.body)) {
      // The header must be sent before items.
      if (typeof left !== "number") throw new Error("Headers not sent yet");

      // Make sure we haven't sent all the items already
      if (!left) throw new Error("All items already sent");

      // Send the item in packstream format
      write(packFrame(item));

      // Send the checksum after the last item
      if (!--left) {
        emit(bodec.fromHex(sha1sum.digest()));
      }
    }
    else {
      throw new Error("Invalid item");
    }
  };