tree234.c 45 KB

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