All files / node-coap/lib block.js

100% Statements 37/37
92% Branches 23/25
100% Functions 5/5
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79                  17x   1x             1x 6x 1x 1x 1x     6x 1x     5x 1x     4x   4x 4x   4x 1x 3x 1x   2x     4x     1x 4x 1x 3x 1x 2x 1x   1x   3x   3x 3x 3x   3x             1x 9x     1x 1x  
/*
 * Copyright (c) 2013-2021 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */
 
function isNullOrUndefined(obj) {
  return typeof obj === "undefined" || obj === null
}
var TwoPowTwenty = 1048575
/**
 * 
 * @param {Number} sequenceNumber The block sequence number.
 * @param {Boolean} moreBlocks If there are more blocks to follow
 * @param {Number} blockSize 
 */
module.exports.generateBlockOption = function(sequenceNumber, moreBlocks, blockSize) {
  if(typeof sequenceNumber === "object") {
    moreBlocks = sequenceNumber.moreBlocks
    blockSize = sequenceNumber.blockSize
    sequenceNumber = sequenceNumber.sequenceNumber
  }
 
  if(isNullOrUndefined(sequenceNumber) || isNullOrUndefined(blockSize) || isNullOrUndefined(sequenceNumber)) {
    throw new Error("Invalid parameters")
  }
 
  if(sequenceNumber > TwoPowTwenty) {
    throw new Error("Sequence number out of range")
  }
 
  var buff = Buffer.alloc(4)
 
  var value = (sequenceNumber << 4) | ((moreBlocks?(1):(0)) << 3) | (blockSize & 7)
  buff.writeInt32BE(value)
 
  if(sequenceNumber >= 4096) {
    buff = buff.slice(1, 4)
  } else if(sequenceNumber >= 16) {
    buff = buff.slice(2, 4)
  } else {
    buff = buff.slice(3, 4)
  }
  
  return buff
}
 
module.exports.parseBlockOption = function(buff) {
  if(buff.length == 1)
    buff = Buffer.concat([Buffer.alloc(3), buff])
  else if(buff.length == 2)
    buff = Buffer.concat([Buffer.alloc(2), buff])
  else if(buff.length == 3)
    buff = Buffer.concat([Buffer.alloc(1), buff])
  else
    throw new Error("Invalid block option buffer length. Must be 1, 2 or 3. It is " + buff.length)
 
  var value = buff.readInt32BE()
 
  var sequenceNumber = (value >> 4) & TwoPowTwenty
  var moreBlocks = ((value & 8) === 8)?1:0
  var blockSize = value & 7
 
  return {
    sequenceNumber: sequenceNumber,
    moreBlocks: moreBlocks,
    blockSize: blockSize
  }
}
 
module.exports.exponentToByteSize = function(expo) {
  return Math.pow(2, expo+4)
}
 
module.exports.byteSizeToExponent = function(byteSize) {
  return Math.round(Math.log(byteSize) / Math.log(2) - 4)
}