home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 November / macformat-018.iso / Utility Spectacular / Developer / Marlais 0.3.1 / gc4.1-mac / cord / cordbscs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-26  |  26.4 KB  |  914 lines  |  [TEXT/R*ch]

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