Back to index

plt-scheme  4.2.1
cordbscs.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 1993-1994 by Xerox Corporation.  All rights reserved.
00003  *
00004  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
00005  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
00006  *
00007  * Permission is hereby granted to use or copy this program
00008  * for any purpose,  provided the above notices are retained on all copies.
00009  * Permission to modify the code and to distribute modified code is granted,
00010  * provided the above notices are retained, and a notice that the code was
00011  * modified is included with the above copyright notice.
00012  *
00013  * Author: Hans-J. Boehm (boehm@parc.xerox.com)
00014  */
00015 /* Boehm, October 3, 1994 5:19 pm PDT */
00016 # include "gc.h"
00017 # include "cord.h"
00018 # include <stdlib.h>
00019 # include <stdio.h>
00020 # include <string.h>
00021 
00022 /* An implementation of the cord primitives.  These are the only      */
00023 /* Functions that understand the representation.  We perform only     */
00024 /* minimal checks on arguments to these functions.  Out of bounds     */
00025 /* arguments to the iteration functions may result in client functions       */
00026 /* invoked on garbage data.  In most cases, client functions should be       */
00027 /* programmed defensively enough that this does not result in memory  */
00028 /* smashes.                                                    */ 
00029 
00030 typedef void (* oom_fn)(void);
00031 
00032 oom_fn CORD_oom_fn = (oom_fn) 0;
00033 
00034 # define OUT_OF_MEMORY {  if (CORD_oom_fn != (oom_fn) 0) (*CORD_oom_fn)(); \
00035                        ABORT("Out of memory\n"); }
00036 # define ABORT(msg) { fprintf(stderr, "%s\n", msg); abort(); }
00037 
00038 typedef unsigned long word;
00039 
00040 typedef union {
00041     struct Concatenation {
00042        char null;
00043        char header;
00044        char depth;   /* concatenation nesting depth. */
00045        unsigned char left_len;
00046                      /* Length of left child if it is sufficiently    */
00047                      /* short; 0 otherwise.                           */
00048 #          define MAX_LEFT_LEN 255
00049        word len;
00050        CORD left;    /* length(left) > 0  */
00051        CORD right;   /* length(right) > 0 */
00052     } concatenation;
00053     struct Function {
00054        char null;
00055        char header;
00056        char depth;   /* always 0   */
00057        char left_len;       /* always 0   */
00058        word len;
00059        CORD_fn fn;
00060        void * client_data;
00061     } function;
00062     struct Generic {
00063        char null;
00064        char header;
00065        char depth;
00066        char left_len;
00067        word len;
00068     } generic;
00069     char string[1];
00070 } CordRep;
00071 
00072 # define CONCAT_HDR 1
00073        
00074 # define FN_HDR 4
00075 # define SUBSTR_HDR 6
00076        /* Substring nodes are a special case of function nodes.       */
00077        /* The client_data field is known to point to a substr_args    */
00078        /* structure, and the function is either CORD_apply_access_fn  */
00079        /* or CORD_index_access_fn.                             */
00080 
00081 /* The following may be applied only to function and concatenation nodes: */
00082 #define IS_CONCATENATION(s)  (((CordRep *)s)->generic.header == CONCAT_HDR)
00083 
00084 #define IS_FUNCTION(s)  ((((CordRep *)s)->generic.header & FN_HDR) != 0)
00085 
00086 #define IS_SUBSTR(s) (((CordRep *)s)->generic.header == SUBSTR_HDR)
00087 
00088 #define LEN(s) (((CordRep *)s) -> generic.len)
00089 #define DEPTH(s) (((CordRep *)s) -> generic.depth)
00090 #define GEN_LEN(s) (CORD_IS_STRING(s) ? strlen(s) : LEN(s))
00091 
00092 #define LEFT_LEN(c) ((c) -> left_len != 0? \
00093                             (c) -> left_len \
00094                             : (CORD_IS_STRING((c) -> left) ? \
00095                                    (c) -> len - GEN_LEN((c) -> right) \
00096                                    : LEN((c) -> left)))
00097 
00098 #define SHORT_LIMIT (sizeof(CordRep) - 1)
00099        /* Cords shorter than this are C strings */
00100 
00101 
00102 /* Dump the internal representation of x to stdout, with initial      */
00103 /* indentation level n.                                               */
00104 void CORD_dump_inner(CORD x, unsigned n)
00105 {
00106     register size_t i;
00107     
00108     for (i = 0; i < (size_t)n; i++) {
00109         fputs("  ", stdout);
00110     }
00111     if (x == 0) {
00112        fputs("NIL\n", stdout);
00113     } else if (CORD_IS_STRING(x)) {
00114         for (i = 0; i <= SHORT_LIMIT; i++) {
00115             if (x[i] == '\0') break;
00116             putchar(x[i]);
00117         }
00118         if (x[i] != '\0') fputs("...", stdout);
00119         putchar('\n');
00120     } else if (IS_CONCATENATION(x)) {
00121         register struct Concatenation * conc =
00122                             &(((CordRep *)x) -> concatenation);
00123         printf("Concatenation: %p (len: %d, depth: %d)\n",
00124                x, (int)(conc -> len), (int)(conc -> depth));
00125         CORD_dump_inner(conc -> left, n+1);
00126         CORD_dump_inner(conc -> right, n+1);
00127     } else /* function */{
00128         register struct Function * func =
00129                             &(((CordRep *)x) -> function);
00130         if (IS_SUBSTR(x)) printf("(Substring) ");
00131         printf("Function: %p (len: %d): ", x, (int)(func -> len));
00132         for (i = 0; i < 20 && i < func -> len; i++) {
00133             putchar((*(func -> fn))(i, func -> client_data));
00134         }
00135         if (i < func -> len) fputs("...", stdout);
00136         putchar('\n');
00137     }
00138 }
00139 
00140 /* Dump the internal representation of x to stdout      */
00141 void CORD_dump(CORD x)
00142 {
00143     CORD_dump_inner(x, 0);
00144     fflush(stdout);
00145 }
00146 
00147 CORD CORD_cat_char_star(CORD x, const char * y, size_t leny)
00148 {
00149     register size_t result_len;
00150     register size_t lenx;
00151     register int depth;
00152     
00153     if (x == CORD_EMPTY) return(y);
00154     if (leny == 0) return(x);
00155     if (CORD_IS_STRING(x)) {
00156         lenx = strlen(x);
00157         result_len = lenx + leny;
00158         if (result_len <= SHORT_LIMIT) {
00159             register char * result = GC_MALLOC_ATOMIC(result_len+1);
00160         
00161             if (result == 0) OUT_OF_MEMORY;
00162             memcpy(result, x, lenx);
00163             memcpy(result + lenx, y, leny);
00164             result[result_len] = '\0';
00165             return((CORD) result);
00166         } else {
00167             depth = 1;
00168         }
00169     } else {
00170        register CORD right;
00171        register CORD left;
00172        register char * new_right;
00173        register size_t right_len;
00174        
00175        lenx = LEN(x);
00176        
00177         if (leny <= SHORT_LIMIT/2
00178            && IS_CONCATENATION(x)
00179             && CORD_IS_STRING(right = ((CordRep *)x) -> concatenation.right)) {
00180             /* Merge y into right part of x. */
00181             if (!CORD_IS_STRING(left = ((CordRep *)x) -> concatenation.left)) {
00182               right_len = lenx - LEN(left);
00183             } else if (((CordRep *)x) -> concatenation.left_len != 0) {
00184                 right_len = lenx - ((CordRep *)x) -> concatenation.left_len;
00185             } else {
00186               right_len = strlen(right);
00187             }
00188             result_len = right_len + leny;  /* length of new_right */
00189             if (result_len <= SHORT_LIMIT) {
00190               new_right = GC_MALLOC_ATOMIC(result_len + 1);
00191               memcpy(new_right, right, right_len);
00192               memcpy(new_right + right_len, y, leny);
00193               new_right[result_len] = '\0';
00194               y = new_right;
00195               leny = result_len;
00196               x = left;
00197               lenx -= right_len;
00198               /* Now fall through to concatenate the two pieces: */
00199             }
00200             if (CORD_IS_STRING(x)) {
00201                 depth = 1;
00202             } else {
00203                 depth = DEPTH(x) + 1;
00204             }
00205         } else {
00206             depth = DEPTH(x) + 1;
00207         }
00208         result_len = lenx + leny;
00209     }
00210     {
00211       /* The general case; lenx, result_len is known: */
00212        register struct Concatenation * result;
00213        
00214        result = GC_NEW(struct Concatenation);
00215        if (result == 0) OUT_OF_MEMORY;
00216        result->header = CONCAT_HDR;
00217        result->depth = depth;
00218        if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
00219        result->len = result_len;
00220        result->left = x;
00221        result->right = y;
00222        if (depth >= MAX_DEPTH) {
00223            return(CORD_balance((CORD)result));
00224        } else {
00225            return((CORD) result);
00226        }
00227     }
00228 }
00229 
00230 
00231 CORD CORD_cat(CORD x, CORD y)
00232 {
00233     register size_t result_len;
00234     register int depth;
00235     register size_t lenx;
00236     
00237     if (x == CORD_EMPTY) return(y);
00238     if (y == CORD_EMPTY) return(x);
00239     if (CORD_IS_STRING(y)) {
00240         return(CORD_cat_char_star(x, y, strlen(y)));
00241     } else if (CORD_IS_STRING(x)) {
00242         lenx = strlen(x);
00243         depth = DEPTH(y) + 1;
00244     } else {
00245         register int depthy = DEPTH(y);
00246         
00247         lenx = LEN(x);
00248         depth = DEPTH(x) + 1;
00249         if (depthy >= depth) depth = depthy + 1;
00250     }
00251     result_len = lenx + LEN(y);
00252     {
00253        register struct Concatenation * result;
00254        
00255        result = GC_NEW(struct Concatenation);
00256        if (result == 0) OUT_OF_MEMORY;
00257        result->header = CONCAT_HDR;
00258        result->depth = depth;
00259        if (lenx <= MAX_LEFT_LEN) result->left_len = lenx;
00260        result->len = result_len;
00261        result->left = x;
00262        result->right = y;
00263        if (depth >= MAX_DEPTH) {
00264            return(CORD_balance((CORD)result));
00265        } else {
00266            return((CORD) result);
00267        }
00268     }
00269 }
00270 
00271 
00272 
00273 CORD CORD_from_fn(CORD_fn fn, void * client_data, size_t len)
00274 {
00275     if (len <= 0) return(0);
00276     if (len <= SHORT_LIMIT) {
00277         register char * result;
00278         register size_t i;
00279         char buf[SHORT_LIMIT+1];
00280         register char c;
00281         
00282         for (i = 0; i < len; i++) {
00283             c = (*fn)(i, client_data);
00284             if (c == '\0') goto gen_case;
00285             buf[i] = c;
00286         }
00287         buf[i] = '\0';
00288         result = GC_MALLOC_ATOMIC(len+1);
00289         if (result == 0) OUT_OF_MEMORY;
00290         strcpy(result, buf);
00291         result[len] = '\0';
00292         return((CORD) result);
00293     }
00294   gen_case:
00295     {
00296        register struct Function * result;
00297        
00298        result = GC_NEW(struct Function);
00299        if (result == 0) OUT_OF_MEMORY;
00300        result->header = FN_HDR;
00301        /* depth is already 0 */
00302        result->len = len;
00303        result->fn = fn;
00304        result->client_data = client_data;
00305        return((CORD) result);
00306     }
00307 }
00308 
00309 size_t CORD_len(CORD x)
00310 {
00311     if (x == 0) {
00312        return(0);
00313     } else {
00314        return(GEN_LEN(x));
00315     }
00316 }
00317 
00318 struct substr_args {
00319     CordRep * sa_cord;
00320     size_t sa_index;
00321 };
00322 
00323 char CORD_index_access_fn(size_t i, void * client_data)
00324 {
00325     register struct substr_args *descr = (struct substr_args *)client_data;
00326     
00327     return(((char *)(descr->sa_cord))[i + descr->sa_index]);
00328 }
00329 
00330 char CORD_apply_access_fn(size_t i, void * client_data)
00331 {
00332     register struct substr_args *descr = (struct substr_args *)client_data;
00333     register struct Function * fn_cord = &(descr->sa_cord->function);
00334     
00335     return((*(fn_cord->fn))(i + descr->sa_index, fn_cord->client_data));
00336 }
00337 
00338 /* A version of CORD_substr that simply returns a function node, thus */
00339 /* postponing its work.     The fourth argument is a function that may       */
00340 /* be used for efficient access to the ith character.                 */
00341 /* Assumes i >= 0 and i + n < length(x).                       */
00342 CORD CORD_substr_closure(CORD x, size_t i, size_t n, CORD_fn f)
00343 {
00344     register struct substr_args * sa = GC_NEW(struct substr_args);
00345     CORD result;
00346     
00347     if (sa == 0) OUT_OF_MEMORY;
00348     sa->sa_cord = (CordRep *)x;
00349     sa->sa_index = i;
00350     result = CORD_from_fn(f, (void *)sa, n);
00351     ((CordRep *)result) -> function.header = SUBSTR_HDR;
00352     return (result);
00353 }
00354 
00355 # define SUBSTR_LIMIT (10 * SHORT_LIMIT)
00356        /* Substrings of function nodes and flat strings shorter than  */
00357        /* this are flat strings.  Othewise we use a functional        */
00358        /* representation, which is significantly slower to access.    */
00359 
00360 /* A version of CORD_substr that assumes i >= 0, n > 0, and i + n < length(x).*/
00361 CORD CORD_substr_checked(CORD x, size_t i, size_t n)
00362 {
00363     if (CORD_IS_STRING(x)) {
00364         if (n > SUBSTR_LIMIT) {
00365             return(CORD_substr_closure(x, i, n, CORD_index_access_fn));
00366         } else {
00367             register char * result = GC_MALLOC_ATOMIC(n+1);
00368             
00369             if (result == 0) OUT_OF_MEMORY;
00370             strncpy(result, x+i, n);
00371             result[n] = '\0';
00372             return(result);
00373         }
00374     } else if (IS_CONCATENATION(x)) {
00375        register struct Concatenation * conc
00376                      = &(((CordRep *)x) -> concatenation);
00377        register size_t left_len;
00378        register size_t right_len;
00379        
00380        left_len = LEFT_LEN(conc);
00381        right_len = conc -> len - left_len;
00382        if (i >= left_len) {
00383            if (n == right_len) return(conc -> right);
00384            return(CORD_substr_checked(conc -> right, i - left_len, n));
00385        } else if (i+n <= left_len) {
00386            if (n == left_len) return(conc -> left);
00387            return(CORD_substr_checked(conc -> left, i, n));
00388        } else {
00389            /* Need at least one character from each side. */
00390            register CORD left_part;
00391            register CORD right_part;
00392            register size_t left_part_len = left_len - i;
00393        
00394            if (i == 0) {
00395                left_part = conc -> left;
00396            } else {
00397                left_part = CORD_substr_checked(conc -> left, i, left_part_len);
00398            }
00399            if (i + n == right_len + left_len) {
00400                 right_part = conc -> right;
00401            } else {
00402                 right_part = CORD_substr_checked(conc -> right, 0,
00403                                              n - left_part_len);
00404            }
00405            return(CORD_cat(left_part, right_part));
00406        }
00407     } else /* function */ {
00408         if (n > SUBSTR_LIMIT) {
00409             if (IS_SUBSTR(x)) {
00410               /* Avoid nesting substring nodes.  */
00411               register struct Function * f = &(((CordRep *)x) -> function);
00412               register struct substr_args *descr =
00413                             (struct substr_args *)(f -> client_data);
00414               
00415               return(CORD_substr_closure((CORD)descr->sa_cord,
00416                                       i + descr->sa_index,
00417                                       n, f -> fn));
00418             } else {
00419                 return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
00420             }
00421         } else {
00422             char * result;
00423             register struct Function * f = &(((CordRep *)x) -> function);
00424             char buf[SUBSTR_LIMIT+1];
00425             register char * p = buf;
00426             register char c;
00427             register int j;
00428             register int lim = i + n;
00429             
00430             for (j = i; j < lim; j++) {
00431               c = (*(f -> fn))(j, f -> client_data);
00432               if (c == '\0') {
00433                   return(CORD_substr_closure(x, i, n, CORD_apply_access_fn));
00434               }
00435               *p++ = c;
00436             }
00437             *p = '\0';
00438             result = GC_MALLOC_ATOMIC(n+1);
00439             if (result == 0) OUT_OF_MEMORY;
00440             strcpy(result, buf);
00441             return(result);
00442         }
00443     }
00444 }
00445 
00446 CORD CORD_substr(CORD x, size_t i, size_t n)
00447 {
00448     register size_t len = CORD_len(x);
00449     
00450     if (i >= len || n <= 0) return(0);
00451        /* n < 0 is impossible in a correct C implementation, but      */
00452        /* quite possible  under SunOS 4.X.                            */
00453     if (i + n > len) n = len - i;
00454 #   ifndef __STDC__
00455       if (i < 0) ABORT("CORD_substr: second arg. negative");
00456        /* Possible only if both client and C implementation are buggy.       */
00457        /* But empirically this happens frequently.                    */
00458 #   endif
00459     return(CORD_substr_checked(x, i, n));
00460 }
00461 
00462 /* See cord.h for definition.  We assume i is in range. */
00463 int CORD_iter5(CORD x, size_t i, CORD_iter_fn f1,
00464                       CORD_batched_iter_fn f2, void * client_data)
00465 {
00466     if (x == 0) return(0);
00467     if (CORD_IS_STRING(x)) {
00468        register const char *p = x+i;
00469        
00470        if (*p == '\0') ABORT("2nd arg to CORD_iter5 too big");
00471         if (f2 != CORD_NO_FN) {
00472             return((*f2)(p, client_data));
00473         } else {
00474            while (*p) {
00475                 if ((*f1)(*p, client_data)) return(1);
00476                 p++;
00477            }
00478            return(0);
00479         }
00480     } else if (IS_CONCATENATION(x)) {
00481        register struct Concatenation * conc
00482                      = &(((CordRep *)x) -> concatenation);
00483        
00484        
00485        if (i > 0) {
00486            register size_t left_len = LEFT_LEN(conc);
00487            
00488            if (i >= left_len) {
00489                return(CORD_iter5(conc -> right, i - left_len, f1, f2,
00490                               client_data));
00491            }
00492        }
00493        if (CORD_iter5(conc -> left, i, f1, f2, client_data)) {
00494            return(1);
00495        }
00496        return(CORD_iter5(conc -> right, 0, f1, f2, client_data));
00497     } else /* function */ {
00498         register struct Function * f = &(((CordRep *)x) -> function);
00499         register size_t j;
00500         register size_t lim = f -> len;
00501         
00502         for (j = i; j < lim; j++) {
00503             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
00504                 return(1);
00505             }
00506         }
00507         return(0);
00508     }
00509 }
00510                      
00511 #undef CORD_iter
00512 int CORD_iter(CORD x, CORD_iter_fn f1, void * client_data)
00513 {
00514     return(CORD_iter5(x, 0, f1, CORD_NO_FN, client_data));
00515 }
00516 
00517 int CORD_riter4(CORD x, size_t i, CORD_iter_fn f1, void * client_data)
00518 {
00519     if (x == 0) return(0);
00520     if (CORD_IS_STRING(x)) {
00521        register const char *p = x + i;
00522        register char c;
00523                
00524        for(;;) {
00525            c = *p;
00526            if (c == '\0') ABORT("2nd arg to CORD_riter4 too big");
00527             if ((*f1)(c, client_data)) return(1);
00528            if (p == x) break;
00529             p--;
00530        }
00531        return(0);
00532     } else if (IS_CONCATENATION(x)) {
00533        register struct Concatenation * conc
00534                      = &(((CordRep *)x) -> concatenation);
00535        register CORD left_part = conc -> left;
00536        register size_t left_len;
00537        
00538        left_len = LEFT_LEN(conc);
00539        if (i >= left_len) {
00540            if (CORD_riter4(conc -> right, i - left_len, f1, client_data)) {
00541               return(1);
00542            }
00543            return(CORD_riter4(left_part, left_len - 1, f1, client_data));
00544        } else {
00545            return(CORD_riter4(left_part, i, f1, client_data));
00546        }
00547     } else /* function */ {
00548         register struct Function * f = &(((CordRep *)x) -> function);
00549         register size_t j;
00550         
00551         for (j = i; ; j--) {
00552             if ((*f1)((*(f -> fn))(j, f -> client_data), client_data)) {
00553                 return(1);
00554             }
00555             if (j == 0) return(0);
00556         }
00557     }
00558 }
00559 
00560 int CORD_riter(CORD x, CORD_iter_fn f1, void * client_data)
00561 {
00562     return(CORD_riter4(x, CORD_len(x) - 1, f1, client_data));
00563 }
00564 
00565 /*
00566  * The following functions are concerned with balancing cords.
00567  * Strategy:
00568  * Scan the cord from left to right, keeping the cord scanned so far
00569  * as a forest of balanced trees of exponentialy decreasing length.
00570  * When a new subtree needs to be added to the forest, we concatenate all
00571  * shorter ones to the new tree in the appropriate order, and then insert
00572  * the result into the forest.
00573  * Crucial invariants:
00574  * 1. The concatenation of the forest (in decreasing order) with the
00575  *     unscanned part of the rope is equal to the rope being balanced.
00576  * 2. All trees in the forest are balanced.
00577  * 3. forest[i] has depth at most i.
00578  */
00579 
00580 typedef struct {
00581     CORD c;
00582     size_t len;             /* Actual length of c       */
00583 } ForestElement;
00584 
00585 static size_t min_len [ MAX_DEPTH ];
00586 
00587 static int min_len_init = 0;
00588 
00589 int CORD_max_len;
00590 
00591 typedef ForestElement Forest [ MAX_DEPTH ];
00592                      /* forest[i].len >= fib(i+1)               */
00593                      /* The string is the concatenation */
00594                      /* of the forest in order of DECREASING */
00595                      /* indices.                        */
00596 
00597 void CORD_init_min_len()
00598 {
00599     register int i;
00600     register size_t last, previous, current;
00601         
00602     min_len[0] = previous = 1;
00603     min_len[1] = last = 2;
00604     for (i = 2; i < MAX_DEPTH; i++) {
00605        current = last + previous;
00606        if (current < last) /* overflow */ current = last;
00607        min_len[i] = current;
00608        previous = last;
00609        last = current;
00610     }
00611     CORD_max_len = last - 1;
00612     min_len_init = 1;
00613 }
00614 
00615 
00616 void CORD_init_forest(ForestElement * forest, size_t max_len)
00617 {
00618     register int i;
00619     
00620     for (i = 0; i < MAX_DEPTH; i++) {
00621        forest[i].c = 0;
00622        if (min_len[i] > max_len) return;
00623     }
00624     ABORT("Cord too long");
00625 }
00626 
00627 /* Add a leaf to the appropriate level in the forest, cleaning        */
00628 /* out lower levels as necessary.                              */
00629 /* Also works if x is a balanced tree of concatenations; however      */
00630 /* in this case an extra concatenation node may be inserted above x;  */
00631 /* This node should not be counted in the statement of the invariants.       */
00632 void CORD_add_forest(ForestElement * forest, CORD x, size_t len)
00633 {
00634     register int i = 0;
00635     register CORD sum = CORD_EMPTY;
00636     register size_t sum_len = 0;
00637     
00638     while (len > min_len[i + 1]) {
00639        if (forest[i].c != 0) {
00640            sum = CORD_cat(forest[i].c, sum);
00641            sum_len += forest[i].len;
00642            forest[i].c = 0;
00643        }
00644         i++;
00645     }
00646     /* Sum has depth at most 1 greter than what would be required     */
00647     /* for balance.                                            */
00648     sum = CORD_cat(sum, x);
00649     sum_len += len;
00650     /* If x was a leaf, then sum is now balanced.  To see this        */
00651     /* consider the two cases in which forest[i-1] either is or is    */
00652     /* not empty.                                              */
00653     while (sum_len >= min_len[i]) {
00654        if (forest[i].c != 0) {
00655            sum = CORD_cat(forest[i].c, sum);
00656            sum_len += forest[i].len;
00657            /* This is again balanced, since sum was balanced, and has */
00658            /* allowable depth that differs from i by at most 1.       */
00659            forest[i].c = 0;
00660        }
00661         i++;
00662     }
00663     i--;
00664     forest[i].c = sum;
00665     forest[i].len = sum_len;
00666 }
00667 
00668 CORD CORD_concat_forest(ForestElement * forest, size_t expected_len)
00669 {
00670     register int i = 0;
00671     CORD sum = 0;
00672     size_t sum_len = 0;
00673     
00674     while (sum_len != expected_len) {
00675        if (forest[i].c != 0) {
00676            sum = CORD_cat(forest[i].c, sum);
00677            sum_len += forest[i].len;
00678        }
00679         i++;
00680     }
00681     return(sum);
00682 }
00683 
00684 /* Insert the frontier of x into forest.  Balanced subtrees are       */
00685 /* treated as leaves.  This potentially adds one to the depth  */
00686 /* of the final tree.                                          */
00687 void CORD_balance_insert(CORD x, size_t len, ForestElement * forest)
00688 {
00689     register int depth;
00690     
00691     if (CORD_IS_STRING(x)) {
00692         CORD_add_forest(forest, x, len);
00693     } else if (IS_CONCATENATION(x)
00694                && ((depth = DEPTH(x)) >= MAX_DEPTH
00695                    || len < min_len[depth])) {
00696        register struct Concatenation * conc
00697                      = &(((CordRep *)x) -> concatenation);
00698        size_t left_len = LEFT_LEN(conc);
00699        
00700        CORD_balance_insert(conc -> left, left_len, forest);
00701        CORD_balance_insert(conc -> right, len - left_len, forest);
00702     } else /* function or balanced */ {
00703        CORD_add_forest(forest, x, len);
00704     }
00705 }
00706 
00707 
00708 CORD CORD_balance(CORD x)
00709 {
00710     Forest forest;
00711     register size_t len;
00712     
00713     if (x == 0) return(0);
00714     if (CORD_IS_STRING(x)) return(x);
00715     if (!min_len_init) CORD_init_min_len();
00716     len = LEN(x);
00717     CORD_init_forest(forest, len);
00718     CORD_balance_insert(x, len, forest);
00719     return(CORD_concat_forest(forest, len));
00720 }
00721 
00722 
00723 /* Position primitives      */
00724 
00725 /* Private routines to deal with the hard cases only: */
00726 
00727 /* P contains a prefix of the  path to cur_pos.  Extend it to a full  */
00728 /* path and set up leaf info.                                         */
00729 /* Return 0 if past the end of cord, 1 o.w.                           */
00730 void CORD__extend_path(register CORD_pos p)
00731 {
00732      register struct CORD_pe * current_pe = &(p[0].path[p[0].path_len]);
00733      register CORD top = current_pe -> pe_cord;
00734      register size_t pos = p[0].cur_pos;
00735      register size_t top_pos = current_pe -> pe_start_pos;
00736      register size_t top_len = GEN_LEN(top);
00737      
00738      /* Fill in the rest of the path. */
00739        while(!CORD_IS_STRING(top) && IS_CONCATENATION(top)) {
00740         register struct Concatenation * conc =
00741                      &(((CordRep *)top) -> concatenation);
00742         register size_t left_len;
00743         
00744         left_len = LEFT_LEN(conc);
00745         current_pe++;
00746         if (pos >= top_pos + left_len) {
00747             current_pe -> pe_cord = top = conc -> right;
00748             current_pe -> pe_start_pos = top_pos = top_pos + left_len;
00749             top_len -= left_len;
00750         } else {
00751             current_pe -> pe_cord = top = conc -> left;
00752             current_pe -> pe_start_pos = top_pos;
00753             top_len = left_len;
00754         }
00755         p[0].path_len++;
00756        }
00757      /* Fill in leaf description for fast access. */
00758        if (CORD_IS_STRING(top)) {
00759          p[0].cur_leaf = top;
00760          p[0].cur_start = top_pos;
00761          p[0].cur_end = top_pos + top_len;
00762        } else {
00763          p[0].cur_end = 0;
00764        }
00765        if (pos >= top_pos + top_len) p[0].path_len = CORD_POS_INVALID;
00766 }
00767 
00768 char CORD__pos_fetch(register CORD_pos p)
00769 {
00770     /* Leaf is a function node */
00771     struct CORD_pe * pe = &((p)[0].path[(p)[0].path_len]);
00772     CORD leaf = pe -> pe_cord;
00773     register struct Function * f = &(((CordRep *)leaf) -> function);
00774     
00775     if (!IS_FUNCTION(leaf)) ABORT("CORD_pos_fetch: bad leaf");
00776     return ((*(f -> fn))(p[0].cur_pos - pe -> pe_start_pos, f -> client_data));
00777 }
00778 
00779 void CORD__next(register CORD_pos p)
00780 {
00781     register size_t cur_pos = p[0].cur_pos + 1;
00782     register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
00783     register CORD leaf = current_pe -> pe_cord;
00784     
00785     /* Leaf is not a string or we're at end of leaf */
00786     p[0].cur_pos = cur_pos;
00787     if (!CORD_IS_STRING(leaf)) {
00788        /* Function leaf     */
00789        register struct Function * f = &(((CordRep *)leaf) -> function);
00790        register size_t start_pos = current_pe -> pe_start_pos;
00791        register size_t end_pos = start_pos + f -> len;
00792        
00793        if (cur_pos < end_pos) {
00794          /* Fill cache and return. */
00795            register size_t i;
00796            register size_t limit = cur_pos + FUNCTION_BUF_SZ;
00797            register CORD_fn fn = f -> fn;
00798            register void * client_data = f -> client_data;
00799            
00800            if (limit > end_pos) {
00801                limit = end_pos;
00802            }
00803            for (i = cur_pos; i < limit; i++) {
00804                p[0].function_buf[i - cur_pos] =
00805                      (*fn)(i - start_pos, client_data);
00806            }
00807            p[0].cur_start = cur_pos;
00808            p[0].cur_leaf = p[0].function_buf;
00809            p[0].cur_end = limit;
00810            return;
00811        }
00812     }
00813     /* End of leaf   */
00814     /* Pop the stack until we find two concatenation nodes with the   */
00815     /* same start position: this implies we were in left part.        */
00816     {
00817        while (p[0].path_len > 0
00818               && current_pe[0].pe_start_pos != current_pe[-1].pe_start_pos) {
00819            p[0].path_len--;
00820            current_pe--;
00821        }
00822        if (p[0].path_len == 0) {
00823            p[0].path_len = CORD_POS_INVALID;
00824             return;
00825        }
00826     }
00827     p[0].path_len--;
00828     CORD__extend_path(p);
00829 }
00830 
00831 void CORD__prev(register CORD_pos p)
00832 {
00833     register struct CORD_pe * pe = &(p[0].path[p[0].path_len]);
00834     
00835     if (p[0].cur_pos == 0) {
00836         p[0].path_len = CORD_POS_INVALID;
00837         return;
00838     }
00839     p[0].cur_pos--;
00840     if (p[0].cur_pos >= pe -> pe_start_pos) return;
00841     
00842     /* Beginning of leaf    */
00843     
00844     /* Pop the stack until we find two concatenation nodes with the   */
00845     /* different start position: this implies we were in right part.  */
00846     {
00847        register struct CORD_pe * current_pe = &((p)[0].path[(p)[0].path_len]);
00848        
00849        while (p[0].path_len > 0
00850               && current_pe[0].pe_start_pos == current_pe[-1].pe_start_pos) {
00851            p[0].path_len--;
00852            current_pe--;
00853        }
00854     }
00855     p[0].path_len--;
00856     CORD__extend_path(p);
00857 }
00858 
00859 #undef CORD_pos_fetch
00860 #undef CORD_next
00861 #undef CORD_prev
00862 #undef CORD_pos_to_index
00863 #undef CORD_pos_to_cord
00864 #undef CORD_pos_valid
00865 
00866 char CORD_pos_fetch(register CORD_pos p)
00867 {
00868     if (p[0].cur_start <= p[0].cur_pos && p[0].cur_pos < p[0].cur_end) {
00869        return(p[0].cur_leaf[p[0].cur_pos - p[0].cur_start]);
00870     } else {
00871         return(CORD__pos_fetch(p));
00872     }
00873 }
00874 
00875 void CORD_next(CORD_pos p)
00876 {
00877     if (p[0].cur_pos < p[0].cur_end - 1) {
00878        p[0].cur_pos++;
00879     } else {
00880        CORD__next(p);
00881     }
00882 }
00883 
00884 void CORD_prev(CORD_pos p)
00885 {
00886     if (p[0].cur_end != 0 && p[0].cur_pos > p[0].cur_start) {
00887        p[0].cur_pos--;
00888     } else {
00889        CORD__prev(p);
00890     }
00891 }
00892 
00893 size_t CORD_pos_to_index(CORD_pos p)
00894 {
00895     return(p[0].cur_pos);
00896 }
00897 
00898 CORD CORD_pos_to_cord(CORD_pos p)
00899 {
00900     return(p[0].path[0].pe_cord);
00901 }
00902 
00903 int CORD_pos_valid(CORD_pos p)
00904 {
00905     return(p[0].path_len != CORD_POS_INVALID);
00906 }
00907 
00908 void CORD_set_pos(CORD_pos p, CORD x, size_t i)
00909 {
00910     if (x == CORD_EMPTY) {
00911        p[0].path_len = CORD_POS_INVALID;
00912        return;
00913     }
00914     p[0].path[0].pe_cord = x;
00915     p[0].path[0].pe_start_pos = 0;
00916     p[0].path_len = 0;
00917     p[0].cur_pos = i;
00918     CORD__extend_path(p);
00919 }