Annotation of parser3/src/lib/cord/cordbscs.c, revision 1.1.2.11

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

E-mail: