implemented Setup.hs to build boehm cpp libs and install them;
[hs-boehmgc.git] / gc-7.2 / cord / cordbscs.c
1 /*
2  * Copyright (c) 1993-1994 by Xerox Corporation.  All rights reserved.
3  *
4  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
5  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
6  *
7  * Permission is hereby granted to use or copy this program
8  * for any purpose,  provided the above notices are retained on all copies.
9  * Permission to modify the code and to distribute modified code is granted,
10  * provided the above notices are retained, and a notice that the code was
11  * modified is included with the above copyright notice.
12  *
13  * Author: Hans-J. Boehm (boehm@parc.xerox.com)
14  */
15 /* Boehm, October 3, 1994 5:19 pm PDT */
16 # include "gc.h"
17 # include "cord.h"
18 # include <stdlib.h>
19 # include <stdio.h>
20 # include <string.h>
21
22 /* An implementation of the cord primitives.  These are the only        */
23 /* Functions that understand the representation.  We perform only       */
24 /* minimal checks on arguments to these functions.  Out of bounds       */
25 /* arguments to the iteration functions may result in client functions  */
26 /* invoked on garbage data.  In most cases, client functions should be  */
27 /* programmed defensively enough that this does not result in memory    */
28 /* smashes.                                                             */
29
30 typedef void (* oom_fn)(void);
31
32 oom_fn CORD_oom_fn = (oom_fn) 0;
33
34 # define OUT_OF_MEMORY {  if (CORD_oom_fn != (oom_fn) 0) (*CORD_oom_fn)(); \
35                           ABORT("Out of memory\n"); }
36 # define ABORT(msg) { fprintf(stderr, "%s\n", msg); abort(); }
37
38 typedef unsigned long word;
39
40 typedef union {
41     struct Concatenation {
42         char null;
43         char header;
44         char depth;     /* concatenation nesting depth. */
45         unsigned char left_len;
46                         /* Length of left child if it is sufficiently   */
47                         /* short; 0 otherwise.                          */
48 #           define MAX_LEFT_LEN 255
49         word len;
50         CORD left;      /* length(left) > 0     */
51         CORD right;     /* length(right) > 0    */
52     } concatenation;
53     struct Function {
54         char null;
55         char header;
56         char depth;     /* always 0     */
57         char left_len;  /* always 0     */
58         word len;
59         CORD_fn fn;
60         void * client_data;
61     } function;
62     struct Generic {
63         char null;
64         char header;
65         char depth;
66         char left_len;
67         word len;
68     } generic;
69     char string[1];
70 } CordRep;
71
72 # define CONCAT_HDR 1
73
74 # define FN_HDR 4
75 # define SUBSTR_HDR 6
76         /* Substring nodes are a special case of function nodes.        */
77         /* The client_data field is known to point to a substr_args     */
78         /* structure, and the function is either CORD_apply_access_fn   */
79         /* or CORD_index_access_fn.                                     */
80
81 /* The following may be applied only to function and concatenation nodes: */
82 #define IS_CONCATENATION(s)  (((CordRep *)s)->generic.header == CONCAT_HDR)
83
84 #define IS_FUNCTION(s)  ((((CordRep *)s)->generic.header & FN_HDR) != 0)
85
86 #define IS_SUBSTR(s) (((CordRep *)s)->generic.header == SUBSTR_HDR)
87
88 #define LEN(s) (((CordRep *)s) -> generic.len)
89 #define DEPTH(s) (((CordRep *)s) -> generic.depth)
90 #define GEN_LEN(s) (CORD_IS_STRING(s) ? strlen(s) : LEN(s))
91
92 #define LEFT_LEN(c) ((c) -> left_len != 0? \
93                                 (c) -> left_len \
94                                 : (CORD_IS_STRING((c) -> left) ? \
95                                         (c) -> len - GEN_LEN((c) -> right) \
96                                         : LEN((c) -> left)))
97
98 #define SHORT_LIMIT (sizeof(CordRep) - 1)
99         /* Cords shorter than this are C strings */
100
101
102 /* Dump the internal representation of x to stdout, with initial        */
103 /* indentation level n.                                                 */
104 void CORD_dump_inner(CORD x, unsigned n)
105 {
106     register size_t i;
107
108     for (i = 0; i < (size_t)n; i++) {
109         fputs("  ", stdout);
110     }
111     if (x == 0) {
112         fputs("NIL\n", stdout);
113     } else if (CORD_IS_STRING(x)) {
114         for (i = 0; i <= SHORT_LIMIT; i++) {
115             if (x[i] == '\0') break;
116             putchar(x[i]);
117         }
118         if (x[i] != '\0') fputs("...", stdout);
119         putchar('\n');
120     } else if (IS_CONCATENATION(x)) {
121         register struct Concatenation * conc =
122                                 &(((CordRep *)x) -> concatenation);
123         printf("Concatenation: %p (len: %d, depth: %d)\n",
124                x, (int)(conc -> len), (int)(conc -> depth));
125         CORD_dump_inner(conc -> left, n+1);
126         CORD_dump_inner(conc -> right, n+1);
127     } else /* function */{
128         register struct Function * func =
129                                 &(((CordRep *)x) -> function);
130         if (IS_SUBSTR(x)) printf("(Substring) ");
131         printf("Function: %p (len: %d): ", x, (int)(func -> len));
132         for (i = 0; i < 20 && i < func -> len; i++) {
133             putchar((*(func -> fn))(i, func -> client_data));
134         }
135         if (i < func -> len) fputs("...", stdout);
136         putchar('\n');
137     }
138 }
139
140 /* Dump the internal representation of x to stdout      */
141 void CORD_dump(CORD x)
142 {
143     CORD_dump_inner(x, 0);
144     fflush(stdout);
145 }
146
147 CORD CORD_cat_char_star(CORD x, const char * y, size_t leny)
148 {
149     register size_t result_len;
150     register size_t lenx;
151     register int depth;
152
153     if (x == CORD_EMPTY) return(y);
154     if (leny == 0) return(x);
155     if (CORD_IS_STRING(x)) {
156         lenx = strlen(x);
157         result_len = lenx + leny;
158         if (result_len <= SHORT_LIMIT) {
159             register char * result = GC_MALLOC_ATOMIC(result_len+1);
160
161             if (result == 0) OUT_OF_MEMORY;
162             memcpy(result, x, lenx);
163             memcpy(result + lenx, y, leny);
164             result[result_len] = '\0';
165             return((CORD) result);
166         } else {
167             depth = 1;
168         }
169     } else {
170         register CORD right;
171         register CORD left;
172         register char * new_right;
173         register size_t right_len;
174
175         lenx = LEN(x);
176
177         if (leny <= SHORT_LIMIT/2
178             && IS_CONCATENATION(x)
179             && CORD_IS_STRING(right = ((CordRep *)x) -> concatenation.right)) {
180             /* Merge y into right part of x. */
181             if (!CORD_IS_STRING(left = ((CordRep *)x) -> concatenation.left)) {
182                 right_len = lenx - LEN(left);
183             } else if (((CordRep *)x) -> concatenation.left_len != 0) {
184                 right_len = lenx - ((CordRep *)x) -> concatenation.left_len;
185             } else {
186                 right_len = strlen(right);
187             }
188             result_len = right_len + leny;  /* length of new_right */
189             if (result_len <= SHORT_LIMIT) {
190                 new_right = GC_MALLOC_ATOMIC(result_len + 1);
191                 if (new_right == 0) OUT_OF_MEMORY;
192                 memcpy(new_right, right, right_len);
193                 memcpy(new_right + right_len, y, leny);
194                 new_right[result_len] = '\0';
195                 y = new_right;
196                 leny = result_len;
197                 x = left;
198                 lenx -= right_len;
199                 /* Now fall through to concatenate the two pieces: */
200             }
201             if (CORD_IS_STRING(x)) {
202                 depth = 1;
203             } else {
204                 depth = DEPTH(x) + 1;
205             }
206         } else {
207             depth = DEPTH(x) + 1;
208         }
209         result_len = lenx + leny;
210     }
211     {
212       /* The general case; lenx, result_len is known: */
213         register struct Concatenation * result;
214
215         result = GC_NEW(struct Concatenation);
216         if (result == 0) OUT_OF_MEMORY;
217         result->header = CONCAT_HDR;
218         result->depth = depth;
219         if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
220         result->len = result_len;
221         result->left = x;
222         result->right = y;
223         if (depth >= MAX_DEPTH) {
224             return(CORD_balance((CORD)result));
225         } else {
226             return((CORD) result);
227         }
228     }
229 }
230
231
232 CORD CORD_cat(CORD x, CORD y)
233 {
234     register size_t result_len;
235     register int depth;
236     register size_t lenx;
237
238     if (x == CORD_EMPTY) return(y);
239     if (y == CORD_EMPTY) return(x);
240     if (CORD_IS_STRING(y)) {
241         return(CORD_cat_char_star(x, y, strlen(y)));
242     } else if (CORD_IS_STRING(x)) {
243         lenx = strlen(x);
244         depth = DEPTH(y) + 1;
245     } else {
246         register int depthy = DEPTH(y);
247
248         lenx = LEN(x);
249         depth = DEPTH(x) + 1;
250         if (depthy >= depth) depth = depthy + 1;
251     }
252     result_len = lenx + LEN(y);
253     {
254         register struct Concatenation * result;
255
256         result = GC_NEW(struct Concatenation);
257         if (result == 0) OUT_OF_MEMORY;
258         result->header = CONCAT_HDR;
259         result->depth = depth;
260         if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
261         result->len = result_len;
262         result->left = x;
263         result->right = y;
264         if (depth >= MAX_DEPTH) {
265             return(CORD_balance((CORD)result));
266         } else {
267             return((CORD) result);
268         }
269     }
270 }
271
272
273
274 CORD CORD_from_fn(CORD_fn fn, void * client_data, size_t len)
275 {
276     if (len <= 0) return(0);
277     if (len <= SHORT_LIMIT) {
278         register char * result;
279         register size_t i;
280         char buf[SHORT_LIMIT+1];
281         register char c;
282
283         for (i = 0; i < len; i++) {
284             c = (*fn)(i, client_data);
285             if (c == '\0') goto gen_case;
286             buf[i] = c;
287         }
288         buf[i] = '\0';
289         result = GC_MALLOC_ATOMIC(len+1);
290         if (result == 0) OUT_OF_MEMORY;
291         strcpy(result, buf);
292         result[len] = '\0';
293         return((CORD) result);
294     }
295   gen_case:
296     {
297         register struct Function * result;
298
299         result = GC_NEW(struct Function);
300         if (result == 0) OUT_OF_MEMORY;
301         result->header = FN_HDR;
302         /* depth is already 0 */
303         result->len = len;
304         result->fn = fn;
305         result->client_data = client_data;
306         return((CORD) result);
307     }
308 }
309
310 size_t CORD_len(CORD x)
311 {
312     if (x == 0) {
313         return(0);
314     } else {
315         return(GEN_LEN(x));
316     }
317 }
318
319 struct substr_args {
320     CordRep * sa_cord;
321     size_t sa_index;
322 };
323
324 char CORD_index_access_fn(size_t i, void * client_data)
325 {
326     register struct substr_args *descr = (struct substr_args *)client_data;
327
328     return(((char *)(descr->sa_cord))[i + descr->sa_index]);
329 }
330
331 char CORD_apply_access_fn(size_t i, void * client_data)
332 {
333     register struct substr_args *descr = (struct substr_args *)client_data;
334     register struct Function * fn_cord = &(descr->sa_cord->function);
335
336     return((*(fn_cord->fn))(i + descr->sa_index, fn_cord->client_data));
337 }
338
339 /* A version of CORD_substr that simply returns a function node, thus   */
340 /* postponing its work. The fourth argument is a function that may      */
341 /* be used for efficient access to the ith character.                   */
342 /* Assumes i >= 0 and i + n < length(x).                                */
343 CORD CORD_substr_closure(CORD x, size_t i, size_t n, CORD_fn f)
344 {
345     register struct substr_args * sa = GC_NEW(struct substr_args);
346     CORD result;
347
348     if (sa == 0) OUT_OF_MEMORY;
349     sa->sa_cord = (CordRep *)x;
350     sa->sa_index = i;
351     result = CORD_from_fn(f, (void *)sa, n);
352     ((CordRep *)result) -> function.header = SUBSTR_HDR;
353     return (result);
354 }
355
356 # define SUBSTR_LIMIT (10 * SHORT_LIMIT)
357         /* Substrings of function nodes and flat strings shorter than   */
358         /* this are flat strings.  Othewise we use a functional         */
359         /* representation, which is significantly slower to access.     */
360
361 /* A version of CORD_substr that assumes i >= 0, n > 0, and i + n < length(x).*/
362 CORD CORD_substr_checked(CORD x, size_t i, size_t n)
363 {
364     if (CORD_IS_STRING(x)) {
365         if (n > SUBSTR_LIMIT) {
366             return(CORD_substr_closure(x, i, n, CORD_index_access_fn));
367         } else {
368             register char * result = GC_MALLOC_ATOMIC(n+1);
369
370             if (result == 0) OUT_OF_MEMORY;
371             strncpy(result, x+i, n);
372             result[n] = '\0';
373             return(result);
374         }
375     } else if (IS_CONCATENATION(x)) {
376         register struct Concatenation * conc
377                         = &(((CordRep *)x) -> concatenation);
378         register size_t left_len;
379         register size_t right_len;
380
381         left_len = LEFT_LEN(conc);
382         right_len = conc -> len - left_len;
383         if (i >= left_len) {
384             if (n == right_len) return(conc -> right);
385             return(CORD_substr_checked(conc -> right, i - left_len, n));
386         } else if (i+n <= left_len) {
387             if (n == left_len) return(conc -> left);
388             return(CORD_substr_checked(conc -> left, i, n));
389         } else {
390             /* Need at least one character from each side. */
391             register CORD left_part;
392             register CORD right_part;
393             register size_t left_part_len = left_len - i;
394
395             if (i == 0) {
396                 left_part = conc -> left;
397             } else {
398                 left_part = CORD_substr_checked(conc -> left, i, left_part_len);
399             }
400             if (i + n == right_len + left_len) {
401                  right_part = conc -> right;
402             } else {
403                  right_part = CORD_substr_checked(conc -> right, 0,
404                                                   n - left_part_len);
405             }
406             return(CORD_cat(left_part, right_part));
407         }
408     } else /* function */ {
409         if (n > SUBSTR_LIMIT) {
410             if (IS_SUBSTR(x)) {
411                 /* Avoid nesting substring nodes.       */
412                 register struct Function * f = &(((CordRep *)x) -> function);
413                 register struct substr_args *descr =
414                                 (struct substr_args *)(f -> client_data);
415
416                 return(CORD_substr_closure((CORD)descr->sa_cord,
417                                            i + descr->sa_index,
418                                            n, f -> fn));
419             } else {
420                 return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
421             }
422         } else {
423             char * result;
424             register struct Function * f = &(((CordRep *)x) -> function);
425             char buf[SUBSTR_LIMIT+1];
426             register char * p = buf;
427             register char c;
428             register int j;
429             register int lim = i + n;
430
431             for (j = i; j < lim; j++) {
432                 c = (*(f -> fn))(j, f -> client_data);
433                 if (c == '\0') {
434                     return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
435                 }
436                 *p++ = c;
437             }
438             *p = '\0';
439             result = GC_MALLOC_ATOMIC(n+1);
440             if (result == 0) OUT_OF_MEMORY;
441             strcpy(result, buf);
442             return(result);
443         }
444     }
445 }
446
447 CORD CORD_substr(CORD x, size_t i, size_t n)
448 {
449     register size_t len = CORD_len(x);
450
451     if (i >= len || n <= 0) return(0);
452         /* n < 0 is impossible in a correct C implementation, but       */
453         /* quite possible  under SunOS 4.X.                             */
454     if (i + n > len) n = len - i;
455 #   ifndef __STDC__
456       if (i < 0) ABORT("CORD_substr: second arg. negative");
457         /* Possible only if both client and C implementation are buggy. */
458         /* But empirically this happens frequently.                     */
459 #   endif
460     return(CORD_substr_checked(x, i, n));
461 }
462
463 /* See cord.h for definition.  We assume i is in range. */
464 int CORD_iter5(CORD x, size_t i, CORD_iter_fn f1,
465                          CORD_batched_iter_fn f2, void * client_data)
466 {
467     if (x == 0) return(0);
468     if (CORD_IS_STRING(x)) {
469         register const char *p = x+i;
470
471         if (*p == '\0') ABORT("2nd arg to CORD_iter5 too big");
472         if (f2 != CORD_NO_FN) {
473             return((*f2)(p, client_data));
474         } else {
475             while (*p) {
476                 if ((*f1)(*p, client_data)) return(1);
477                 p++;
478             }
479             return(0);
480         }
481     } else if (IS_CONCATENATION(x)) {
482         register struct Concatenation * conc
483                         = &(((CordRep *)x) -> concatenation);
484
485
486         if (i > 0) {
487             register size_t left_len = LEFT_LEN(conc);
488
489             if (i >= left_len) {
490                 return(CORD_iter5(conc -> right, i - left_len, f1, f2,
491                                   client_data));
492             }
493         }
494         if (CORD_iter5(conc -> left, i, f1, f2, client_data)) {
495             return(1);
496         }
497         return(CORD_iter5(conc -> right, 0, f1, f2, client_data));
498     } else /* function */ {
499         register struct Function * f = &(((CordRep *)x) -> function);
500         register size_t j;
501         register size_t lim = f -> len;
502
503         for (j = i; j < lim; j++) {
504             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
505                 return(1);
506             }
507         }
508         return(0);
509     }
510 }
511
512 #undef CORD_iter
513 int CORD_iter(CORD x, CORD_iter_fn f1, void * client_data)
514 {
515     return(CORD_iter5(x, 0, f1, CORD_NO_FN, client_data));
516 }
517
518 int CORD_riter4(CORD x, size_t i, CORD_iter_fn f1, void * client_data)
519 {
520     if (x == 0) return(0);
521     if (CORD_IS_STRING(x)) {
522         register const char *p = x + i;
523         register char c;
524
525         for(;;) {
526             c = *p;
527             if (c == '\0') ABORT("2nd arg to CORD_riter4 too big");
528             if ((*f1)(c, client_data)) return(1);
529             if (p == x) break;
530             p--;
531         }
532         return(0);
533     } else if (IS_CONCATENATION(x)) {
534         register struct Concatenation * conc
535                         = &(((CordRep *)x) -> concatenation);
536         register CORD left_part = conc -> left;
537         register size_t left_len;
538
539         left_len = LEFT_LEN(conc);
540         if (i >= left_len) {
541             if (CORD_riter4(conc -> right, i - left_len, f1, client_data)) {
542                 return(1);
543             }
544             return(CORD_riter4(left_part, left_len - 1, f1, client_data));
545         } else {
546             return(CORD_riter4(left_part, i, f1, client_data));
547         }
548     } else /* function */ {
549         register struct Function * f = &(((CordRep *)x) -> function);
550         register size_t j;
551
552         for (j = i; ; j--) {
553             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
554                 return(1);
555             }
556             if (j == 0) return(0);
557         }
558     }
559 }
560
561 int CORD_riter(CORD x, CORD_iter_fn f1, void * client_data)
562 {
563     size_t len = CORD_len(x);
564     if (len == 0) return(0);
565     return(CORD_riter4(x, len - 1, f1, client_data));
566 }
567
568 /*
569  * The following functions are concerned with balancing cords.
570  * Strategy:
571  * Scan the cord from left to right, keeping the cord scanned so far
572  * as a forest of balanced trees of exponentialy decreasing length.
573  * When a new subtree needs to be added to the forest, we concatenate all
574  * shorter ones to the new tree in the appropriate order, and then insert
575  * the result into the forest.
576  * Crucial invariants:
577  * 1. The concatenation of the forest (in decreasing order) with the
578  *     unscanned part of the rope is equal to the rope being balanced.
579  * 2. All trees in the forest are balanced.
580  * 3. forest[i] has depth at most i.
581  */
582
583 typedef struct {
584     CORD c;
585     size_t len;         /* Actual length of c   */
586 } ForestElement;
587
588 static size_t min_len [ MAX_DEPTH ];
589
590 static int min_len_init = 0;
591
592 int CORD_max_len;
593
594 typedef ForestElement Forest [ MAX_DEPTH ];
595                         /* forest[i].len >= fib(i+1)            */
596                         /* The string is the concatenation      */
597                         /* of the forest in order of DECREASING */
598                         /* indices.                             */
599
600 void CORD_init_min_len()
601 {
602     register int i;
603     register size_t last, previous, current;
604
605     min_len[0] = previous = 1;
606     min_len[1] = last = 2;
607     for (i = 2; i < MAX_DEPTH; i++) {
608         current = last + previous;
609         if (current < last) /* overflow */ current = last;
610         min_len[i] = current;
611         previous = last;
612         last = current;
613     }
614     CORD_max_len = last - 1;
615     min_len_init = 1;
616 }
617
618
619 void CORD_init_forest(ForestElement * forest, size_t max_len)
620 {
621     register int i;
622
623     for (i = 0; i < MAX_DEPTH; i++) {
624         forest[i].c = 0;
625         if (min_len[i] > max_len) return;
626     }
627     ABORT("Cord too long");
628 }
629
630 /* Add a leaf to the appropriate level in the forest, cleaning          */
631 /* out lower levels as necessary.                                       */
632 /* Also works if x is a balanced tree of concatenations; however        */
633 /* in this case an extra concatenation node may be inserted above x;    */
634 /* This node should not be counted in the statement of the invariants.  */
635 void CORD_add_forest(ForestElement * forest, CORD x, size_t len)
636 {
637     register int i = 0;
638     register CORD sum = CORD_EMPTY;
639     register size_t sum_len = 0;
640
641     while (len > min_len[i + 1]) {
642         if (forest[i].c != 0) {
643             sum = CORD_cat(forest[i].c, sum);
644             sum_len += forest[i].len;
645             forest[i].c = 0;
646         }
647         i++;
648     }
649     /* Sum has depth at most 1 greter than what would be required       */
650     /* for balance.                                                     */
651     sum = CORD_cat(sum, x);
652     sum_len += len;
653     /* If x was a leaf, then sum is now balanced.  To see this          */
654     /* consider the two cases in which forest[i-1] either is or is      */
655     /* not empty.                                                       */
656     while (sum_len >= min_len[i]) {
657         if (forest[i].c != 0) {
658             sum = CORD_cat(forest[i].c, sum);
659             sum_len += forest[i].len;
660             /* This is again balanced, since sum was balanced, and has  */
661             /* allowable depth that differs from i by at most 1.        */
662             forest[i].c = 0;
663         }
664         i++;
665     }
666     i--;
667     forest[i].c = sum;
668     forest[i].len = sum_len;
669 }
670
671 CORD CORD_concat_forest(ForestElement * forest, size_t expected_len)
672 {
673     register int i = 0;
674     CORD sum = 0;
675     size_t sum_len = 0;
676
677     while (sum_len != expected_len) {
678         if (forest[i].c != 0) {
679             sum = CORD_cat(forest[i].c, sum);
680             sum_len += forest[i].len;
681         }
682         i++;
683     }
684     return(sum);
685 }
686
687 /* Insert the frontier of x into forest.  Balanced subtrees are */
688 /* treated as leaves.  This potentially adds one to the depth   */
689 /* of the final tree.                                           */
690 void CORD_balance_insert(CORD x, size_t len, ForestElement * forest)
691 {
692     register int depth;
693
694     if (CORD_IS_STRING(x)) {
695         CORD_add_forest(forest, x, len);
696     } else if (IS_CONCATENATION(x)
697                && ((depth = DEPTH(x)) >= MAX_DEPTH
698                    || len < min_len[depth])) {
699         register struct Concatenation * conc
700                         = &(((CordRep *)x) -> concatenation);
701         size_t left_len = LEFT_LEN(conc);
702
703         CORD_balance_insert(conc -> left, left_len, forest);
704         CORD_balance_insert(conc -> right, len - left_len, forest);
705     } else /* function or balanced */ {
706         CORD_add_forest(forest, x, len);
707     }
708 }
709
710
711 CORD CORD_balance(CORD x)
712 {
713     Forest forest;
714     register size_t len;
715
716     if (x == 0) return(0);
717     if (CORD_IS_STRING(x)) return(x);
718     if (!min_len_init) CORD_init_min_len();
719     len = LEN(x);
720     CORD_init_forest(forest, len);
721     CORD_balance_insert(x, len, forest);
722     return(CORD_concat_forest(forest, len));
723 }
724
725
726 /* Position primitives  */
727
728 /* Private routines to deal with the hard cases only: */
729
730 /* P contains a prefix of the  path to cur_pos. Extend it to a full     */
731 /* path and set up leaf info.                                           */
732 /* Return 0 if past the end of cord, 1 o.w.                             */
733 void CORD__extend_path(register CORD_pos p)
734 {
735      register struct CORD_pe * current_pe = &(p[0].path[p[0].path_len]);
736      register CORD top = current_pe -> pe_cord;
737      register size_t pos = p[0].cur_pos;
738      register size_t top_pos = current_pe -> pe_start_pos;
739      register size_t top_len = GEN_LEN(top);
740
741      /* Fill in the rest of the path. */
742        while(!CORD_IS_STRING(top) && IS_CONCATENATION(top)) {
743          register struct Concatenation * conc =
744                         &(((CordRep *)top) -> concatenation);
745          register size_t left_len;
746
747          left_len = LEFT_LEN(conc);
748          current_pe++;
749          if (pos >= top_pos + left_len) {
750              current_pe -> pe_cord = top = conc -> right;
751              current_pe -> pe_start_pos = top_pos = top_pos + left_len;
752              top_len -= left_len;
753          } else {
754              current_pe -> pe_cord = top = conc -> left;
755              current_pe -> pe_start_pos = top_pos;
756              top_len = left_len;
757          }
758          p[0].path_len++;
759        }
760      /* Fill in leaf description for fast access. */
761        if (CORD_IS_STRING(top)) {
762          p[0].cur_leaf = top;
763          p[0].cur_start = top_pos;
764          p[0].cur_end = top_pos + top_len;
765        } else {
766          p[0].cur_end = 0;
767        }
768        if (pos >= top_pos + top_len) p[0].path_len = CORD_POS_INVALID;
769 }
770
771 char CORD__pos_fetch(register CORD_pos p)
772 {
773     /* Leaf is a function node */
774     struct CORD_pe * pe = &((p)[0].path[(p)[0].path_len]);
775     CORD leaf = pe -> pe_cord;
776     register struct Function * f = &(((CordRep *)leaf) -> function);
777
778     if (!IS_FUNCTION(leaf)) ABORT("CORD_pos_fetch: bad leaf");
779     return ((*(f -> fn))(p[0].cur_pos - pe -> pe_start_pos, f -> client_data));
780 }
781
782 void CORD__next(register CORD_pos p)
783 {
784     register size_t cur_pos = p[0].cur_pos + 1;
785     register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
786     register CORD leaf = current_pe -> pe_cord;
787
788     /* Leaf is not a string or we're at end of leaf */
789     p[0].cur_pos = cur_pos;
790     if (!CORD_IS_STRING(leaf)) {
791         /* Function leaf        */
792         register struct Function * f = &(((CordRep *)leaf) -> function);
793         register size_t start_pos = current_pe -> pe_start_pos;
794         register size_t end_pos = start_pos + f -> len;
795
796         if (cur_pos < end_pos) {
797           /* Fill cache and return. */
798             register size_t i;
799             register size_t limit = cur_pos + FUNCTION_BUF_SZ;
800             register CORD_fn fn = f -> fn;
801             register void * client_data = f -> client_data;
802
803             if (limit > end_pos) {
804                 limit = end_pos;
805             }
806             for (i = cur_pos; i < limit; i++) {
807                 p[0].function_buf[i - cur_pos] =
808                         (*fn)(i - start_pos, client_data);
809             }
810             p[0].cur_start = cur_pos;
811             p[0].cur_leaf = p[0].function_buf;
812             p[0].cur_end = limit;
813             return;
814         }
815     }
816     /* End of leaf      */
817     /* Pop the stack until we find two concatenation nodes with the     */
818     /* same start position: this implies we were in left part.          */
819     {
820         while (p[0].path_len > 0
821                && current_pe[0].pe_start_pos != current_pe[-1].pe_start_pos) {
822             p[0].path_len--;
823             current_pe--;
824         }
825         if (p[0].path_len == 0) {
826             p[0].path_len = CORD_POS_INVALID;
827             return;
828         }
829     }
830     p[0].path_len--;
831     CORD__extend_path(p);
832 }
833
834 void CORD__prev(register CORD_pos p)
835 {
836     register struct CORD_pe * pe = &(p[0].path[p[0].path_len]);
837
838     if (p[0].cur_pos == 0) {
839         p[0].path_len = CORD_POS_INVALID;
840         return;
841     }
842     p[0].cur_pos--;
843     if (p[0].cur_pos >= pe -> pe_start_pos) return;
844
845     /* Beginning of leaf        */
846
847     /* Pop the stack until we find two concatenation nodes with the     */
848     /* different start position: this implies we were in right part.    */
849     {
850         register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
851
852         while (p[0].path_len > 0
853                && current_pe[0].pe_start_pos == current_pe[-1].pe_start_pos) {
854             p[0].path_len--;
855             current_pe--;
856         }
857     }
858     p[0].path_len--;
859     CORD__extend_path(p);
860 }
861
862 #undef CORD_pos_fetch
863 #undef CORD_next
864 #undef CORD_prev
865 #undef CORD_pos_to_index
866 #undef CORD_pos_to_cord
867 #undef CORD_pos_valid
868
869 char CORD_pos_fetch(register CORD_pos p)
870 {
871     if (p[0].cur_start <= p[0].cur_pos && p[0].cur_pos < p[0].cur_end) {
872         return(p[0].cur_leaf[p[0].cur_pos - p[0].cur_start]);
873     } else {
874         return(CORD__pos_fetch(p));
875     }
876 }
877
878 void CORD_next(CORD_pos p)
879 {
880     if (p[0].cur_pos < p[0].cur_end - 1) {
881         p[0].cur_pos++;
882     } else {
883         CORD__next(p);
884     }
885 }
886
887 void CORD_prev(CORD_pos p)
888 {
889     if (p[0].cur_end != 0 && p[0].cur_pos > p[0].cur_start) {
890         p[0].cur_pos--;
891     } else {
892         CORD__prev(p);
893     }
894 }
895
896 size_t CORD_pos_to_index(CORD_pos p)
897 {
898     return(p[0].cur_pos);
899 }
900
901 CORD CORD_pos_to_cord(CORD_pos p)
902 {
903     return(p[0].path[0].pe_cord);
904 }
905
906 int CORD_pos_valid(CORD_pos p)
907 {
908     return(p[0].path_len != CORD_POS_INVALID);
909 }
910
911 void CORD_set_pos(CORD_pos p, CORD x, size_t i)
912 {
913     if (x == CORD_EMPTY) {
914         p[0].path_len = CORD_POS_INVALID;
915         return;
916     }
917     p[0].path[0].pe_cord = x;
918     p[0].path[0].pe_start_pos = 0;
919     p[0].path_len = 0;
920     p[0].cur_pos = i;
921     CORD__extend_path(p);
922 }