tree234.c 53 KB

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