tree234.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. /*
  2. * tree234.c: reasonably generic counted 2-3-4 tree routines.
  3. *
  4. * This file is copyright 1999-2001 Simon Tatham.
  5. *
  6. * Permission is hereby granted, free of charge, to any person
  7. * obtaining a copy of this software and associated documentation
  8. * files (the "Software"), to deal in the Software without
  9. * restriction, including without limitation the rights to use,
  10. * copy, modify, merge, publish, distribute, sublicense, and/or
  11. * sell copies of the Software, and to permit persons to whom the
  12. * Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be
  16. * included in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  20. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. * NONINFRINGEMENT. IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
  22. * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  23. * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  24. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. * SOFTWARE.
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <assert.h>
  30. #include "tree234.h"
  31. #ifdef TEST
  32. #define LOG(x) (printf x)
  33. #define snew(type) ((type *)malloc(sizeof(type)))
  34. #define snewn(n, type) ((type *)malloc((n) * sizeof(type)))
  35. #define sresize(ptr, n, type) \
  36. ((type *)realloc(sizeof((type *)0 == (ptr)) ? (ptr) : (ptr), \
  37. (n) * sizeof(type)))
  38. #define sfree(ptr) free(ptr)
  39. #else
  40. #include "puttymem.h"
  41. #define LOG(x)
  42. #endif
  43. typedef struct node234_Tag node234;
  44. struct tree234_Tag {
  45. node234 *root;
  46. cmpfn234 cmp;
  47. };
  48. struct node234_Tag {
  49. node234 *parent;
  50. node234 *kids[4];
  51. int counts[4];
  52. void *elems[3];
  53. };
  54. /*
  55. * Create a 2-3-4 tree.
  56. */
  57. tree234 *newtree234(cmpfn234 cmp)
  58. {
  59. tree234 *ret = snew(tree234);
  60. LOG(("created tree %p\n", ret));
  61. ret->root = NULL;
  62. ret->cmp = cmp;
  63. return ret;
  64. }
  65. /*
  66. * Free a 2-3-4 tree (not including freeing the elements).
  67. */
  68. static void freenode234(node234 * n)
  69. {
  70. if (!n)
  71. return;
  72. freenode234(n->kids[0]);
  73. freenode234(n->kids[1]);
  74. freenode234(n->kids[2]);
  75. freenode234(n->kids[3]);
  76. sfree(n);
  77. }
  78. void freetree234(tree234 * t)
  79. {
  80. freenode234(t->root);
  81. sfree(t);
  82. }
  83. /*
  84. * Internal function to count a node.
  85. */
  86. static int countnode234(node234 * n)
  87. {
  88. int count = 0;
  89. int i;
  90. if (!n)
  91. return 0;
  92. for (i = 0; i < 4; i++)
  93. count += n->counts[i];
  94. for (i = 0; i < 3; i++)
  95. if (n->elems[i])
  96. count++;
  97. return count;
  98. }
  99. /*
  100. * Count the elements in a tree.
  101. */
  102. int count234(tree234 * t)
  103. {
  104. if (t->root)
  105. return countnode234(t->root);
  106. else
  107. return 0;
  108. }
  109. /*
  110. * Add an element e to a 2-3-4 tree t. Returns e on success, or if
  111. * an existing element compares equal, returns that.
  112. */
  113. static void *add234_internal(tree234 * t, void *e, int index)
  114. {
  115. node234 *n, **np, *left, *right;
  116. void *orig_e = e;
  117. int c, lcount, rcount;
  118. LOG(("adding node %p to tree %p\n", e, t));
  119. if (t->root == NULL) {
  120. t->root = snew(node234);
  121. t->root->elems[1] = t->root->elems[2] = NULL;
  122. t->root->kids[0] = t->root->kids[1] = NULL;
  123. t->root->kids[2] = t->root->kids[3] = NULL;
  124. t->root->counts[0] = t->root->counts[1] = 0;
  125. t->root->counts[2] = t->root->counts[3] = 0;
  126. t->root->parent = NULL;
  127. t->root->elems[0] = e;
  128. LOG((" created root %p\n", t->root));
  129. return orig_e;
  130. }
  131. n = NULL; /* placate gcc; will always be set below since t->root != NULL */
  132. np = &t->root;
  133. while (*np) {
  134. int childnum;
  135. n = *np;
  136. LOG((" node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d\n",
  137. n,
  138. n->kids[0], n->counts[0], n->elems[0],
  139. n->kids[1], n->counts[1], n->elems[1],
  140. n->kids[2], n->counts[2], n->elems[2],
  141. n->kids[3], n->counts[3]));
  142. if (index >= 0) {
  143. if (!n->kids[0]) {
  144. /*
  145. * Leaf node. We want to insert at kid position
  146. * equal to the index:
  147. *
  148. * 0 A 1 B 2 C 3
  149. */
  150. childnum = index;
  151. } else {
  152. /*
  153. * Internal node. We always descend through it (add
  154. * always starts at the bottom, never in the
  155. * middle).
  156. */
  157. do { /* this is a do ... while (0) to allow `break' */
  158. if (index <= n->counts[0]) {
  159. childnum = 0;
  160. break;
  161. }
  162. index -= n->counts[0] + 1;
  163. if (index <= n->counts[1]) {
  164. childnum = 1;
  165. break;
  166. }
  167. index -= n->counts[1] + 1;
  168. if (index <= n->counts[2]) {
  169. childnum = 2;
  170. break;
  171. }
  172. index -= n->counts[2] + 1;
  173. if (index <= n->counts[3]) {
  174. childnum = 3;
  175. break;
  176. }
  177. return NULL; /* error: index out of range */
  178. } while (0);
  179. }
  180. } else {
  181. if ((c = t->cmp(e, n->elems[0])) < 0)
  182. childnum = 0;
  183. else if (c == 0)
  184. return n->elems[0]; /* already exists */
  185. else if (n->elems[1] == NULL
  186. || (c = t->cmp(e, n->elems[1])) < 0) childnum = 1;
  187. else if (c == 0)
  188. return n->elems[1]; /* already exists */
  189. else if (n->elems[2] == NULL
  190. || (c = t->cmp(e, n->elems[2])) < 0) childnum = 2;
  191. else if (c == 0)
  192. return n->elems[2]; /* already exists */
  193. else
  194. childnum = 3;
  195. }
  196. np = &n->kids[childnum];
  197. LOG((" moving to child %d (%p)\n", childnum, *np));
  198. }
  199. /*
  200. * We need to insert the new element in n at position np.
  201. */
  202. left = NULL;
  203. lcount = 0;
  204. right = NULL;
  205. rcount = 0;
  206. while (n) {
  207. LOG((" at %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d\n",
  208. n,
  209. n->kids[0], n->counts[0], n->elems[0],
  210. n->kids[1], n->counts[1], n->elems[1],
  211. n->kids[2], n->counts[2], n->elems[2],
  212. n->kids[3], n->counts[3]));
  213. LOG((" need to insert %p/%d [%p] %p/%d at position %d\n",
  214. left, lcount, e, right, rcount, (int)(np - n->kids)));
  215. if (n->elems[1] == NULL) {
  216. /*
  217. * Insert in a 2-node; simple.
  218. */
  219. if (np == &n->kids[0]) {
  220. LOG((" inserting on left of 2-node\n"));
  221. n->kids[2] = n->kids[1];
  222. n->counts[2] = n->counts[1];
  223. n->elems[1] = n->elems[0];
  224. n->kids[1] = right;
  225. n->counts[1] = rcount;
  226. n->elems[0] = e;
  227. n->kids[0] = left;
  228. n->counts[0] = lcount;
  229. } else { /* np == &n->kids[1] */
  230. LOG((" inserting on right of 2-node\n"));
  231. n->kids[2] = right;
  232. n->counts[2] = rcount;
  233. n->elems[1] = e;
  234. n->kids[1] = left;
  235. n->counts[1] = lcount;
  236. }
  237. if (n->kids[0])
  238. n->kids[0]->parent = n;
  239. if (n->kids[1])
  240. n->kids[1]->parent = n;
  241. if (n->kids[2])
  242. n->kids[2]->parent = n;
  243. LOG((" done\n"));
  244. break;
  245. } else if (n->elems[2] == NULL) {
  246. /*
  247. * Insert in a 3-node; simple.
  248. */
  249. if (np == &n->kids[0]) {
  250. LOG((" inserting on left of 3-node\n"));
  251. n->kids[3] = n->kids[2];
  252. n->counts[3] = n->counts[2];
  253. n->elems[2] = n->elems[1];
  254. n->kids[2] = n->kids[1];
  255. n->counts[2] = n->counts[1];
  256. n->elems[1] = n->elems[0];
  257. n->kids[1] = right;
  258. n->counts[1] = rcount;
  259. n->elems[0] = e;
  260. n->kids[0] = left;
  261. n->counts[0] = lcount;
  262. } else if (np == &n->kids[1]) {
  263. LOG((" inserting in middle of 3-node\n"));
  264. n->kids[3] = n->kids[2];
  265. n->counts[3] = n->counts[2];
  266. n->elems[2] = n->elems[1];
  267. n->kids[2] = right;
  268. n->counts[2] = rcount;
  269. n->elems[1] = e;
  270. n->kids[1] = left;
  271. n->counts[1] = lcount;
  272. } else { /* np == &n->kids[2] */
  273. LOG((" inserting on right of 3-node\n"));
  274. n->kids[3] = right;
  275. n->counts[3] = rcount;
  276. n->elems[2] = e;
  277. n->kids[2] = left;
  278. n->counts[2] = lcount;
  279. }
  280. if (n->kids[0])
  281. n->kids[0]->parent = n;
  282. if (n->kids[1])
  283. n->kids[1]->parent = n;
  284. if (n->kids[2])
  285. n->kids[2]->parent = n;
  286. if (n->kids[3])
  287. n->kids[3]->parent = n;
  288. LOG((" done\n"));
  289. break;
  290. } else {
  291. node234 *m = snew(node234);
  292. m->parent = n->parent;
  293. LOG((" splitting a 4-node; created new node %p\n", m));
  294. /*
  295. * Insert in a 4-node; split into a 2-node and a
  296. * 3-node, and move focus up a level.
  297. *
  298. * I don't think it matters which way round we put the
  299. * 2 and the 3. For simplicity, we'll put the 3 first
  300. * always.
  301. */
  302. if (np == &n->kids[0]) {
  303. m->kids[0] = left;
  304. m->counts[0] = lcount;
  305. m->elems[0] = e;
  306. m->kids[1] = right;
  307. m->counts[1] = rcount;
  308. m->elems[1] = n->elems[0];
  309. m->kids[2] = n->kids[1];
  310. m->counts[2] = n->counts[1];
  311. e = n->elems[1];
  312. n->kids[0] = n->kids[2];
  313. n->counts[0] = n->counts[2];
  314. n->elems[0] = n->elems[2];
  315. n->kids[1] = n->kids[3];
  316. n->counts[1] = n->counts[3];
  317. } else if (np == &n->kids[1]) {
  318. m->kids[0] = n->kids[0];
  319. m->counts[0] = n->counts[0];
  320. m->elems[0] = n->elems[0];
  321. m->kids[1] = left;
  322. m->counts[1] = lcount;
  323. m->elems[1] = e;
  324. m->kids[2] = right;
  325. m->counts[2] = rcount;
  326. e = n->elems[1];
  327. n->kids[0] = n->kids[2];
  328. n->counts[0] = n->counts[2];
  329. n->elems[0] = n->elems[2];
  330. n->kids[1] = n->kids[3];
  331. n->counts[1] = n->counts[3];
  332. } else if (np == &n->kids[2]) {
  333. m->kids[0] = n->kids[0];
  334. m->counts[0] = n->counts[0];
  335. m->elems[0] = n->elems[0];
  336. m->kids[1] = n->kids[1];
  337. m->counts[1] = n->counts[1];
  338. m->elems[1] = n->elems[1];
  339. m->kids[2] = left;
  340. m->counts[2] = lcount;
  341. /* e = e; */
  342. n->kids[0] = right;
  343. n->counts[0] = rcount;
  344. n->elems[0] = n->elems[2];
  345. n->kids[1] = n->kids[3];
  346. n->counts[1] = n->counts[3];
  347. } else { /* np == &n->kids[3] */
  348. m->kids[0] = n->kids[0];
  349. m->counts[0] = n->counts[0];
  350. m->elems[0] = n->elems[0];
  351. m->kids[1] = n->kids[1];
  352. m->counts[1] = n->counts[1];
  353. m->elems[1] = n->elems[1];
  354. m->kids[2] = n->kids[2];
  355. m->counts[2] = n->counts[2];
  356. n->kids[0] = left;
  357. n->counts[0] = lcount;
  358. n->elems[0] = e;
  359. n->kids[1] = right;
  360. n->counts[1] = rcount;
  361. e = n->elems[2];
  362. }
  363. m->kids[3] = n->kids[3] = n->kids[2] = NULL;
  364. m->counts[3] = n->counts[3] = n->counts[2] = 0;
  365. m->elems[2] = n->elems[2] = n->elems[1] = NULL;
  366. if (m->kids[0])
  367. m->kids[0]->parent = m;
  368. if (m->kids[1])
  369. m->kids[1]->parent = m;
  370. if (m->kids[2])
  371. m->kids[2]->parent = m;
  372. if (n->kids[0])
  373. n->kids[0]->parent = n;
  374. if (n->kids[1])
  375. n->kids[1]->parent = n;
  376. LOG((" left (%p): %p/%d [%p] %p/%d [%p] %p/%d\n", m,
  377. m->kids[0], m->counts[0], m->elems[0],
  378. m->kids[1], m->counts[1], m->elems[1],
  379. m->kids[2], m->counts[2]));
  380. LOG((" right (%p): %p/%d [%p] %p/%d\n", n,
  381. n->kids[0], n->counts[0], n->elems[0],
  382. n->kids[1], n->counts[1]));
  383. left = m;
  384. lcount = countnode234(left);
  385. right = n;
  386. rcount = countnode234(right);
  387. }
  388. if (n->parent)
  389. np = (n->parent->kids[0] == n ? &n->parent->kids[0] :
  390. n->parent->kids[1] == n ? &n->parent->kids[1] :
  391. n->parent->kids[2] == n ? &n->parent->kids[2] :
  392. &n->parent->kids[3]);
  393. n = n->parent;
  394. }
  395. /*
  396. * If we've come out of here by `break', n will still be
  397. * non-NULL and all we need to do is go back up the tree
  398. * updating counts. If we've come here because n is NULL, we
  399. * need to create a new root for the tree because the old one
  400. * has just split into two. */
  401. if (n) {
  402. while (n->parent) {
  403. int count = countnode234(n);
  404. int childnum;
  405. childnum = (n->parent->kids[0] == n ? 0 :
  406. n->parent->kids[1] == n ? 1 :
  407. n->parent->kids[2] == n ? 2 : 3);
  408. n->parent->counts[childnum] = count;
  409. n = n->parent;
  410. }
  411. } else {
  412. LOG((" root is overloaded, split into two\n"));
  413. t->root = snew(node234);
  414. t->root->kids[0] = left;
  415. t->root->counts[0] = lcount;
  416. t->root->elems[0] = e;
  417. t->root->kids[1] = right;
  418. t->root->counts[1] = rcount;
  419. t->root->elems[1] = NULL;
  420. t->root->kids[2] = NULL;
  421. t->root->counts[2] = 0;
  422. t->root->elems[2] = NULL;
  423. t->root->kids[3] = NULL;
  424. t->root->counts[3] = 0;
  425. t->root->parent = NULL;
  426. if (t->root->kids[0])
  427. t->root->kids[0]->parent = t->root;
  428. if (t->root->kids[1])
  429. t->root->kids[1]->parent = t->root;
  430. LOG((" new root is %p/%d [%p] %p/%d\n",
  431. t->root->kids[0], t->root->counts[0],
  432. t->root->elems[0], t->root->kids[1], t->root->counts[1]));
  433. }
  434. return orig_e;
  435. }
  436. void *add234(tree234 * t, void *e)
  437. {
  438. if (!t->cmp) /* tree is unsorted */
  439. return NULL;
  440. return add234_internal(t, e, -1);
  441. }
  442. void *addpos234(tree234 * t, void *e, int index)
  443. {
  444. if (index < 0 || /* index out of range */
  445. t->cmp) /* tree is sorted */
  446. return NULL; /* return failure */
  447. return add234_internal(t, e, index); /* this checks the upper bound */
  448. }
  449. /*
  450. * Look up the element at a given numeric index in a 2-3-4 tree.
  451. * Returns NULL if the index is out of range.
  452. */
  453. void *index234(tree234 * t, int index)
  454. {
  455. node234 *n;
  456. if (!t->root)
  457. return NULL; /* tree is empty */
  458. if (index < 0 || index >= countnode234(t->root))
  459. return NULL; /* out of range */
  460. n = t->root;
  461. while (n) {
  462. if (index < n->counts[0])
  463. n = n->kids[0];
  464. else if (index -= n->counts[0] + 1, index < 0)
  465. return n->elems[0];
  466. else if (index < n->counts[1])
  467. n = n->kids[1];
  468. else if (index -= n->counts[1] + 1, index < 0)
  469. return n->elems[1];
  470. else if (index < n->counts[2])
  471. n = n->kids[2];
  472. else if (index -= n->counts[2] + 1, index < 0)
  473. return n->elems[2];
  474. else
  475. n = n->kids[3];
  476. }
  477. /* We shouldn't ever get here. I wonder how we did. */
  478. return NULL;
  479. }
  480. /*
  481. * Find an element e in a sorted 2-3-4 tree t. Returns NULL if not
  482. * found. e is always passed as the first argument to cmp, so cmp
  483. * can be an asymmetric function if desired. cmp can also be passed
  484. * as NULL, in which case the compare function from the tree proper
  485. * will be used.
  486. */
  487. void *findrelpos234(tree234 * t, void *e, cmpfn234 cmp,
  488. int relation, int *index)
  489. {
  490. node234 *n;
  491. void *ret;
  492. int c;
  493. int idx, ecount, kcount, cmpret;
  494. if (t->root == NULL)
  495. return NULL;
  496. if (cmp == NULL)
  497. cmp = t->cmp;
  498. n = t->root;
  499. /*
  500. * Attempt to find the element itself.
  501. */
  502. idx = 0;
  503. ecount = -1;
  504. /*
  505. * Prepare a fake `cmp' result if e is NULL.
  506. */
  507. cmpret = 0;
  508. if (e == NULL) {
  509. assert(relation == REL234_LT || relation == REL234_GT);
  510. if (relation == REL234_LT)
  511. cmpret = +1; /* e is a max: always greater */
  512. else if (relation == REL234_GT)
  513. cmpret = -1; /* e is a min: always smaller */
  514. }
  515. while (1) {
  516. for (kcount = 0; kcount < 4; kcount++) {
  517. if (kcount >= 3 || n->elems[kcount] == NULL ||
  518. (c = cmpret ? cmpret : cmp(e, n->elems[kcount])) < 0) {
  519. break;
  520. }
  521. if (n->kids[kcount])
  522. idx += n->counts[kcount];
  523. if (c == 0) {
  524. ecount = kcount;
  525. break;
  526. }
  527. idx++;
  528. }
  529. if (ecount >= 0)
  530. break;
  531. if (n->kids[kcount])
  532. n = n->kids[kcount];
  533. else
  534. break;
  535. }
  536. if (ecount >= 0) {
  537. /*
  538. * We have found the element we're looking for. It's
  539. * n->elems[ecount], at tree index idx. If our search
  540. * relation is EQ, LE or GE we can now go home.
  541. */
  542. if (relation != REL234_LT && relation != REL234_GT) {
  543. if (index)
  544. *index = idx;
  545. return n->elems[ecount];
  546. }
  547. /*
  548. * Otherwise, we'll do an indexed lookup for the previous
  549. * or next element. (It would be perfectly possible to
  550. * implement these search types in a non-counted tree by
  551. * going back up from where we are, but far more fiddly.)
  552. */
  553. if (relation == REL234_LT)
  554. idx--;
  555. else
  556. idx++;
  557. } else {
  558. /*
  559. * We've found our way to the bottom of the tree and we
  560. * know where we would insert this node if we wanted to:
  561. * we'd put it in in place of the (empty) subtree
  562. * n->kids[kcount], and it would have index idx
  563. *
  564. * But the actual element isn't there. So if our search
  565. * relation is EQ, we're doomed.
  566. */
  567. if (relation == REL234_EQ)
  568. return NULL;
  569. /*
  570. * Otherwise, we must do an index lookup for index idx-1
  571. * (if we're going left - LE or LT) or index idx (if we're
  572. * going right - GE or GT).
  573. */
  574. if (relation == REL234_LT || relation == REL234_LE) {
  575. idx--;
  576. }
  577. }
  578. /*
  579. * We know the index of the element we want; just call index234
  580. * to do the rest. This will return NULL if the index is out of
  581. * bounds, which is exactly what we want.
  582. */
  583. ret = index234(t, idx);
  584. if (ret && index)
  585. *index = idx;
  586. return ret;
  587. }
  588. void *find234(tree234 * t, void *e, cmpfn234 cmp)
  589. {
  590. return findrelpos234(t, e, cmp, REL234_EQ, NULL);
  591. }
  592. void *findrel234(tree234 * t, void *e, cmpfn234 cmp, int relation)
  593. {
  594. return findrelpos234(t, e, cmp, relation, NULL);
  595. }
  596. void *findpos234(tree234 * t, void *e, cmpfn234 cmp, int *index)
  597. {
  598. return findrelpos234(t, e, cmp, REL234_EQ, index);
  599. }
  600. /*
  601. * Delete an element e in a 2-3-4 tree. Does not free the element,
  602. * merely removes all links to it from the tree nodes.
  603. */
  604. static void *delpos234_internal(tree234 * t, int index)
  605. {
  606. node234 *n;
  607. void *retval;
  608. int ei = -1;
  609. retval = 0;
  610. n = t->root;
  611. LOG(("deleting item %d from tree %p\n", index, t));
  612. while (1) {
  613. while (n) {
  614. int ki;
  615. node234 *sub;
  616. LOG(
  617. (" node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d index=%d\n",
  618. n, n->kids[0], n->counts[0], n->elems[0], n->kids[1],
  619. n->counts[1], n->elems[1], n->kids[2], n->counts[2],
  620. n->elems[2], n->kids[3], n->counts[3], index));
  621. if (index < n->counts[0]) {
  622. ki = 0;
  623. } else if (index -= n->counts[0] + 1, index < 0) {
  624. ei = 0;
  625. break;
  626. } else if (index < n->counts[1]) {
  627. ki = 1;
  628. } else if (index -= n->counts[1] + 1, index < 0) {
  629. ei = 1;
  630. break;
  631. } else if (index < n->counts[2]) {
  632. ki = 2;
  633. } else if (index -= n->counts[2] + 1, index < 0) {
  634. ei = 2;
  635. break;
  636. } else {
  637. ki = 3;
  638. }
  639. /*
  640. * Recurse down to subtree ki. If it has only one element,
  641. * we have to do some transformation to start with.
  642. */
  643. LOG((" moving to subtree %d\n", ki));
  644. sub = n->kids[ki];
  645. if (!sub->elems[1]) {
  646. LOG((" subtree has only one element!\n", ki));
  647. if (ki > 0 && n->kids[ki - 1]->elems[1]) {
  648. /*
  649. * Case 3a, left-handed variant. Child ki has
  650. * only one element, but child ki-1 has two or
  651. * more. So we need to move a subtree from ki-1
  652. * to ki.
  653. *
  654. * . C . . B .
  655. * / \ -> / \
  656. * [more] a A b B c d D e [more] a A b c C d D e
  657. */
  658. node234 *sib = n->kids[ki - 1];
  659. int lastelem = (sib->elems[2] ? 2 :
  660. sib->elems[1] ? 1 : 0);
  661. sub->kids[2] = sub->kids[1];
  662. sub->counts[2] = sub->counts[1];
  663. sub->elems[1] = sub->elems[0];
  664. sub->kids[1] = sub->kids[0];
  665. sub->counts[1] = sub->counts[0];
  666. sub->elems[0] = n->elems[ki - 1];
  667. sub->kids[0] = sib->kids[lastelem + 1];
  668. sub->counts[0] = sib->counts[lastelem + 1];
  669. if (sub->kids[0])
  670. sub->kids[0]->parent = sub;
  671. n->elems[ki - 1] = sib->elems[lastelem];
  672. sib->kids[lastelem + 1] = NULL;
  673. sib->counts[lastelem + 1] = 0;
  674. sib->elems[lastelem] = NULL;
  675. n->counts[ki] = countnode234(sub);
  676. LOG((" case 3a left\n"));
  677. LOG(
  678. (" index and left subtree count before adjustment: %d, %d\n",
  679. index, n->counts[ki - 1]));
  680. index += n->counts[ki - 1];
  681. n->counts[ki - 1] = countnode234(sib);
  682. index -= n->counts[ki - 1];
  683. LOG(
  684. (" index and left subtree count after adjustment: %d, %d\n",
  685. index, n->counts[ki - 1]));
  686. } else if (ki < 3 && n->kids[ki + 1]
  687. && n->kids[ki + 1]->elems[1]) {
  688. /*
  689. * Case 3a, right-handed variant. ki has only
  690. * one element but ki+1 has two or more. Move a
  691. * subtree from ki+1 to ki.
  692. *
  693. * . B . . C .
  694. * / \ -> / \
  695. * a A b c C d D e [more] a A b B c d D e [more]
  696. */
  697. node234 *sib = n->kids[ki + 1];
  698. int j;
  699. sub->elems[1] = n->elems[ki];
  700. sub->kids[2] = sib->kids[0];
  701. sub->counts[2] = sib->counts[0];
  702. if (sub->kids[2])
  703. sub->kids[2]->parent = sub;
  704. n->elems[ki] = sib->elems[0];
  705. sib->kids[0] = sib->kids[1];
  706. sib->counts[0] = sib->counts[1];
  707. for (j = 0; j < 2 && sib->elems[j + 1]; j++) {
  708. sib->kids[j + 1] = sib->kids[j + 2];
  709. sib->counts[j + 1] = sib->counts[j + 2];
  710. sib->elems[j] = sib->elems[j + 1];
  711. }
  712. sib->kids[j + 1] = NULL;
  713. sib->counts[j + 1] = 0;
  714. sib->elems[j] = NULL;
  715. n->counts[ki] = countnode234(sub);
  716. n->counts[ki + 1] = countnode234(sib);
  717. LOG((" case 3a right\n"));
  718. } else {
  719. /*
  720. * Case 3b. ki has only one element, and has no
  721. * neighbour with more than one. So pick a
  722. * neighbour and merge it with ki, taking an
  723. * element down from n to go in the middle.
  724. *
  725. * . B . .
  726. * / \ -> |
  727. * a A b c C d a A b B c C d
  728. *
  729. * (Since at all points we have avoided
  730. * descending to a node with only one element,
  731. * we can be sure that n is not reduced to
  732. * nothingness by this move, _unless_ it was
  733. * the very first node, ie the root of the
  734. * tree. In that case we remove the now-empty
  735. * root and replace it with its single large
  736. * child as shown.)
  737. */
  738. node234 *sib;
  739. int j;
  740. if (ki > 0) {
  741. ki--;
  742. index += n->counts[ki] + 1;
  743. }
  744. sib = n->kids[ki];
  745. sub = n->kids[ki + 1];
  746. sub->kids[3] = sub->kids[1];
  747. sub->counts[3] = sub->counts[1];
  748. sub->elems[2] = sub->elems[0];
  749. sub->kids[2] = sub->kids[0];
  750. sub->counts[2] = sub->counts[0];
  751. sub->elems[1] = n->elems[ki];
  752. sub->kids[1] = sib->kids[1];
  753. sub->counts[1] = sib->counts[1];
  754. if (sub->kids[1])
  755. sub->kids[1]->parent = sub;
  756. sub->elems[0] = sib->elems[0];
  757. sub->kids[0] = sib->kids[0];
  758. sub->counts[0] = sib->counts[0];
  759. if (sub->kids[0])
  760. sub->kids[0]->parent = sub;
  761. n->counts[ki + 1] = countnode234(sub);
  762. sfree(sib);
  763. /*
  764. * That's built the big node in sub. Now we
  765. * need to remove the reference to sib in n.
  766. */
  767. for (j = ki; j < 3 && n->kids[j + 1]; j++) {
  768. n->kids[j] = n->kids[j + 1];
  769. n->counts[j] = n->counts[j + 1];
  770. n->elems[j] = j < 2 ? n->elems[j + 1] : NULL;
  771. }
  772. n->kids[j] = NULL;
  773. n->counts[j] = 0;
  774. if (j < 3)
  775. n->elems[j] = NULL;
  776. LOG((" case 3b ki=%d\n", ki));
  777. if (!n->elems[0]) {
  778. /*
  779. * The root is empty and needs to be
  780. * removed.
  781. */
  782. LOG((" shifting root!\n"));
  783. t->root = sub;
  784. sub->parent = NULL;
  785. sfree(n);
  786. }
  787. }
  788. }
  789. n = sub;
  790. }
  791. if (!retval)
  792. retval = n->elems[ei];
  793. if (ei == -1)
  794. return NULL; /* although this shouldn't happen */
  795. /*
  796. * Treat special case: this is the one remaining item in
  797. * the tree. n is the tree root (no parent), has one
  798. * element (no elems[1]), and has no kids (no kids[0]).
  799. */
  800. if (!n->parent && !n->elems[1] && !n->kids[0]) {
  801. LOG((" removed last element in tree\n"));
  802. sfree(n);
  803. t->root = NULL;
  804. return retval;
  805. }
  806. /*
  807. * Now we have the element we want, as n->elems[ei], and we
  808. * have also arranged for that element not to be the only
  809. * one in its node. So...
  810. */
  811. if (!n->kids[0] && n->elems[1]) {
  812. /*
  813. * Case 1. n is a leaf node with more than one element,
  814. * so it's _really easy_. Just delete the thing and
  815. * we're done.
  816. */
  817. int i;
  818. LOG((" case 1\n"));
  819. for (i = ei; i < 2 && n->elems[i + 1]; i++)
  820. n->elems[i] = n->elems[i + 1];
  821. n->elems[i] = NULL;
  822. /*
  823. * Having done that to the leaf node, we now go back up
  824. * the tree fixing the counts.
  825. */
  826. while (n->parent) {
  827. int childnum;
  828. childnum = (n->parent->kids[0] == n ? 0 :
  829. n->parent->kids[1] == n ? 1 :
  830. n->parent->kids[2] == n ? 2 : 3);
  831. n->parent->counts[childnum]--;
  832. n = n->parent;
  833. }
  834. return retval; /* finished! */
  835. } else if (n->kids[ei]->elems[1]) {
  836. /*
  837. * Case 2a. n is an internal node, and the root of the
  838. * subtree to the left of e has more than one element.
  839. * So find the predecessor p to e (ie the largest node
  840. * in that subtree), place it where e currently is, and
  841. * then start the deletion process over again on the
  842. * subtree with p as target.
  843. */
  844. node234 *m = n->kids[ei];
  845. void *target;
  846. LOG((" case 2a\n"));
  847. while (m->kids[0]) {
  848. m = (m->kids[3] ? m->kids[3] :
  849. m->kids[2] ? m->kids[2] :
  850. m->kids[1] ? m->kids[1] : m->kids[0]);
  851. }
  852. target = (m->elems[2] ? m->elems[2] :
  853. m->elems[1] ? m->elems[1] : m->elems[0]);
  854. n->elems[ei] = target;
  855. index = n->counts[ei] - 1;
  856. n = n->kids[ei];
  857. } else if (n->kids[ei + 1]->elems[1]) {
  858. /*
  859. * Case 2b, symmetric to 2a but s/left/right/ and
  860. * s/predecessor/successor/. (And s/largest/smallest/).
  861. */
  862. node234 *m = n->kids[ei + 1];
  863. void *target;
  864. LOG((" case 2b\n"));
  865. while (m->kids[0]) {
  866. m = m->kids[0];
  867. }
  868. target = m->elems[0];
  869. n->elems[ei] = target;
  870. n = n->kids[ei + 1];
  871. index = 0;
  872. } else {
  873. /*
  874. * Case 2c. n is an internal node, and the subtrees to
  875. * the left and right of e both have only one element.
  876. * So combine the two subnodes into a single big node
  877. * with their own elements on the left and right and e
  878. * in the middle, then restart the deletion process on
  879. * that subtree, with e still as target.
  880. */
  881. node234 *a = n->kids[ei], *b = n->kids[ei + 1];
  882. int j;
  883. LOG((" case 2c\n"));
  884. a->elems[1] = n->elems[ei];
  885. a->kids[2] = b->kids[0];
  886. a->counts[2] = b->counts[0];
  887. if (a->kids[2])
  888. a->kids[2]->parent = a;
  889. a->elems[2] = b->elems[0];
  890. a->kids[3] = b->kids[1];
  891. a->counts[3] = b->counts[1];
  892. if (a->kids[3])
  893. a->kids[3]->parent = a;
  894. sfree(b);
  895. n->counts[ei] = countnode234(a);
  896. /*
  897. * That's built the big node in a, and destroyed b. Now
  898. * remove the reference to b (and e) in n.
  899. */
  900. for (j = ei; j < 2 && n->elems[j + 1]; j++) {
  901. n->elems[j] = n->elems[j + 1];
  902. n->kids[j + 1] = n->kids[j + 2];
  903. n->counts[j + 1] = n->counts[j + 2];
  904. }
  905. n->elems[j] = NULL;
  906. n->kids[j + 1] = NULL;
  907. n->counts[j + 1] = 0;
  908. /*
  909. * It's possible, in this case, that we've just removed
  910. * the only element in the root of the tree. If so,
  911. * shift the root.
  912. */
  913. if (n->elems[0] == NULL) {
  914. LOG((" shifting root!\n"));
  915. t->root = a;
  916. a->parent = NULL;
  917. sfree(n);
  918. }
  919. /*
  920. * Now go round the deletion process again, with n
  921. * pointing at the new big node and e still the same.
  922. */
  923. n = a;
  924. index = a->counts[0] + a->counts[1] + 1;
  925. }
  926. }
  927. }
  928. void *delpos234(tree234 * t, int index)
  929. {
  930. if (index < 0 || index >= countnode234(t->root))
  931. return NULL;
  932. return delpos234_internal(t, index);
  933. }
  934. void *del234(tree234 * t, void *e)
  935. {
  936. int index;
  937. if (!findrelpos234(t, e, NULL, REL234_EQ, &index))
  938. return NULL; /* it wasn't in there anyway */
  939. return delpos234_internal(t, index); /* it's there; delete it. */
  940. }
  941. #ifdef TEST
  942. /*
  943. * Test code for the 2-3-4 tree. This code maintains an alternative
  944. * representation of the data in the tree, in an array (using the
  945. * obvious and slow insert and delete functions). After each tree
  946. * operation, the verify() function is called, which ensures all
  947. * the tree properties are preserved:
  948. * - node->child->parent always equals node
  949. * - tree->root->parent always equals NULL
  950. * - number of kids == 0 or number of elements + 1;
  951. * - tree has the same depth everywhere
  952. * - every node has at least one element
  953. * - subtree element counts are accurate
  954. * - any NULL kid pointer is accompanied by a zero count
  955. * - in a sorted tree: ordering property between elements of a
  956. * node and elements of its children is preserved
  957. * and also ensures the list represented by the tree is the same
  958. * list it should be. (This last check also doubly verifies the
  959. * ordering properties, because the `same list it should be' is by
  960. * definition correctly ordered. It also ensures all nodes are
  961. * distinct, because the enum functions would get caught in a loop
  962. * if not.)
  963. */
  964. #include <stdarg.h>
  965. /*
  966. * Error reporting function.
  967. */
  968. void error(char *fmt, ...)
  969. {
  970. va_list ap;
  971. printf("ERROR: ");
  972. va_start(ap, fmt);
  973. vfprintf(stdout, fmt, ap);
  974. va_end(ap);
  975. printf("\n");
  976. }
  977. /* The array representation of the data. */
  978. void **array;
  979. int arraylen, arraysize;
  980. cmpfn234 cmp;
  981. /* The tree representation of the same data. */
  982. tree234 *tree;
  983. typedef struct {
  984. int treedepth;
  985. int elemcount;
  986. } chkctx;
  987. int chknode(chkctx * ctx, int level, node234 * node,
  988. void *lowbound, void *highbound)
  989. {
  990. int nkids, nelems;
  991. int i;
  992. int count;
  993. /* Count the non-NULL kids. */
  994. for (nkids = 0; nkids < 4 && node->kids[nkids]; nkids++);
  995. /* Ensure no kids beyond the first NULL are non-NULL. */
  996. for (i = nkids; i < 4; i++)
  997. if (node->kids[i]) {
  998. error("node %p: nkids=%d but kids[%d] non-NULL",
  999. node, nkids, i);
  1000. } else if (node->counts[i]) {
  1001. error("node %p: kids[%d] NULL but count[%d]=%d nonzero",
  1002. node, i, i, node->counts[i]);
  1003. }
  1004. /* Count the non-NULL elements. */
  1005. for (nelems = 0; nelems < 3 && node->elems[nelems]; nelems++);
  1006. /* Ensure no elements beyond the first NULL are non-NULL. */
  1007. for (i = nelems; i < 3; i++)
  1008. if (node->elems[i]) {
  1009. error("node %p: nelems=%d but elems[%d] non-NULL",
  1010. node, nelems, i);
  1011. }
  1012. if (nkids == 0) {
  1013. /*
  1014. * If nkids==0, this is a leaf node; verify that the tree
  1015. * depth is the same everywhere.
  1016. */
  1017. if (ctx->treedepth < 0)
  1018. ctx->treedepth = level; /* we didn't know the depth yet */
  1019. else if (ctx->treedepth != level)
  1020. error("node %p: leaf at depth %d, previously seen depth %d",
  1021. node, level, ctx->treedepth);
  1022. } else {
  1023. /*
  1024. * If nkids != 0, then it should be nelems+1, unless nelems
  1025. * is 0 in which case nkids should also be 0 (and so we
  1026. * shouldn't be in this condition at all).
  1027. */
  1028. int shouldkids = (nelems ? nelems + 1 : 0);
  1029. if (nkids != shouldkids) {
  1030. error("node %p: %d elems should mean %d kids but has %d",
  1031. node, nelems, shouldkids, nkids);
  1032. }
  1033. }
  1034. /*
  1035. * nelems should be at least 1.
  1036. */
  1037. if (nelems == 0) {
  1038. error("node %p: no elems", node, nkids);
  1039. }
  1040. /*
  1041. * Add nelems to the running element count of the whole tree.
  1042. */
  1043. ctx->elemcount += nelems;
  1044. /*
  1045. * Check ordering property: all elements should be strictly >
  1046. * lowbound, strictly < highbound, and strictly < each other in
  1047. * sequence. (lowbound and highbound are NULL at edges of tree
  1048. * - both NULL at root node - and NULL is considered to be <
  1049. * everything and > everything. IYSWIM.)
  1050. */
  1051. if (cmp) {
  1052. for (i = -1; i < nelems; i++) {
  1053. void *lower = (i == -1 ? lowbound : node->elems[i]);
  1054. void *higher =
  1055. (i + 1 == nelems ? highbound : node->elems[i + 1]);
  1056. if (lower && higher && cmp(lower, higher) >= 0) {
  1057. error("node %p: kid comparison [%d=%s,%d=%s] failed",
  1058. node, i, lower, i + 1, higher);
  1059. }
  1060. }
  1061. }
  1062. /*
  1063. * Check parent pointers: all non-NULL kids should have a
  1064. * parent pointer coming back to this node.
  1065. */
  1066. for (i = 0; i < nkids; i++)
  1067. if (node->kids[i]->parent != node) {
  1068. error("node %p kid %d: parent ptr is %p not %p",
  1069. node, i, node->kids[i]->parent, node);
  1070. }
  1071. /*
  1072. * Now (finally!) recurse into subtrees.
  1073. */
  1074. count = nelems;
  1075. for (i = 0; i < nkids; i++) {
  1076. void *lower = (i == 0 ? lowbound : node->elems[i - 1]);
  1077. void *higher = (i >= nelems ? highbound : node->elems[i]);
  1078. int subcount =
  1079. chknode(ctx, level + 1, node->kids[i], lower, higher);
  1080. if (node->counts[i] != subcount) {
  1081. error("node %p kid %d: count says %d, subtree really has %d",
  1082. node, i, node->counts[i], subcount);
  1083. }
  1084. count += subcount;
  1085. }
  1086. return count;
  1087. }
  1088. void verify(void)
  1089. {
  1090. chkctx ctx;
  1091. int i;
  1092. void *p;
  1093. ctx.treedepth = -1; /* depth unknown yet */
  1094. ctx.elemcount = 0; /* no elements seen yet */
  1095. /*
  1096. * Verify validity of tree properties.
  1097. */
  1098. if (tree->root) {
  1099. if (tree->root->parent != NULL)
  1100. error("root->parent is %p should be null", tree->root->parent);
  1101. chknode(&ctx, 0, tree->root, NULL, NULL);
  1102. }
  1103. printf("tree depth: %d\n", ctx.treedepth);
  1104. /*
  1105. * Enumerate the tree and ensure it matches up to the array.
  1106. */
  1107. for (i = 0; NULL != (p = index234(tree, i)); i++) {
  1108. if (i >= arraylen)
  1109. error("tree contains more than %d elements", arraylen);
  1110. if (array[i] != p)
  1111. error("enum at position %d: array says %s, tree says %s",
  1112. i, array[i], p);
  1113. }
  1114. if (ctx.elemcount != i) {
  1115. error("tree really contains %d elements, enum gave %d",
  1116. ctx.elemcount, i);
  1117. }
  1118. if (i < arraylen) {
  1119. error("enum gave only %d elements, array has %d", i, arraylen);
  1120. }
  1121. i = count234(tree);
  1122. if (ctx.elemcount != i) {
  1123. error("tree really contains %d elements, count234 gave %d",
  1124. ctx.elemcount, i);
  1125. }
  1126. }
  1127. void internal_addtest(void *elem, int index, void *realret)
  1128. {
  1129. int i, j;
  1130. void *retval;
  1131. if (arraysize < arraylen + 1) {
  1132. arraysize = arraylen + 1 + 256;
  1133. array = sresize(array, arraysize, void *);
  1134. }
  1135. i = index;
  1136. /* now i points to the first element >= elem */
  1137. retval = elem; /* expect elem returned (success) */
  1138. for (j = arraylen; j > i; j--)
  1139. array[j] = array[j - 1];
  1140. array[i] = elem; /* add elem to array */
  1141. arraylen++;
  1142. if (realret != retval) {
  1143. error("add: retval was %p expected %p", realret, retval);
  1144. }
  1145. verify();
  1146. }
  1147. void addtest(void *elem)
  1148. {
  1149. int i;
  1150. void *realret;
  1151. realret = add234(tree, elem);
  1152. i = 0;
  1153. while (i < arraylen && cmp(elem, array[i]) > 0)
  1154. i++;
  1155. if (i < arraylen && !cmp(elem, array[i])) {
  1156. void *retval = array[i]; /* expect that returned not elem */
  1157. if (realret != retval) {
  1158. error("add: retval was %p expected %p", realret, retval);
  1159. }
  1160. } else
  1161. internal_addtest(elem, i, realret);
  1162. }
  1163. void addpostest(void *elem, int i)
  1164. {
  1165. void *realret;
  1166. realret = addpos234(tree, elem, i);
  1167. internal_addtest(elem, i, realret);
  1168. }
  1169. void delpostest(int i)
  1170. {
  1171. int index = i;
  1172. void *elem = array[i], *ret;
  1173. /* i points to the right element */
  1174. while (i < arraylen - 1) {
  1175. array[i] = array[i + 1];
  1176. i++;
  1177. }
  1178. arraylen--; /* delete elem from array */
  1179. if (tree->cmp)
  1180. ret = del234(tree, elem);
  1181. else
  1182. ret = delpos234(tree, index);
  1183. if (ret != elem) {
  1184. error("del returned %p, expected %p", ret, elem);
  1185. }
  1186. verify();
  1187. }
  1188. void deltest(void *elem)
  1189. {
  1190. int i;
  1191. i = 0;
  1192. while (i < arraylen && cmp(elem, array[i]) > 0)
  1193. i++;
  1194. if (i >= arraylen || cmp(elem, array[i]) != 0)
  1195. return; /* don't do it! */
  1196. delpostest(i);
  1197. }
  1198. /* A sample data set and test utility. Designed for pseudo-randomness,
  1199. * and yet repeatability. */
  1200. /*
  1201. * This random number generator uses the `portable implementation'
  1202. * given in ANSI C99 draft N869. It assumes `unsigned' is 32 bits;
  1203. * change it if not.
  1204. */
  1205. int randomnumber(unsigned *seed)
  1206. {
  1207. *seed *= 1103515245;
  1208. *seed += 12345;
  1209. return ((*seed) / 65536) % 32768;
  1210. }
  1211. int mycmp(void *av, void *bv)
  1212. {
  1213. char const *a = (char const *) av;
  1214. char const *b = (char const *) bv;
  1215. return strcmp(a, b);
  1216. }
  1217. #define lenof(x) ( sizeof((x)) / sizeof(*(x)) )
  1218. char *strings[] = {
  1219. "a", "ab", "absque", "coram", "de",
  1220. "palam", "clam", "cum", "ex", "e",
  1221. "sine", "tenus", "pro", "prae",
  1222. "banana", "carrot", "cabbage", "broccoli", "onion", "zebra",
  1223. "penguin", "blancmange", "pangolin", "whale", "hedgehog",
  1224. "giraffe", "peanut", "bungee", "foo", "bar", "baz", "quux",
  1225. "murfl", "spoo", "breen", "flarn", "octothorpe",
  1226. "snail", "tiger", "elephant", "octopus", "warthog", "armadillo",
  1227. "aardvark", "wyvern", "dragon", "elf", "dwarf", "orc", "goblin",
  1228. "pixie", "basilisk", "warg", "ape", "lizard", "newt", "shopkeeper",
  1229. "wand", "ring", "amulet"
  1230. };
  1231. #define NSTR lenof(strings)
  1232. int findtest(void)
  1233. {
  1234. const static int rels[] = {
  1235. REL234_EQ, REL234_GE, REL234_LE, REL234_LT, REL234_GT
  1236. };
  1237. const static char *const relnames[] = {
  1238. "EQ", "GE", "LE", "LT", "GT"
  1239. };
  1240. int i, j, rel, index;
  1241. char *p, *ret, *realret, *realret2;
  1242. int lo, hi, mid, c;
  1243. for (i = 0; i < NSTR; i++) {
  1244. p = strings[i];
  1245. for (j = 0; j < sizeof(rels) / sizeof(*rels); j++) {
  1246. rel = rels[j];
  1247. lo = 0;
  1248. hi = arraylen - 1;
  1249. while (lo <= hi) {
  1250. mid = (lo + hi) / 2;
  1251. c = strcmp(p, array[mid]);
  1252. if (c < 0)
  1253. hi = mid - 1;
  1254. else if (c > 0)
  1255. lo = mid + 1;
  1256. else
  1257. break;
  1258. }
  1259. if (c == 0) {
  1260. if (rel == REL234_LT)
  1261. ret = (mid > 0 ? array[--mid] : NULL);
  1262. else if (rel == REL234_GT)
  1263. ret = (mid < arraylen - 1 ? array[++mid] : NULL);
  1264. else
  1265. ret = array[mid];
  1266. } else {
  1267. assert(lo == hi + 1);
  1268. if (rel == REL234_LT || rel == REL234_LE) {
  1269. mid = hi;
  1270. ret = (hi >= 0 ? array[hi] : NULL);
  1271. } else if (rel == REL234_GT || rel == REL234_GE) {
  1272. mid = lo;
  1273. ret = (lo < arraylen ? array[lo] : NULL);
  1274. } else
  1275. ret = NULL;
  1276. }
  1277. realret = findrelpos234(tree, p, NULL, rel, &index);
  1278. if (realret != ret) {
  1279. error("find(\"%s\",%s) gave %s should be %s",
  1280. p, relnames[j], realret, ret);
  1281. }
  1282. if (realret && index != mid) {
  1283. error("find(\"%s\",%s) gave %d should be %d",
  1284. p, relnames[j], index, mid);
  1285. }
  1286. if (realret && rel == REL234_EQ) {
  1287. realret2 = index234(tree, index);
  1288. if (realret2 != realret) {
  1289. error("find(\"%s\",%s) gave %s(%d) but %d -> %s",
  1290. p, relnames[j], realret, index, index, realret2);
  1291. }
  1292. }
  1293. #if 0
  1294. printf("find(\"%s\",%s) gave %s(%d)\n", p, relnames[j],
  1295. realret, index);
  1296. #endif
  1297. }
  1298. }
  1299. realret = findrelpos234(tree, NULL, NULL, REL234_GT, &index);
  1300. if (arraylen && (realret != array[0] || index != 0)) {
  1301. error("find(NULL,GT) gave %s(%d) should be %s(0)",
  1302. realret, index, array[0]);
  1303. } else if (!arraylen && (realret != NULL)) {
  1304. error("find(NULL,GT) gave %s(%d) should be NULL", realret, index);
  1305. }
  1306. realret = findrelpos234(tree, NULL, NULL, REL234_LT, &index);
  1307. if (arraylen
  1308. && (realret != array[arraylen - 1] || index != arraylen - 1)) {
  1309. error("find(NULL,LT) gave %s(%d) should be %s(0)", realret, index,
  1310. array[arraylen - 1]);
  1311. } else if (!arraylen && (realret != NULL)) {
  1312. error("find(NULL,LT) gave %s(%d) should be NULL", realret, index);
  1313. }
  1314. }
  1315. int main(void)
  1316. {
  1317. int in[NSTR];
  1318. int i, j, k;
  1319. unsigned seed = 0;
  1320. for (i = 0; i < NSTR; i++)
  1321. in[i] = 0;
  1322. array = NULL;
  1323. arraylen = arraysize = 0;
  1324. tree = newtree234(mycmp);
  1325. cmp = mycmp;
  1326. verify();
  1327. for (i = 0; i < 10000; i++) {
  1328. j = randomnumber(&seed);
  1329. j %= NSTR;
  1330. printf("trial: %d\n", i);
  1331. if (in[j]) {
  1332. printf("deleting %s (%d)\n", strings[j], j);
  1333. deltest(strings[j]);
  1334. in[j] = 0;
  1335. } else {
  1336. printf("adding %s (%d)\n", strings[j], j);
  1337. addtest(strings[j]);
  1338. in[j] = 1;
  1339. }
  1340. findtest();
  1341. }
  1342. while (arraylen > 0) {
  1343. j = randomnumber(&seed);
  1344. j %= arraylen;
  1345. deltest(array[j]);
  1346. }
  1347. freetree234(tree);
  1348. /*
  1349. * Now try an unsorted tree. We don't really need to test
  1350. * delpos234 because we know del234 is based on it, so it's
  1351. * already been tested in the above sorted-tree code; but for
  1352. * completeness we'll use it to tear down our unsorted tree
  1353. * once we've built it.
  1354. */
  1355. tree = newtree234(NULL);
  1356. cmp = NULL;
  1357. verify();
  1358. for (i = 0; i < 1000; i++) {
  1359. printf("trial: %d\n", i);
  1360. j = randomnumber(&seed);
  1361. j %= NSTR;
  1362. k = randomnumber(&seed);
  1363. k %= count234(tree) + 1;
  1364. printf("adding string %s at index %d\n", strings[j], k);
  1365. addpostest(strings[j], k);
  1366. }
  1367. while (count234(tree) > 0) {
  1368. printf("cleanup: tree size %d\n", count234(tree));
  1369. j = randomnumber(&seed);
  1370. j %= count234(tree);
  1371. printf("deleting string %s from index %d\n",
  1372. (const char *)array[j], j);
  1373. delpostest(j);
  1374. }
  1375. return 0;
  1376. }
  1377. #endif