tree234.c 52 KB

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