UnicodeTrieBuilder.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. using System;
  16. using System.IO;
  17. using System.IO.Compression;
  18. using System.Text;
  19. // Ported from: https://github.com/foliojs/unicode-trie
  20. namespace Topten.RichTextKit
  21. {
  22. internal class UnicodeTrieBuilder
  23. {
  24. // Shift size for getting the index-1 table offset.
  25. internal const int SHIFT_1 = 6 + 5;
  26. // Shift size for getting the index-2 table offset.
  27. internal const int SHIFT_2 = 5;
  28. // Difference between the two shift sizes,
  29. // for getting an index-1 offset from an index-2 offset. 6=11-5
  30. const int SHIFT_1_2 = SHIFT_1 - SHIFT_2;
  31. // Number of index-1 entries for the BMP. 32=0x20
  32. // This part of the index-1 table is omitted from the serialized form.
  33. internal const int OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> SHIFT_1;
  34. // Number of code points per index-1 table entry. 2048=0x800
  35. const int CP_PER_INDEX_1_ENTRY = 1 << SHIFT_1;
  36. // Number of entries in an index-2 block. 64=0x40
  37. const int INDEX_2_BLOCK_LENGTH = 1 << SHIFT_1_2;
  38. // Mask for getting the lower bits for the in-index-2-block offset. */
  39. internal const int INDEX_2_MASK = INDEX_2_BLOCK_LENGTH - 1;
  40. // Number of entries in a data block. 32=0x20
  41. const int DATA_BLOCK_LENGTH = 1 << SHIFT_2;
  42. // Mask for getting the lower bits for the in-data-block offset.
  43. internal const int DATA_MASK = DATA_BLOCK_LENGTH - 1;
  44. // Shift size for shifting left the index array values.
  45. // Increases possible data size with 16-bit index values at the cost
  46. // of compactability.
  47. // This requires data blocks to be aligned by DATA_GRANULARITY.
  48. internal const int INDEX_SHIFT = 2;
  49. // The alignment size of a data block. Also the granularity for compaction.
  50. internal const int DATA_GRANULARITY = 1 << INDEX_SHIFT;
  51. // The BMP part of the index-2 table is fixed and linear and starts at offset 0.
  52. // Length=2048=0x800=0x10000>>SHIFT_2.
  53. const int INDEX_2_OFFSET = 0;
  54. // The part of the index-2 table for U+D800..U+DBFF stores values for
  55. // lead surrogate code _units_ not code _points_.
  56. // Values for lead surrogate code _points_ are indexed with this portion of the table.
  57. // Length=32=0x20=0x400>>SHIFT_2. (There are 1024=0x400 lead surrogates.)
  58. internal const int LSCP_INDEX_2_OFFSET = 0x10000 >> SHIFT_2;
  59. const int LSCP_INDEX_2_LENGTH = 0x400 >> SHIFT_2;
  60. // Count the lengths of both BMP pieces. 2080=0x820
  61. const int INDEX_2_BMP_LENGTH = LSCP_INDEX_2_OFFSET + LSCP_INDEX_2_LENGTH;
  62. // The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
  63. // Length 32=0x20 for lead bytes C0..DF, regardless of SHIFT_2.
  64. const int UTF8_2B_INDEX_2_OFFSET = INDEX_2_BMP_LENGTH;
  65. const int UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; // U+0800 is the first code point after 2-byte UTF-8
  66. // The index-1 table, only used for supplementary code points, at offset 2112=0x840.
  67. // Variable length, for code points up to highStart, where the last single-value range starts.
  68. // Maximum length 512=0x200=0x100000>>SHIFT_1.
  69. // (For 0x100000 supplementary code points U+10000..U+10ffff.)
  70. //
  71. // The part of the index-2 table for supplementary code points starts
  72. // after this index-1 table.
  73. //
  74. // Both the index-1 table and the following part of the index-2 table
  75. // are omitted completely if there is only BMP data.
  76. internal const int INDEX_1_OFFSET = UTF8_2B_INDEX_2_OFFSET + UTF8_2B_INDEX_2_LENGTH;
  77. const int MAX_INDEX_1_LENGTH = 0x100000 >> SHIFT_1;
  78. // The illegal-UTF-8 data block follows the ASCII block, at offset 128=0x80.
  79. // Used with linear access for single bytes 0..0xbf for simple error handling.
  80. // Length 64=0x40, not DATA_BLOCK_LENGTH.
  81. const int BAD_UTF8_DATA_OFFSET = 0x80;
  82. // The start of non-linear-ASCII data blocks, at offset 192=0xc0.
  83. // !!!!
  84. const int DATA_START_OFFSET = 0xc0;
  85. // The null data block.
  86. // Length 64=0x40 even if DATA_BLOCK_LENGTH is smaller,
  87. // to work with 6-bit trail bytes from 2-byte UTF-8.
  88. const int DATA_NULL_OFFSET = DATA_START_OFFSET;
  89. // The start of allocated data blocks.
  90. const int NEW_DATA_START_OFFSET = DATA_NULL_OFFSET + 0x40;
  91. // The start of data blocks for U+0800 and above.
  92. // Below, compaction uses a block length of 64 for 2-byte UTF-8.
  93. // From here on, compaction uses DATA_BLOCK_LENGTH.
  94. // Data values for 0x780 code points beyond ASCII.
  95. const int DATA_0800_OFFSET = NEW_DATA_START_OFFSET + 0x780;
  96. // Start with allocation of 16k data entries. */
  97. const int INITIAL_DATA_LENGTH = 1 << 14;
  98. // Grow about 8x each time.
  99. const int MEDIUM_DATA_LENGTH = 1 << 17;
  100. // Maximum length of the runtime data array.
  101. // Limited by 16-bit index values that are left-shifted by INDEX_SHIFT,
  102. // and by uint16_t UTrie2Header.shiftedDataLength.
  103. const int MAX_DATA_LENGTH_RUNTIME = 0xffff << INDEX_SHIFT;
  104. const int INDEX_1_LENGTH = 0x110000 >> SHIFT_1;
  105. // Maximum length of the build-time data array.
  106. // One entry per 0x110000 code points, plus the illegal-UTF-8 block and the null block,
  107. // plus values for the 0x400 surrogate code units.
  108. const int MAX_DATA_LENGTH_BUILDTIME = 0x110000 + 0x40 + 0x40 + 0x400;
  109. // At build time, leave a gap in the index-2 table,
  110. // at least as long as the maximum lengths of the 2-byte UTF-8 index-2 table
  111. // and the supplementary index-1 table.
  112. // Round up to INDEX_2_BLOCK_LENGTH for proper compacting.
  113. const int INDEX_GAP_OFFSET = INDEX_2_BMP_LENGTH;
  114. const int INDEX_GAP_LENGTH = ((UTF8_2B_INDEX_2_LENGTH + MAX_INDEX_1_LENGTH) + INDEX_2_MASK) & ~INDEX_2_MASK;
  115. // Maximum length of the build-time index-2 array.
  116. // Maximum number of Unicode code points (0x110000) shifted right by SHIFT_2,
  117. // plus the part of the index-2 table for lead surrogate code points,
  118. // plus the build-time index gap,
  119. // plus the null index-2 block.)
  120. const int MAX_INDEX_2_LENGTH = (0x110000 >> SHIFT_2) + LSCP_INDEX_2_LENGTH + INDEX_GAP_LENGTH + INDEX_2_BLOCK_LENGTH;
  121. // The null index-2 block, following the gap in the index-2 table.
  122. const int INDEX_2_NULL_OFFSET = INDEX_GAP_OFFSET + INDEX_GAP_LENGTH;
  123. // The start of allocated index-2 blocks.
  124. const int INDEX_2_START_OFFSET = INDEX_2_NULL_OFFSET + INDEX_2_BLOCK_LENGTH;
  125. // Maximum length of the runtime index array.
  126. // Limited by its own 16-bit index values, and by uint16_t UTrie2Header.indexLength.
  127. // (The actual maximum length is lower,
  128. // (0x110000>>SHIFT_2)+UTF8_2B_INDEX_2_LENGTH+MAX_INDEX_1_LENGTH.)
  129. const int MAX_INDEX_LENGTH = 0xffff;
  130. static bool equal(uint[] a, int s, int t, int length)
  131. {
  132. for (var i = 0; i < length; i++)
  133. {
  134. if (a[s + i] != a[t + i])
  135. {
  136. return false;
  137. }
  138. }
  139. return true;
  140. }
  141. static bool equal(int[] a, int s, int t, int length)
  142. {
  143. for (var i = 0; i < length; i++)
  144. {
  145. if (a[s + i] != a[t + i])
  146. {
  147. return false;
  148. }
  149. }
  150. return true;
  151. }
  152. uint _initialValue;
  153. uint _errorValue;
  154. int[] _index1;
  155. int[] _index2;
  156. int _highStart;
  157. UInt32[] _data;
  158. int _dataCapacity;
  159. int _firstFreeBlock;
  160. bool _isCompacted;
  161. int[] _map;
  162. int _dataNullOffset;
  163. int _dataLength;
  164. int _index2NullOffset;
  165. int _index2Length;
  166. public UnicodeTrieBuilder(uint initialValue = 0, uint errorValue = 0)
  167. {
  168. _initialValue = initialValue;
  169. _errorValue = errorValue;
  170. _index1 = new int[INDEX_1_LENGTH];
  171. _index2 = new int[MAX_INDEX_2_LENGTH];
  172. _highStart = 0x110000;
  173. _data = new uint[INITIAL_DATA_LENGTH];
  174. _dataCapacity = INITIAL_DATA_LENGTH;
  175. _firstFreeBlock = 0;
  176. _isCompacted = false;
  177. // Multi-purpose per-data-block table.
  178. //
  179. // Before compacting:
  180. //
  181. // Per-data-block reference counters/free-block list.
  182. // 0: unused
  183. // >0: reference counter (number of index-2 entries pointing here)
  184. // <0: next free data block in free-block list
  185. //
  186. // While compacting:
  187. //
  188. // Map of adjusted indexes, used in compactData() and compactIndex2().
  189. // Maps from original indexes to new ones.
  190. _map = new int[MAX_DATA_LENGTH_BUILDTIME >> SHIFT_2];
  191. int i;
  192. for (i = 0; i < 0x80; i++)
  193. {
  194. _data[i] = _initialValue;
  195. }
  196. for (; i < 0xc0; i++)
  197. {
  198. _data[i] = _errorValue;
  199. }
  200. for (i = DATA_NULL_OFFSET; i < NEW_DATA_START_OFFSET; i++)
  201. {
  202. _data[i] = _initialValue;
  203. }
  204. _dataNullOffset = DATA_NULL_OFFSET;
  205. _dataLength = NEW_DATA_START_OFFSET;
  206. // set the index-2 indexes for the 2=0x80>>SHIFT_2 ASCII data blocks
  207. int j;
  208. i = 0;
  209. for (j = 0; j < 0x80; j += DATA_BLOCK_LENGTH) {
  210. _index2[i] = j;
  211. _map[i++] = 1;
  212. }
  213. // reference counts for the bad-UTF-8-data block
  214. for (; j < 0xc0; j += DATA_BLOCK_LENGTH) {
  215. _map[i++] = 0;
  216. }
  217. // Reference counts for the null data block: all blocks except for the ASCII blocks.
  218. // Plus 1 so that we don't drop this block during compaction.
  219. // Plus as many as needed for lead surrogate code points.
  220. // i==newTrie->dataNullOffset
  221. _map[i++] = ((0x110000 >> SHIFT_2) - (0x80 >> SHIFT_2)) + 1 + LSCP_INDEX_2_LENGTH;
  222. j += DATA_BLOCK_LENGTH;
  223. for (; j < NEW_DATA_START_OFFSET; j += DATA_BLOCK_LENGTH) {
  224. _map[i++] = 0;
  225. }
  226. // set the remaining indexes in the BMP index-2 block
  227. // to the null data block
  228. for (i = 0x80 >> SHIFT_2; i < INDEX_2_BMP_LENGTH; i++) {
  229. _index2[i] = DATA_NULL_OFFSET;
  230. }
  231. // Fill the index gap with impossible values so that compaction
  232. // does not overlap other index-2 blocks with the gap.
  233. for (i = 0; i < INDEX_GAP_LENGTH; i++) {
  234. _index2[INDEX_GAP_OFFSET + i] = -1;
  235. }
  236. // set the indexes in the null index-2 block
  237. for (i = 0; i < INDEX_2_BLOCK_LENGTH; i++) {
  238. _index2[INDEX_2_NULL_OFFSET + i] = DATA_NULL_OFFSET;
  239. }
  240. _index2NullOffset = INDEX_2_NULL_OFFSET;
  241. _index2Length = INDEX_2_START_OFFSET;
  242. // set the index-1 indexes for the linear index-2 block
  243. j = 0;
  244. for (i = 0; i < OMITTED_BMP_INDEX_1_LENGTH; i++) {
  245. _index1[i] = j;
  246. j += INDEX_2_BLOCK_LENGTH;
  247. }
  248. // set the remaining index-1 indexes to the null index-2 block
  249. for (; i < INDEX_1_LENGTH; i++) {
  250. _index1[i] = INDEX_2_NULL_OFFSET;
  251. }
  252. // Preallocate and reset data for U+0080..U+07ff,
  253. // for 2-byte UTF-8 which will be compacted in 64-blocks
  254. // even if DATA_BLOCK_LENGTH is smaller.
  255. for (i = 0x80; i < 0x800; i += DATA_BLOCK_LENGTH) {
  256. Set(i, _initialValue);
  257. }
  258. }
  259. public UnicodeTrieBuilder Set(int codePoint, uint value)
  260. {
  261. if ((codePoint < 0) || (codePoint > 0x10ffff))
  262. {
  263. throw new InvalidOperationException("Invalid code point");
  264. }
  265. if (_isCompacted)
  266. {
  267. throw new InvalidOperationException("Already compacted");
  268. }
  269. var block = getDataBlock(codePoint, true);
  270. _data[block + (codePoint & DATA_MASK)] = value;
  271. return this;
  272. }
  273. public UnicodeTrieBuilder SetRange(int start, int end, uint value, bool overwrite = true)
  274. {
  275. if ((start > 0x10ffff) || (end > 0x10ffff) || (start > end))
  276. {
  277. throw new InvalidOperationException("Invalid code point");
  278. }
  279. if (_isCompacted)
  280. {
  281. throw new InvalidOperationException("Already compacted");
  282. }
  283. if (!overwrite && (value == _initialValue))
  284. {
  285. return this; // nothing to do
  286. }
  287. var limit = end + 1;
  288. if ((start & DATA_MASK) != 0)
  289. {
  290. // set partial block at [start..following block boundary
  291. var block = getDataBlock(start, true);
  292. var nextStart = (start + DATA_BLOCK_LENGTH) & ~DATA_MASK;
  293. if (nextStart <= limit)
  294. {
  295. fillBlock(block, start & DATA_MASK, DATA_BLOCK_LENGTH, value, _initialValue, overwrite);
  296. start = nextStart;
  297. }
  298. else
  299. {
  300. fillBlock(block, start & DATA_MASK, limit & DATA_MASK, value, _initialValue, overwrite);
  301. return this;
  302. }
  303. }
  304. // number of positions in the last, partial block
  305. var rest = limit & DATA_MASK;
  306. // round down limit to a block boundary
  307. limit &= ~DATA_MASK;
  308. // iterate over all-value blocks
  309. int repeatBlock;
  310. if (value == _initialValue)
  311. {
  312. repeatBlock = _dataNullOffset;
  313. }
  314. else
  315. {
  316. repeatBlock = -1;
  317. }
  318. while (start < limit)
  319. {
  320. var setRepeatBlock = false;
  321. if ((value == _initialValue) && isInNullBlock(start, true))
  322. {
  323. start += DATA_BLOCK_LENGTH; // nothing to do
  324. continue;
  325. }
  326. // get index value
  327. var i2 = getIndex2Block(start, true);
  328. i2 += (start >> SHIFT_2) & INDEX_2_MASK;
  329. var block = _index2[i2];
  330. if (isWritableBlock(block))
  331. {
  332. // already allocated
  333. if (overwrite && (block >= DATA_0800_OFFSET))
  334. {
  335. // We overwrite all values, and it's not a
  336. // protected (ASCII-linear or 2-byte UTF-8) block:
  337. // replace with the repeatBlock.
  338. setRepeatBlock = true;
  339. }
  340. else
  341. {
  342. // protected block: just write the values into this block
  343. fillBlock(block, 0, DATA_BLOCK_LENGTH, value, _initialValue, overwrite);
  344. }
  345. }
  346. else if ((_data[block] != value) && (overwrite || (block == _dataNullOffset)))
  347. {
  348. // Set the repeatBlock instead of the null block or previous repeat block:
  349. //
  350. // If !isWritableBlock() then all entries in the block have the same value
  351. // because it's the null block or a range block (the repeatBlock from a previous
  352. // call to utrie2_setRange32()).
  353. // No other blocks are used multiple times before compacting.
  354. //
  355. // The null block is the only non-writable block with the initialValue because
  356. // of the repeatBlock initialization above. (If value==initialValue, then
  357. // the repeatBlock will be the null data block.)
  358. //
  359. // We set our repeatBlock if the desired value differs from the block's value,
  360. // and if we overwrite any data or if the data is all initial values
  361. // (which is the same as the block being the null block, see above).
  362. setRepeatBlock = true;
  363. }
  364. if (setRepeatBlock)
  365. {
  366. if (repeatBlock >= 0)
  367. {
  368. setIndex2Entry(i2, repeatBlock);
  369. }
  370. else
  371. {
  372. // create and set and fill the repeatBlock
  373. repeatBlock = getDataBlock(start, true);
  374. writeBlock(repeatBlock, value);
  375. }
  376. }
  377. start += DATA_BLOCK_LENGTH;
  378. }
  379. if (rest > 0)
  380. {
  381. // set partial block at [last block boundary..limit
  382. var block = getDataBlock(start, true);
  383. fillBlock(block, 0, rest, value, _initialValue, overwrite);
  384. }
  385. return this;
  386. }
  387. public uint Get(int c, bool fromLSCP = true)
  388. {
  389. if ((c < 0) || (c > 0x10ffff))
  390. {
  391. return _errorValue;
  392. }
  393. if ((c >= _highStart) && (!((c >= 0xd800) && (c < 0xdc00)) || fromLSCP))
  394. {
  395. return _data[_dataLength - DATA_GRANULARITY];
  396. }
  397. int i2;
  398. if (((c >= 0xd800) && (c < 0xdc00)) && fromLSCP)
  399. {
  400. i2 = (LSCP_INDEX_2_OFFSET - (0xd800 >> SHIFT_2)) + (c >> SHIFT_2);
  401. }
  402. else
  403. {
  404. i2 = _index1[c >> SHIFT_1] + ((c >> SHIFT_2) & INDEX_2_MASK);
  405. }
  406. var block = _index2[i2];
  407. return _data[block + (c & DATA_MASK)];
  408. }
  409. public byte[] ToBuffer()
  410. {
  411. var mem = new MemoryStream();
  412. Save(mem);
  413. return mem.GetBuffer();
  414. }
  415. public void Save(Stream stream)
  416. {
  417. var trie = this.Freeze();
  418. trie.Save(stream);
  419. }
  420. bool isInNullBlock(int c, bool forLSCP)
  421. {
  422. int i2;
  423. if (((c & 0xfffffc00) == 0xd800) && forLSCP)
  424. {
  425. i2 = (LSCP_INDEX_2_OFFSET - (0xd800 >> SHIFT_2)) + (c >> SHIFT_2);
  426. }
  427. else
  428. {
  429. i2 = _index1[c >> SHIFT_1] + ((c >> SHIFT_2) & INDEX_2_MASK);
  430. }
  431. var block = _index2[i2];
  432. return block == _dataNullOffset;
  433. }
  434. int allocIndex2Block()
  435. {
  436. var newBlock = _index2Length;
  437. var newTop = newBlock + INDEX_2_BLOCK_LENGTH;
  438. if (newTop > _index2.Length)
  439. {
  440. // Should never occur.
  441. // Either MAX_BUILD_TIME_INDEX_LENGTH is incorrect,
  442. // or the code writes more values than should be possible.
  443. throw new InvalidOperationException("Internal error in Trie2 creation.");
  444. }
  445. _index2Length = newTop;
  446. Array.Copy(_index2, _index2NullOffset, _index2, newBlock, INDEX_2_BLOCK_LENGTH);
  447. // _index2.set(_index2.subarray(_index2NullOffset, _index2NullOffset + INDEX_2_BLOCK_LENGTH), newBlock);
  448. return newBlock;
  449. }
  450. int getIndex2Block(int c, bool forLSCP)
  451. {
  452. if ((c >= 0xd800) && (c < 0xdc00) && forLSCP)
  453. {
  454. return LSCP_INDEX_2_OFFSET;
  455. }
  456. var i1 = c >> SHIFT_1;
  457. var i2 = _index1[i1];
  458. if (i2 == _index2NullOffset)
  459. {
  460. i2 = allocIndex2Block();
  461. _index1[i1] = i2;
  462. }
  463. return i2;
  464. }
  465. bool isWritableBlock(int block)
  466. {
  467. return (block != _dataNullOffset) && (_map[block >> SHIFT_2] == 1);
  468. }
  469. int allocDataBlock(int copyBlock)
  470. {
  471. int newBlock;
  472. if (_firstFreeBlock != 0)
  473. {
  474. // get the first free block
  475. newBlock = _firstFreeBlock;
  476. _firstFreeBlock = -_map[newBlock >> SHIFT_2];
  477. }
  478. else
  479. {
  480. // get a new block from the high end
  481. newBlock = _dataLength;
  482. var newTop = newBlock + DATA_BLOCK_LENGTH;
  483. if (newTop > _dataCapacity)
  484. {
  485. // out of memory in the data array
  486. int capacity;
  487. if (_dataCapacity < MEDIUM_DATA_LENGTH)
  488. {
  489. capacity = MEDIUM_DATA_LENGTH;
  490. }
  491. else if (_dataCapacity < MAX_DATA_LENGTH_BUILDTIME)
  492. {
  493. capacity = MAX_DATA_LENGTH_BUILDTIME;
  494. }
  495. else
  496. {
  497. // Should never occur.
  498. // Either MAX_DATA_LENGTH_BUILDTIME is incorrect,
  499. // or the code writes more values than should be possible.
  500. throw new InvalidOperationException("Internal error in Trie2 creation.");
  501. }
  502. var newData = new UInt32[capacity];
  503. Array.Copy(_data, newData, _dataLength);
  504. _data = newData;
  505. _dataCapacity = capacity;
  506. }
  507. _dataLength = newTop;
  508. }
  509. Array.Copy(_data, copyBlock, _data, newBlock, DATA_BLOCK_LENGTH);
  510. //_data.set(_data.subarray(copyBlock, copyBlock + DATA_BLOCK_LENGTH), newBlock);
  511. _map[newBlock >> SHIFT_2] = 0;
  512. return newBlock;
  513. }
  514. void releaseDataBlock(int block)
  515. {
  516. // put this block at the front of the free-block chain
  517. _map[block >> SHIFT_2] = -_firstFreeBlock;
  518. _firstFreeBlock = block;
  519. }
  520. void setIndex2Entry(int i2, int block)
  521. {
  522. ++_map[block >> SHIFT_2]; // increment first, in case block == oldBlock!
  523. var oldBlock = _index2[i2];
  524. if (--_map[oldBlock >> SHIFT_2] == 0)
  525. {
  526. releaseDataBlock(oldBlock);
  527. }
  528. _index2[i2] = block;
  529. }
  530. int getDataBlock(int c, bool forLSCP)
  531. {
  532. var i2 = getIndex2Block(c, forLSCP);
  533. i2 += (c >> SHIFT_2) & INDEX_2_MASK;
  534. var oldBlock = _index2[i2];
  535. if (isWritableBlock(oldBlock))
  536. {
  537. return oldBlock;
  538. }
  539. // allocate a new data block
  540. var newBlock = allocDataBlock(oldBlock);
  541. setIndex2Entry(i2, newBlock);
  542. return newBlock;
  543. }
  544. void fillBlock(int block, int start, int limit, uint value, uint initialValue, bool overwrite)
  545. {
  546. int i;
  547. if (overwrite)
  548. {
  549. for (i = block + start; i < block + limit; i++)
  550. {
  551. _data[i] = value;
  552. }
  553. }
  554. else
  555. {
  556. for (i = block + start; i < block + limit; i++)
  557. {
  558. if (_data[i] == initialValue)
  559. {
  560. _data[i] = value;
  561. }
  562. }
  563. }
  564. }
  565. void writeBlock(int block, uint value)
  566. {
  567. var limit = block + DATA_BLOCK_LENGTH;
  568. while (block < limit)
  569. {
  570. _data[block++] = value;
  571. }
  572. }
  573. int findHighStart(uint highValue)
  574. {
  575. int prevBlock, prevI2Block;
  576. // set variables for previous range
  577. if (highValue == _initialValue)
  578. {
  579. prevI2Block = _index2NullOffset;
  580. prevBlock = _dataNullOffset;
  581. }
  582. else
  583. {
  584. prevI2Block = -1;
  585. prevBlock = -1;
  586. }
  587. int prev = 0x110000;
  588. // enumerate index-2 blocks
  589. var i1 = INDEX_1_LENGTH;
  590. var c = prev;
  591. while (c > 0)
  592. {
  593. var i2Block = _index1[--i1];
  594. if (i2Block == prevI2Block)
  595. {
  596. // the index-2 block is the same as the previous one, and filled with highValue
  597. c -= CP_PER_INDEX_1_ENTRY;
  598. continue;
  599. }
  600. prevI2Block = i2Block;
  601. if (i2Block == _index2NullOffset)
  602. {
  603. // this is the null index-2 block
  604. if (highValue != _initialValue)
  605. {
  606. return c;
  607. }
  608. c -= CP_PER_INDEX_1_ENTRY;
  609. }
  610. else
  611. {
  612. // enumerate data blocks for one index-2 block
  613. var i2 = INDEX_2_BLOCK_LENGTH;
  614. while (i2 > 0)
  615. {
  616. var block = _index2[i2Block + --i2];
  617. if (block == prevBlock)
  618. {
  619. // the block is the same as the previous one, and filled with highValue
  620. c -= DATA_BLOCK_LENGTH;
  621. continue;
  622. }
  623. prevBlock = block;
  624. if (block == _dataNullOffset)
  625. {
  626. // this is the null data block
  627. if (highValue != _initialValue)
  628. {
  629. return c;
  630. }
  631. c -= DATA_BLOCK_LENGTH;
  632. }
  633. else
  634. {
  635. var j = DATA_BLOCK_LENGTH;
  636. while (j > 0)
  637. {
  638. var value = _data[block + --j];
  639. if (value != highValue)
  640. {
  641. return c;
  642. }
  643. --c;
  644. }
  645. }
  646. }
  647. }
  648. }
  649. // deliver last range
  650. return 0;
  651. }
  652. int findSameDataBlock(int dataLength, int otherBlock, int blockLength)
  653. {
  654. // ensure that we do not even partially get past dataLength
  655. dataLength -= blockLength;
  656. var block = 0;
  657. while (block <= dataLength)
  658. {
  659. if (equal(_data, block, otherBlock, blockLength))
  660. {
  661. return block;
  662. }
  663. block += DATA_GRANULARITY;
  664. }
  665. return -1;
  666. }
  667. int findSameIndex2Block(int index2Length, int otherBlock) {
  668. // ensure that we do not even partially get past index2Length
  669. index2Length -= INDEX_2_BLOCK_LENGTH;
  670. for (var block = 0; block <= index2Length; block++)
  671. {
  672. if (equal(_index2, block, otherBlock, INDEX_2_BLOCK_LENGTH))
  673. {
  674. return block;
  675. }
  676. }
  677. return -1;
  678. }
  679. void compactData()
  680. {
  681. // do not compact linear-ASCII data
  682. var newStart = DATA_START_OFFSET;
  683. var start = 0;
  684. var i = 0;
  685. while (start < newStart)
  686. {
  687. _map[i++] = start;
  688. start += DATA_BLOCK_LENGTH;
  689. }
  690. // Start with a block length of 64 for 2-byte UTF-8,
  691. // then switch to DATA_BLOCK_LENGTH.
  692. var blockLength = 64;
  693. var blockCount = blockLength >> SHIFT_2;
  694. start = newStart;
  695. while (start < _dataLength)
  696. {
  697. // start: index of first entry of current block
  698. // newStart: index where the current block is to be moved
  699. // (right after current end of already-compacted data)
  700. int mapIndex, movedStart;
  701. if (start == DATA_0800_OFFSET)
  702. {
  703. blockLength = DATA_BLOCK_LENGTH;
  704. blockCount = 1;
  705. }
  706. // skip blocks that are not used
  707. if (_map[start >> SHIFT_2] <= 0)
  708. {
  709. // advance start to the next block
  710. start += blockLength;
  711. // leave newStart with the previous block!
  712. continue;
  713. }
  714. // search for an identical block
  715. if ((movedStart = findSameDataBlock(newStart, start, blockLength)) >= 0)
  716. {
  717. // found an identical block, set the other block's index value for the current block
  718. mapIndex = start >> SHIFT_2;
  719. for (i = blockCount; i > 0; i--)
  720. {
  721. _map[mapIndex++] = movedStart;
  722. movedStart += DATA_BLOCK_LENGTH;
  723. }
  724. // advance start to the next block
  725. start += blockLength;
  726. // leave newStart with the previous block!
  727. continue;
  728. }
  729. // see if the beginning of this block can be overlapped with the end of the previous block
  730. // look for maximum overlap (modulo granularity) with the previous, adjacent block
  731. var overlap = blockLength - DATA_GRANULARITY;
  732. while ((overlap > 0) && !equal(_data, (newStart - overlap), start, overlap))
  733. {
  734. overlap -= DATA_GRANULARITY;
  735. }
  736. if ((overlap > 0) || (newStart < start))
  737. {
  738. // some overlap, or just move the whole block
  739. movedStart = newStart - overlap;
  740. mapIndex = start >> SHIFT_2;
  741. for (i = blockCount; i > 0; i--)
  742. {
  743. _map[mapIndex++] = movedStart;
  744. movedStart += DATA_BLOCK_LENGTH;
  745. }
  746. // move the non-overlapping indexes to their new positions
  747. start += overlap;
  748. for (i = blockLength - overlap; i > 0; i--)
  749. {
  750. _data[newStart++] = _data[start++];
  751. }
  752. }
  753. else
  754. { // no overlap && newStart==start
  755. mapIndex = start >> SHIFT_2;
  756. for (i = blockCount; i > 0; i--)
  757. {
  758. _map[mapIndex++] = start;
  759. start += DATA_BLOCK_LENGTH;
  760. }
  761. newStart = start;
  762. }
  763. }
  764. // now adjust the index-2 table
  765. i = 0;
  766. while (i < _index2Length)
  767. {
  768. // Gap indexes are invalid (-1). Skip over the gap.
  769. if (i == INDEX_GAP_OFFSET)
  770. {
  771. i += INDEX_GAP_LENGTH;
  772. }
  773. _index2[i] = _map[_index2[i] >> SHIFT_2];
  774. ++i;
  775. }
  776. _dataNullOffset = _map[_dataNullOffset >> SHIFT_2];
  777. // ensure dataLength alignment
  778. while ((newStart & (DATA_GRANULARITY - 1)) != 0)
  779. {
  780. _data[newStart++] = _initialValue;
  781. }
  782. _dataLength = newStart;
  783. }
  784. void compactIndex2()
  785. {
  786. // do not compact linear-BMP index-2 blocks
  787. var newStart = INDEX_2_BMP_LENGTH;
  788. var start = 0;
  789. var i = 0;
  790. while (start < newStart)
  791. {
  792. _map[i++] = start;
  793. start += INDEX_2_BLOCK_LENGTH;
  794. }
  795. // Reduce the index table gap to what will be needed at runtime.
  796. newStart += UTF8_2B_INDEX_2_LENGTH + ((_highStart - 0x10000) >> SHIFT_1);
  797. start = INDEX_2_NULL_OFFSET;
  798. while (start < _index2Length)
  799. {
  800. // start: index of first entry of current block
  801. // newStart: index where the current block is to be moved
  802. // (right after current end of already-compacted data)
  803. // search for an identical block
  804. int movedStart;
  805. if ((movedStart = findSameIndex2Block(newStart, start)) >= 0)
  806. {
  807. // found an identical block, set the other block's index value for the current block
  808. _map[start >> SHIFT_1_2] = movedStart;
  809. // advance start to the next block
  810. start += INDEX_2_BLOCK_LENGTH;
  811. // leave newStart with the previous block!
  812. continue;
  813. }
  814. // see if the beginning of this block can be overlapped with the end of the previous block
  815. // look for maximum overlap with the previous, adjacent block
  816. var overlap = INDEX_2_BLOCK_LENGTH - 1;
  817. while ((overlap > 0) && !equal(_index2, (newStart - overlap), start, overlap))
  818. {
  819. --overlap;
  820. }
  821. if ((overlap > 0) || (newStart < start))
  822. {
  823. // some overlap, or just move the whole block
  824. _map[start >> SHIFT_1_2] = newStart - overlap;
  825. // move the non-overlapping indexes to their new positions
  826. start += overlap;
  827. for (i = INDEX_2_BLOCK_LENGTH - overlap; i > 0; i--)
  828. {
  829. _index2[newStart++] = _index2[start++];
  830. }
  831. }
  832. else
  833. { // no overlap && newStart==start
  834. _map[start >> SHIFT_1_2] = start;
  835. start += INDEX_2_BLOCK_LENGTH;
  836. newStart = start;
  837. }
  838. }
  839. // now adjust the index-1 table
  840. for (i = 0; i < INDEX_1_LENGTH; i++)
  841. {
  842. _index1[i] = _map[_index1[i] >> SHIFT_1_2];
  843. }
  844. _index2NullOffset = _map[_index2NullOffset >> SHIFT_1_2];
  845. // Ensure data table alignment:
  846. // Needs to be granularity-aligned for 16-bit trie
  847. // (so that dataMove will be down-shiftable),
  848. // and 2-aligned for uint32_t data.
  849. // Arbitrary value: 0x3fffc not possible for real data.
  850. while ((newStart & ((DATA_GRANULARITY - 1) | 1)) != 0)
  851. {
  852. _index2[newStart++] = 0x0000ffff << INDEX_SHIFT;
  853. }
  854. _index2Length = newStart;
  855. }
  856. void compact()
  857. {
  858. // find highStart and round it up
  859. var highValue = Get(0x10ffff);
  860. var highStart = findHighStart(highValue);
  861. highStart = (highStart + (CP_PER_INDEX_1_ENTRY - 1)) & ~(CP_PER_INDEX_1_ENTRY - 1);
  862. if (highStart == 0x110000)
  863. {
  864. highValue = _errorValue;
  865. }
  866. // Set trie->highStart only after utrie2_get32(trie, highStart).
  867. // Otherwise utrie2_get32(trie, highStart) would try to read the highValue.
  868. _highStart = highStart;
  869. if (_highStart < 0x110000)
  870. {
  871. // Blank out [highStart..10ffff] to release associated data blocks.
  872. var suppHighStart = _highStart <= 0x10000 ? 0x10000 : _highStart;
  873. SetRange(suppHighStart, 0x10ffff, _initialValue, true);
  874. }
  875. compactData();
  876. if (_highStart > 0x10000)
  877. {
  878. compactIndex2();
  879. }
  880. // Store the highValue in the data array and round up the dataLength.
  881. // Must be done after compactData() because that assumes that dataLength
  882. // is a multiple of DATA_BLOCK_LENGTH.
  883. _data[_dataLength++] = highValue;
  884. while ((_dataLength & (DATA_GRANULARITY - 1)) != 0)
  885. {
  886. _data[_dataLength++] = _initialValue;
  887. }
  888. _isCompacted = true;
  889. }
  890. public UnicodeTrie Freeze()
  891. {
  892. int allIndexesLength, i;
  893. if (!_isCompacted)
  894. {
  895. compact();
  896. }
  897. if (_highStart <= 0x10000)
  898. {
  899. allIndexesLength = INDEX_1_OFFSET;
  900. }
  901. else
  902. {
  903. allIndexesLength = _index2Length;
  904. }
  905. var dataMove = allIndexesLength;
  906. // are indexLength and dataLength within limits?
  907. if ((allIndexesLength > MAX_INDEX_LENGTH) || // for unshifted indexLength
  908. ((dataMove + _dataNullOffset) > 0xffff) || // for unshifted dataNullOffset
  909. ((dataMove + DATA_0800_OFFSET) > 0xffff) || // for unshifted 2-byte UTF-8 index-2 values
  910. ((dataMove + _dataLength) > MAX_DATA_LENGTH_RUNTIME))
  911. { // for shiftedDataLength
  912. throw new InvalidOperationException("Trie data is too large.");
  913. }
  914. // calculate the sizes of, and allocate, the index and data arrays
  915. var indexLength = allIndexesLength + _dataLength;
  916. var data = new int[indexLength];
  917. // write the index-2 array values shifted right by INDEX_SHIFT, after adding dataMove
  918. var destIdx = 0;
  919. for (i = 0; i < INDEX_2_BMP_LENGTH; i++)
  920. {
  921. data[destIdx++] = ((_index2[i] + dataMove) >> INDEX_SHIFT);
  922. }
  923. // write UTF-8 2-byte index-2 values, not right-shifted
  924. for (i = 0; i < 0xc2 - 0xc0; i++)
  925. { // C0..C1
  926. data[destIdx++] = (dataMove + BAD_UTF8_DATA_OFFSET);
  927. }
  928. for (; i < 0xe0 - 0xc0; i++)
  929. { // C2..DF
  930. data[destIdx++] = (dataMove + _index2[i << (6 - SHIFT_2)]);
  931. }
  932. if (_highStart > 0x10000)
  933. {
  934. var index1Length = (_highStart - 0x10000) >> SHIFT_1;
  935. var index2Offset = INDEX_2_BMP_LENGTH + UTF8_2B_INDEX_2_LENGTH + index1Length;
  936. // write 16-bit index-1 values for supplementary code points
  937. for (i = 0; i < index1Length; i++)
  938. {
  939. data[destIdx++] = (INDEX_2_OFFSET + _index1[i + OMITTED_BMP_INDEX_1_LENGTH]);
  940. }
  941. // write the index-2 array values for supplementary code points,
  942. // shifted right by INDEX_SHIFT, after adding dataMove
  943. for (i = 0; i < _index2Length - index2Offset; i++)
  944. {
  945. data[destIdx++] = ((dataMove + _index2[index2Offset + i]) >> INDEX_SHIFT);
  946. }
  947. }
  948. // write 16-bit data values
  949. for (i = 0; i < _dataLength; i++)
  950. {
  951. data[destIdx++] = (int)_data[i];
  952. }
  953. return new UnicodeTrie(data, _highStart, _errorValue);
  954. }
  955. }
  956. }