PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/ZipPla/iTextSharp/iTextSharp/text/pdf/hyphenation/TernaryTree.cs

https://bitbucket.org/udaken/zippla-mirror
C# | 631 lines | 387 code | 75 blank | 169 comment | 89 complexity | 680d22f2ccfc5cffed063cfeb9a429a2 MD5 | raw file
  1. using System;
  2. using System.Collections;
  3. using System.Text;
  4. /*
  5. * $Id$
  6. * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
  7. * For details on use and redistribution please refer to the
  8. * LICENSE file included with these sources.
  9. */
  10. namespace iTextSharp.text.pdf.hyphenation {
  11. /**
  12. * <h2>Ternary Search Tree</h2>
  13. *
  14. * <p>A ternary search tree is a hibrid between a binary tree and
  15. * a digital search tree (trie). Keys are limited to strings.
  16. * A data value of type char is stored in each leaf node.
  17. * It can be used as an index (or pointer) to the data.
  18. * Branches that only contain one key are compressed to one node
  19. * by storing a pointer to the trailer substring of the key.
  20. * This class is intended to serve as base class or helper class
  21. * to implement Dictionary collections or the like. Ternary trees
  22. * have some nice properties as the following: the tree can be
  23. * traversed in sorted order, partial matches (wildcard) can be
  24. * implemented, retrieval of all keys within a given distance
  25. * from the target, etc. The storage requirements are higher than
  26. * a binary tree but a lot less than a trie. Performance is
  27. * comparable with a hash table, sometimes it outperforms a hash
  28. * function (most of the time can determine a miss faster than a hash).</p>
  29. *
  30. * <p>The main purpose of this java port is to serve as a base for
  31. * implementing TeX's hyphenation algorithm (see The TeXBook,
  32. * appendix H). Each language requires from 5000 to 15000 hyphenation
  33. * patterns which will be keys in this tree. The strings patterns
  34. * are usually small (from 2 to 5 characters), but each char in the
  35. * tree is stored in a node. Thus memory usage is the main concern.
  36. * We will sacrify 'elegance' to keep memory requirenments to the
  37. * minimum. Using java's char type as pointer (yes, I know pointer
  38. * it is a forbidden word in java) we can keep the size of the node
  39. * to be just 8 bytes (3 pointers and the data char). This gives
  40. * room for about 65000 nodes. In my tests the english patterns
  41. * took 7694 nodes and the german patterns 10055 nodes,
  42. * so I think we are safe.</p>
  43. *
  44. * <p>All said, this is a map with strings as keys and char as value.
  45. * Pretty limited!. It can be extended to a general map by
  46. * using the string representation of an object and using the
  47. * char value as an index to an array that contains the object
  48. * values.</p>
  49. *
  50. * @author cav@uniscope.co.jp
  51. */
  52. public class TernaryTree : ICloneable {
  53. /**
  54. * We use 4 arrays to represent a node. I guess I should have created
  55. * a proper node class, but somehow Knuth's pascal code made me forget
  56. * we now have a portable language with memory management and
  57. * automatic garbage collection! And now is kind of late, furthermore,
  58. * if it ain't broken, don't fix it.
  59. */
  60. /**
  61. * Pointer to low branch and to rest of the key when it is
  62. * stored directly in this node, we don't have unions in java!
  63. */
  64. protected char[] lo;
  65. /**
  66. * Pointer to high branch.
  67. */
  68. protected char[] hi;
  69. /**
  70. * Pointer to equal branch and to data when this node is a string terminator.
  71. */
  72. protected char[] eq;
  73. /**
  74. * <P>The character stored in this node: splitchar
  75. * Two special values are reserved:</P>
  76. * <ul><li>0x0000 as string terminator</li>
  77. * <li>0xFFFF to indicate that the branch starting at
  78. * this node is compressed</li></ul>
  79. * <p>This shouldn't be a problem if we give the usual semantics to
  80. * strings since 0xFFFF is garanteed not to be an Unicode character.</p>
  81. */
  82. protected char[] sc;
  83. /**
  84. * This vector holds the trailing of the keys when the branch is compressed.
  85. */
  86. protected CharVector kv;
  87. protected char root;
  88. protected char freenode;
  89. protected int length; // number of items in tree
  90. protected static int BLOCK_SIZE = 2048; // allocation size for arrays
  91. internal TernaryTree() {
  92. Init();
  93. }
  94. virtual protected void Init() {
  95. root = (char)0;
  96. freenode = (char)1;
  97. length = 0;
  98. lo = new char[BLOCK_SIZE];
  99. hi = new char[BLOCK_SIZE];
  100. eq = new char[BLOCK_SIZE];
  101. sc = new char[BLOCK_SIZE];
  102. kv = new CharVector();
  103. }
  104. /**
  105. * Branches are initially compressed, needing
  106. * one node per key plus the size of the string
  107. * key. They are decompressed as needed when
  108. * another key with same prefix
  109. * is inserted. This saves a lot of space,
  110. * specially for long keys.
  111. */
  112. virtual public void Insert(string key, char val) {
  113. // make sure we have enough room in the arrays
  114. int len = key.Length
  115. + 1; // maximum number of nodes that may be generated
  116. if (freenode + len > eq.Length)
  117. RedimNodeArrays(eq.Length + BLOCK_SIZE);
  118. char[] strkey = new char[len--];
  119. key.CopyTo(0, strkey, 0, len);
  120. strkey[len] = (char)0;
  121. root = Insert(root, strkey, 0, val);
  122. }
  123. virtual public void Insert(char[] key, int start, char val) {
  124. int len = Strlen(key) + 1;
  125. if (freenode + len > eq.Length)
  126. RedimNodeArrays(eq.Length + BLOCK_SIZE);
  127. root = Insert(root, key, start, val);
  128. }
  129. /**
  130. * The actual insertion function, recursive version.
  131. */
  132. private char Insert(char p, char[] key, int start, char val) {
  133. int len = Strlen(key, start);
  134. if (p == 0) {
  135. // this means there is no branch, this node will start a new branch.
  136. // Instead of doing that, we store the key somewhere else and create
  137. // only one node with a pointer to the key
  138. p = freenode++;
  139. eq[p] = val; // holds data
  140. length++;
  141. hi[p] = (char)0;
  142. if (len > 0) {
  143. sc[p] = (char)0xFFFF; // indicates branch is compressed
  144. lo[p] = (char)kv.Alloc(len
  145. + 1); // use 'lo' to hold pointer to key
  146. Strcpy(kv.Arr, lo[p], key, start);
  147. } else {
  148. sc[p] = (char)0;
  149. lo[p] = (char)0;
  150. }
  151. return p;
  152. }
  153. if (sc[p] == 0xFFFF) {
  154. // branch is compressed: need to decompress
  155. // this will generate garbage in the external key array
  156. // but we can do some garbage collection later
  157. char pp = freenode++;
  158. lo[pp] = lo[p]; // previous pointer to key
  159. eq[pp] = eq[p]; // previous pointer to data
  160. lo[p] = (char)0;
  161. if (len > 0) {
  162. sc[p] = kv[lo[pp]];
  163. eq[p] = pp;
  164. lo[pp]++;
  165. if (kv[lo[pp]] == 0) {
  166. // key completly decompressed leaving garbage in key array
  167. lo[pp] = (char)0;
  168. sc[pp] = (char)0;
  169. hi[pp] = (char)0;
  170. } else
  171. sc[pp] =
  172. (char)0xFFFF; // we only got first char of key, rest is still there
  173. } else {
  174. // In this case we can save a node by swapping the new node
  175. // with the compressed node
  176. sc[pp] = (char)0xFFFF;
  177. hi[p] = pp;
  178. sc[p] = (char)0;
  179. eq[p] = val;
  180. length++;
  181. return p;
  182. }
  183. }
  184. char s = key[start];
  185. if (s < sc[p])
  186. lo[p] = Insert(lo[p], key, start, val);
  187. else if (s == sc[p]) {
  188. if (s != 0)
  189. eq[p] = Insert(eq[p], key, start + 1, val);
  190. else {
  191. // key already in tree, overwrite data
  192. eq[p] = val;
  193. }
  194. } else
  195. hi[p] = Insert(hi[p], key, start, val);
  196. return p;
  197. }
  198. /**
  199. * Compares 2 null terminated char arrays
  200. */
  201. public static int Strcmp(char[] a, int startA, char[] b, int startB) {
  202. for (; a[startA] == b[startB]; startA++, startB++)
  203. if (a[startA] == 0)
  204. return 0;
  205. return a[startA] - b[startB];
  206. }
  207. /**
  208. * Compares a string with null terminated char array
  209. */
  210. public static int Strcmp(string str, char[] a, int start) {
  211. int i, d, len = str.Length;
  212. for (i = 0; i < len; i++) {
  213. d = (int)str[i] - a[start + i];
  214. if (d != 0)
  215. return d;
  216. if (a[start + i] == 0)
  217. return d;
  218. }
  219. if (a[start + i] != 0)
  220. return (int)-a[start + i];
  221. return 0;
  222. }
  223. public static void Strcpy(char[] dst, int di, char[] src, int si) {
  224. while (src[si] != 0)
  225. dst[di++] = src[si++];
  226. dst[di] = (char)0;
  227. }
  228. public static int Strlen(char[] a, int start) {
  229. int len = 0;
  230. for (int i = start; i < a.Length && a[i] != 0; i++)
  231. len++;
  232. return len;
  233. }
  234. public static int Strlen(char[] a) {
  235. return Strlen(a, 0);
  236. }
  237. virtual public int Find(string key) {
  238. int len = key.Length;
  239. char[] strkey = new char[len + 1];
  240. key.CopyTo(0, strkey, 0, len);
  241. strkey[len] = (char)0;
  242. return Find(strkey, 0);
  243. }
  244. virtual public int Find(char[] key, int start) {
  245. int d;
  246. char p = root;
  247. int i = start;
  248. char c;
  249. while (p != 0) {
  250. if (sc[p] == 0xFFFF) {
  251. if (Strcmp(key, i, kv.Arr, lo[p]) == 0)
  252. return eq[p];
  253. else
  254. return -1;
  255. }
  256. c = key[i];
  257. d = c - sc[p];
  258. if (d == 0) {
  259. if (c == 0)
  260. return eq[p];
  261. i++;
  262. p = eq[p];
  263. } else if (d < 0)
  264. p = lo[p];
  265. else
  266. p = hi[p];
  267. }
  268. return -1;
  269. }
  270. virtual public bool Knows(string key) {
  271. return (Find(key) >= 0);
  272. }
  273. // redimension the arrays
  274. private void RedimNodeArrays(int newsize) {
  275. int len = newsize < lo.Length ? newsize : lo.Length;
  276. char[] na = new char[newsize];
  277. Array.Copy(lo, 0, na, 0, len);
  278. lo = na;
  279. na = new char[newsize];
  280. Array.Copy(hi, 0, na, 0, len);
  281. hi = na;
  282. na = new char[newsize];
  283. Array.Copy(eq, 0, na, 0, len);
  284. eq = na;
  285. na = new char[newsize];
  286. Array.Copy(sc, 0, na, 0, len);
  287. sc = na;
  288. }
  289. virtual public int Size {
  290. get {
  291. return length;
  292. }
  293. }
  294. virtual public Object Clone() {
  295. TernaryTree t = new TernaryTree();
  296. t.lo = (char[])this.lo.Clone();
  297. t.hi = (char[])this.hi.Clone();
  298. t.eq = (char[])this.eq.Clone();
  299. t.sc = (char[])this.sc.Clone();
  300. t.kv = (CharVector)this.kv.Clone();
  301. t.root = this.root;
  302. t.freenode = this.freenode;
  303. t.length = this.length;
  304. return t;
  305. }
  306. /**
  307. * Recursively insert the median first and then the median of the
  308. * lower and upper halves, and so on in order to get a balanced
  309. * tree. The array of keys is assumed to be sorted in ascending
  310. * order.
  311. */
  312. virtual protected void InsertBalanced(string[] k, char[] v, int offset, int n) {
  313. int m;
  314. if (n < 1)
  315. return;
  316. m = n >> 1;
  317. Insert(k[m + offset], v[m + offset]);
  318. InsertBalanced(k, v, offset, m);
  319. InsertBalanced(k, v, offset + m + 1, n - m - 1);
  320. }
  321. /**
  322. * Balance the tree for best search performance
  323. */
  324. virtual public void Balance() {
  325. // System.out.Print("Before root splitchar = "); System.out.Println(sc[root]);
  326. int i = 0, n = length;
  327. string[] k = new string[n];
  328. char[] v = new char[n];
  329. Iterator iter = new Iterator(this);
  330. while (iter.HasMoreElements()) {
  331. v[i] = iter.Value;
  332. k[i++] = (string)iter.NextElement();
  333. }
  334. Init();
  335. InsertBalanced(k, v, 0, n);
  336. // With uniform letter distribution sc[root] should be around 'm'
  337. // System.out.Print("After root splitchar = "); System.out.Println(sc[root]);
  338. }
  339. /**
  340. * Each node stores a character (splitchar) which is part of
  341. * some Key(s). In a compressed branch (one that only contain
  342. * a single string key) the trailer of the key which is not
  343. * already in nodes is stored externally in the kv array.
  344. * As items are inserted, key substrings decrease.
  345. * Some substrings may completely disappear when the whole
  346. * branch is totally decompressed.
  347. * The tree is traversed to find the key substrings actually
  348. * used. In addition, duplicate substrings are removed using
  349. * a map (implemented with a TernaryTree!).
  350. *
  351. */
  352. virtual public void TrimToSize() {
  353. // first balance the tree for best performance
  354. Balance();
  355. // redimension the node arrays
  356. RedimNodeArrays(freenode);
  357. // ok, compact kv array
  358. CharVector kx = new CharVector();
  359. kx.Alloc(1);
  360. TernaryTree map = new TernaryTree();
  361. Compact(kx, map, root);
  362. kv = kx;
  363. kv.TrimToSize();
  364. }
  365. private void Compact(CharVector kx, TernaryTree map, char p) {
  366. int k;
  367. if (p == 0)
  368. return;
  369. if (sc[p] == 0xFFFF) {
  370. k = map.Find(kv.Arr, lo[p]);
  371. if (k < 0) {
  372. k = kx.Alloc(Strlen(kv.Arr, lo[p]) + 1);
  373. Strcpy(kx.Arr, k, kv.Arr, lo[p]);
  374. map.Insert(kx.Arr, k, (char)k);
  375. }
  376. lo[p] = (char)k;
  377. } else {
  378. Compact(kx, map, lo[p]);
  379. if (sc[p] != 0)
  380. Compact(kx, map, eq[p]);
  381. Compact(kx, map, hi[p]);
  382. }
  383. }
  384. virtual public Iterator Keys {
  385. get {
  386. return new Iterator(this);
  387. }
  388. }
  389. public class Iterator {
  390. /**
  391. * current node index
  392. */
  393. int cur;
  394. /**
  395. * current key
  396. */
  397. string curkey;
  398. /**
  399. * TernaryTree parent
  400. */
  401. TernaryTree parent;
  402. private class Item : ICloneable {
  403. internal char parent;
  404. internal char child;
  405. public Item() {
  406. parent = (char)0;
  407. child = (char)0;
  408. }
  409. public Item(char p, char c) {
  410. parent = p;
  411. child = c;
  412. }
  413. virtual public Object Clone() {
  414. return new Item(parent, child);
  415. }
  416. }
  417. /**
  418. * Node stack
  419. */
  420. Stack ns;
  421. /**
  422. * key stack implemented with a StringBuilder
  423. */
  424. StringBuilder ks;
  425. public Iterator(TernaryTree parent) {
  426. this.parent = parent;
  427. cur = -1;
  428. ns = new Stack();
  429. ks = new StringBuilder();
  430. Rewind();
  431. }
  432. virtual public void Rewind() {
  433. ns.Clear();
  434. ks.Length = 0;
  435. cur = parent.root;
  436. Run();
  437. }
  438. virtual public Object NextElement() {
  439. string res = curkey;
  440. cur = Up();
  441. Run();
  442. return res;
  443. }
  444. virtual public char Value {
  445. get {
  446. if (cur >= 0)
  447. return this.parent.eq[cur];
  448. return (char)0;
  449. }
  450. }
  451. virtual public bool HasMoreElements() {
  452. return (cur != -1);
  453. }
  454. /**
  455. * traverse upwards
  456. */
  457. private int Up() {
  458. Item i = new Item();
  459. int res = 0;
  460. if (ns.Count == 0)
  461. return -1;
  462. if (cur != 0 && parent.sc[cur] == 0)
  463. return parent.lo[cur];
  464. bool climb = true;
  465. while (climb) {
  466. i = (Item)ns.Pop();
  467. i.child++;
  468. switch (i.child) {
  469. case (char)1:
  470. if (parent.sc[i.parent] != 0) {
  471. res = parent.eq[i.parent];
  472. ns.Push(i.Clone());
  473. ks.Append(parent.sc[i.parent]);
  474. } else {
  475. i.child++;
  476. ns.Push(i.Clone());
  477. res = parent.hi[i.parent];
  478. }
  479. climb = false;
  480. break;
  481. case (char)2:
  482. res = parent.hi[i.parent];
  483. ns.Push(i.Clone());
  484. if (ks.Length > 0)
  485. ks.Length = ks.Length - 1; // pop
  486. climb = false;
  487. break;
  488. default:
  489. if (ns.Count == 0)
  490. return -1;
  491. climb = true;
  492. break;
  493. }
  494. }
  495. return res;
  496. }
  497. /**
  498. * traverse the tree to find next key
  499. */
  500. private int Run() {
  501. if (cur == -1)
  502. return -1;
  503. bool leaf = false;
  504. for (; ; ) {
  505. // first go down on low branch until leaf or compressed branch
  506. while (cur != 0) {
  507. if (parent.sc[cur] == 0xFFFF) {
  508. leaf = true;
  509. break;
  510. }
  511. ns.Push(new Item((char)cur, '\u0000'));
  512. if (parent.sc[cur] == 0) {
  513. leaf = true;
  514. break;
  515. }
  516. cur = parent.lo[cur];
  517. }
  518. if (leaf)
  519. break;
  520. // nothing found, go up one node and try again
  521. cur = Up();
  522. if (cur == -1) {
  523. return -1;
  524. }
  525. }
  526. // The current node should be a data node and
  527. // the key should be in the key stack (at least partially)
  528. StringBuilder buf = new StringBuilder(ks.ToString());
  529. if (parent.sc[cur] == 0xFFFF) {
  530. int p = parent.lo[cur];
  531. while (parent.kv[p] != 0)
  532. buf.Append(parent.kv[p++]);
  533. }
  534. curkey = buf.ToString();
  535. return 0;
  536. }
  537. }
  538. public virtual void PrintStats() {
  539. Console.Error.WriteLine("Number of keys = " + length.ToString());
  540. Console.Error.WriteLine("Node count = " + freenode.ToString());
  541. // Console.Error.WriteLine("Array length = " + int.ToString(eq.Length));
  542. Console.Error.WriteLine("Key Array length = "
  543. + kv.Length.ToString());
  544. /*
  545. * for (int i=0; i<kv.Length; i++)
  546. * if ( kv[i] != 0 )
  547. * System.out.Print(kv[i]);
  548. * else
  549. * System.out.Println("");
  550. * System.out.Println("Keys:");
  551. * for (Enumeration enum = Keys(); enum.HasMoreElements(); )
  552. * System.out.Println(enum.NextElement());
  553. */
  554. }
  555. }
  556. }