dbcs-codec.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. "use strict"
  2. // Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
  3. // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
  4. // To save memory and loading time, we read table files only when requested.
  5. exports._dbcs = DBCSCodec;
  6. var UNASSIGNED = -1,
  7. GB18030_CODE = -2,
  8. SEQ_START = -10,
  9. NODE_START = -1000,
  10. UNASSIGNED_NODE = new Array(0x100),
  11. DEF_CHAR = -1;
  12. for (var i = 0; i < 0x100; i++)
  13. UNASSIGNED_NODE[i] = UNASSIGNED;
  14. // Class DBCSCodec reads and initializes mapping tables.
  15. function DBCSCodec(codecOptions, iconv) {
  16. this.encodingName = codecOptions.encodingName;
  17. if (!codecOptions)
  18. throw new Error("DBCS codec is called without the data.")
  19. if (!codecOptions.table)
  20. throw new Error("Encoding '" + this.encodingName + "' has no data.");
  21. // Load tables.
  22. var mappingTable = codecOptions.table();
  23. // Decode tables: MBCS -> Unicode.
  24. // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
  25. // Trie root is decodeTables[0].
  26. // Values: >= 0 -> unicode character code. can be > 0xFFFF
  27. // == UNASSIGNED -> unknown/unassigned sequence.
  28. // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
  29. // <= NODE_START -> index of the next node in our trie to process next byte.
  30. // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
  31. this.decodeTables = [];
  32. this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
  33. // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
  34. this.decodeTableSeq = [];
  35. // Actual mapping tables consist of chunks. Use them to fill up decode tables.
  36. for (var i = 0; i < mappingTable.length; i++)
  37. this._addDecodeChunk(mappingTable[i]);
  38. this.defaultCharUnicode = iconv.defaultCharUnicode;
  39. // Encode tables: Unicode -> DBCS.
  40. // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
  41. // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
  42. // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
  43. // == UNASSIGNED -> no conversion found. Output a default char.
  44. // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
  45. this.encodeTable = [];
  46. // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
  47. // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
  48. // means end of sequence (needed when one sequence is a strict subsequence of another).
  49. // Objects are kept separately from encodeTable to increase performance.
  50. this.encodeTableSeq = [];
  51. // Some chars can be decoded, but need not be encoded.
  52. var skipEncodeChars = {};
  53. if (codecOptions.encodeSkipVals)
  54. for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
  55. var val = codecOptions.encodeSkipVals[i];
  56. if (typeof val === 'number')
  57. skipEncodeChars[val] = true;
  58. else
  59. for (var j = val.from; j <= val.to; j++)
  60. skipEncodeChars[j] = true;
  61. }
  62. // Use decode trie to recursively fill out encode tables.
  63. this._fillEncodeTable(0, 0, skipEncodeChars);
  64. // Add more encoding pairs when needed.
  65. if (codecOptions.encodeAdd) {
  66. for (var uChar in codecOptions.encodeAdd)
  67. if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
  68. this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
  69. }
  70. this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
  71. if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
  72. if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
  73. // Load & create GB18030 tables when needed.
  74. if (typeof codecOptions.gb18030 === 'function') {
  75. this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
  76. // Add GB18030 decode tables.
  77. var thirdByteNodeIdx = this.decodeTables.length;
  78. var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
  79. var fourthByteNodeIdx = this.decodeTables.length;
  80. var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
  81. for (var i = 0x81; i <= 0xFE; i++) {
  82. var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
  83. var secondByteNode = this.decodeTables[secondByteNodeIdx];
  84. for (var j = 0x30; j <= 0x39; j++)
  85. secondByteNode[j] = NODE_START - thirdByteNodeIdx;
  86. }
  87. for (var i = 0x81; i <= 0xFE; i++)
  88. thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
  89. for (var i = 0x30; i <= 0x39; i++)
  90. fourthByteNode[i] = GB18030_CODE
  91. }
  92. }
  93. DBCSCodec.prototype.encoder = DBCSEncoder;
  94. DBCSCodec.prototype.decoder = DBCSDecoder;
  95. // Decoder helpers
  96. DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
  97. var bytes = [];
  98. for (; addr > 0; addr >>= 8)
  99. bytes.push(addr & 0xFF);
  100. if (bytes.length == 0)
  101. bytes.push(0);
  102. var node = this.decodeTables[0];
  103. for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
  104. var val = node[bytes[i]];
  105. if (val == UNASSIGNED) { // Create new node.
  106. node[bytes[i]] = NODE_START - this.decodeTables.length;
  107. this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
  108. }
  109. else if (val <= NODE_START) { // Existing node.
  110. node = this.decodeTables[NODE_START - val];
  111. }
  112. else
  113. throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
  114. }
  115. return node;
  116. }
  117. DBCSCodec.prototype._addDecodeChunk = function(chunk) {
  118. // First element of chunk is the hex mbcs code where we start.
  119. var curAddr = parseInt(chunk[0], 16);
  120. // Choose the decoding node where we'll write our chars.
  121. var writeTable = this._getDecodeTrieNode(curAddr);
  122. curAddr = curAddr & 0xFF;
  123. // Write all other elements of the chunk to the table.
  124. for (var k = 1; k < chunk.length; k++) {
  125. var part = chunk[k];
  126. if (typeof part === "string") { // String, write as-is.
  127. for (var l = 0; l < part.length;) {
  128. var code = part.charCodeAt(l++);
  129. if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
  130. var codeTrail = part.charCodeAt(l++);
  131. if (0xDC00 <= codeTrail && codeTrail < 0xE000)
  132. writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
  133. else
  134. throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);
  135. }
  136. else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
  137. var len = 0xFFF - code + 2;
  138. var seq = [];
  139. for (var m = 0; m < len; m++)
  140. seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
  141. writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
  142. this.decodeTableSeq.push(seq);
  143. }
  144. else
  145. writeTable[curAddr++] = code; // Basic char
  146. }
  147. }
  148. else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
  149. var charCode = writeTable[curAddr - 1] + 1;
  150. for (var l = 0; l < part; l++)
  151. writeTable[curAddr++] = charCode++;
  152. }
  153. else
  154. throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);
  155. }
  156. if (curAddr > 0xFF)
  157. throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
  158. }
  159. // Encoder helpers
  160. DBCSCodec.prototype._getEncodeBucket = function(uCode) {
  161. var high = uCode >> 8; // This could be > 0xFF because of astral characters.
  162. if (this.encodeTable[high] === undefined)
  163. this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
  164. return this.encodeTable[high];
  165. }
  166. DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
  167. var bucket = this._getEncodeBucket(uCode);
  168. var low = uCode & 0xFF;
  169. if (bucket[low] <= SEQ_START)
  170. this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
  171. else if (bucket[low] == UNASSIGNED)
  172. bucket[low] = dbcsCode;
  173. }
  174. DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
  175. // Get the root of character tree according to first character of the sequence.
  176. var uCode = seq[0];
  177. var bucket = this._getEncodeBucket(uCode);
  178. var low = uCode & 0xFF;
  179. var node;
  180. if (bucket[low] <= SEQ_START) {
  181. // There's already a sequence with - use it.
  182. node = this.encodeTableSeq[SEQ_START-bucket[low]];
  183. }
  184. else {
  185. // There was no sequence object - allocate a new one.
  186. node = {};
  187. if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
  188. bucket[low] = SEQ_START - this.encodeTableSeq.length;
  189. this.encodeTableSeq.push(node);
  190. }
  191. // Traverse the character tree, allocating new nodes as needed.
  192. for (var j = 1; j < seq.length-1; j++) {
  193. var oldVal = node[uCode];
  194. if (typeof oldVal === 'object')
  195. node = oldVal;
  196. else {
  197. node = node[uCode] = {}
  198. if (oldVal !== undefined)
  199. node[DEF_CHAR] = oldVal
  200. }
  201. }
  202. // Set the leaf to given dbcsCode.
  203. uCode = seq[seq.length-1];
  204. node[uCode] = dbcsCode;
  205. }
  206. DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
  207. var node = this.decodeTables[nodeIdx];
  208. for (var i = 0; i < 0x100; i++) {
  209. var uCode = node[i];
  210. var mbCode = prefix + i;
  211. if (skipEncodeChars[mbCode])
  212. continue;
  213. if (uCode >= 0)
  214. this._setEncodeChar(uCode, mbCode);
  215. else if (uCode <= NODE_START)
  216. this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
  217. else if (uCode <= SEQ_START)
  218. this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
  219. }
  220. }
  221. // == Encoder ==================================================================
  222. function DBCSEncoder(options, codec) {
  223. // Encoder state
  224. this.leadSurrogate = -1;
  225. this.seqObj = undefined;
  226. // Static data
  227. this.encodeTable = codec.encodeTable;
  228. this.encodeTableSeq = codec.encodeTableSeq;
  229. this.defaultCharSingleByte = codec.defCharSB;
  230. this.gb18030 = codec.gb18030;
  231. }
  232. DBCSEncoder.prototype.write = function(str) {
  233. var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)),
  234. leadSurrogate = this.leadSurrogate,
  235. seqObj = this.seqObj, nextChar = -1,
  236. i = 0, j = 0;
  237. while (true) {
  238. // 0. Get next character.
  239. if (nextChar === -1) {
  240. if (i == str.length) break;
  241. var uCode = str.charCodeAt(i++);
  242. }
  243. else {
  244. var uCode = nextChar;
  245. nextChar = -1;
  246. }
  247. // 1. Handle surrogates.
  248. if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
  249. if (uCode < 0xDC00) { // We've got lead surrogate.
  250. if (leadSurrogate === -1) {
  251. leadSurrogate = uCode;
  252. continue;
  253. } else {
  254. leadSurrogate = uCode;
  255. // Double lead surrogate found.
  256. uCode = UNASSIGNED;
  257. }
  258. } else { // We've got trail surrogate.
  259. if (leadSurrogate !== -1) {
  260. uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
  261. leadSurrogate = -1;
  262. } else {
  263. // Incomplete surrogate pair - only trail surrogate found.
  264. uCode = UNASSIGNED;
  265. }
  266. }
  267. }
  268. else if (leadSurrogate !== -1) {
  269. // Incomplete surrogate pair - only lead surrogate found.
  270. nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
  271. leadSurrogate = -1;
  272. }
  273. // 2. Convert uCode character.
  274. var dbcsCode = UNASSIGNED;
  275. if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
  276. var resCode = seqObj[uCode];
  277. if (typeof resCode === 'object') { // Sequence continues.
  278. seqObj = resCode;
  279. continue;
  280. } else if (typeof resCode == 'number') { // Sequence finished. Write it.
  281. dbcsCode = resCode;
  282. } else if (resCode == undefined) { // Current character is not part of the sequence.
  283. // Try default character for this sequence
  284. resCode = seqObj[DEF_CHAR];
  285. if (resCode !== undefined) {
  286. dbcsCode = resCode; // Found. Write it.
  287. nextChar = uCode; // Current character will be written too in the next iteration.
  288. } else {
  289. // TODO: What if we have no default? (resCode == undefined)
  290. // Then, we should write first char of the sequence as-is and try the rest recursively.
  291. // Didn't do it for now because no encoding has this situation yet.
  292. // Currently, just skip the sequence and write current char.
  293. }
  294. }
  295. seqObj = undefined;
  296. }
  297. else if (uCode >= 0) { // Regular character
  298. var subtable = this.encodeTable[uCode >> 8];
  299. if (subtable !== undefined)
  300. dbcsCode = subtable[uCode & 0xFF];
  301. if (dbcsCode <= SEQ_START) { // Sequence start
  302. seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
  303. continue;
  304. }
  305. if (dbcsCode == UNASSIGNED && this.gb18030) {
  306. // Use GB18030 algorithm to find character(s) to write.
  307. var idx = findIdx(this.gb18030.uChars, uCode);
  308. if (idx != -1) {
  309. var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
  310. newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
  311. newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
  312. newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
  313. newBuf[j++] = 0x30 + dbcsCode;
  314. continue;
  315. }
  316. }
  317. }
  318. // 3. Write dbcsCode character.
  319. if (dbcsCode === UNASSIGNED)
  320. dbcsCode = this.defaultCharSingleByte;
  321. if (dbcsCode < 0x100) {
  322. newBuf[j++] = dbcsCode;
  323. }
  324. else if (dbcsCode < 0x10000) {
  325. newBuf[j++] = dbcsCode >> 8; // high byte
  326. newBuf[j++] = dbcsCode & 0xFF; // low byte
  327. }
  328. else {
  329. newBuf[j++] = dbcsCode >> 16;
  330. newBuf[j++] = (dbcsCode >> 8) & 0xFF;
  331. newBuf[j++] = dbcsCode & 0xFF;
  332. }
  333. }
  334. this.seqObj = seqObj;
  335. this.leadSurrogate = leadSurrogate;
  336. return newBuf.slice(0, j);
  337. }
  338. DBCSEncoder.prototype.end = function() {
  339. if (this.leadSurrogate === -1 && this.seqObj === undefined)
  340. return; // All clean. Most often case.
  341. var newBuf = new Buffer(10), j = 0;
  342. if (this.seqObj) { // We're in the sequence.
  343. var dbcsCode = this.seqObj[DEF_CHAR];
  344. if (dbcsCode !== undefined) { // Write beginning of the sequence.
  345. if (dbcsCode < 0x100) {
  346. newBuf[j++] = dbcsCode;
  347. }
  348. else {
  349. newBuf[j++] = dbcsCode >> 8; // high byte
  350. newBuf[j++] = dbcsCode & 0xFF; // low byte
  351. }
  352. } else {
  353. // See todo above.
  354. }
  355. this.seqObj = undefined;
  356. }
  357. if (this.leadSurrogate !== -1) {
  358. // Incomplete surrogate pair - only lead surrogate found.
  359. newBuf[j++] = this.defaultCharSingleByte;
  360. this.leadSurrogate = -1;
  361. }
  362. return newBuf.slice(0, j);
  363. }
  364. // Export for testing
  365. DBCSEncoder.prototype.findIdx = findIdx;
  366. // == Decoder ==================================================================
  367. function DBCSDecoder(options, codec) {
  368. // Decoder state
  369. this.nodeIdx = 0;
  370. this.prevBuf = new Buffer(0);
  371. // Static data
  372. this.decodeTables = codec.decodeTables;
  373. this.decodeTableSeq = codec.decodeTableSeq;
  374. this.defaultCharUnicode = codec.defaultCharUnicode;
  375. this.gb18030 = codec.gb18030;
  376. }
  377. DBCSDecoder.prototype.write = function(buf) {
  378. var newBuf = new Buffer(buf.length*2),
  379. nodeIdx = this.nodeIdx,
  380. prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,
  381. seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.
  382. uCode;
  383. if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.
  384. prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);
  385. for (var i = 0, j = 0; i < buf.length; i++) {
  386. var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];
  387. // Lookup in current trie node.
  388. var uCode = this.decodeTables[nodeIdx][curByte];
  389. if (uCode >= 0) {
  390. // Normal character, just use it.
  391. }
  392. else if (uCode === UNASSIGNED) { // Unknown char.
  393. // TODO: Callback with seq.
  394. //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
  395. i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).
  396. uCode = this.defaultCharUnicode.charCodeAt(0);
  397. }
  398. else if (uCode === GB18030_CODE) {
  399. var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
  400. var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);
  401. var idx = findIdx(this.gb18030.gbChars, ptr);
  402. uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
  403. }
  404. else if (uCode <= NODE_START) { // Go to next trie node.
  405. nodeIdx = NODE_START - uCode;
  406. continue;
  407. }
  408. else if (uCode <= SEQ_START) { // Output a sequence of chars.
  409. var seq = this.decodeTableSeq[SEQ_START - uCode];
  410. for (var k = 0; k < seq.length - 1; k++) {
  411. uCode = seq[k];
  412. newBuf[j++] = uCode & 0xFF;
  413. newBuf[j++] = uCode >> 8;
  414. }
  415. uCode = seq[seq.length-1];
  416. }
  417. else
  418. throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
  419. // Write the character to buffer, handling higher planes using surrogate pair.
  420. if (uCode > 0xFFFF) {
  421. uCode -= 0x10000;
  422. var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
  423. newBuf[j++] = uCodeLead & 0xFF;
  424. newBuf[j++] = uCodeLead >> 8;
  425. uCode = 0xDC00 + uCode % 0x400;
  426. }
  427. newBuf[j++] = uCode & 0xFF;
  428. newBuf[j++] = uCode >> 8;
  429. // Reset trie node.
  430. nodeIdx = 0; seqStart = i+1;
  431. }
  432. this.nodeIdx = nodeIdx;
  433. this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
  434. return newBuf.slice(0, j).toString('ucs2');
  435. }
  436. DBCSDecoder.prototype.end = function() {
  437. var ret = '';
  438. // Try to parse all remaining chars.
  439. while (this.prevBuf.length > 0) {
  440. // Skip 1 character in the buffer.
  441. ret += this.defaultCharUnicode;
  442. var buf = this.prevBuf.slice(1);
  443. // Parse remaining as usual.
  444. this.prevBuf = new Buffer(0);
  445. this.nodeIdx = 0;
  446. if (buf.length > 0)
  447. ret += this.write(buf);
  448. }
  449. this.nodeIdx = 0;
  450. return ret;
  451. }
  452. // Binary search for GB18030. Returns largest i such that table[i] <= val.
  453. function findIdx(table, val) {
  454. if (table[0] > val)
  455. return -1;
  456. var l = 0, r = table.length;
  457. while (l < r-1) { // always table[l] <= val < table[r]
  458. var mid = l + Math.floor((r-l+1)/2);
  459. if (table[mid] <= val)
  460. l = mid;
  461. else
  462. r = mid;
  463. }
  464. return l;
  465. }