tree234.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  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. direction = +1;
  604. } else {
  605. state->_hi = state->_last - 1;
  606. direction = -1;
  607. }
  608. if (state->_lo > state->_hi) {
  609. /*
  610. * We've run out of elements in this node, i.e. we've
  611. * narrowed to nothing but a child pointer. Descend to
  612. * that child, and update _base to the leftmost index of
  613. * its subtree.
  614. */
  615. for (i = 0; i < state->_lo; i++)
  616. state->_base += 1 + node->counts[i];
  617. state->_node = node = node->kids[state->_lo];
  618. state->_last = -1;
  619. }
  620. }
  621. if (state->_last == -1) {
  622. /*
  623. * We've just entered a new node - either because of the above
  624. * code, or because we were called from search234_start - and
  625. * anything in that node is a viable answer.
  626. */
  627. state->_lo = 0;
  628. state->_hi = node ? elements234(node)-1 : 0;
  629. }
  630. /*
  631. * Now we've got something we can return.
  632. */
  633. if (!node) {
  634. state->element = NULL;
  635. state->index = state->_base;
  636. } else {
  637. state->_last = (state->_lo + state->_hi) / 2;
  638. state->element = node->elems[state->_last];
  639. state->index = state->_base + state->_last;
  640. for (i = 0; i <= state->_last; i++)
  641. state->index += node->counts[i];
  642. }
  643. }
  644. /*
  645. * Delete an element e in a 2-3-4 tree. Does not free the element,
  646. * merely removes all links to it from the tree nodes.
  647. */
  648. static void *delpos234_internal(tree234 * t, int index)
  649. {
  650. node234 *n;
  651. void *retval;
  652. int ei = -1;
  653. retval = 0;
  654. n = t->root;
  655. LOG(("deleting item %d from tree %p\n", index, t));
  656. while (1) {
  657. while (n) {
  658. int ki;
  659. node234 *sub;
  660. LOG(
  661. (" node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d index=%d\n",
  662. n, n->kids[0], n->counts[0], n->elems[0], n->kids[1],
  663. n->counts[1], n->elems[1], n->kids[2], n->counts[2],
  664. n->elems[2], n->kids[3], n->counts[3], index));
  665. if (index < n->counts[0]) {
  666. ki = 0;
  667. } else if (index -= n->counts[0] + 1, index < 0) {
  668. ei = 0;
  669. break;
  670. } else if (index < n->counts[1]) {
  671. ki = 1;
  672. } else if (index -= n->counts[1] + 1, index < 0) {
  673. ei = 1;
  674. break;
  675. } else if (index < n->counts[2]) {
  676. ki = 2;
  677. } else if (index -= n->counts[2] + 1, index < 0) {
  678. ei = 2;
  679. break;
  680. } else {
  681. ki = 3;
  682. }
  683. /*
  684. * Recurse down to subtree ki. If it has only one element,
  685. * we have to do some transformation to start with.
  686. */
  687. LOG((" moving to subtree %d\n", ki));
  688. sub = n->kids[ki];
  689. if (!sub->elems[1]) {
  690. LOG((" subtree has only one element!\n"));
  691. if (ki > 0 && n->kids[ki - 1]->elems[1]) {
  692. /*
  693. * Case 3a, left-handed variant. Child ki has
  694. * only one element, but child ki-1 has two or
  695. * more. So we need to move a subtree from ki-1
  696. * to ki.
  697. *
  698. * . C . . B .
  699. * / \ -> / \
  700. * [more] a A b B c d D e [more] a A b c C d D e
  701. */
  702. node234 *sib = n->kids[ki - 1];
  703. int lastelem = (sib->elems[2] ? 2 :
  704. sib->elems[1] ? 1 : 0);
  705. sub->kids[2] = sub->kids[1];
  706. sub->counts[2] = sub->counts[1];
  707. sub->elems[1] = sub->elems[0];
  708. sub->kids[1] = sub->kids[0];
  709. sub->counts[1] = sub->counts[0];
  710. sub->elems[0] = n->elems[ki - 1];
  711. sub->kids[0] = sib->kids[lastelem + 1];
  712. sub->counts[0] = sib->counts[lastelem + 1];
  713. if (sub->kids[0])
  714. sub->kids[0]->parent = sub;
  715. n->elems[ki - 1] = sib->elems[lastelem];
  716. sib->kids[lastelem + 1] = NULL;
  717. sib->counts[lastelem + 1] = 0;
  718. sib->elems[lastelem] = NULL;
  719. n->counts[ki] = countnode234(sub);
  720. LOG((" case 3a left\n"));
  721. LOG(
  722. (" index and left subtree count before adjustment: %d, %d\n",
  723. index, n->counts[ki - 1]));
  724. index += n->counts[ki - 1];
  725. n->counts[ki - 1] = countnode234(sib);
  726. index -= n->counts[ki - 1];
  727. LOG(
  728. (" index and left subtree count after adjustment: %d, %d\n",
  729. index, n->counts[ki - 1]));
  730. } else if (ki < 3 && n->kids[ki + 1]
  731. && n->kids[ki + 1]->elems[1]) {
  732. /*
  733. * Case 3a, right-handed variant. ki has only
  734. * one element but ki+1 has two or more. Move a
  735. * subtree from ki+1 to ki.
  736. *
  737. * . B . . C .
  738. * / \ -> / \
  739. * a A b c C d D e [more] a A b B c d D e [more]
  740. */
  741. node234 *sib = n->kids[ki + 1];
  742. int j;
  743. sub->elems[1] = n->elems[ki];
  744. sub->kids[2] = sib->kids[0];
  745. sub->counts[2] = sib->counts[0];
  746. if (sub->kids[2])
  747. sub->kids[2]->parent = sub;
  748. n->elems[ki] = sib->elems[0];
  749. sib->kids[0] = sib->kids[1];
  750. sib->counts[0] = sib->counts[1];
  751. for (j = 0; j < 2 && sib->elems[j + 1]; j++) {
  752. sib->kids[j + 1] = sib->kids[j + 2];
  753. sib->counts[j + 1] = sib->counts[j + 2];
  754. sib->elems[j] = sib->elems[j + 1];
  755. }
  756. sib->kids[j + 1] = NULL;
  757. sib->counts[j + 1] = 0;
  758. sib->elems[j] = NULL;
  759. n->counts[ki] = countnode234(sub);
  760. n->counts[ki + 1] = countnode234(sib);
  761. LOG((" case 3a right\n"));
  762. } else {
  763. /*
  764. * Case 3b. ki has only one element, and has no
  765. * neighbour with more than one. So pick a
  766. * neighbour and merge it with ki, taking an
  767. * element down from n to go in the middle.
  768. *
  769. * . B . .
  770. * / \ -> |
  771. * a A b c C d a A b B c C d
  772. *
  773. * (Since at all points we have avoided
  774. * descending to a node with only one element,
  775. * we can be sure that n is not reduced to
  776. * nothingness by this move, _unless_ it was
  777. * the very first node, ie the root of the
  778. * tree. In that case we remove the now-empty
  779. * root and replace it with its single large
  780. * child as shown.)
  781. */
  782. node234 *sib;
  783. int j;
  784. if (ki > 0) {
  785. ki--;
  786. index += n->counts[ki] + 1;
  787. }
  788. sib = n->kids[ki];
  789. sub = n->kids[ki + 1];
  790. sub->kids[3] = sub->kids[1];
  791. sub->counts[3] = sub->counts[1];
  792. sub->elems[2] = sub->elems[0];
  793. sub->kids[2] = sub->kids[0];
  794. sub->counts[2] = sub->counts[0];
  795. sub->elems[1] = n->elems[ki];
  796. sub->kids[1] = sib->kids[1];
  797. sub->counts[1] = sib->counts[1];
  798. if (sub->kids[1])
  799. sub->kids[1]->parent = sub;
  800. sub->elems[0] = sib->elems[0];
  801. sub->kids[0] = sib->kids[0];
  802. sub->counts[0] = sib->counts[0];
  803. if (sub->kids[0])
  804. sub->kids[0]->parent = sub;
  805. n->counts[ki + 1] = countnode234(sub);
  806. sfree(sib);
  807. /*
  808. * That's built the big node in sub. Now we
  809. * need to remove the reference to sib in n.
  810. */
  811. for (j = ki; j < 3 && n->kids[j + 1]; j++) {
  812. n->kids[j] = n->kids[j + 1];
  813. n->counts[j] = n->counts[j + 1];
  814. n->elems[j] = j < 2 ? n->elems[j + 1] : NULL;
  815. }
  816. n->kids[j] = NULL;
  817. n->counts[j] = 0;
  818. if (j < 3)
  819. n->elems[j] = NULL;
  820. LOG((" case 3b ki=%d\n", ki));
  821. if (!n->elems[0]) {
  822. /*
  823. * The root is empty and needs to be
  824. * removed.
  825. */
  826. LOG((" shifting root!\n"));
  827. t->root = sub;
  828. sub->parent = NULL;
  829. sfree(n);
  830. }
  831. }
  832. }
  833. n = sub;
  834. }
  835. if (!retval)
  836. retval = n->elems[ei];
  837. if (ei == -1)
  838. return NULL; /* although this shouldn't happen */
  839. /*
  840. * Treat special case: this is the one remaining item in
  841. * the tree. n is the tree root (no parent), has one
  842. * element (no elems[1]), and has no kids (no kids[0]).
  843. */
  844. if (!n->parent && !n->elems[1] && !n->kids[0]) {
  845. LOG((" removed last element in tree\n"));
  846. sfree(n);
  847. t->root = NULL;
  848. return retval;
  849. }
  850. /*
  851. * Now we have the element we want, as n->elems[ei], and we
  852. * have also arranged for that element not to be the only
  853. * one in its node. So...
  854. */
  855. if (!n->kids[0] && n->elems[1]) {
  856. /*
  857. * Case 1. n is a leaf node with more than one element,
  858. * so it's _really easy_. Just delete the thing and
  859. * we're done.
  860. */
  861. int i;
  862. LOG((" case 1\n"));
  863. for (i = ei; i < 2 && n->elems[i + 1]; i++)
  864. n->elems[i] = n->elems[i + 1];
  865. n->elems[i] = NULL;
  866. /*
  867. * Having done that to the leaf node, we now go back up
  868. * the tree fixing the counts.
  869. */
  870. while (n->parent) {
  871. int childnum;
  872. childnum = (n->parent->kids[0] == n ? 0 :
  873. n->parent->kids[1] == n ? 1 :
  874. n->parent->kids[2] == n ? 2 : 3);
  875. n->parent->counts[childnum]--;
  876. n = n->parent;
  877. }
  878. return retval; /* finished! */
  879. } else if (n->kids[ei]->elems[1]) {
  880. /*
  881. * Case 2a. n is an internal node, and the root of the
  882. * subtree to the left of e has more than one element.
  883. * So find the predecessor p to e (ie the largest node
  884. * in that subtree), place it where e currently is, and
  885. * then start the deletion process over again on the
  886. * subtree with p as target.
  887. */
  888. node234 *m = n->kids[ei];
  889. void *target;
  890. LOG((" case 2a\n"));
  891. while (m->kids[0]) {
  892. m = (m->kids[3] ? m->kids[3] :
  893. m->kids[2] ? m->kids[2] :
  894. m->kids[1] ? m->kids[1] : m->kids[0]);
  895. }
  896. target = (m->elems[2] ? m->elems[2] :
  897. m->elems[1] ? m->elems[1] : m->elems[0]);
  898. n->elems[ei] = target;
  899. index = n->counts[ei] - 1;
  900. n = n->kids[ei];
  901. } else if (n->kids[ei + 1]->elems[1]) {
  902. /*
  903. * Case 2b, symmetric to 2a but s/left/right/ and
  904. * s/predecessor/successor/. (And s/largest/smallest/).
  905. */
  906. node234 *m = n->kids[ei + 1];
  907. void *target;
  908. LOG((" case 2b\n"));
  909. while (m->kids[0]) {
  910. m = m->kids[0];
  911. }
  912. target = m->elems[0];
  913. n->elems[ei] = target;
  914. n = n->kids[ei + 1];
  915. index = 0;
  916. } else {
  917. /*
  918. * Case 2c. n is an internal node, and the subtrees to
  919. * the left and right of e both have only one element.
  920. * So combine the two subnodes into a single big node
  921. * with their own elements on the left and right and e
  922. * in the middle, then restart the deletion process on
  923. * that subtree, with e still as target.
  924. */
  925. node234 *a = n->kids[ei], *b = n->kids[ei + 1];
  926. int j;
  927. LOG((" case 2c\n"));
  928. a->elems[1] = n->elems[ei];
  929. a->kids[2] = b->kids[0];
  930. a->counts[2] = b->counts[0];
  931. if (a->kids[2])
  932. a->kids[2]->parent = a;
  933. a->elems[2] = b->elems[0];
  934. a->kids[3] = b->kids[1];
  935. a->counts[3] = b->counts[1];
  936. if (a->kids[3])
  937. a->kids[3]->parent = a;
  938. sfree(b);
  939. n->counts[ei] = countnode234(a);
  940. /*
  941. * That's built the big node in a, and destroyed b. Now
  942. * remove the reference to b (and e) in n.
  943. */
  944. for (j = ei; j < 2 && n->elems[j + 1]; j++) {
  945. n->elems[j] = n->elems[j + 1];
  946. n->kids[j + 1] = n->kids[j + 2];
  947. n->counts[j + 1] = n->counts[j + 2];
  948. }
  949. n->elems[j] = NULL;
  950. n->kids[j + 1] = NULL;
  951. n->counts[j + 1] = 0;
  952. /*
  953. * It's possible, in this case, that we've just removed
  954. * the only element in the root of the tree. If so,
  955. * shift the root.
  956. */
  957. if (n->elems[0] == NULL) {
  958. LOG((" shifting root!\n"));
  959. t->root = a;
  960. a->parent = NULL;
  961. sfree(n);
  962. }
  963. /*
  964. * Now go round the deletion process again, with n
  965. * pointing at the new big node and e still the same.
  966. */
  967. n = a;
  968. index = a->counts[0] + a->counts[1] + 1;
  969. }
  970. }
  971. }
  972. void *delpos234(tree234 * t, int index)
  973. {
  974. if (index < 0 || index >= countnode234(t->root))
  975. return NULL;
  976. return delpos234_internal(t, index);
  977. }
  978. void *del234(tree234 * t, void *e)
  979. {
  980. int index;
  981. if (!findrelpos234(t, e, NULL, REL234_EQ, &index))
  982. return NULL; /* it wasn't in there anyway */
  983. return delpos234_internal(t, index); /* it's there; delete it. */
  984. }
  985. #ifdef TEST
  986. /*
  987. * Test code for the 2-3-4 tree. This code maintains an alternative
  988. * representation of the data in the tree, in an array (using the
  989. * obvious and slow insert and delete functions). After each tree
  990. * operation, the verify() function is called, which ensures all
  991. * the tree properties are preserved:
  992. * - node->child->parent always equals node
  993. * - tree->root->parent always equals NULL
  994. * - number of kids == 0 or number of elements + 1;
  995. * - tree has the same depth everywhere
  996. * - every node has at least one element
  997. * - subtree element counts are accurate
  998. * - any NULL kid pointer is accompanied by a zero count
  999. * - in a sorted tree: ordering property between elements of a
  1000. * node and elements of its children is preserved
  1001. * and also ensures the list represented by the tree is the same
  1002. * list it should be. (This last check also doubly verifies the
  1003. * ordering properties, because the `same list it should be' is by
  1004. * definition correctly ordered. It also ensures all nodes are
  1005. * distinct, because the enum functions would get caught in a loop
  1006. * if not.)
  1007. */
  1008. #include <stdarg.h>
  1009. #include <string.h>
  1010. int n_errors = 0;
  1011. /*
  1012. * Error reporting function.
  1013. */
  1014. void error(char *fmt, ...)
  1015. {
  1016. va_list ap;
  1017. printf("ERROR: ");
  1018. va_start(ap, fmt);
  1019. vfprintf(stdout, fmt, ap);
  1020. va_end(ap);
  1021. printf("\n");
  1022. n_errors++;
  1023. }
  1024. /* The array representation of the data. */
  1025. void **array;
  1026. int arraylen, arraysize;
  1027. cmpfn234 cmp;
  1028. /* The tree representation of the same data. */
  1029. tree234 *tree;
  1030. typedef struct {
  1031. int treedepth;
  1032. int elemcount;
  1033. } chkctx;
  1034. int chknode(chkctx * ctx, int level, node234 * node,
  1035. void *lowbound, void *highbound)
  1036. {
  1037. int nkids, nelems;
  1038. int i;
  1039. int count;
  1040. /* Count the non-NULL kids. */
  1041. for (nkids = 0; nkids < 4 && node->kids[nkids]; nkids++);
  1042. /* Ensure no kids beyond the first NULL are non-NULL. */
  1043. for (i = nkids; i < 4; i++)
  1044. if (node->kids[i]) {
  1045. error("node %p: nkids=%d but kids[%d] non-NULL",
  1046. node, nkids, i);
  1047. } else if (node->counts[i]) {
  1048. error("node %p: kids[%d] NULL but count[%d]=%d nonzero",
  1049. node, i, i, node->counts[i]);
  1050. }
  1051. /* Count the non-NULL elements. */
  1052. for (nelems = 0; nelems < 3 && node->elems[nelems]; nelems++);
  1053. /* Ensure no elements beyond the first NULL are non-NULL. */
  1054. for (i = nelems; i < 3; i++)
  1055. if (node->elems[i]) {
  1056. error("node %p: nelems=%d but elems[%d] non-NULL",
  1057. node, nelems, i);
  1058. }
  1059. if (nkids == 0) {
  1060. /*
  1061. * If nkids==0, this is a leaf node; verify that the tree
  1062. * depth is the same everywhere.
  1063. */
  1064. if (ctx->treedepth < 0)
  1065. ctx->treedepth = level; /* we didn't know the depth yet */
  1066. else if (ctx->treedepth != level)
  1067. error("node %p: leaf at depth %d, previously seen depth %d",
  1068. node, level, ctx->treedepth);
  1069. } else {
  1070. /*
  1071. * If nkids != 0, then it should be nelems+1, unless nelems
  1072. * is 0 in which case nkids should also be 0 (and so we
  1073. * shouldn't be in this condition at all).
  1074. */
  1075. int shouldkids = (nelems ? nelems + 1 : 0);
  1076. if (nkids != shouldkids) {
  1077. error("node %p: %d elems should mean %d kids but has %d",
  1078. node, nelems, shouldkids, nkids);
  1079. }
  1080. }
  1081. /*
  1082. * nelems should be at least 1.
  1083. */
  1084. if (nelems == 0) {
  1085. error("node %p: no elems", node, nkids);
  1086. }
  1087. /*
  1088. * Add nelems to the running element count of the whole tree.
  1089. */
  1090. ctx->elemcount += nelems;
  1091. /*
  1092. * Check ordering property: all elements should be strictly >
  1093. * lowbound, strictly < highbound, and strictly < each other in
  1094. * sequence. (lowbound and highbound are NULL at edges of tree
  1095. * - both NULL at root node - and NULL is considered to be <
  1096. * everything and > everything. IYSWIM.)
  1097. */
  1098. if (cmp) {
  1099. for (i = -1; i < nelems; i++) {
  1100. void *lower = (i == -1 ? lowbound : node->elems[i]);
  1101. void *higher =
  1102. (i + 1 == nelems ? highbound : node->elems[i + 1]);
  1103. if (lower && higher && cmp(lower, higher) >= 0) {
  1104. error("node %p: kid comparison [%d=%s,%d=%s] failed",
  1105. node, i, lower, i + 1, higher);
  1106. }
  1107. }
  1108. }
  1109. /*
  1110. * Check parent pointers: all non-NULL kids should have a
  1111. * parent pointer coming back to this node.
  1112. */
  1113. for (i = 0; i < nkids; i++)
  1114. if (node->kids[i]->parent != node) {
  1115. error("node %p kid %d: parent ptr is %p not %p",
  1116. node, i, node->kids[i]->parent, node);
  1117. }
  1118. /*
  1119. * Now (finally!) recurse into subtrees.
  1120. */
  1121. count = nelems;
  1122. for (i = 0; i < nkids; i++) {
  1123. void *lower = (i == 0 ? lowbound : node->elems[i - 1]);
  1124. void *higher = (i >= nelems ? highbound : node->elems[i]);
  1125. int subcount =
  1126. chknode(ctx, level + 1, node->kids[i], lower, higher);
  1127. if (node->counts[i] != subcount) {
  1128. error("node %p kid %d: count says %d, subtree really has %d",
  1129. node, i, node->counts[i], subcount);
  1130. }
  1131. count += subcount;
  1132. }
  1133. return count;
  1134. }
  1135. void verify(void)
  1136. {
  1137. chkctx ctx;
  1138. int i;
  1139. void *p;
  1140. ctx.treedepth = -1; /* depth unknown yet */
  1141. ctx.elemcount = 0; /* no elements seen yet */
  1142. /*
  1143. * Verify validity of tree properties.
  1144. */
  1145. if (tree->root) {
  1146. if (tree->root->parent != NULL)
  1147. error("root->parent is %p should be null", tree->root->parent);
  1148. chknode(&ctx, 0, tree->root, NULL, NULL);
  1149. }
  1150. printf("tree depth: %d\n", ctx.treedepth);
  1151. /*
  1152. * Enumerate the tree and ensure it matches up to the array.
  1153. */
  1154. for (i = 0; NULL != (p = index234(tree, i)); i++) {
  1155. if (i >= arraylen)
  1156. error("tree contains more than %d elements", arraylen);
  1157. if (array[i] != p)
  1158. error("enum at position %d: array says %s, tree says %s",
  1159. i, array[i], p);
  1160. }
  1161. if (ctx.elemcount != i) {
  1162. error("tree really contains %d elements, enum gave %d",
  1163. ctx.elemcount, i);
  1164. }
  1165. if (i < arraylen) {
  1166. error("enum gave only %d elements, array has %d", i, arraylen);
  1167. }
  1168. i = count234(tree);
  1169. if (ctx.elemcount != i) {
  1170. error("tree really contains %d elements, count234 gave %d",
  1171. ctx.elemcount, i);
  1172. }
  1173. }
  1174. void internal_addtest(void *elem, int index, void *realret)
  1175. {
  1176. int i, j;
  1177. void *retval;
  1178. if (arraysize < arraylen + 1) {
  1179. arraysize = arraylen + 1 + 256;
  1180. array = sresize(array, arraysize, void *);
  1181. }
  1182. i = index;
  1183. /* now i points to the first element >= elem */
  1184. retval = elem; /* expect elem returned (success) */
  1185. for (j = arraylen; j > i; j--)
  1186. array[j] = array[j - 1];
  1187. array[i] = elem; /* add elem to array */
  1188. arraylen++;
  1189. if (realret != retval) {
  1190. error("add: retval was %p expected %p", realret, retval);
  1191. }
  1192. verify();
  1193. }
  1194. void addtest(void *elem)
  1195. {
  1196. int i;
  1197. void *realret;
  1198. realret = add234(tree, elem);
  1199. i = 0;
  1200. while (i < arraylen && cmp(elem, array[i]) > 0)
  1201. i++;
  1202. if (i < arraylen && !cmp(elem, array[i])) {
  1203. void *retval = array[i]; /* expect that returned not elem */
  1204. if (realret != retval) {
  1205. error("add: retval was %p expected %p", realret, retval);
  1206. }
  1207. } else
  1208. internal_addtest(elem, i, realret);
  1209. }
  1210. void addpostest(void *elem, int i)
  1211. {
  1212. void *realret;
  1213. realret = addpos234(tree, elem, i);
  1214. internal_addtest(elem, i, realret);
  1215. }
  1216. void delpostest(int i)
  1217. {
  1218. int index = i;
  1219. void *elem = array[i], *ret;
  1220. /* i points to the right element */
  1221. while (i < arraylen - 1) {
  1222. array[i] = array[i + 1];
  1223. i++;
  1224. }
  1225. arraylen--; /* delete elem from array */
  1226. if (tree->cmp)
  1227. ret = del234(tree, elem);
  1228. else
  1229. ret = delpos234(tree, index);
  1230. if (ret != elem) {
  1231. error("del returned %p, expected %p", ret, elem);
  1232. }
  1233. verify();
  1234. }
  1235. void deltest(void *elem)
  1236. {
  1237. int i;
  1238. i = 0;
  1239. while (i < arraylen && cmp(elem, array[i]) > 0)
  1240. i++;
  1241. if (i >= arraylen || cmp(elem, array[i]) != 0)
  1242. return; /* don't do it! */
  1243. delpostest(i);
  1244. }
  1245. /* A sample data set and test utility. Designed for pseudo-randomness,
  1246. * and yet repeatability. */
  1247. /*
  1248. * This random number generator uses the `portable implementation'
  1249. * given in ANSI C99 draft N869. It assumes `unsigned' is 32 bits;
  1250. * change it if not.
  1251. */
  1252. int randomnumber(unsigned *seed)
  1253. {
  1254. *seed *= 1103515245;
  1255. *seed += 12345;
  1256. return ((*seed) / 65536) % 32768;
  1257. }
  1258. int mycmp(void *av, void *bv)
  1259. {
  1260. char const *a = (char const *) av;
  1261. char const *b = (char const *) bv;
  1262. return strcmp(a, b);
  1263. }
  1264. #define lenof(x) ( sizeof((x)) / sizeof(*(x)) )
  1265. char *strings[] = {
  1266. "a", "ab", "absque", "coram", "de",
  1267. "palam", "clam", "cum", "ex", "e",
  1268. "sine", "tenus", "pro", "prae",
  1269. "banana", "carrot", "cabbage", "broccoli", "onion", "zebra",
  1270. "penguin", "blancmange", "pangolin", "whale", "hedgehog",
  1271. "giraffe", "peanut", "bungee", "foo", "bar", "baz", "quux",
  1272. "murfl", "spoo", "breen", "flarn", "octothorpe",
  1273. "snail", "tiger", "elephant", "octopus", "warthog", "armadillo",
  1274. "aardvark", "wyvern", "dragon", "elf", "dwarf", "orc", "goblin",
  1275. "pixie", "basilisk", "warg", "ape", "lizard", "newt", "shopkeeper",
  1276. "wand", "ring", "amulet"
  1277. };
  1278. #define NSTR lenof(strings)
  1279. int findtest(void)
  1280. {
  1281. const static int rels[] = {
  1282. REL234_EQ, REL234_GE, REL234_LE, REL234_LT, REL234_GT
  1283. };
  1284. const static char *const relnames[] = {
  1285. "EQ", "GE", "LE", "LT", "GT"
  1286. };
  1287. int i, j, rel, index;
  1288. char *p, *ret, *realret, *realret2;
  1289. int lo, hi, mid, c;
  1290. for (i = 0; i < NSTR; i++) {
  1291. p = strings[i];
  1292. for (j = 0; j < sizeof(rels) / sizeof(*rels); j++) {
  1293. rel = rels[j];
  1294. lo = 0;
  1295. hi = arraylen - 1;
  1296. while (lo <= hi) {
  1297. mid = (lo + hi) / 2;
  1298. c = strcmp(p, array[mid]);
  1299. if (c < 0)
  1300. hi = mid - 1;
  1301. else if (c > 0)
  1302. lo = mid + 1;
  1303. else
  1304. break;
  1305. }
  1306. if (c == 0) {
  1307. if (rel == REL234_LT)
  1308. ret = (mid > 0 ? array[--mid] : NULL);
  1309. else if (rel == REL234_GT)
  1310. ret = (mid < arraylen - 1 ? array[++mid] : NULL);
  1311. else
  1312. ret = array[mid];
  1313. } else {
  1314. assert(lo == hi + 1);
  1315. if (rel == REL234_LT || rel == REL234_LE) {
  1316. mid = hi;
  1317. ret = (hi >= 0 ? array[hi] : NULL);
  1318. } else if (rel == REL234_GT || rel == REL234_GE) {
  1319. mid = lo;
  1320. ret = (lo < arraylen ? array[lo] : NULL);
  1321. } else
  1322. ret = NULL;
  1323. }
  1324. realret = findrelpos234(tree, p, NULL, rel, &index);
  1325. if (realret != ret) {
  1326. error("find(\"%s\",%s) gave %s should be %s",
  1327. p, relnames[j], realret, ret);
  1328. }
  1329. if (realret && index != mid) {
  1330. error("find(\"%s\",%s) gave %d should be %d",
  1331. p, relnames[j], index, mid);
  1332. }
  1333. if (realret && rel == REL234_EQ) {
  1334. realret2 = index234(tree, index);
  1335. if (realret2 != realret) {
  1336. error("find(\"%s\",%s) gave %s(%d) but %d -> %s",
  1337. p, relnames[j], realret, index, index, realret2);
  1338. }
  1339. }
  1340. #if 0
  1341. printf("find(\"%s\",%s) gave %s(%d)\n", p, relnames[j],
  1342. realret, index);
  1343. #endif
  1344. }
  1345. }
  1346. realret = findrelpos234(tree, NULL, NULL, REL234_GT, &index);
  1347. if (arraylen && (realret != array[0] || index != 0)) {
  1348. error("find(NULL,GT) gave %s(%d) should be %s(0)",
  1349. realret, index, array[0]);
  1350. } else if (!arraylen && (realret != NULL)) {
  1351. error("find(NULL,GT) gave %s(%d) should be NULL", realret, index);
  1352. }
  1353. realret = findrelpos234(tree, NULL, NULL, REL234_LT, &index);
  1354. if (arraylen
  1355. && (realret != array[arraylen - 1] || index != arraylen - 1)) {
  1356. error("find(NULL,LT) gave %s(%d) should be %s(0)", realret, index,
  1357. array[arraylen - 1]);
  1358. } else if (!arraylen && (realret != NULL)) {
  1359. error("find(NULL,LT) gave %s(%d) should be NULL", realret, index);
  1360. }
  1361. }
  1362. void searchtest_recurse(search234_state ss, int lo, int hi,
  1363. char **expected, char *directionbuf,
  1364. char *directionptr)
  1365. {
  1366. *directionptr = '\0';
  1367. if (!ss.element) {
  1368. if (lo != hi) {
  1369. error("search234(%s) gave NULL for non-empty interval [%d,%d)",
  1370. directionbuf, lo, hi);
  1371. } else if (ss.index != lo) {
  1372. error("search234(%s) gave index %d should be %d",
  1373. directionbuf, ss.index, lo);
  1374. } else {
  1375. printf("%*ssearch234(%s) gave NULL,%d\n",
  1376. (int)(directionptr-directionbuf) * 2, "", directionbuf,
  1377. ss.index);
  1378. }
  1379. } else if (lo == hi) {
  1380. error("search234(%s) gave %s for empty interval [%d,%d)",
  1381. directionbuf, (char *)ss.element, lo, hi);
  1382. } else if (ss.element != expected[ss.index]) {
  1383. error("search234(%s) gave element %s should be %s",
  1384. directionbuf, (char *)ss.element, expected[ss.index]);
  1385. } else if (ss.index < lo || ss.index >= hi) {
  1386. error("search234(%s) gave index %d should be in [%d,%d)",
  1387. directionbuf, ss.index, lo, hi);
  1388. return;
  1389. } else {
  1390. search234_state next;
  1391. printf("%*ssearch234(%s) gave %s,%d\n",
  1392. (int)(directionptr-directionbuf) * 2, "", directionbuf,
  1393. (char *)ss.element, ss.index);
  1394. next = ss;
  1395. search234_step(&next, -1);
  1396. *directionptr = '-';
  1397. searchtest_recurse(next, lo, ss.index,
  1398. expected, directionbuf, directionptr+1);
  1399. next = ss;
  1400. search234_step(&next, +1);
  1401. *directionptr = '+';
  1402. searchtest_recurse(next, ss.index+1, hi,
  1403. expected, directionbuf, directionptr+1);
  1404. }
  1405. }
  1406. void searchtest(void)
  1407. {
  1408. char *expected[NSTR], *p;
  1409. char directionbuf[NSTR * 10];
  1410. int n;
  1411. search234_state ss;
  1412. printf("beginning searchtest:");
  1413. for (n = 0; (p = index234(tree, n)) != NULL; n++) {
  1414. expected[n] = p;
  1415. printf(" %d=%s", n, p);
  1416. }
  1417. printf(" count=%d\n", n);
  1418. search234_start(&ss, tree);
  1419. searchtest_recurse(ss, 0, n, expected, directionbuf, directionbuf);
  1420. }
  1421. int main(void)
  1422. {
  1423. int in[NSTR];
  1424. int i, j, k;
  1425. unsigned seed = 0;
  1426. for (i = 0; i < NSTR; i++)
  1427. in[i] = 0;
  1428. array = NULL;
  1429. arraylen = arraysize = 0;
  1430. tree = newtree234(mycmp);
  1431. cmp = mycmp;
  1432. verify();
  1433. searchtest();
  1434. for (i = 0; i < 10000; i++) {
  1435. j = randomnumber(&seed);
  1436. j %= NSTR;
  1437. printf("trial: %d\n", i);
  1438. if (in[j]) {
  1439. printf("deleting %s (%d)\n", strings[j], j);
  1440. deltest(strings[j]);
  1441. in[j] = 0;
  1442. } else {
  1443. printf("adding %s (%d)\n", strings[j], j);
  1444. addtest(strings[j]);
  1445. in[j] = 1;
  1446. }
  1447. findtest();
  1448. searchtest();
  1449. }
  1450. while (arraylen > 0) {
  1451. j = randomnumber(&seed);
  1452. j %= arraylen;
  1453. deltest(array[j]);
  1454. }
  1455. freetree234(tree);
  1456. /*
  1457. * Now try an unsorted tree. We don't really need to test
  1458. * delpos234 because we know del234 is based on it, so it's
  1459. * already been tested in the above sorted-tree code; but for
  1460. * completeness we'll use it to tear down our unsorted tree
  1461. * once we've built it.
  1462. */
  1463. tree = newtree234(NULL);
  1464. cmp = NULL;
  1465. verify();
  1466. for (i = 0; i < 1000; i++) {
  1467. printf("trial: %d\n", i);
  1468. j = randomnumber(&seed);
  1469. j %= NSTR;
  1470. k = randomnumber(&seed);
  1471. k %= count234(tree) + 1;
  1472. printf("adding string %s at index %d\n", strings[j], k);
  1473. addpostest(strings[j], k);
  1474. }
  1475. while (count234(tree) > 0) {
  1476. printf("cleanup: tree size %d\n", count234(tree));
  1477. j = randomnumber(&seed);
  1478. j %= count234(tree);
  1479. printf("deleting string %s from index %d\n",
  1480. (const char *)array[j], j);
  1481. delpostest(j);
  1482. }
  1483. printf("%d errors found\n", n_errors);
  1484. return (n_errors != 0);
  1485. }
  1486. #endif