dbcs-codec.js 21 KB

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