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

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

E-mail: