Best Python code snippet using ATX
buffer.js
Source:buffer.js  
1'use strict';2const binding = internalBinding('buffer');3const {4  ERR_BUFFER_OUT_OF_BOUNDS,5  ERR_INVALID_ARG_TYPE,6  ERR_OUT_OF_RANGE7} = require('internal/errors').codes;8const { validateNumber } = require('internal/validators');9const { setupBufferJS } = binding;10// Remove from the binding so that function is only available as exported here.11// (That is, for internal use only.)12delete binding.setupBufferJS;13// Temporary buffers to convert numbers.14const float32Array = new Float32Array(1);15const uInt8Float32Array = new Uint8Array(float32Array.buffer);16const float64Array = new Float64Array(1);17const uInt8Float64Array = new Uint8Array(float64Array.buffer);18// Check endianness.19float32Array[0] = -1; // 0xBF80000020// Either it is [0, 0, 128, 191] or [191, 128, 0, 0]. It is not possible to21// check this with `os.endianness()` because that is determined at compile time.22const bigEndian = uInt8Float32Array[3] === 0;23function checkBounds(buf, offset, byteLength) {24  validateNumber(offset, 'offset');25  if (buf[offset] === undefined || buf[offset + byteLength] === undefined)26    boundsError(offset, buf.length - (byteLength + 1));27}28function checkInt(value, min, max, buf, offset, byteLength) {29  if (value > max || value < min) {30    throw new ERR_OUT_OF_RANGE('value', `>= ${min} and <= ${max}`, value);31  }32  checkBounds(buf, offset, byteLength);33}34function boundsError(value, length, type) {35  if (Math.floor(value) !== value) {36    validateNumber(value, type);37    throw new ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value);38  }39  if (length < 0)40    throw new ERR_BUFFER_OUT_OF_BOUNDS();41  throw new ERR_OUT_OF_RANGE(type || 'offset',42                             `>= ${type ? 1 : 0} and <= ${length}`,43                             value);44}45// Read integers.46function readUIntLE(offset, byteLength) {47  if (offset === undefined)48    throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset);49  if (byteLength === 6)50    return readUInt48LE(this, offset);51  if (byteLength === 5)52    return readUInt40LE(this, offset);53  if (byteLength === 3)54    return readUInt24LE(this, offset);55  if (byteLength === 4)56    return this.readUInt32LE(offset);57  if (byteLength === 2)58    return this.readUInt16LE(offset);59  if (byteLength === 1)60    return this.readUInt8(offset);61  boundsError(byteLength, 6, 'byteLength');62}63function readUInt48LE(buf, offset = 0) {64  validateNumber(offset, 'offset');65  const first = buf[offset];66  const last = buf[offset + 5];67  if (first === undefined || last === undefined)68    boundsError(offset, buf.length - 6);69  return first +70    buf[++offset] * 2 ** 8 +71    buf[++offset] * 2 ** 16 +72    buf[++offset] * 2 ** 24 +73    (buf[++offset] + last * 2 ** 8) * 2 ** 32;74}75function readUInt40LE(buf, offset = 0) {76  validateNumber(offset, 'offset');77  const first = buf[offset];78  const last = buf[offset + 4];79  if (first === undefined || last === undefined)80    boundsError(offset, buf.length - 5);81  return first +82    buf[++offset] * 2 ** 8 +83    buf[++offset] * 2 ** 16 +84    buf[++offset] * 2 ** 24 +85    last * 2 ** 32;86}87function readUInt32LE(offset = 0) {88  validateNumber(offset, 'offset');89  const first = this[offset];90  const last = this[offset + 3];91  if (first === undefined || last === undefined)92    boundsError(offset, this.length - 4);93  return first +94    this[++offset] * 2 ** 8 +95    this[++offset] * 2 ** 16 +96    last * 2 ** 24;97}98function readUInt24LE(buf, offset = 0) {99  validateNumber(offset, 'offset');100  const first = buf[offset];101  const last = buf[offset + 2];102  if (first === undefined || last === undefined)103    boundsError(offset, buf.length - 3);104  return first + buf[++offset] * 2 ** 8 + last * 2 ** 16;105}106function readUInt16LE(offset = 0) {107  validateNumber(offset, 'offset');108  const first = this[offset];109  const last = this[offset + 1];110  if (first === undefined || last === undefined)111    boundsError(offset, this.length - 2);112  return first + last * 2 ** 8;113}114function readUInt8(offset = 0) {115  validateNumber(offset, 'offset');116  const val = this[offset];117  if (val === undefined)118    boundsError(offset, this.length - 1);119  return val;120}121function readUIntBE(offset, byteLength) {122  if (offset === undefined)123    throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset);124  if (byteLength === 6)125    return readUInt48BE(this, offset);126  if (byteLength === 5)127    return readUInt40BE(this, offset);128  if (byteLength === 3)129    return readUInt24BE(this, offset);130  if (byteLength === 4)131    return this.readUInt32BE(offset);132  if (byteLength === 2)133    return this.readUInt16BE(offset);134  if (byteLength === 1)135    return this.readUInt8(offset);136  boundsError(byteLength, 6, 'byteLength');137}138function readUInt48BE(buf, offset = 0) {139  validateNumber(offset, 'offset');140  const first = buf[offset];141  const last = buf[offset + 5];142  if (first === undefined || last === undefined)143    boundsError(offset, buf.length - 6);144  return (first * 2 ** 8 + buf[++offset]) * 2 ** 32 +145    buf[++offset] * 2 ** 24 +146    buf[++offset] * 2 ** 16 +147    buf[++offset] * 2 ** 8 +148    last;149}150function readUInt40BE(buf, offset = 0) {151  validateNumber(offset, 'offset');152  const first = buf[offset];153  const last = buf[offset + 4];154  if (first === undefined || last === undefined)155    boundsError(offset, buf.length - 5);156  return first * 2 ** 32 +157    buf[++offset] * 2 ** 24 +158    buf[++offset] * 2 ** 16 +159    buf[++offset] * 2 ** 8 +160    last;161}162function readUInt32BE(offset = 0) {163  validateNumber(offset, 'offset');164  const first = this[offset];165  const last = this[offset + 3];166  if (first === undefined || last === undefined)167    boundsError(offset, this.length - 4);168  return first * 2 ** 24 +169    this[++offset] * 2 ** 16 +170    this[++offset] * 2 ** 8 +171    last;172}173function readUInt24BE(buf, offset = 0) {174  validateNumber(offset, 'offset');175  const first = buf[offset];176  const last = buf[offset + 2];177  if (first === undefined || last === undefined)178    boundsError(offset, buf.length - 3);179  return first * 2 ** 16 + buf[++offset] * 2 ** 8 + last;180}181function readUInt16BE(offset = 0) {182  validateNumber(offset, 'offset');183  const first = this[offset];184  const last = this[offset + 1];185  if (first === undefined || last === undefined)186    boundsError(offset, this.length - 2);187  return first * 2 ** 8 + last;188}189function readIntLE(offset, byteLength) {190  if (offset === undefined)191    throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset);192  if (byteLength === 6)193    return readInt48LE(this, offset);194  if (byteLength === 5)195    return readInt40LE(this, offset);196  if (byteLength === 3)197    return readInt24LE(this, offset);198  if (byteLength === 4)199    return this.readInt32LE(offset);200  if (byteLength === 2)201    return this.readInt16LE(offset);202  if (byteLength === 1)203    return this.readInt8(offset);204  boundsError(byteLength, 6, 'byteLength');205}206function readInt48LE(buf, offset = 0) {207  validateNumber(offset, 'offset');208  const first = buf[offset];209  const last = buf[offset + 5];210  if (first === undefined || last === undefined)211    boundsError(offset, buf.length - 6);212  const val = buf[offset + 4] + last * 2 ** 8;213  return (val | (val & 2 ** 15) * 0x1fffe) * 2 ** 32 +214    first +215    buf[++offset] * 2 ** 8 +216    buf[++offset] * 2 ** 16 +217    buf[++offset] * 2 ** 24;218}219function readInt40LE(buf, offset = 0) {220  validateNumber(offset, 'offset');221  const first = buf[offset];222  const last = buf[offset + 4];223  if (first === undefined || last === undefined)224    boundsError(offset, buf.length - 5);225  return (last | (last & 2 ** 7) * 0x1fffffe) * 2 ** 32 +226    first +227    buf[++offset] * 2 ** 8 +228    buf[++offset] * 2 ** 16 +229    buf[++offset] * 2 ** 24;230}231function readInt32LE(offset = 0) {232  validateNumber(offset, 'offset');233  const first = this[offset];234  const last = this[offset + 3];235  if (first === undefined || last === undefined)236    boundsError(offset, this.length - 4);237  return first +238    this[++offset] * 2 ** 8 +239    this[++offset] * 2 ** 16 +240    (last << 24); // Overflow241}242function readInt24LE(buf, offset = 0) {243  validateNumber(offset, 'offset');244  const first = buf[offset];245  const last = buf[offset + 2];246  if (first === undefined || last === undefined)247    boundsError(offset, buf.length - 3);248  const val = first + buf[++offset] * 2 ** 8 + last * 2 ** 16;249  return val | (val & 2 ** 23) * 0x1fe;250}251function readInt16LE(offset = 0) {252  validateNumber(offset, 'offset');253  const first = this[offset];254  const last = this[offset + 1];255  if (first === undefined || last === undefined)256    boundsError(offset, this.length - 2);257  const val = first + last * 2 ** 8;258  return val | (val & 2 ** 15) * 0x1fffe;259}260function readInt8(offset = 0) {261  validateNumber(offset, 'offset');262  const val = this[offset];263  if (val === undefined)264    boundsError(offset, this.length - 1);265  return val | (val & 2 ** 7) * 0x1fffffe;266}267function readIntBE(offset, byteLength) {268  if (offset === undefined)269    throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset);270  if (byteLength === 6)271    return readInt48BE(this, offset);272  if (byteLength === 5)273    return readInt40BE(this, offset);274  if (byteLength === 3)275    return readInt24BE(this, offset);276  if (byteLength === 4)277    return this.readInt32BE(offset);278  if (byteLength === 2)279    return this.readInt16BE(offset);280  if (byteLength === 1)281    return this.readInt8(offset);282  boundsError(byteLength, 6, 'byteLength');283}284function readInt48BE(buf, offset = 0) {285  validateNumber(offset, 'offset');286  const first = buf[offset];287  const last = buf[offset + 5];288  if (first === undefined || last === undefined)289    boundsError(offset, buf.length - 6);290  const val = buf[++offset] + first * 2 ** 8;291  return (val | (val & 2 ** 15) * 0x1fffe) * 2 ** 32 +292    buf[++offset] * 2 ** 24 +293    buf[++offset] * 2 ** 16 +294    buf[++offset] * 2 ** 8 +295    last;296}297function readInt40BE(buf, offset = 0) {298  validateNumber(offset, 'offset');299  const first = buf[offset];300  const last = buf[offset + 4];301  if (first === undefined || last === undefined)302    boundsError(offset, buf.length - 5);303  return (first | (first & 2 ** 7) * 0x1fffffe) * 2 ** 32 +304    buf[++offset] * 2 ** 24 +305    buf[++offset] * 2 ** 16 +306    buf[++offset] * 2 ** 8 +307    last;308}309function readInt32BE(offset = 0) {310  validateNumber(offset, 'offset');311  const first = this[offset];312  const last = this[offset + 3];313  if (first === undefined || last === undefined)314    boundsError(offset, this.length - 4);315  return (first << 24) + // Overflow316    this[++offset] * 2 ** 16 +317    this[++offset] * 2 ** 8 +318    last;319}320function readInt24BE(buf, offset = 0) {321  validateNumber(offset, 'offset');322  const first = buf[offset];323  const last = buf[offset + 2];324  if (first === undefined || last === undefined)325    boundsError(offset, buf.length - 3);326  const val = first * 2 ** 16 + buf[++offset] * 2 ** 8 + last;327  return val | (val & 2 ** 23) * 0x1fe;328}329function readInt16BE(offset = 0) {330  validateNumber(offset, 'offset');331  const first = this[offset];332  const last = this[offset + 1];333  if (first === undefined || last === undefined)334    boundsError(offset, this.length - 2);335  const val = first * 2 ** 8 + last;336  return val | (val & 2 ** 15) * 0x1fffe;337}338// Read floats339function readFloatBackwards(offset = 0) {340  validateNumber(offset, 'offset');341  const first = this[offset];342  const last = this[offset + 3];343  if (first === undefined || last === undefined)344    boundsError(offset, this.length - 4);345  uInt8Float32Array[3] = first;346  uInt8Float32Array[2] = this[++offset];347  uInt8Float32Array[1] = this[++offset];348  uInt8Float32Array[0] = last;349  return float32Array[0];350}351function readFloatForwards(offset = 0) {352  validateNumber(offset, 'offset');353  const first = this[offset];354  const last = this[offset + 3];355  if (first === undefined || last === undefined)356    boundsError(offset, this.length - 4);357  uInt8Float32Array[0] = first;358  uInt8Float32Array[1] = this[++offset];359  uInt8Float32Array[2] = this[++offset];360  uInt8Float32Array[3] = last;361  return float32Array[0];362}363function readDoubleBackwards(offset = 0) {364  validateNumber(offset, 'offset');365  const first = this[offset];366  const last = this[offset + 7];367  if (first === undefined || last === undefined)368    boundsError(offset, this.length - 8);369  uInt8Float64Array[7] = first;370  uInt8Float64Array[6] = this[++offset];371  uInt8Float64Array[5] = this[++offset];372  uInt8Float64Array[4] = this[++offset];373  uInt8Float64Array[3] = this[++offset];374  uInt8Float64Array[2] = this[++offset];375  uInt8Float64Array[1] = this[++offset];376  uInt8Float64Array[0] = last;377  return float64Array[0];378}379function readDoubleForwards(offset = 0) {380  validateNumber(offset, 'offset');381  const first = this[offset];382  const last = this[offset + 7];383  if (first === undefined || last === undefined)384    boundsError(offset, this.length - 8);385  uInt8Float64Array[0] = first;386  uInt8Float64Array[1] = this[++offset];387  uInt8Float64Array[2] = this[++offset];388  uInt8Float64Array[3] = this[++offset];389  uInt8Float64Array[4] = this[++offset];390  uInt8Float64Array[5] = this[++offset];391  uInt8Float64Array[6] = this[++offset];392  uInt8Float64Array[7] = last;393  return float64Array[0];394}395// Write integers.396function writeUIntLE(value, offset, byteLength) {397  if (byteLength === 6)398    return writeU_Int48LE(this, value, offset, 0, 0xffffffffffff);399  if (byteLength === 5)400    return writeU_Int40LE(this, value, offset, 0, 0xffffffffff);401  if (byteLength === 3)402    return writeU_Int24LE(this, value, offset, 0, 0xffffff);403  if (byteLength === 4)404    return writeU_Int32LE(this, value, offset, 0, 0xffffffff);405  if (byteLength === 2)406    return writeU_Int16LE(this, value, offset, 0, 0xffff);407  if (byteLength === 1)408    return writeU_Int8(this, value, offset, 0, 0xff);409  boundsError(byteLength, 6, 'byteLength');410}411function writeU_Int48LE(buf, value, offset, min, max) {412  value = +value;413  checkInt(value, min, max, buf, offset, 5);414  const newVal = Math.floor(value * 2 ** -32);415  buf[offset++] = value;416  value = value >>> 8;417  buf[offset++] = value;418  value = value >>> 8;419  buf[offset++] = value;420  value = value >>> 8;421  buf[offset++] = value;422  buf[offset++] = newVal;423  buf[offset++] = (newVal >>> 8);424  return offset;425}426function writeU_Int40LE(buf, value, offset, min, max) {427  value = +value;428  checkInt(value, min, max, buf, offset, 4);429  const newVal = value;430  buf[offset++] = value;431  value = value >>> 8;432  buf[offset++] = value;433  value = value >>> 8;434  buf[offset++] = value;435  value = value >>> 8;436  buf[offset++] = value;437  buf[offset++] = Math.floor(newVal * 2 ** -32);438  return offset;439}440function writeU_Int32LE(buf, value, offset, min, max) {441  value = +value;442  checkInt(value, min, max, buf, offset, 3);443  buf[offset++] = value;444  value = value >>> 8;445  buf[offset++] = value;446  value = value >>> 8;447  buf[offset++] = value;448  value = value >>> 8;449  buf[offset++] = value;450  return offset;451}452function writeUInt32LE(value, offset = 0) {453  return writeU_Int32LE(this, value, offset, 0, 0xffffffff);454}455function writeU_Int24LE(buf, value, offset, min, max) {456  value = +value;457  checkInt(value, min, max, buf, offset, 2);458  buf[offset++] = value;459  value = value >>> 8;460  buf[offset++] = value;461  value = value >>> 8;462  buf[offset++] = value;463  return offset;464}465function writeU_Int16LE(buf, value, offset, min, max) {466  value = +value;467  checkInt(value, min, max, buf, offset, 1);468  buf[offset++] = value;469  buf[offset++] = (value >>> 8);470  return offset;471}472function writeUInt16LE(value, offset = 0) {473  return writeU_Int16LE(this, value, offset, 0, 0xffff);474}475function writeU_Int8(buf, value, offset, min, max) {476  value = +value;477  // `checkInt()` can not be used here because it checks two entries.478  validateNumber(offset, 'offset');479  if (value > max || value < min) {480    throw new ERR_OUT_OF_RANGE('value', `>= ${min} and <= ${max}`, value);481  }482  if (buf[offset] === undefined)483    boundsError(offset, buf.length - 1);484  buf[offset] = value;485  return offset + 1;486}487function writeUInt8(value, offset = 0) {488  return writeU_Int8(this, value, offset, 0, 0xff);489}490function writeUIntBE(value, offset, byteLength) {491  if (byteLength === 6)492    return writeU_Int48BE(this, value, offset, 0, 0xffffffffffffff);493  if (byteLength === 5)494    return writeU_Int40BE(this, value, offset, 0, 0xffffffffff);495  if (byteLength === 3)496    return writeU_Int24BE(this, value, offset, 0, 0xffffff);497  if (byteLength === 4)498    return writeU_Int32BE(this, value, offset, 0, 0xffffffff);499  if (byteLength === 2)500    return writeU_Int16BE(this, value, offset, 0, 0xffff);501  if (byteLength === 1)502    return writeU_Int8(this, value, offset, 0, 0xff);503  boundsError(byteLength, 6, 'byteLength');504}505function writeU_Int48BE(buf, value, offset, min, max) {506  value = +value;507  checkInt(value, min, max, buf, offset, 5);508  const newVal = Math.floor(value * 2 ** -32);509  buf[offset++] = (newVal >>> 8);510  buf[offset++] = newVal;511  buf[offset + 3] = value;512  value = value >>> 8;513  buf[offset + 2] = value;514  value = value >>> 8;515  buf[offset + 1] = value;516  value = value >>> 8;517  buf[offset] = value;518  return offset + 4;519}520function writeU_Int40BE(buf, value, offset, min, max) {521  value = +value;522  checkInt(value, min, max, buf, offset, 4);523  buf[offset++] = Math.floor(value * 2 ** -32);524  buf[offset + 3] = value;525  value = value >>> 8;526  buf[offset + 2] = value;527  value = value >>> 8;528  buf[offset + 1] = value;529  value = value >>> 8;530  buf[offset] = value;531  return offset + 4;532}533function writeU_Int32BE(buf, value, offset, min, max) {534  value = +value;535  checkInt(value, min, max, buf, offset, 3);536  buf[offset + 3] = value;537  value = value >>> 8;538  buf[offset + 2] = value;539  value = value >>> 8;540  buf[offset + 1] = value;541  value = value >>> 8;542  buf[offset] = value;543  return offset + 4;544}545function writeUInt32BE(value, offset = 0) {546  return writeU_Int32BE(this, value, offset, 0, 0xffffffff);547}548function writeU_Int24BE(buf, value, offset, min, max) {549  value = +value;550  checkInt(value, min, max, buf, offset, 2);551  buf[offset + 2] = value;552  value = value >>> 8;553  buf[offset + 1] = value;554  value = value >>> 8;555  buf[offset] = value;556  return offset + 3;557}558function writeU_Int16BE(buf, value, offset, min, max) {559  value = +value;560  checkInt(value, min, max, buf, offset, 1);561  buf[offset++] = (value >>> 8);562  buf[offset++] = value;563  return offset;564}565function writeUInt16BE(value, offset = 0) {566  return writeU_Int16BE(this, value, offset, 0, 0xffff);567}568function writeIntLE(value, offset, byteLength) {569  if (byteLength === 6)570    return writeU_Int48LE(this, value, offset, -0x800000000000, 0x7fffffffffff);571  if (byteLength === 5)572    return writeU_Int40LE(this, value, offset, -0x8000000000, 0x7fffffffff);573  if (byteLength === 3)574    return writeU_Int24LE(this, value, offset, -0x800000, 0x7fffff);575  if (byteLength === 4)576    return writeU_Int32LE(this, value, offset, -0x80000000, 0x7fffffff);577  if (byteLength === 2)578    return writeU_Int16LE(this, value, offset, -0x8000, 0x7fff);579  if (byteLength === 1)580    return writeU_Int8(this, value, offset, -0x80, 0x7f);581  boundsError(byteLength, 6, 'byteLength');582}583function writeInt32LE(value, offset = 0) {584  return writeU_Int32LE(this, value, offset, -0x80000000, 0x7fffffff);585}586function writeInt16LE(value, offset = 0) {587  return writeU_Int16LE(this, value, offset, -0x8000, 0x7fff);588}589function writeInt8(value, offset = 0) {590  return writeU_Int8(this, value, offset, -0x80, 0x7f);591}592function writeIntBE(value, offset, byteLength) {593  if (byteLength === 6)594    return writeU_Int48BE(this, value, offset, -0x800000000000, 0x7fffffffffff);595  if (byteLength === 5)596    return writeU_Int40BE(this, value, offset, -0x8000000000, 0x7fffffffff);597  if (byteLength === 3)598    return writeU_Int24BE(this, value, offset, -0x800000, 0x7fffff);599  if (byteLength === 4)600    return writeU_Int32BE(this, value, offset, -0x80000000, 0x7fffffff);601  if (byteLength === 2)602    return writeU_Int16BE(this, value, offset, -0x8000, 0x7fff);603  if (byteLength === 1)604    return writeU_Int8(this, value, offset, -0x80, 0x7f);605  boundsError(byteLength, 6, 'byteLength');606}607function writeInt32BE(value, offset = 0) {608  return writeU_Int32BE(this, value, offset, -0x80000000, 0x7fffffff);609}610function writeInt16BE(value, offset = 0) {611  return writeU_Int16BE(this, value, offset, -0x8000, 0x7fff);612}613// Write floats.614function writeDoubleForwards(val, offset = 0) {615  val = +val;616  checkBounds(this, offset, 7);617  float64Array[0] = val;618  this[offset++] = uInt8Float64Array[0];619  this[offset++] = uInt8Float64Array[1];620  this[offset++] = uInt8Float64Array[2];621  this[offset++] = uInt8Float64Array[3];622  this[offset++] = uInt8Float64Array[4];623  this[offset++] = uInt8Float64Array[5];624  this[offset++] = uInt8Float64Array[6];625  this[offset++] = uInt8Float64Array[7];626  return offset;627}628function writeDoubleBackwards(val, offset = 0) {629  val = +val;630  checkBounds(this, offset, 7);631  float64Array[0] = val;632  this[offset++] = uInt8Float64Array[7];633  this[offset++] = uInt8Float64Array[6];634  this[offset++] = uInt8Float64Array[5];635  this[offset++] = uInt8Float64Array[4];636  this[offset++] = uInt8Float64Array[3];637  this[offset++] = uInt8Float64Array[2];638  this[offset++] = uInt8Float64Array[1];639  this[offset++] = uInt8Float64Array[0];640  return offset;641}642function writeFloatForwards(val, offset = 0) {643  val = +val;644  checkBounds(this, offset, 3);645  float32Array[0] = val;646  this[offset++] = uInt8Float32Array[0];647  this[offset++] = uInt8Float32Array[1];648  this[offset++] = uInt8Float32Array[2];649  this[offset++] = uInt8Float32Array[3];650  return offset;651}652function writeFloatBackwards(val, offset = 0) {653  val = +val;654  checkBounds(this, offset, 3);655  float32Array[0] = val;656  this[offset++] = uInt8Float32Array[3];657  this[offset++] = uInt8Float32Array[2];658  this[offset++] = uInt8Float32Array[1];659  this[offset++] = uInt8Float32Array[0];660  return offset;661}662// FastBuffer wil be inserted here by lib/buffer.js663module.exports = {664  setupBufferJS,665  // Container to export all read write functions.666  readWrites: {667    readUIntLE,668    readUInt32LE,669    readUInt16LE,670    readUInt8,671    readUIntBE,672    readUInt32BE,673    readUInt16BE,674    readIntLE,675    readInt32LE,676    readInt16LE,677    readInt8,678    readIntBE,679    readInt32BE,680    readInt16BE,681    writeUIntLE,682    writeUInt32LE,683    writeUInt16LE,684    writeUInt8,685    writeUIntBE,686    writeUInt32BE,687    writeUInt16BE,688    writeIntLE,689    writeInt32LE,690    writeInt16LE,691    writeInt8,692    writeIntBE,693    writeInt32BE,694    writeInt16BE,695    readFloatLE: bigEndian ? readFloatBackwards : readFloatForwards,696    readFloatBE: bigEndian ? readFloatForwards : readFloatBackwards,697    readDoubleLE: bigEndian ? readDoubleBackwards : readDoubleForwards,698    readDoubleBE: bigEndian ? readDoubleForwards : readDoubleBackwards,699    writeFloatLE: bigEndian ? writeFloatBackwards : writeFloatForwards,700    writeFloatBE: bigEndian ? writeFloatForwards : writeFloatBackwards,701    writeDoubleLE: bigEndian ? writeDoubleBackwards : writeDoubleForwards,702    writeDoubleBE: bigEndian ? writeDoubleForwards : writeDoubleBackwards703  }...worder.py
Source:worder.py  
...79    def get_function_and_args_in_header(self, offset):80        return self.code_finder.get_function_and_args_in_header(offset)81    def get_lambda_and_args(self, offset):82        return self.code_finder.get_lambda_and_args(offset)83    def find_function_offset(self, offset):84        return self.code_finder.find_function_offset(offset)85class _RealFinder(object):86    def __init__(self, code, raw):87        self.code = code88        self.raw = raw89    def _find_word_start(self, offset):90        current_offset = offset91        while current_offset >= 0 and self._is_id_char(current_offset):92            current_offset -= 193        return current_offset + 194    def _find_word_end(self, offset):95        while offset + 1 < len(self.code) and self._is_id_char(offset + 1):96            offset += 197        return offset98    def _find_last_non_space_char(self, offset):99        while offset >= 0 and self.code[offset].isspace():100            if self.code[offset] == '\n':101                return offset102            offset -= 1103        return max(-1, offset)104    def get_word_at(self, offset):105        offset = self._get_fixed_offset(offset)106        return self.raw[self._find_word_start(offset):107                        self._find_word_end(offset) + 1]108    def _get_fixed_offset(self, offset):109        if offset >= len(self.code):110            return offset - 1111        if not self._is_id_char(offset):112            if offset > 0 and self._is_id_char(offset - 1):113                return offset - 1114            if offset < len(self.code) - 1 and self._is_id_char(offset + 1):115                return offset + 1116        return offset117    def _is_id_char(self, offset):118        return self.code[offset].isalnum() or self.code[offset] == '_'119    def _find_string_start(self, offset):120        kind = self.code[offset]121        try:122            return self.code.rindex(kind, 0, offset)123        except ValueError:124            return 0125    def _find_parens_start(self, offset):126        offset = self._find_last_non_space_char(offset - 1)127        while offset >= 0 and self.code[offset] not in '[({':128            if self.code[offset] not in ':,':129                offset = self._find_primary_start(offset)130            offset = self._find_last_non_space_char(offset - 1)131        return offset132    def _find_atom_start(self, offset):133        old_offset = offset134        if self.code[offset] == '\n':135            return offset + 1136        if self.code[offset].isspace():137            offset = self._find_last_non_space_char(offset)138        if self.code[offset] in '\'"':139            return self._find_string_start(offset)140        if self.code[offset] in ')]}':141            return self._find_parens_start(offset)142        if self._is_id_char(offset):143            return self._find_word_start(offset)144        return old_offset145    def _find_primary_without_dot_start(self, offset):146        """It tries to find the undotted primary start147        It is different from `self._get_atom_start()` in that it148        follows function calls, too; such as in ``f(x)``.149        """150        last_atom = offset151        offset = self._find_last_non_space_char(last_atom)152        while offset > 0 and self.code[offset] in ')]':153            last_atom = self._find_parens_start(offset)154            offset = self._find_last_non_space_char(last_atom - 1)155        if offset >= 0 and (self.code[offset] in '"\'})]' or156                            self._is_id_char(offset)):157            atom_start = self._find_atom_start(offset)158            if not keyword.iskeyword(self.code[atom_start:offset + 1]):159                return atom_start160        return last_atom161    def _find_primary_start(self, offset):162        if offset >= len(self.code):163            offset = len(self.code) - 1164        if self.code[offset] != '.':165            offset = self._find_primary_without_dot_start(offset)166        else:167            offset = offset + 1168        while offset > 0:169            prev = self._find_last_non_space_char(offset - 1)170            if offset <= 0 or self.code[prev] != '.':171                break172            offset = self._find_primary_without_dot_start(prev - 1)173            if not self._is_id_char(offset):174                break175        return offset176    def get_primary_at(self, offset):177        offset = self._get_fixed_offset(offset)178        start, end = self.get_primary_range(offset)179        return self.raw[start:end].strip()180    def get_splitted_primary_before(self, offset):181        """returns expression, starting, starting_offset182        This function is used in `rope.codeassist.assist` function.183        """184        if offset == 0:185            return ('', '', 0)186        end = offset - 1187        word_start = self._find_atom_start(end)188        real_start = self._find_primary_start(end)189        if self.code[word_start:offset].strip() == '':190            word_start = end191        if self.code[end].isspace():192            word_start = end193        if self.code[real_start:word_start].strip() == '':194            real_start = word_start195        if real_start == word_start == end and not self._is_id_char(end):196            return ('', '', offset)197        if real_start == word_start:198            return ('', self.raw[word_start:offset], word_start)199        else:200            if self.code[end] == '.':201                return (self.raw[real_start:end], '', offset)202            last_dot_position = word_start203            if self.code[word_start] != '.':204                last_dot_position = self._find_last_non_space_char(word_start - 1)205            last_char_position = self._find_last_non_space_char(last_dot_position - 1)206            if self.code[word_start].isspace():207                word_start = offset208            return (self.raw[real_start:last_char_position + 1],209                    self.raw[word_start:offset], word_start)210    def _get_line_start(self, offset):211        try:212            return self.code.rindex('\n', 0, offset + 1)213        except ValueError:214            return 0215    def _get_line_end(self, offset):216        try:217            return self.code.index('\n', offset)218        except ValueError:219            return len(self.code)220    def is_name_assigned_in_class_body(self, offset):221        word_start = self._find_word_start(offset - 1)222        word_end = self._find_word_end(offset) + 1223        if '.' in self.code[word_start:word_end]:224            return False225        line_start = self._get_line_start(word_start)226        line = self.code[line_start:word_start].strip()227        return not line and self.get_assignment_type(offset) == '='228    def is_a_class_or_function_name_in_header(self, offset):229        word_start = self._find_word_start(offset - 1)230        line_start = self._get_line_start(word_start)231        prev_word = self.code[line_start:word_start].strip()232        return prev_word in ['def', 'class']233    def _find_first_non_space_char(self, offset):234        if offset >= len(self.code):235            return len(self.code)236        while offset < len(self.code) and self.code[offset].isspace():237            if self.code[offset] == '\n':238                return offset239            offset += 1240        return offset241    def is_a_function_being_called(self, offset):242        word_end = self._find_word_end(offset) + 1243        next_char = self._find_first_non_space_char(word_end)244        return next_char < len(self.code) and \245               self.code[next_char] == '(' and \246               not self.is_a_class_or_function_name_in_header(offset)247    def _find_import_end(self, start):248        return self._get_line_end(start)249    def is_import_statement(self, offset):250        try:251            last_import = self.code.rindex('import ', 0, offset)252        except ValueError:253            return False254        return self._find_import_end(last_import + 7) >= offset255    def is_from_statement(self, offset):256        try:257            last_from = self.code.rindex('from ', 0, offset)258            from_import = self.code.index(' import ', last_from)259            from_names = from_import + 8260        except ValueError:261            return False262        from_names = self._find_first_non_space_char(from_names)263        return self._find_import_end(from_names) >= offset264    def is_from_statement_module(self, offset):265        if offset >= len(self.code) - 1:266            return False267        stmt_start = self._find_primary_start(offset)268        line_start = self._get_line_start(stmt_start)269        prev_word = self.code[line_start:stmt_start].strip()270        return prev_word == 'from'271    def is_a_name_after_from_import(self, offset):272        try:273            if len(self.code) > offset and  self.code[offset] == '\n':274                line_start = self._get_line_start(offset - 1)275            else:276                line_start = self._get_line_start(offset)277            last_from = self.code.rindex('from ', line_start, offset)278            from_import = self.code.index(' import ', last_from)279            from_names = from_import + 8280        except ValueError:281            return False282        if from_names - 1 > offset:283            return False284        return self._find_import_end(from_names) >= offset285    def get_from_module(self, offset):286        try:287            last_from = self.code.rindex('from ', 0, offset)288            import_offset = self.code.index(' import ', last_from)289            end = self._find_last_non_space_char(import_offset)290            return self.get_primary_at(end)291        except ValueError:292            pass293    def is_from_aliased(self, offset):294        if not self.is_a_name_after_from_import(offset):295            return False296        try:297            end = self._find_word_end(offset)298            as_end = min(self._find_word_end(end + 1), len(self.code))299            as_start = self._find_word_start(as_end)300            if self.code[as_start:as_end + 1] == 'as':301                return True302        except ValueError:303            return False304    def get_from_aliased(self, offset):305        try:306            end = self._find_word_end(offset)307            as_ = self._find_word_end(end + 1)308            alias = self._find_word_end(as_ + 1)309            start = self._find_word_start(alias)310            return self.raw[start:alias + 1]311        except ValueError:312            pass313    def is_function_keyword_parameter(self, offset):314        word_end = self._find_word_end(offset)315        if word_end + 1 == len(self.code):316            return False317        next_char = self._find_first_non_space_char(word_end + 1)318        equals = self.code[next_char:next_char + 2]319        if equals == '==' or not equals.startswith('='):320            return False321        word_start = self._find_word_start(offset)322        prev_char = self._find_last_non_space_char(word_start - 1)323        return prev_char - 1 >= 0 and self.code[prev_char] in ',('324    def is_on_function_call_keyword(self, offset):325        stop = self._get_line_start(offset)326        if self._is_id_char(offset):327            offset = self._find_word_start(offset) - 1328        offset = self._find_last_non_space_char(offset)329        if offset <= stop or self.code[offset] not in '(,':330            return False331        parens_start = self.find_parens_start_from_inside(offset)332        return stop < parens_start333    def find_parens_start_from_inside(self, offset):334        stop = self._get_line_start(offset)335        opens = 1336        while offset > stop:337            if self.code[offset] == '(':338                break339            if self.code[offset] != ',':340                offset = self._find_primary_start(offset)341            offset -= 1342        return max(stop, offset)343    def is_assigned_here(self, offset):344        return self.get_assignment_type(offset) is not None345    def get_assignment_type(self, offset):346        # XXX: does not handle tuple assignments347        word_end = self._find_word_end(offset)348        next_char = self._find_first_non_space_char(word_end + 1)349        single = self.code[next_char:next_char + 1]350        double = self.code[next_char:next_char + 2]351        triple = self.code[next_char:next_char + 3]352        if double not in ('==', '<=', '>=', '!='):353            for op in [single, double, triple]:354                if op.endswith('='):355                    return op356    def get_primary_range(self, offset):357        start = self._find_primary_start(offset)358        end = self._find_word_end(offset) + 1359        return (start, end)360    def get_word_range(self, offset):361        offset = max(0, offset)362        start = self._find_word_start(offset)363        end = self._find_word_end(offset) + 1364        return (start, end)365    def get_word_parens_range(self, offset, opening='(', closing=')'):366        end = self._find_word_end(offset)367        start_parens = self.code.index(opening, end)368        index = start_parens369        open_count = 0370        while index < len(self.code):371            if self.code[index] == opening:372                open_count += 1373            if self.code[index] == closing:374                open_count -= 1375            if open_count == 0:376                return (start_parens, index + 1)377            index += 1378        return (start_parens, index)379    def get_parameters(self, first, last):380        keywords = []381        args = []382        current = self._find_last_non_space_char(last - 1)383        while current > first:384            primary_start = current385            current = self._find_primary_start(current)386            while current != first and self.code[current] not in '=,':387                current = self._find_last_non_space_char(current - 1)388            primary = self.raw[current + 1:primary_start + 1].strip()389            if self.code[current] == '=':390                primary_start = current - 1391                current -= 1392                while current != first and self.code[current] not in ',':393                    current = self._find_last_non_space_char(current - 1)394                param_name = self.raw[current + 1:primary_start + 1].strip()395                keywords.append((param_name, primary))396            else:397                args.append(primary)398            current = self._find_last_non_space_char(current - 1)399        args.reverse()400        keywords.reverse()401        return args, keywords402    def is_assigned_in_a_tuple_assignment(self, offset):403        start = self._get_line_start(offset)404        end = self._get_line_end(offset)405        primary_start = self._find_primary_start(offset)406        primary_end = self._find_word_end(offset)407        prev_char_offset = self._find_last_non_space_char(primary_start - 1)408        next_char_offset = self._find_first_non_space_char(primary_end + 1)409        next_char = prev_char = ''410        if prev_char_offset >= start:411            prev_char = self.code[prev_char_offset]412        if next_char_offset < end:413            next_char = self.code[next_char_offset]414        try:415            equals_offset = self.code.index('=', start, end)416        except ValueError:417            return False418        if prev_char not in '(,' and next_char not in ',)':419            return False420        parens_start = self.find_parens_start_from_inside(offset)421        # XXX: only handling (x, y) = value422        return offset < equals_offset and \423               self.code[start:parens_start].strip() == ''424    def get_function_and_args_in_header(self, offset):425        offset = self.find_function_offset(offset)426        lparens, rparens = self.get_word_parens_range(offset)427        return self.raw[offset:rparens + 1]428    def find_function_offset(self, offset, definition='def '):429        while True:430            offset = self.code.index(definition, offset)431            if offset == 0 or not self._is_id_char(offset - 1):432                break433            offset += 1434        def_ = offset + 4435        return self._find_first_non_space_char(def_)436    def get_lambda_and_args(self, offset):437        offset = self.find_function_offset(offset, definition = 'lambda ')438        lparens, rparens = self.get_word_parens_range(offset, opening=' ', closing=':')...index.js
Source:index.js  
1var types = require('./types')2var rcodes = require('./rcodes')3var opcodes = require('./opcodes')4var ip = require('ip')5var Buffer = require('safe-buffer').Buffer6var QUERY_FLAG = 07var RESPONSE_FLAG = 1 << 158var FLUSH_MASK = 1 << 159var NOT_FLUSH_MASK = ~FLUSH_MASK10var QU_MASK = 1 << 1511var NOT_QU_MASK = ~QU_MASK12var name = exports.txt = exports.name = {}13name.encode = function (str, buf, offset) {14  if (!buf) buf = Buffer.alloc(name.encodingLength(str))15  if (!offset) offset = 016  var oldOffset = offset17  // strip leading and trailing .18  var n = str.replace(/^\.|\.$/gm, '')19  if (n.length) {20    var list = n.split('.')21    for (var i = 0; i < list.length; i++) {22      var len = buf.write(list[i], offset + 1)23      buf[offset] = len24      offset += len + 125    }26  }27  buf[offset++] = 028  name.encode.bytes = offset - oldOffset29  return buf30}31name.encode.bytes = 032name.decode = function (buf, offset) {33  if (!offset) offset = 034  var list = []35  var oldOffset = offset36  var len = buf[offset++]37  if (len === 0) {38    name.decode.bytes = 139    return '.'40  }41  if (len >= 0xc0) {42    var res = name.decode(buf, buf.readUInt16BE(offset - 1) - 0xc000)43    name.decode.bytes = 244    return res45  }46  while (len) {47    if (len >= 0xc0) {48      list.push(name.decode(buf, buf.readUInt16BE(offset - 1) - 0xc000))49      offset++50      break51    }52    list.push(buf.toString('utf-8', offset, offset + len))53    offset += len54    len = buf[offset++]55  }56  name.decode.bytes = offset - oldOffset57  return list.join('.')58}59name.decode.bytes = 060name.encodingLength = function (n) {61  if (n === '.' || n === '..') return 162  return Buffer.byteLength(n.replace(/^\.|\.$/gm, '')) + 263}64var string = {}65string.encode = function (s, buf, offset) {66  if (!buf) buf = Buffer.alloc(string.encodingLength(s))67  if (!offset) offset = 068  var len = buf.write(s, offset + 1)69  buf[offset] = len70  string.encode.bytes = len + 171  return buf72}73string.encode.bytes = 074string.decode = function (buf, offset) {75  if (!offset) offset = 076  var len = buf[offset]77  var s = buf.toString('utf-8', offset + 1, offset + 1 + len)78  string.decode.bytes = len + 179  return s80}81string.decode.bytes = 082string.encodingLength = function (s) {83  return Buffer.byteLength(s) + 184}85var header = {}86header.encode = function (h, buf, offset) {87  if (!buf) buf = header.encodingLength(h)88  if (!offset) offset = 089  var flags = (h.flags || 0) & 3276790  var type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG91  buf.writeUInt16BE(h.id || 0, offset)92  buf.writeUInt16BE(flags | type, offset + 2)93  buf.writeUInt16BE(h.questions.length, offset + 4)94  buf.writeUInt16BE(h.answers.length, offset + 6)95  buf.writeUInt16BE(h.authorities.length, offset + 8)96  buf.writeUInt16BE(h.additionals.length, offset + 10)97  return buf98}99header.encode.bytes = 12100header.decode = function (buf, offset) {101  if (!offset) offset = 0102  if (buf.length < 12) throw new Error('Header must be 12 bytes')103  var flags = buf.readUInt16BE(offset + 2)104  return {105    id: buf.readUInt16BE(offset),106    type: flags & RESPONSE_FLAG ? 'response' : 'query',107    flags: flags & 32767,108    flag_qr: ((flags >> 15) & 0x1) === 1,109    opcode: opcodes.toString((flags >> 11) & 0xf),110    flag_auth: ((flags >> 10) & 0x1) === 1,111    flag_trunc: ((flags >> 9) & 0x1) === 1,112    flag_rd: ((flags >> 8) & 0x1) === 1,113    flag_ra: ((flags >> 7) & 0x1) === 1,114    flag_z: ((flags >> 6) & 0x1) === 1,115    flag_ad: ((flags >> 5) & 0x1) === 1,116    flag_cd: ((flags >> 4) & 0x1) === 1,117    rcode: rcodes.toString(flags & 0xf),118    questions: new Array(buf.readUInt16BE(offset + 4)),119    answers: new Array(buf.readUInt16BE(offset + 6)),120    authorities: new Array(buf.readUInt16BE(offset + 8)),121    additionals: new Array(buf.readUInt16BE(offset + 10))122  }123}124header.decode.bytes = 12125header.encodingLength = function () {126  return 12127}128var runknown = exports.unknown = {}129runknown.encode = function (data, buf, offset) {130  if (!buf) buf = Buffer.alloc(runknown.encodingLength(data))131  if (!offset) offset = 0132  buf.writeUInt16BE(data.length, offset)133  data.copy(buf, offset + 2)134  runknown.encode.bytes = data.length + 2135  return buf136}137runknown.encode.bytes = 0138runknown.decode = function (buf, offset) {139  if (!offset) offset = 0140  var len = buf.readUInt16BE(offset)141  var data = buf.slice(offset + 2, offset + 2 + len)142  runknown.decode.bytes = len + 2143  return data144}145runknown.decode.bytes = 0146runknown.encodingLength = function (data) {147  return data.length + 2148}149var rns = exports.ns = {}150rns.encode = function (data, buf, offset) {151  if (!buf) buf = Buffer.alloc(rns.encodingLength(data))152  if (!offset) offset = 0153  name.encode(data, buf, offset + 2)154  buf.writeUInt16BE(name.encode.bytes, offset)155  rns.encode.bytes = name.encode.bytes + 2156  return buf157}158rns.encode.bytes = 0159rns.decode = function (buf, offset) {160  if (!offset) offset = 0161  var len = buf.readUInt16BE(offset)162  var dd = name.decode(buf, offset + 2)163  rns.decode.bytes = len + 2164  return dd165}166rns.decode.bytes = 0167rns.encodingLength = function (data) {168  return name.encodingLength(data) + 2169}170var rsoa = exports.soa = {}171rsoa.encode = function (data, buf, offset) {172  if (!buf) buf = Buffer.alloc(rsoa.encodingLength(data))173  if (!offset) offset = 0174  var oldOffset = offset175  offset += 2176  name.encode(data.mname, buf, offset)177  offset += name.encode.bytes178  name.encode(data.rname, buf, offset)179  offset += name.encode.bytes180  buf.writeUInt32BE(data.serial || 0, offset)181  offset += 4182  buf.writeUInt32BE(data.refresh || 0, offset)183  offset += 4184  buf.writeUInt32BE(data.retry || 0, offset)185  offset += 4186  buf.writeUInt32BE(data.expire || 0, offset)187  offset += 4188  buf.writeUInt32BE(data.minimum || 0, offset)189  offset += 4190  buf.writeUInt16BE(offset - oldOffset - 2, oldOffset)191  rsoa.encode.bytes = offset - oldOffset192  return buf193}194rsoa.encode.bytes = 0195rsoa.decode = function (buf, offset) {196  if (!offset) offset = 0197  var oldOffset = offset198  var data = {}199  offset += 2200  data.mname = name.decode(buf, offset)201  offset += name.decode.bytes202  data.rname = name.decode(buf, offset)203  offset += name.decode.bytes204  data.serial = buf.readUInt32BE(offset)205  offset += 4206  data.refresh = buf.readUInt32BE(offset)207  offset += 4208  data.retry = buf.readUInt32BE(offset)209  offset += 4210  data.expire = buf.readUInt32BE(offset)211  offset += 4212  data.minimum = buf.readUInt32BE(offset)213  offset += 4214  rsoa.decode.bytes = offset - oldOffset215  return data216}217rsoa.decode.bytes = 0218rsoa.encodingLength = function (data) {219  return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname)220}221var rtxt = exports.txt = exports.null = {}222var rnull = rtxt223rtxt.encode = function (data, buf, offset) {224  if (!buf) buf = Buffer.alloc(rtxt.encodingLength(data))225  if (!offset) offset = 0226  if (typeof data === 'string') data = Buffer.from(data)227  if (!data) data = Buffer.alloc(0)228  var oldOffset = offset229  offset += 2230  var len = data.length231  data.copy(buf, offset, 0, len)232  offset += len233  buf.writeUInt16BE(offset - oldOffset - 2, oldOffset)234  rtxt.encode.bytes = offset - oldOffset235  return buf236}237rtxt.encode.bytes = 0238rtxt.decode = function (buf, offset) {239  if (!offset) offset = 0240  var oldOffset = offset241  var len = buf.readUInt16BE(offset)242  offset += 2243  var data = buf.slice(offset, offset + len)244  offset += len245  rtxt.decode.bytes = offset - oldOffset246  return data247}248rtxt.decode.bytes = 0249rtxt.encodingLength = function (data) {250  if (!data) return 2251  return (Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)) + 2252}253var rhinfo = exports.hinfo = {}254rhinfo.encode = function (data, buf, offset) {255  if (!buf) buf = Buffer.alloc(rhinfo.encodingLength(data))256  if (!offset) offset = 0257  var oldOffset = offset258  offset += 2259  string.encode(data.cpu, buf, offset)260  offset += string.encode.bytes261  string.encode(data.os, buf, offset)262  offset += string.encode.bytes263  buf.writeUInt16BE(offset - oldOffset - 2, oldOffset)264  rhinfo.encode.bytes = offset - oldOffset265  return buf266}267rhinfo.encode.bytes = 0268rhinfo.decode = function (buf, offset) {269  if (!offset) offset = 0270  var oldOffset = offset271  var data = {}272  offset += 2273  data.cpu = string.decode(buf, offset)274  offset += string.decode.bytes275  data.os = string.decode(buf, offset)276  offset += string.decode.bytes277  rhinfo.decode.bytes = offset - oldOffset278  return data279}280rhinfo.decode.bytes = 0281rhinfo.encodingLength = function (data) {282  return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2283}284var rptr = exports.ptr = {}285var rcname = exports.cname = rptr286var rdname = exports.dname = rptr287rptr.encode = function (data, buf, offset) {288  if (!buf) buf = Buffer.alloc(rptr.encodingLength(data))289  if (!offset) offset = 0290  name.encode(data, buf, offset + 2)291  buf.writeUInt16BE(name.encode.bytes, offset)292  rptr.encode.bytes = name.encode.bytes + 2293  return buf294}295rptr.encode.bytes = 0296rptr.decode = function (buf, offset) {297  if (!offset) offset = 0298  var data = name.decode(buf, offset + 2)299  rptr.decode.bytes = name.decode.bytes + 2300  return data301}302rptr.decode.bytes = 0303rptr.encodingLength = function (data) {304  return name.encodingLength(data) + 2305}306var rsrv = exports.srv = {}307rsrv.encode = function (data, buf, offset) {308  if (!buf) buf = Buffer.alloc(rsrv.encodingLength(data))309  if (!offset) offset = 0310  buf.writeUInt16BE(data.priority || 0, offset + 2)311  buf.writeUInt16BE(data.weight || 0, offset + 4)312  buf.writeUInt16BE(data.port || 0, offset + 6)313  name.encode(data.target, buf, offset + 8)314  var len = name.encode.bytes + 6315  buf.writeUInt16BE(len, offset)316  rsrv.encode.bytes = len + 2317  return buf318}319rsrv.encode.bytes = 0320rsrv.decode = function (buf, offset) {321  if (!offset) offset = 0322  var len = buf.readUInt16BE(offset)323  var data = {}324  data.priority = buf.readUInt16BE(offset + 2)325  data.weight = buf.readUInt16BE(offset + 4)326  data.port = buf.readUInt16BE(offset + 6)327  data.target = name.decode(buf, offset + 8)328  rsrv.decode.bytes = len + 2329  return data330}331rsrv.decode.bytes = 0332rsrv.encodingLength = function (data) {333  return 8 + name.encodingLength(data.target)334}335var rcaa = exports.caa = {}336rcaa.ISSUER_CRITICAL = 1 << 7337rcaa.encode = function (data, buf, offset) {338  var len = rcaa.encodingLength(data)339  if (!buf) buf = Buffer.alloc(rcaa.encodingLength(data))340  if (!offset) offset = 0341  if (data.issuerCritical) {342    data.flags = rcaa.ISSUER_CRITICAL343  }344  buf.writeUInt16BE(len - 2, offset)345  offset += 2346  buf.writeUInt8(data.flags || 0, offset)347  offset += 1348  string.encode(data.tag, buf, offset)349  offset += string.encode.bytes350  buf.write(data.value, offset)351  offset += Buffer.byteLength(data.value)352  rcaa.encode.bytes = len353  return buf354}355rcaa.encode.bytes = 0356rcaa.decode = function (buf, offset) {357  if (!offset) offset = 0358  var len = buf.readUInt16BE(offset)359  offset += 2360  var oldOffset = offset361  var data = {}362  data.flags = buf.readUInt8(offset)363  offset += 1364  data.tag = string.decode(buf, offset)365  offset += string.decode.bytes366  data.value = buf.toString('utf-8', offset, oldOffset + len)367  data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL)368  rcaa.decode.bytes = len + 2369  return data370}371rcaa.decode.bytes = 0372rcaa.encodingLength = function (data) {373  return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2374}375var ra = exports.a = {}376ra.encode = function (host, buf, offset) {377  if (!buf) buf = Buffer.alloc(ra.encodingLength(host))378  if (!offset) offset = 0379  buf.writeUInt16BE(4, offset)380  offset += 2381  ip.toBuffer(host, buf, offset)382  ra.encode.bytes = 6383  return buf384}385ra.encode.bytes = 0386ra.decode = function (buf, offset) {387  if (!offset) offset = 0388  offset += 2389  var host = ip.toString(buf, offset, 4)390  ra.decode.bytes = 6391  return host392}393ra.decode.bytes = 0394ra.encodingLength = function () {395  return 6396}397var raaaa = exports.aaaa = {}398raaaa.encode = function (host, buf, offset) {399  if (!buf) buf = Buffer.alloc(raaaa.encodingLength(host))400  if (!offset) offset = 0401  buf.writeUInt16BE(16, offset)402  offset += 2403  ip.toBuffer(host, buf, offset)404  raaaa.encode.bytes = 18405  return buf406}407raaaa.encode.bytes = 0408raaaa.decode = function (buf, offset) {409  if (!offset) offset = 0410  offset += 2411  var host = ip.toString(buf, offset, 16)412  raaaa.decode.bytes = 18413  return host414}415raaaa.decode.bytes = 0416raaaa.encodingLength = function () {417  return 18418}419var renc = exports.record = function (type) {420  switch (type.toUpperCase()) {421    case 'A': return ra422    case 'PTR': return rptr423    case 'CNAME': return rcname424    case 'DNAME': return rdname425    case 'TXT': return rtxt426    case 'NULL': return rnull427    case 'AAAA': return raaaa428    case 'SRV': return rsrv429    case 'HINFO': return rhinfo430    case 'CAA': return rcaa431    case 'NS': return rns432    case 'SOA': return rsoa433  }434  return runknown435}436var answer = exports.answer = {}437answer.encode = function (a, buf, offset) {438  if (!buf) buf = Buffer.alloc(answer.encodingLength(a))439  if (!offset) offset = 0440  var oldOffset = offset441  name.encode(a.name, buf, offset)442  offset += name.encode.bytes443  buf.writeUInt16BE(types.toType(a.type), offset)444  var klass = a.class === undefined ? 1 : a.class445  if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit446  buf.writeUInt16BE(klass, offset + 2)447  buf.writeUInt32BE(a.ttl || 0, offset + 4)448  var enc = renc(a.type)449  enc.encode(a.data, buf, offset + 8)450  offset += 8 + enc.encode.bytes451  answer.encode.bytes = offset - oldOffset452  return buf453}454answer.encode.bytes = 0455answer.decode = function (buf, offset) {456  if (!offset) offset = 0457  var a = {}458  var oldOffset = offset459  a.name = name.decode(buf, offset)460  offset += name.decode.bytes461  a.type = types.toString(buf.readUInt16BE(offset))462  a.class = buf.readUInt16BE(offset + 2)463  a.ttl = buf.readUInt32BE(offset + 4)464  a.flush = !!(a.class & FLUSH_MASK)465  if (a.flush) a.class &= NOT_FLUSH_MASK466  var enc = renc(a.type)467  a.data = enc.decode(buf, offset + 8)468  offset += 8 + enc.decode.bytes469  answer.decode.bytes = offset - oldOffset470  return a471}472answer.decode.bytes = 0473answer.encodingLength = function (a) {474  return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(a.data)475}476var question = exports.question = {}477question.encode = function (q, buf, offset) {478  if (!buf) buf = Buffer.alloc(question.encodingLength(q))479  if (!offset) offset = 0480  var oldOffset = offset481  name.encode(q.name, buf, offset)482  offset += name.encode.bytes483  buf.writeUInt16BE(types.toType(q.type), offset)484  offset += 2485  buf.writeUInt16BE(q.class === undefined ? 1 : q.class, offset)486  offset += 2487  question.encode.bytes = offset - oldOffset488  return q489}490question.encode.bytes = 0491question.decode = function (buf, offset) {492  if (!offset) offset = 0493  var oldOffset = offset494  var q = {}495  q.name = name.decode(buf, offset)496  offset += name.decode.bytes497  q.type = types.toString(buf.readUInt16BE(offset))498  offset += 2499  q.class = buf.readUInt16BE(offset)500  offset += 2501  var qu = !!(q.class & QU_MASK)502  if (qu) q.class &= NOT_QU_MASK503  question.decode.bytes = offset - oldOffset504  return q505}506question.decode.bytes = 0507question.encodingLength = function (q) {508  return name.encodingLength(q.name) + 4509}510exports.AUTHORITATIVE_ANSWER = 1 << 10511exports.TRUNCATED_RESPONSE = 1 << 9512exports.RECURSION_DESIRED = 1 << 8513exports.RECURSION_AVAILABLE = 1 << 7514exports.AUTHENTIC_DATA = 1 << 5515exports.CHECKING_DISABLED = 1 << 4516exports.encode = function (result, buf, offset) {517  var allocing = !buf518  if (allocing) buf = Buffer.alloc(exports.encodingLength(result))519  if (!offset) offset = 0520  var oldOffset = offset521  if (!result.questions) result.questions = []522  if (!result.answers) result.answers = []523  if (!result.authorities) result.authorities = []524  if (!result.additionals) result.additionals = []525  header.encode(result, buf, offset)526  offset += header.encode.bytes527  offset = encodeList(result.questions, question, buf, offset)528  offset = encodeList(result.answers, answer, buf, offset)529  offset = encodeList(result.authorities, answer, buf, offset)530  offset = encodeList(result.additionals, answer, buf, offset)531  exports.encode.bytes = offset - oldOffset532  // just a quick sanity check533  if (allocing && exports.encode.bytes !== buf.length) {534    return buf.slice(0, exports.encode.bytes)535  }536  return buf537}538exports.encode.bytes = 0539exports.decode = function (buf, offset) {540  if (!offset) offset = 0541  var oldOffset = offset542  var result = header.decode(buf, offset)543  offset += header.decode.bytes544  offset = decodeList(result.questions, question, buf, offset)545  offset = decodeList(result.answers, answer, buf, offset)546  offset = decodeList(result.authorities, answer, buf, offset)547  offset = decodeList(result.additionals, answer, buf, offset)548  exports.decode.bytes = offset - oldOffset549  return result550}551exports.decode.bytes = 0552exports.encodingLength = function (result) {553  return header.encodingLength(result) +554    encodingLengthList(result.questions || [], question) +555    encodingLengthList(result.answers || [], answer) +556    encodingLengthList(result.authorities || [], answer) +557    encodingLengthList(result.additionals || [], answer)558}559function encodingLengthList (list, enc) {560  var len = 0561  for (var i = 0; i < list.length; i++) len += enc.encodingLength(list[i])562  return len563}564function encodeList (list, enc, buf, offset) {565  for (var i = 0; i < list.length; i++) {566    enc.encode(list[i], buf, offset)567    offset += enc.encode.bytes568  }569  return offset570}571function decodeList (list, enc, buf, offset) {572  for (var i = 0; i < list.length; i++) {573    list[i] = enc.decode(buf, offset)574    offset += enc.decode.bytes575  }576  return offset...acpi_extract.py
Source:acpi_extract.py  
1#!/usr/bin/python2# Copyright (C) 2011 Red Hat, Inc., Michael S. Tsirkin <mst@redhat.com>3#4# This file may be distributed under the terms of the GNU GPLv3 license.5# Process mixed ASL/AML listing (.lst file) produced by iasl -l6# Locate and execute ACPI_EXTRACT directives, output offset info7# 8# Documentation of ACPI_EXTRACT_* directive tags:9# 10# These directive tags output offset information from AML for BIOS runtime11# table generation.12# Each directive is of the form:13# ACPI_EXTRACT_<TYPE> <array_name> <Operator> (...)14# and causes the extractor to create an array15# named <array_name> with offset, in the generated AML,16# of an object of a given type in the following <Operator>.17# 18# A directive must fit on a single code line.19# 20# Object type in AML is verified, a mismatch causes a build failure.21# 22# Directives and operators currently supported are:23# ACPI_EXTRACT_NAME_DWORD_CONST - extract a Dword Const object from Name()24# ACPI_EXTRACT_NAME_WORD_CONST - extract a Word Const object from Name()25# ACPI_EXTRACT_NAME_BYTE_CONST - extract a Byte Const object from Name()26# ACPI_EXTRACT_METHOD_STRING - extract a NameString from Method()27# ACPI_EXTRACT_NAME_STRING - extract a NameString from Name()28# ACPI_EXTRACT_PROCESSOR_START - start of Processor() block29# ACPI_EXTRACT_PROCESSOR_STRING - extract a NameString from Processor()30# ACPI_EXTRACT_PROCESSOR_END - offset at last byte of Processor() + 131#32# ACPI_EXTRACT_ALL_CODE - create an array storing the generated AML bytecode33# 34# ACPI_EXTRACT is not allowed anywhere else in code, except in comments.35import re;36import sys;37import fileinput;38aml = []39asl = []40output = {}41debug = ""42class asl_line:43    line = None44    lineno = None45    aml_offset = None46def die(diag):47    sys.stderr.write("Error: %s; %s\n" % (diag, debug))48    sys.exit(1)49    50#Store an ASL command, matching AML offset, and input line (for debugging)51def add_asl(lineno, line):52    l = asl_line()53    l.line = line54    l.lineno = lineno55    l.aml_offset = len(aml)56    asl.append(l)57#Store an AML byte sequence58#Verify that offset output by iasl matches # of bytes so far59def add_aml(offset, line):60    o = int(offset, 16);61    # Sanity check: offset must match size of code so far62    if (o != len(aml)):63        die("Offset 0x%x != 0x%x" % (o, len(aml)))64    # Strip any trailing dots and ASCII dump after "65    line = re.sub(r'\s*\.*\s*".*$',"", line)66    # Strip traling whitespace67    line = re.sub(r'\s+$',"", line)68    # Strip leading whitespace69    line = re.sub(r'^\s+',"", line)70    # Split on whitespace71    code = re.split(r'\s+', line)72    for c in code:73        # Require a legal hex number, two digits74        if (not(re.search(r'^[0-9A-Fa-f][0-9A-Fa-f]$', c))):75            die("Unexpected octet %s" % c);76        aml.append(int(c, 16));77# Process aml bytecode array, decoding AML78def aml_pkglen_bytes(offset):79    # PkgLength can be multibyte. Bits 8-7 give the # of extra bytes.80    pkglenbytes = aml[offset] >> 6;81    return pkglenbytes + 182def aml_pkglen(offset):83    pkgstart = offset84    pkglenbytes = aml_pkglen_bytes(offset)85    pkglen = aml[offset] & 0x3F86    # If multibyte, first nibble only uses bits 0-387    if ((pkglenbytes > 0) and (pkglen & 0x30)):88        die("PkgLen bytes 0x%x but first nibble 0x%x expected 0x0X" %89            (pkglen, pkglen))90    offset += 191    pkglenbytes -= 192    for i in range(pkglenbytes):93        pkglen |= aml[offset + i] << (i * 8 + 4)94    if (len(aml) < pkgstart + pkglen):95        die("PckgLen 0x%x at offset 0x%x exceeds AML size 0x%x" %96            (pkglen, offset, len(aml)))97    return pkglen98# Given method offset, find its NameString offset99def aml_method_string(offset):100    #0x14 MethodOp PkgLength NameString MethodFlags TermList101    if (aml[offset] != 0x14):102        die( "Method offset 0x%x: expected 0x14 actual 0x%x" %103             (offset, aml[offset]));104    offset += 1;105    pkglenbytes = aml_pkglen_bytes(offset)106    offset += pkglenbytes;107    return offset;108# Given name offset, find its NameString offset109def aml_name_string(offset):110    #0x08 NameOp NameString DataRef111    if (aml[offset] != 0x08):112        die( "Name offset 0x%x: expected 0x08 actual 0x%x" %113             (offset, aml[offset]));114    return offset + 1;115# Given data offset, find dword const offset116def aml_data_dword_const(offset):117    #0x08 NameOp NameString DataRef118    if (aml[offset] != 0x0C):119        die( "Name offset 0x%x: expected 0x0C actual 0x%x" %120             (offset, aml[offset]));121    return offset + 1;122# Given data offset, find word const offset123def aml_data_word_const(offset):124    #0x08 NameOp NameString DataRef125    if (aml[offset] != 0x0B):126        die( "Name offset 0x%x: expected 0x0B actual 0x%x" %127             (offset, aml[offset]));128    return offset + 1;129# Given data offset, find byte const offset130def aml_data_byte_const(offset):131    #0x08 NameOp NameString DataRef132    if (aml[offset] != 0x0A):133        die( "Name offset 0x%x: expected 0x0A actual 0x%x" %134             (offset, aml[offset]));135    return offset + 1;136# Given name offset, find dword const offset137def aml_name_dword_const(offset):138    return aml_data_dword_const(aml_name_string(offset) + 4)139# Given name offset, find word const offset140def aml_name_word_const(offset):141    return aml_data_word_const(aml_name_string(offset) + 4)142# Given name offset, find byte const offset143def aml_name_byte_const(offset):144    return aml_data_byte_const(aml_name_string(offset) + 4)145def aml_processor_start(offset):146    #0x5B 0x83 ProcessorOp PkgLength NameString ProcID147    if ((aml[offset] != 0x5B) or (aml[offset + 1] != 0x83)):148        die( "Name offset 0x%x: expected 0x5B 0x83 actual 0x%x 0x%x" %149             (offset, aml[offset], aml[offset + 1]));150    return offset151def aml_processor_string(offset):152    #0x5B 0x83 ProcessorOp PkgLength NameString ProcID153    start = aml_processor_start(offset)154    offset += 2155    pkglenbytes = aml_pkglen_bytes(offset)156    offset += pkglenbytes157    return offset158def aml_processor_end(offset):159    start = aml_processor_start(offset)160    offset += 2161    pkglenbytes = aml_pkglen_bytes(offset)162    pkglen = aml_pkglen(offset)163    return offset + pkglen164lineno = 0165for line in fileinput.input():166    # Strip trailing newline167    line = line.rstrip();168    # line number and debug string to output in case of errors169    lineno = lineno + 1170    debug = "input line %d: %s" % (lineno, line)171    #ASL listing: space, then line#, then ...., then code172    pasl = re.compile('^\s+([0-9]+)\.\.\.\.\s*')173    m = pasl.search(line)174    if (m):175        add_asl(lineno, pasl.sub("", line));176    # AML listing: offset in hex, then ...., then code177    paml = re.compile('^([0-9A-Fa-f]+)\.\.\.\.\s*')178    m = paml.search(line)179    if (m):180        add_aml(m.group(1), paml.sub("", line))181# Now go over code182# Track AML offset of a previous non-empty ASL command183prev_aml_offset = -1184for i in range(len(asl)):185    debug = "input line %d: %s" % (asl[i].lineno, asl[i].line)186    l = asl[i].line187    # skip if not an extract directive188    a = len(re.findall(r'ACPI_EXTRACT', l))189    if (not a):190        # If not empty, store AML offset. Will be used for sanity checks191        # IASL seems to put {}. at random places in the listing.192        # Ignore any non-words for the purpose of this test.193        m = re.search(r'\w+', l)194        if (m):195                prev_aml_offset = asl[i].aml_offset196        continue197    if (a > 1):198        die("Expected at most one ACPI_EXTRACT per line, actual %d" % a)199    mext = re.search(r'''200                      ^\s* # leading whitespace201                      /\*\s* # start C comment202                      (ACPI_EXTRACT_\w+) # directive: group(1)203                      \s+ # whitspace separates directive from array name204                      (\w+) # array name: group(2)205                      \s*\*/ # end of C comment206                      \s*$ # trailing whitespace207                      ''', l, re.VERBOSE)208    if (not mext):209        die("Stray ACPI_EXTRACT in input")210    # previous command must have produced some AML,211    # otherwise we are in a middle of a block212    if (prev_aml_offset == asl[i].aml_offset):213        die("ACPI_EXTRACT directive in the middle of a block")214    directive = mext.group(1)215    array = mext.group(2)216    offset = asl[i].aml_offset217    if (directive == "ACPI_EXTRACT_ALL_CODE"):218        if array in output:219            die("%s directive used more than once" % directive)220        output[array] = aml221        continue222    if (directive == "ACPI_EXTRACT_NAME_DWORD_CONST"):223        offset = aml_name_dword_const(offset)224    elif (directive == "ACPI_EXTRACT_NAME_WORD_CONST"):225        offset = aml_name_word_const(offset)226    elif (directive == "ACPI_EXTRACT_NAME_BYTE_CONST"):227        offset = aml_name_byte_const(offset)228    elif (directive == "ACPI_EXTRACT_NAME_STRING"):229        offset = aml_name_string(offset)230    elif (directive == "ACPI_EXTRACT_METHOD_STRING"):231        offset = aml_method_string(offset)232    elif (directive == "ACPI_EXTRACT_PROCESSOR_START"):233        offset = aml_processor_start(offset)234    elif (directive == "ACPI_EXTRACT_PROCESSOR_STRING"):235        offset = aml_processor_string(offset)236    elif (directive == "ACPI_EXTRACT_PROCESSOR_END"):237        offset = aml_processor_end(offset)238    else:239        die("Unsupported directive %s" % directive)240    if array not in output:241        output[array] = []242    output[array].append(offset)243debug = "at end of file"244def get_value_type(maxvalue):245    #Use type large enough to fit the table246    if (maxvalue >= 0x10000):247            return "int"248    elif (maxvalue >= 0x100):249            return "short"250    else:251            return "char"252# Pretty print output253for array in output.keys():254    otype = get_value_type(max(output[array]))255    odata = []256    for value in output[array]:257        odata.append("0x%x" % value)258    sys.stdout.write("static unsigned %s %s[] = {\n" % (otype, array))259    sys.stdout.write(",\n".join(odata))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
