source: libcfa/src/collections/string_res.cfa @ e891349

Last change on this file since e891349 was e891349, checked in by Michael Brooks <mlbrooks@…>, 9 months ago

Tweak string assignment-strcpy-strncpy and concatenate-strcat-strncat declarations.

Implement -n- versions correctly.

Refactor to include string_res layer.

Add missing tests.

  • Property mode set to 100644
File size: 42.7 KB
RevLine 
[f450f2f]1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// string_res -- variable-length, mutable run of text, with resource semantics
8//
9// Author           : Michael L. Brooks
10// Created On       : Fri Sep 03 11:00:00 2021
[7d25f44]11// Last Modified By : Peter A. Buhr
[06280ad]12// Last Modified On : Tue Jan 16 22:19:27 2024
13// Update Count     : 35
[f450f2f]14//
15
16#include "string_res.hfa"
[0f781fb8]17#include "string_sharectx.hfa"
[08ed947]18#include "stdlib.hfa"
[d32679d5]19#include <ctype.h>
[08ed947]20
21// Workaround for observed performance penalty from calling CFA's alloc.
22// Workaround is:  EndVbyte = TEMP_ALLOC(char, CurrSize)
23// Should be:      EndVbyte = alloc(CurrSize)
[681e12f]24#define TEMP_ALLOC(T, n) (( T * ) malloc( n * sizeof( T ) ))
[0f781fb8]25
[218096f]26#include <assert.h>
[f450f2f]27
28//######################### VbyteHeap "header" #########################
29
30#ifdef VbyteDebug
[6cc87c0]31HandleNode *HeaderPtr;
[f450f2f]32#endif // VbyteDebug
33
34struct VbyteHeap {
[681e12f]35    int NoOfCompactions;                                                // number of compactions of the byte area
36    int NoOfExtensions;                                                 // number of extensions in the size of the byte area
37    int NoOfReductions;                                                 // number of reductions in the size of the byte area
[f450f2f]38   
[681e12f]39    int InitSize;                                                               // initial number of bytes in the byte-string area
40    int CurrSize;                                                               // current number of bytes in the byte-string area
41    char *StartVbyte;                                                   // pointer to the `st byte of the start of the byte-string area
42    char *EndVbyte;                                                             // pointer to the next byte after the end of the currently used portion of byte-string area
43    void *ExtVbyte;                                                             // pointer to the next byte after the end of the byte-string area
[f450f2f]44
[681e12f]45    HandleNode Header;                                                  // header node for handle list
[f450f2f]46}; // VbyteHeap
47
48   
[681e12f]49static void compaction( VbyteHeap & );                  // compaction of the byte area
50static void garbage( VbyteHeap &, int );                // garbage collect the byte area
[4e8df745]51static void extend( VbyteHeap &, int );                 // extend the size of the byte area
52static void reduce( VbyteHeap &, int );                 // reduce the size of the byte area
[f450f2f]53
[4e8df745]54static void ?{}( VbyteHeap &, size_t = 1000 );
55static void ^?{}( VbyteHeap & );
[94647b0b]56
[4e8df745]57static int ByteCmp( char *, int, int, char *, int, int );       // compare 2 blocks of bytes
58static char *VbyteAlloc( VbyteHeap &, int );                    // allocate a block bytes in the heap
59static char *VbyteTryAdjustLast( VbyteHeap &, int );
[f450f2f]60
[4e8df745]61static void AddThisAfter( HandleNode &, HandleNode & );
62static void DeleteNode( HandleNode & );
63static void MoveThisAfter( HandleNode &, const HandleNode & );          // move current handle after parameter handle
[f450f2f]64
65
66// Allocate the storage for the variable sized area and intialize the heap variables.
67
[681e12f]68static void ?{}( VbyteHeap & s, size_t Size ) with(s) {
[f450f2f]69#ifdef VbyteDebug
[681e12f]70    serr | "enter:VbyteHeap::VbyteHeap, s:" | &s | " Size:" | Size;
[f450f2f]71#endif // VbyteDebug
72    NoOfCompactions = NoOfExtensions = NoOfReductions = 0;
73    InitSize = CurrSize = Size;
[08ed947]74    StartVbyte = EndVbyte = TEMP_ALLOC(char, CurrSize);
[f450f2f]75    ExtVbyte = (void *)( StartVbyte + CurrSize );
76    Header.flink = Header.blink = &Header;
[681e12f]77    Header.ulink = &s;
[f450f2f]78#ifdef VbyteDebug
79    HeaderPtr = &Header;
[681e12f]80    serr | "exit:VbyteHeap::VbyteHeap, s:" | &s;
[f450f2f]81#endif // VbyteDebug
82} // VbyteHeap
83
84
85// Release the dynamically allocated storage for the byte area.
86
[681e12f]87static void ^?{}( VbyteHeap & s ) with(s) {
[f450f2f]88    free( StartVbyte );
89} // ~VbyteHeap
90
91
92//######################### HandleNode #########################
93
94
95// Create a handle node. The handle is not linked into the handle list.  This is the responsibilitiy of the handle
96// creator.
97
[681e12f]98static void ?{}( HandleNode & s ) with(s) {
[f450f2f]99#ifdef VbyteDebug
[681e12f]100    serr | "enter:HandleNode::HandleNode, s:" | &s;
[f450f2f]101#endif // VbyteDebug
102    s = 0;
103    lnth = 0;
104#ifdef VbyteDebug
[681e12f]105    serr | "exit:HandleNode::HandleNode, s:" | &s;
[f450f2f]106#endif // VbyteDebug
107} // HandleNode
108
109// Create a handle node. The handle is linked into the handle list at the end. This means that this handle will NOT be
110// in order by string address, but this is not a problem because a string with length zero does nothing during garbage
111// collection.
112
[681e12f]113static void ?{}( HandleNode & s, VbyteHeap & vh ) with(s) {
[f450f2f]114#ifdef VbyteDebug
[681e12f]115    serr | "enter:HandleNode::HandleNode, s:" | &s;
[f450f2f]116#endif // VbyteDebug
117    s = 0;
118    lnth = 0;
[0f781fb8]119    ulink = &vh;
[681e12f]120    AddThisAfter( s, *vh.Header.blink );
[f450f2f]121#ifdef VbyteDebug
[681e12f]122    serr | "exit:HandleNode::HandleNode, s:" | &s;
[f450f2f]123#endif // VbyteDebug
124} // HandleNode
125
126
127// Delete a node from the handle list by unchaining it from the list. If the handle node was allocated dynamically, it
128// is the responsibility of the creator to destroy it.
129
[681e12f]130static void ^?{}( HandleNode & s ) with(s) {
[f450f2f]131#ifdef VbyteDebug
[681e12f]132    serr | "enter:HandleNode::~HandleNode, s:" | & s;
[f450f2f]133    {
134        serr | nlOff;
135        serr | " lnth:" | lnth | " s:" | (void *)s | ",\"";
[9ca5e56]136        for ( i; lnth ) {
[f450f2f]137            serr | s[i];
138        } // for
139        serr | "\" flink:" | flink | " blink:" | blink | nl;
140        serr | nlOn;
141    }
142#endif // VbyteDebug
[681e12f]143    DeleteNode( s );
[f450f2f]144} // ~HandleNode
145
146
[0f781fb8]147//######################### String Sharing Context #########################
[f450f2f]148
[0f781fb8]149static string_sharectx * ambient_string_sharectx;               // fickle top of stack
150static string_sharectx default_string_sharectx = {NEW_SHARING}; // stable bottom of stack
[f450f2f]151
[681e12f]152void ?{}( string_sharectx & s, StringSharectx_Mode mode ) with( s ) {
[0f781fb8]153    (older){ ambient_string_sharectx };
154    if ( mode == NEW_SHARING ) {
[804bf677]155        (activeHeap){ new( (size_t) 1000 ) };
[0f781fb8]156    } else {
157        verify( mode == NO_SHARING );
158        (activeHeap){ 0p };
159    }
[681e12f]160    ambient_string_sharectx = & s;
[0f781fb8]161}
162
[681e12f]163void ^?{}( string_sharectx & s ) with( s ) {
[0f781fb8]164    if ( activeHeap ) delete( activeHeap );
165
[681e12f]166    // unlink s from older-list starting from ambient_string_sharectx
167    // usually, s==ambient_string_sharectx and the loop runs zero times
[0f781fb8]168    string_sharectx *& c = ambient_string_sharectx;
[681e12f]169    while ( c != &s ) &c = &c->older;              // find s
170    c = s.older;                                   // unlink
[0f781fb8]171}
172
173//######################### String Resource #########################
174
175
176VbyteHeap * DEBUG_string_heap() {
177    assert( ambient_string_sharectx->activeHeap && "No sharing context is active" );
178    return ambient_string_sharectx->activeHeap;
179}
[6cc87c0]180
181size_t DEBUG_string_bytes_avail_until_gc( VbyteHeap * heap ) {
[06280ad]182    return ((char *)heap->ExtVbyte) - heap->EndVbyte;
[6cc87c0]183}
184
[7b0e8b7]185size_t DEBUG_string_bytes_in_heap( VbyteHeap * heap ) {
186    return heap->CurrSize;
187}
188
[6cc87c0]189const char * DEBUG_string_heap_start( VbyteHeap * heap ) {
190    return heap->StartVbyte;
191}
192
[f450f2f]193// Returns the size of the string in bytes
[681e12f]194size_t size(const string_res & s) with(s) {
[f450f2f]195    return Handle.lnth;
196}
197
198// Output operator
[681e12f]199ofstream & ?|?(ofstream & out, const string_res & s) {
[9ca5e56]200        // CFA string is NOT null terminated, so print exactly lnth characters in a minimum width of 0.
201        out | wd( 0, s.Handle.lnth, s.Handle.s ) | nonl;
[f450f2f]202    return out;
203}
204
[681e12f]205void ?|?(ofstream & out, const string_res & s) {
[9ca5e56]206        (ofstream &)(out | s); ends( out );
[f450f2f]207}
208
[d32679d5]209// Input operator
[681e12f]210ifstream & ?|?(ifstream & in, string_res & s) {
[d32679d5]211    // Reading into a temp before assigning to s is near zero overhead in typical cases because of sharing.
212    // If s is a substring of something larger, simple assignment takes care of that case correctly.
213    // But directly reading a variable amount of text into the middle of a larger context is not practical.
214    string_res temp;
215
216    // Read in chunks.  Often, one chunk is enough.  Keep the string that accumulates chunks last in the heap,
217    // so available room is rest of heap.  When a chunk fills the heap, force growth then take the next chunk.
[0860d9c]218    for (bool cont = true; cont; ) {
219        cont = false;
220
[d32679d5]221        // Append dummy content to temp, forcing expansion when applicable (occurs always on subsequent loops)
222        // length 2 ensures room for at least one real char, plus scanf/pipe-cstr's null terminator
223        temp += "--";
224        assert( temp.Handle.ulink->EndVbyte == temp.Handle.s + temp.Handle.lnth );    // last in heap
225
226        // reset, to overwrite the appended "--"
227        temp.Handle.lnth -= 2;
228        temp.Handle.ulink->EndVbyte -= 2;
229
[0860d9c]230        // rest of heap is available to read into
[06280ad]231        int lenReadable = (char *)temp.Handle.ulink->ExtVbyte - temp.Handle.ulink->EndVbyte;
[0860d9c]232        assert (lenReadable >= 2);
[d32679d5]233
234        // get bytes
[0860d9c]235        try {
[37ceccb]236                        *(temp.Handle.ulink->EndVbyte) = '\0';   // pre-assign empty cstring
[0860d9c]237            in | wdi( lenReadable, temp.Handle.ulink->EndVbyte );
[681e12f]238        } catch (cstring_length *) {
[0860d9c]239            cont = true;
240        }
[d32679d5]241        int lenWasRead = strlen(temp.Handle.ulink->EndVbyte);
242
243        // update metadata
244        temp.Handle.lnth += lenWasRead;
245        temp.Handle.ulink->EndVbyte += lenWasRead;
246    }
247
[37ceccb]248        if ( temp.Handle.lnth > 0 ) s = temp;
[d32679d5]249    return in;
250}
251
[681e12f]252void ?|?( ifstream & in, string_res & s ) {
253    (ifstream &)(in | s);
[ff56dd2e]254}
255
256ifstream & ?|?( ifstream & is, _Istream_Rstr f ) {
257        // .---------------,
258        // | | | | |...|0|0| null terminator and guard if missing
259        // `---------------'
260        enum { gwd = 128 + 1, wd = gwd - 1 };                           // guard and unguard width
261        char cstr[gwd];                                                                         // read in chunks
262        bool cont = false;
263
264        _Istream_Cstr cf = { cstr, (_Istream_str_base)f };
265        if ( ! cf.flags.rwd ) cf.wd = wd;
266
267        cstr[wd] = '\0';                                                                        // guard null terminate string
268        try {
[37ceccb]269                cstr[0] = '\0';                                                                 // pre-assign as empty cstring
[ff56dd2e]270                is | cf;
271        } catch( cstring_length * ) {
272                cont = true;
273        } finally {
[681e12f]274                if ( ! cf.flags.ignore                                                  // ok to initialize string
275//                       &&     cstr[0] != '\0'                                                 // something was read
276                        ) {
[37ceccb]277                        *(f.s) = cstr;
278                }
[ff56dd2e]279        } // try
280        for ( ; cont; )  {                                                                      // overflow read ?
281                cont = false;
282                try {
[37ceccb]283                        cstr[0] = '\0';                                                         // pre-assign as empty cstring
[ff56dd2e]284                        is | cf;
285                } catch( cstring_length * ) {
286                        cont = true;                                                            // continue not allowed
287                } finally {
[681e12f]288                        if ( ! cf.flags.ignore && cstr[0] != '\0' ) { // something was read
[37ceccb]289                                *(f.s) += cstr;                                                 // build string chunk at a time
290                        }
[ff56dd2e]291                } // try
292        } // for
293        return is;
294} // ?|?
295
296void ?|?( ifstream & in, _Istream_Rstr f ) {
[f842032]297    (ifstream &)(in | f);
[ff56dd2e]298}
299
[d32679d5]300
[f450f2f]301// Empty constructor
[681e12f]302void ?{}(string_res & s) with(s) {
[804bf677]303    if( ambient_string_sharectx->activeHeap ) {
304        (Handle){ * ambient_string_sharectx->activeHeap };
305        (shareEditSet_owns_ulink){ false };
[2b30370]306        verify( Handle.s == 0p && Handle.lnth == 0 );
[804bf677]307    } else {
308        (Handle){ * new( (size_t) 10 ) };  // TODO: can I lazily avoid allocating for empty string
309        (shareEditSet_owns_ulink){ true };
[2b30370]310        Handle.s = Handle.ulink->StartVbyte;
311        verify( Handle.lnth == 0 );
[804bf677]312    }
[f450f2f]313    s.shareEditSet_prev = &s;
314    s.shareEditSet_next = &s;
315}
316
[06280ad]317static void eagerCopyCtorHelper(string_res & s, const char * rhs, size_t rhslnth) with(s) {
[804bf677]318    if( ambient_string_sharectx->activeHeap ) {
319        (Handle){ * ambient_string_sharectx->activeHeap };
320        (shareEditSet_owns_ulink){ false };
321    } else {
322        (Handle){ * new( rhslnth ) };
323        (shareEditSet_owns_ulink){ true };
324    }
[0f781fb8]325    Handle.s = VbyteAlloc(*Handle.ulink, rhslnth);
[f450f2f]326    Handle.lnth = rhslnth;
[08ed947]327    memmove( Handle.s, rhs, rhslnth );
[f450f2f]328    s.shareEditSet_prev = &s;
329    s.shareEditSet_next = &s;
330}
331
[4b3b352]332// Constructor from a raw buffer and size
[06280ad]333void ?{}(string_res & s, const char * rhs, size_t rhslnth) with(s) {
[4b3b352]334    eagerCopyCtorHelper(s, rhs, rhslnth);
335}
336
[fe18b46]337// private ctor (not in header): use specified heap (ignore ambient) and copy chars in
[06280ad]338void ?{}( string_res & s, VbyteHeap & heap, const char * rhs, size_t rhslnth ) with(s) {
[fe18b46]339    (Handle){ heap };
340    Handle.s = VbyteAlloc(*Handle.ulink, rhslnth);
341    Handle.lnth = rhslnth;
342    (s.shareEditSet_owns_ulink){ false };
[08ed947]343    memmove( Handle.s, rhs, rhslnth );
[fe18b46]344    s.shareEditSet_prev = &s;
345    s.shareEditSet_next = &s;
346}
347
[f450f2f]348// General copy constructor
[681e12f]349void ?{}(string_res & s, const string_res & s2, StrResInitMode mode, size_t start, size_t end ) {
[f450f2f]350
[218096f]351    verify( start <= end && end <= s2.Handle.lnth );
352
[fe18b46]353    if (s2.Handle.ulink != ambient_string_sharectx->activeHeap && mode == COPY_VALUE) {
354        // crossing heaps (including private): copy eagerly
355        eagerCopyCtorHelper(s, s2.Handle.s + start, end - start);
356        verify(s.shareEditSet_prev == &s);
357        verify(s.shareEditSet_next == &s);
358    } else {
[4b3b352]359        (s.Handle){};
360        s.Handle.s = s2.Handle.s + start;
361        s.Handle.lnth = end - start;
[fe18b46]362        s.Handle.ulink = s2.Handle.ulink;
363
[4b3b352]364        AddThisAfter(s.Handle, s2.Handle );                     // insert this handle after rhs handle
365        // ^ bug?  skip others at early point in string
[fe18b46]366
[4b3b352]367        if (mode == COPY_VALUE) {
[fe18b46]368            verify(s2.Handle.ulink == ambient_string_sharectx->activeHeap);
369            // requested logical copy in same heap: defer copy until write
370
371            (s.shareEditSet_owns_ulink){ false };
372
[4b3b352]373            // make s alone in its shareEditSet
374            s.shareEditSet_prev = &s;
375            s.shareEditSet_next = &s;
376        } else {
377            verify( mode == SHARE_EDITS );
[fe18b46]378            // sharing edits with source forces same heap as source (ignore context)
379
380            (s.shareEditSet_owns_ulink){ s2.shareEditSet_owns_ulink };
[f450f2f]381
[4b3b352]382            // s2 is logically const but not implementation const
383            string_res & s2mod = (string_res &) s2;
[f450f2f]384
[4b3b352]385            // insert s after s2 on shareEditSet
386            s.shareEditSet_next = s2mod.shareEditSet_next;
387            s.shareEditSet_prev = &s2mod;
388            s.shareEditSet_next->shareEditSet_prev = &s;
389            s.shareEditSet_prev->shareEditSet_next = &s;
[6cc87c0]390        }
[f450f2f]391    }
[4b3b352]392}
[f450f2f]393
[681e12f]394static void assignEditSet(string_res & s, string_res * shareEditSetStartPeer, string_res * shareEditSetEndPeer,
[4b3b352]395    char * resultSesStart,
396    size_t resultSesLnth,
397    HandleNode * resultPadPosition, size_t bsize ) {
[6cc87c0]398
399    char * beforeBegin = shareEditSetStartPeer->Handle.s;
[681e12f]400    size_t beforeLen = s.Handle.s - beforeBegin;
[f450f2f]401
[681e12f]402    char * afterBegin = s.Handle.s + s.Handle.lnth;
[6cc87c0]403    size_t afterLen = shareEditSetEndPeer->Handle.s + shareEditSetEndPeer->Handle.lnth - afterBegin;
[f450f2f]404
[681e12f]405    size_t oldLnth = s.Handle.lnth;
[f450f2f]406
[681e12f]407    s.Handle.s = resultSesStart + beforeLen;
408    s.Handle.lnth = bsize;
[6f7aff3]409    if (resultPadPosition)
[681e12f]410        MoveThisAfter( s.Handle, *resultPadPosition );
[f450f2f]411
412    // adjust all substring string and handle locations, and check if any substring strings are outside the new base string
[4b3b352]413    char *limit = resultSesStart + resultSesLnth;
[681e12f]414    for ( string_res * p = s.shareEditSet_next; p != &s; p = p->shareEditSet_next ) {
[218096f]415        verify (p->Handle.s >= beforeBegin);
[6cc87c0]416        if ( p->Handle.s >= afterBegin ) {
[218096f]417            verify ( p->Handle.s <= afterBegin + afterLen );
418            verify ( p->Handle.s + p->Handle.lnth <= afterBegin + afterLen );
[6cc87c0]419            // p starts after the edit
420            // take start and end as end-anchored
421            size_t startOffsetFromEnd = afterBegin + afterLen - p->Handle.s;
422            p->Handle.s = limit - startOffsetFromEnd;
423            // p->Handle.lnth unaffected
424        } else if ( p->Handle.s <= beforeBegin + beforeLen ) {
425            // p starts before, or at the start of, the edit
426            if ( p->Handle.s + p->Handle.lnth <= beforeBegin + beforeLen ) {
[f450f2f]427                // p ends before the edit
428                // take end as start-anchored too
429                // p->Handle.lnth unaffected
430            } else if ( p->Handle.s + p->Handle.lnth < afterBegin ) {
[6cc87c0]431                // p ends during the edit; p does not include the last character replaced
[f450f2f]432                // clip end of p to end at start of edit
433                p->Handle.lnth = beforeLen - ( p->Handle.s - beforeBegin );
434            } else {
435                // p ends after the edit
[218096f]436                verify ( p->Handle.s + p->Handle.lnth <= afterBegin + afterLen );
[f450f2f]437                // take end as end-anchored
438                // stretch-shrink p according to the edit
[681e12f]439                p->Handle.lnth += s.Handle.lnth;
[f450f2f]440                p->Handle.lnth -= oldLnth;
441            }
442            // take start as start-anchored
443            size_t startOffsetFromStart = p->Handle.s - beforeBegin;
[4b3b352]444            p->Handle.s = resultSesStart + startOffsetFromStart;
[6cc87c0]445        } else {
[218096f]446            verify ( p->Handle.s < afterBegin );
[f450f2f]447            // p starts during the edit
[218096f]448            verify( p->Handle.s + p->Handle.lnth >= beforeBegin + beforeLen );
[f450f2f]449            if ( p->Handle.s + p->Handle.lnth < afterBegin ) {
[6cc87c0]450                // p ends during the edit; p does not include the last character replaced
[f450f2f]451                // set p to empty string at start of edit
[681e12f]452                p->Handle.s = s.Handle.s;
[f450f2f]453                p->Handle.lnth = 0;
454            } else {
[6cc87c0]455                // p includes the end of the edit
[f450f2f]456                // clip start of p to start at end of edit
[6cc87c0]457                int charsToClip = afterBegin - p->Handle.s;
[681e12f]458                p->Handle.s = s.Handle.s + s.Handle.lnth;
[6cc87c0]459                p->Handle.lnth -= charsToClip;
[f450f2f]460            }
461        }
[6f7aff3]462        if (resultPadPosition)
463            MoveThisAfter( p->Handle, *resultPadPosition );     // move substring handle to maintain sorted order by string position
[4b3b352]464    }
465}
466
[681e12f]467// traverse the share-edit set (SES) to recover the range of a base string to which `s` belongs
468static void locateInShareEditSet( string_res & s, string_res *& shareEditSetStartPeer, string_res *& shareEditSetEndPeer ) {
469    shareEditSetStartPeer = & s;
470    shareEditSetEndPeer = & s;
471    for (string_res * editPeer = s.shareEditSet_next; editPeer != &s; editPeer = editPeer->shareEditSet_next) {
[4b3b352]472        if ( editPeer->Handle.s < shareEditSetStartPeer->Handle.s ) {
473            shareEditSetStartPeer = editPeer;
474        }
475        if ( shareEditSetEndPeer->Handle.s + shareEditSetEndPeer->Handle.lnth < editPeer->Handle.s + editPeer->Handle.lnth) {
476            shareEditSetEndPeer = editPeer;
477        }
[f450f2f]478    }
[d32679d5]479}
480
[06280ad]481static string_res & assign_(string_res & s, const char * buffer, size_t bsize, const string_res & valSrc) {
[d32679d5]482
483    string_res * shareEditSetStartPeer;
484    string_res * shareEditSetEndPeer;
[681e12f]485    locateInShareEditSet( s, shareEditSetStartPeer, shareEditSetEndPeer );
[4b3b352]486
487    verify( shareEditSetEndPeer->Handle.s >= shareEditSetStartPeer->Handle.s );
[0ca15b7]488    size_t origEditSetLength = shareEditSetEndPeer->Handle.s + shareEditSetEndPeer->Handle.lnth - shareEditSetStartPeer->Handle.s;
[681e12f]489    verify( origEditSetLength >= s.Handle.lnth );
[4b3b352]490
[681e12f]491    if ( s.shareEditSet_owns_ulink ) {                 // assigning to private context
[6f7aff3]492        // ok to overwrite old value within LHS
493        char * prefixStartOrig = shareEditSetStartPeer->Handle.s;
[681e12f]494        int prefixLen = s.Handle.s - prefixStartOrig;
495        char * suffixStartOrig = s.Handle.s + s.Handle.lnth;
[6f7aff3]496        int suffixLen = shareEditSetEndPeer->Handle.s + shareEditSetEndPeer->Handle.lnth - suffixStartOrig;
497
[681e12f]498        int delta = bsize - s.Handle.lnth;
499        if ( char * oldBytes = VbyteTryAdjustLast( *s.Handle.ulink, delta ) ) {
[6f7aff3]500            // growing: copy from old to new
[681e12f]501            char * dest = VbyteAlloc( *s.Handle.ulink, origEditSetLength + delta );
[fe18b46]502            char *destCursor = dest;  memcpy(destCursor, prefixStartOrig, prefixLen);
503            destCursor += prefixLen;  memcpy(destCursor, buffer         , bsize    );
504            destCursor += bsize;      memcpy(destCursor, suffixStartOrig, suffixLen);
[681e12f]505            assignEditSet(s, shareEditSetStartPeer, shareEditSetEndPeer,
[6f7aff3]506                dest,
[0ca15b7]507                origEditSetLength + delta,
[6f7aff3]508                0p, bsize);
509            free( oldBytes );
510        } else {
511            // room is already allocated in-place: bubble suffix and overwite middle
512            memmove( suffixStartOrig + delta, suffixStartOrig, suffixLen );
[681e12f]513            memcpy( s.Handle.s, buffer, bsize );
[6f7aff3]514
[681e12f]515            assignEditSet(s, shareEditSetStartPeer, shareEditSetEndPeer,
[6f7aff3]516                shareEditSetStartPeer->Handle.s,
[0ca15b7]517                origEditSetLength + delta,
[6f7aff3]518                0p, bsize);
519        }
[4b3b352]520
[6f7aff3]521    } else if (                                           // assigning to shared context
[681e12f]522        s.Handle.lnth == origEditSetLength &&          // overwriting entire run of SES
[6f7aff3]523        & valSrc &&                                       // sourcing from a managed string
[681e12f]524        valSrc.Handle.ulink == s.Handle.ulink  ) {     // sourcing from same heap
[4b3b352]525
[6f7aff3]526        // SES's result will only use characters from the source string => reuse source
[681e12f]527        assignEditSet(s, shareEditSetStartPeer, shareEditSetEndPeer,
[4b3b352]528            valSrc.Handle.s,
529            valSrc.Handle.lnth,
530            &((string_res&)valSrc).Handle, bsize);
531       
532    } else {
[6f7aff3]533        // overwriting a proper substring of some string: mash characters from old and new together (copy on write)
534        // OR we are importing characters: need to copy eagerly (can't refer to source)
[4b3b352]535
536        // full string is from start of shareEditSetStartPeer thru end of shareEditSetEndPeer
[681e12f]537        // `s` occurs in the middle of it, to be replaced
[4b3b352]538        // build up the new text in `pasting`
539
540        string_res pasting = {
[681e12f]541            * s.Handle.ulink,                               // maintain same heap, regardless of context
[4b3b352]542            shareEditSetStartPeer->Handle.s,                   // start of SES
[681e12f]543            s.Handle.s - shareEditSetStartPeer->Handle.s }; // length of SES, before s
[4b3b352]544        append( pasting,
[681e12f]545            buffer,                                            // start of replacement for s
546            bsize );                                           // length of replacement for s
[4b3b352]547        append( pasting,
[681e12f]548            s.Handle.s + s.Handle.lnth,                  // start of SES after s
[4b3b352]549            shareEditSetEndPeer->Handle.s + shareEditSetEndPeer->Handle.lnth -
[681e12f]550            (s.Handle.s + s.Handle.lnth) );              // length of SES, after s
[4b3b352]551
552        // The above string building can trigger compaction.
553        // The reference points (that are arguments of the string building) may move during that building.
[681e12f]554        // From s point on, they are stable.
[4b3b352]555
[681e12f]556        assignEditSet(s, shareEditSetStartPeer, shareEditSetEndPeer,
[4b3b352]557            pasting.Handle.s,
558            pasting.Handle.lnth,
559            &pasting.Handle, bsize);
560    }
[1733184]561
[681e12f]562    return s;
[4b3b352]563}
564
[e891349]565string_res & assign(string_res & s, const string_res & src, size_t maxlen) {
566    return assign_(s, src.Handle.s, min(src.Handle.lnth, maxlen), *0p);
567}
568
[06280ad]569string_res & assign(string_res & s, const char * buffer, size_t bsize) {
[681e12f]570    return assign_(s, buffer, bsize, *0p);
[f450f2f]571}
572
[681e12f]573string_res & ?=?(string_res & s, char c) {
574    return assign(s, &c, 1);
[d8d512e]575}
576
577// Copy assignment operator
[681e12f]578string_res & ?=?(string_res & s, const string_res & rhs) with( s ) {
579    return assign_(s, rhs.Handle.s, rhs.Handle.lnth, rhs);
[d8d512e]580}
581
[681e12f]582string_res & ?=?(string_res & s, string_res & rhs) with( s ) {
[f450f2f]583    const string_res & rhs2 = rhs;
[681e12f]584    return s = rhs2;
[f450f2f]585}
586
587
588// Destructor
[681e12f]589void ^?{}(string_res & s) with(s) {
[f450f2f]590    // much delegated to implied ^VbyteSM
591
592    // sever s from its share-edit peers, if any (four no-ops when already solo)
593    s.shareEditSet_prev->shareEditSet_next = s.shareEditSet_next;
594    s.shareEditSet_next->shareEditSet_prev = s.shareEditSet_prev;
[218096f]595    // s.shareEditSet_next = &s;
596    // s.shareEditSet_prev = &s;
[804bf677]597
598    if (shareEditSet_owns_ulink && s.shareEditSet_next == &s) { // last one out
599        delete( s.Handle.ulink );
600    }
[f450f2f]601}
602
603
604// Returns the character at the given index
605// With unicode support, this may be different from just the byte at the given
606// offset from the start of the string.
[681e12f]607char ?[?](const string_res & s, size_t index) with(s) {
[f450f2f]608    //TODO: Check if index is valid (no exceptions yet)
609    return Handle.s[index];
610}
611
[681e12f]612void assignAt(const string_res & s, size_t index, char val) {
[218096f]613    string_res editZone = { s, SHARE_EDITS, index, index+1 };
614    assign(editZone, &val, 1);
615}
616
[d8d512e]617
[f450f2f]618///////////////////////////////////////////////////////////////////
[d8d512e]619// Concatenation
[f450f2f]620
[681e12f]621void append(string_res & str1, const char * buffer, size_t bsize) {
[4e8df745]622    size_t clnth = str1.Handle.lnth + bsize;
623    if ( str1.Handle.s + str1.Handle.lnth == buffer ) { // already juxtapose ?
[d8d512e]624        // no-op
[f450f2f]625    } else {                                            // must copy some text
[4e8df745]626        if ( str1.Handle.s + str1.Handle.lnth == VbyteAlloc(*str1.Handle.ulink, 0) ) { // str1 at end of string area ?
[0f781fb8]627            VbyteAlloc( *str1.Handle.ulink, bsize ); // create room for 2nd part at the end of string area
[f450f2f]628        } else {                                        // copy the two parts
[fe18b46]629            char * str1newBuf = VbyteAlloc( *str1.Handle.ulink, clnth );
630            char * str1oldBuf = str1.Handle.s;  // must read after VbyteAlloc call in case it gs's
631            str1.Handle.s = str1newBuf;
[4e8df745]632            memcpy( str1.Handle.s, str1oldBuf,  str1.Handle.lnth );
[f450f2f]633        } // if
[4e8df745]634        memcpy( str1.Handle.s + str1.Handle.lnth, buffer, bsize );
[f450f2f]635    } // if
636    str1.Handle.lnth = clnth;
637}
638
[681e12f]639void ?+=?(string_res & str1, const string_res & str2) {
[d8d512e]640    append( str1, str2.Handle.s, str2.Handle.lnth );
[f450f2f]641}
642
[e891349]643void append(string_res & str1, const string_res & str2, size_t maxlen) {
644    append( str1, str2.Handle.s, min(str2.Handle.lnth, maxlen) );
645}
646
[681e12f]647void ?+=?(string_res & s, char c) {
648    append( s, & c, 1 );
[f450f2f]649}
[e891349]650void ?+=?(string_res & s, const char * c) {
651    append( s, c, strlen(c) );
652}
[f450f2f]653
[38951c31]654///////////////////////////////////////////////////////////////////
655// Repetition
656
657void ?*=?(string_res & s, size_t factor) {
658    string_res s2 = { s, COPY_VALUE, 0, size(s) };
659    s = "";
660    for (factor) s += s2;
661}
662
[f450f2f]663//////////////////////////////////////////////////////////
664// Comparisons
665
[681e12f]666int strcmp(const string_res & s1, const string_res & s2) {
[416b443]667    // return 0;
668    int ans1 = memcmp(s1.Handle.s, s2.Handle.s, min(s1.Handle.lnth, s2.Handle.lnth));
669    if (ans1 != 0) return ans1;
670    return s1.Handle.lnth - s2.Handle.lnth;
[f450f2f]671}
672
[681e12f]673bool ?==?(const string_res & s1, const string_res & s2) { return strcmp(s1, s2) == 0; }
674bool ?!=?(const string_res & s1, const string_res & s2) { return strcmp(s1, s2) != 0; }
675bool ?>? (const string_res & s1, const string_res & s2) { return strcmp(s1, s2) >  0; }
676bool ?>=?(const string_res & s1, const string_res & s2) { return strcmp(s1, s2) >= 0; }
677bool ?<=?(const string_res & s1, const string_res & s2) { return strcmp(s1, s2) <= 0; }
678bool ?<? (const string_res & s1, const string_res & s2) { return strcmp(s1, s2) <  0; }
[416b443]679
[06280ad]680int strcmp (const string_res & s1, const char * s2) {
[416b443]681    string_res s2x = s2;
[681e12f]682    return strcmp(s1, s2x);
[f450f2f]683}
[416b443]684
[06280ad]685bool ?==?(const string_res & s1, const char * s2) { return strcmp(s1, s2) == 0; }
686bool ?!=?(const string_res & s1, const char * s2) { return strcmp(s1, s2) != 0; }
687bool ?>? (const string_res & s1, const char * s2) { return strcmp(s1, s2) >  0; }
688bool ?>=?(const string_res & s1, const char * s2) { return strcmp(s1, s2) >= 0; }
689bool ?<=?(const string_res & s1, const char * s2) { return strcmp(s1, s2) <= 0; }
690bool ?<? (const string_res & s1, const char * s2) { return strcmp(s1, s2) <  0; }
[416b443]691
[06280ad]692int strcmp (const char * s1, const string_res & s2) {
[416b443]693    string_res s1x = s1;
[681e12f]694    return strcmp(s1x, s2);
[f450f2f]695}
696
[06280ad]697bool ?==?(const char * s1, const string_res & s2) { return strcmp(s1, s2) == 0; }
698bool ?!=?(const char * s1, const string_res & s2) { return strcmp(s1, s2) != 0; }
699bool ?>? (const char * s1, const string_res & s2) { return strcmp(s1, s2) >  0; }
700bool ?>=?(const char * s1, const string_res & s2) { return strcmp(s1, s2) >= 0; }
701bool ?<=?(const char * s1, const string_res & s2) { return strcmp(s1, s2) <= 0; }
702bool ?<? (const char * s1, const string_res & s2) { return strcmp(s1, s2) <  0; }
[416b443]703
704
[f450f2f]705
706//////////////////////////////////////////////////////////
707// Search
708
[681e12f]709bool contains(const string_res & s, char ch) {
[9ca5e56]710    for ( i; size(s) ) {
[f450f2f]711        if (s[i] == ch) return true;
712    }
713    return false;
714}
715
[681e12f]716int find(const string_res & s, char search) {
[08ed947]717    return findFrom(s, 0, search);
[f450f2f]718}
719
[681e12f]720int findFrom(const string_res & s, size_t fromPos, char search) {
[08ed947]721    // FIXME: This paricular overload (find of single char) is optimized to use memchr.
722    // The general overload (find of string, memchr applying to its first character) and `contains` should be adjusted to match.
723    char * searchFrom = s.Handle.s + fromPos;
724    size_t searchLnth = s.Handle.lnth - fromPos;
725    int searchVal = search;
726    char * foundAt = (char *) memchr(searchFrom, searchVal, searchLnth);
727    if (foundAt == 0p) return s.Handle.lnth;
728    else return foundAt - s.Handle.s;
729}
[f450f2f]730
[681e12f]731int find(const string_res & s, const string_res & search) {
[08ed947]732    return findFrom(s, 0, search);
733}
734
[681e12f]735int findFrom(const string_res & s, size_t fromPos, const string_res & search) {
[08ed947]736    return findFrom(s, fromPos, search.Handle.s, search.Handle.lnth);
[f450f2f]737}
738
[06280ad]739int find(const string_res & s, const char * search) {
[08ed947]740    return findFrom(s, 0, search);
741}
[06280ad]742int findFrom(const string_res & s, size_t fromPos, const char * search) {
[08ed947]743    return findFrom(s, fromPos, search, strlen(search));
[f450f2f]744}
745
[06280ad]746int find(const string_res & s, const char * search, size_t searchsize) {
[08ed947]747    return findFrom(s, 0, search, searchsize);
748}
749
[06280ad]750int findFrom(const string_res & s, size_t fromPos, const char * search, size_t searchsize) {
[08ed947]751
752    /* Remaining implementations essentially ported from Sunjay's work */
753
754
[f450f2f]755    // FIXME: This is a naive algorithm. We probably want to switch to someting
756    // like Boyer-Moore in the future.
757    // https://en.wikipedia.org/wiki/String_searching_algorithm
758
759    // Always find the empty string
760    if (searchsize == 0) {
761        return 0;
762    }
763
[9ca5e56]764    for ( i; fromPos ~ s.Handle.lnth ) {
[f450f2f]765        size_t remaining = s.Handle.lnth - i;
766        // Never going to find the search string if the remaining string is
767        // smaller than search
768        if (remaining < searchsize) {
769            break;
770        }
771
772        bool matched = true;
[9ca5e56]773        for ( j; searchsize ) {
[f450f2f]774            if (search[j] != s.Handle.s[i + j]) {
775                matched = false;
776                break;
777            }
778        }
779        if (matched) {
780            return i;
781        }
782    }
783
784    return s.Handle.lnth;
785}
786
[681e12f]787bool includes(const string_res & s, const string_res & search) {
[f450f2f]788    return includes(s, search.Handle.s, search.Handle.lnth);
789}
790
[06280ad]791bool includes(const string_res & s, const char * search) {
[f450f2f]792    return includes(s, search, strlen(search));
793}
794
[06280ad]795bool includes(const string_res & s, const char * search, size_t searchsize) {
[f450f2f]796    return find(s, search, searchsize) < s.Handle.lnth;
797}
798
[681e12f]799bool startsWith(const string_res & s, const string_res & prefix) {
[f450f2f]800    return startsWith(s, prefix.Handle.s, prefix.Handle.lnth);
801}
802
[06280ad]803bool startsWith(const string_res & s, const char * prefix) {
[f450f2f]804    return startsWith(s, prefix, strlen(prefix));
805}
806
[06280ad]807bool startsWith(const string_res & s, const char * prefix, size_t prefixsize) {
[f450f2f]808    if (s.Handle.lnth < prefixsize) {
809        return false;
810    }
811    return memcmp(s.Handle.s, prefix, prefixsize) == 0;
812}
813
[681e12f]814bool endsWith(const string_res & s, const string_res & suffix) {
[f450f2f]815    return endsWith(s, suffix.Handle.s, suffix.Handle.lnth);
816}
817
[06280ad]818bool endsWith(const string_res & s, const char * suffix) {
[f450f2f]819    return endsWith(s, suffix, strlen(suffix));
820}
821
[06280ad]822bool endsWith(const string_res & s, const char * suffix, size_t suffixsize) {
[f450f2f]823    if (s.Handle.lnth < suffixsize) {
824        return false;
825    }
826    // Amount to offset the bytes pointer so that we are comparing the end of s
827    // to suffix. s.bytes + offset should be the first byte to compare against suffix
828    size_t offset = s.Handle.lnth - suffixsize;
829    return memcmp(s.Handle.s + offset, suffix, suffixsize) == 0;
830}
831
832    /* Back to Mike's work */
833
834
835///////////////////////////////////////////////////////////////////////////
836// charclass, include, exclude
837
[681e12f]838void ?{}( charclass_res & s, const string_res & chars) {
839    (s){ chars.Handle.s, chars.Handle.lnth };
[f450f2f]840}
841
[681e12f]842void ?{}( charclass_res & s, const char * chars ) {
843    (s){ chars, strlen(chars) };
[f450f2f]844}
845
[681e12f]846void ?{}( charclass_res & s, const char * chars, size_t charssize ) {
847    (s.chars){ chars, charssize };
[f450f2f]848    // now sort it ?
849}
850
[681e12f]851void ^?{}( charclass_res & s ) {
852    ^(s.chars){};
[f450f2f]853}
854
855static bool test( const charclass_res & mask, char c ) {
856    // instead, use sorted char list?
857    return contains( mask.chars, c );
858}
859
[681e12f]860int exclude(const string_res & s, const charclass_res & mask) {
[9ca5e56]861    for ( i; size(s) ) {
[f450f2f]862        if ( test(mask, s[i]) ) return i;
863    }
864    return size(s);
865}
866
[681e12f]867int include(const string_res & s, const charclass_res & mask) {
[9ca5e56]868    for ( i; size(s) ) {
[f450f2f]869        if ( ! test(mask, s[i]) ) return i;
870    }
871    return size(s);
872}
873
874//######################### VbyteHeap "implementation" #########################
875
876
877// Add a new HandleNode node n after the current HandleNode node.
878
[681e12f]879static void AddThisAfter( HandleNode & s, HandleNode & n ) with(s) {
[f450f2f]880#ifdef VbyteDebug
[681e12f]881    serr | "enter:AddThisAfter, s:" | &s | " n:" | &n;
[f450f2f]882#endif // VbyteDebug
[08ed947]883    // Performance note: we are on the critical path here. MB has ensured that the verifies don't contribute to runtime (are compiled away, like they're supposed to be).
[0f781fb8]884    verify( n.ulink != 0p );
[681e12f]885    verify( s.ulink == n.ulink );
[f450f2f]886    flink = n.flink;
887    blink = &n;
[681e12f]888    n.flink->blink = &s;
889    n.flink = &s;
[f450f2f]890#ifdef VbyteDebug
891    {
892                serr | "HandleList:";
893                serr | nlOff;
894                for ( HandleNode *ni = HeaderPtr->flink; ni != HeaderPtr; ni = ni->flink ) {
895                        serr | "\tnode:" | ni | " lnth:" | ni->lnth | " s:" | (void *)ni->s | ",\"";
[9ca5e56]896                        for ( i; ni->lnth ) {
[f450f2f]897                                serr | ni->s[i];
898                        } // for
899                        serr | "\" flink:" | ni->flink | " blink:" | ni->blink | nl;
900                } // for
901                serr | nlOn;
902    }
903    serr | "exit:AddThisAfter";
904#endif // VbyteDebug
905} // AddThisAfter
906
907
908// Delete the current HandleNode node.
909
[681e12f]910static void DeleteNode( HandleNode & s ) with(s) {
[f450f2f]911#ifdef VbyteDebug
[681e12f]912    serr | "enter:DeleteNode, s:" | &s;
[f450f2f]913#endif // VbyteDebug
914    flink->blink = blink;
915    blink->flink = flink;
916#ifdef VbyteDebug
917    serr | "exit:DeleteNode";
918#endif // VbyteDebug
919} //  DeleteNode
920
921
922// Allocates specified storage for a string from byte-string area. If not enough space remains to perform the
[6f7aff3]923// allocation, the garbage collection routine is called.
[f450f2f]924
[681e12f]925static char * VbyteAlloc( VbyteHeap & s, int size ) with(s) {
[f450f2f]926#ifdef VbyteDebug
927    serr | "enter:VbyteAlloc, size:" | size;
928#endif // VbyteDebug
929    uintptr_t NoBytes;
930    char *r;
931
932    NoBytes = ( uintptr_t )EndVbyte + size;
[681e12f]933    if ( NoBytes > ( uintptr_t )ExtVbyte ) {                    // enough room for new byte-string ?
934                garbage( s, size );                                                             // firer up the garbage collector
[4e8df745]935                verify( (( uintptr_t )EndVbyte + size) <= ( uintptr_t )ExtVbyte  && "garbage run did not free up required space" );
[f450f2f]936    } // if
937    r = EndVbyte;
938    EndVbyte += size;
939#ifdef VbyteDebug
940    serr | "exit:VbyteAlloc, r:" | (void *)r | " EndVbyte:" | (void *)EndVbyte | " ExtVbyte:" | ExtVbyte;
941#endif // VbyteDebug
942    return r;
943} // VbyteAlloc
944
945
[6f7aff3]946// Adjusts the last allocation in this heap by delta bytes, or resets this heap to be able to offer
947// new allocations of its original size + delta bytes. Positive delta means bigger;
948// negative means smaller.  A null return indicates that the original heap location has room for
949// the requested growth.  A non-null return indicates that copying to a new location is required
950// but has not been done; the returned value is the old heap storage location; `this` heap is
951// modified to reference the new location.  In the copy-requred case, the caller should use
952// VbyteAlloc to claim the new space, while doing optimal copying from old to new, then free old.
953
[681e12f]954static char * VbyteTryAdjustLast( VbyteHeap & s, int delta ) with(s) {
[6f7aff3]955    if ( ( uintptr_t )EndVbyte + delta <= ( uintptr_t )ExtVbyte ) {
956        // room available
957        EndVbyte += delta;
958        return 0p;
959    }
960
961    char *oldBytes = StartVbyte;
962
963    NoOfExtensions += 1;
964    CurrSize *= 2;
[08ed947]965    StartVbyte = EndVbyte = TEMP_ALLOC(char, CurrSize);
[6f7aff3]966    ExtVbyte = StartVbyte + CurrSize;
967
968    return oldBytes;
969}
970
971
[f450f2f]972// Move an existing HandleNode node h somewhere after the current HandleNode node so that it is in ascending order by
973// the address in the byte string area.
974
[681e12f]975static void MoveThisAfter( HandleNode & s, const HandleNode  & h ) with(s) {
[f450f2f]976#ifdef VbyteDebug
[681e12f]977    serr | "enter:MoveThisAfter, s:" | & s | " h:" | & h;
[f450f2f]978#endif // VbyteDebug
[0f781fb8]979    verify( h.ulink != 0p );
[681e12f]980    verify( s.ulink == h.ulink );
[f450f2f]981    if ( s < h.s ) {                                    // check argument values
982                // serr | "VbyteSM: Error - Cannot move byte string starting at:" | s | " after byte string starting at:"
983                //      | ( h->s ) | " and keep handles in ascending order";
984                // exit(-1 );
[218096f]985                verify( 0 && "VbyteSM: Error - Cannot move byte strings as requested and keep handles in ascending order");
[f450f2f]986    } // if
987
988    HandleNode *i;
989    for ( i = h.flink; i->s != 0 && s > ( i->s ); i = i->flink ); // find the position for this node after h
[681e12f]990    if ( & s != i->blink ) {
991                DeleteNode( s );
992                AddThisAfter( s, *i->blink );
[f450f2f]993    } // if
994#ifdef VbyteDebug
995    {
996        serr | "HandleList:";
997        serr | nlOff;
998        for ( HandleNode *n = HeaderPtr->flink; n != HeaderPtr; n = n->flink ) {
999            serr | "\tnode:" | n | " lnth:" | n->lnth | " s:" | (void *)n->s | ",\"";
[9ca5e56]1000            for ( i; n->lnth ) {
1001                        serr | n->s[i];
[f450f2f]1002            } // for
[6cc87c0]1003            serr | "\" flink:" | n->flink | " blink:" | n->blink | nl;
[f450f2f]1004        } // for
1005        serr | nlOn;
1006    }
[6cc87c0]1007    serr | "exit:MoveThisAfter";
[f450f2f]1008#endif // VbyteDebug
1009} // MoveThisAfter
1010
1011
1012
1013
1014
1015//######################### VbyteHeap #########################
1016
1017// Compare two byte strings in the byte-string area. The routine returns the following values:
1018//
1019// 1 => Src1-byte-string > Src2-byte-string
1020// 0 => Src1-byte-string = Src2-byte-string
1021// -1 => Src1-byte-string < Src2-byte-string
1022
[0f781fb8]1023int ByteCmp( char *Src1, int Src1Start, int Src1Lnth, char *Src2, int Src2Start, int Src2Lnth )  {
[f450f2f]1024#ifdef VbyteDebug
1025    serr | "enter:ByteCmp, Src1Start:" | Src1Start | " Src1Lnth:" | Src1Lnth | " Src2Start:" | Src2Start | " Src2Lnth:" | Src2Lnth;
1026#endif // VbyteDebug
1027    int cmp;
1028
1029    CharZip: for ( int i = 0; ; i += 1 ) {
1030        if ( i == Src2Lnth - 1 ) {
1031            for ( ; ; i += 1 ) {
1032                if ( i == Src1Lnth - 1 ) {
1033                    cmp = 0;
1034                    break CharZip;
1035                } // exit
1036                if ( Src1[Src1Start + i] != ' ') {
1037                        // SUSPECTED BUG:  this could be be why Peter got the bug report about == " "  (why is this case here at all?)
1038                    cmp = 1;
1039                    break CharZip;
1040                } // exit
1041            } // for
1042        } // exit
1043        if ( i == Src1Lnth - 1 ) {
1044            for ( ; ; i += 1 ) {
1045                if ( i == Src2Lnth - 1 ) {
1046                    cmp = 0;
1047                    break CharZip;
1048                } // exit
1049                if ( Src2[Src2Start + i] != ' ') {
1050                    cmp = -1;
1051                    break CharZip;
1052                } // exit
1053            } // for
1054        } // exit
1055      if ( Src2[Src2Start + i] != Src1[Src1Start+ i]) {
1056            cmp = Src1[Src1Start + i] > Src2[Src2Start + i] ? 1 : -1;
1057            break CharZip;
1058        } // exit
1059    } // for
1060#ifdef VbyteDebug
1061    serr | "exit:ByteCmp, cmp:" | cmp;
1062#endif // VbyteDebug
1063    return cmp;
1064} // ByteCmp
1065
1066
1067// The compaction moves all of the byte strings currently in use to the beginning of the byte-string area and modifies
1068// the handles to reflect the new positions of the byte strings. Compaction assumes that the handle list is in ascending
1069// order by pointers into the byte-string area.  The strings associated with substrings do not have to be moved because
1070// the containing string has been moved. Hence, they only require that their string pointers be adjusted.
1071
[681e12f]1072void compaction(VbyteHeap & s) with(s) {
[f450f2f]1073    HandleNode *h;
1074    char *obase, *nbase, *limit;
1075   
1076    NoOfCompactions += 1;
1077    EndVbyte = StartVbyte;
1078    h = Header.flink;                                   // ignore header node
[9ca5e56]1079    for () {
[94647b0b]1080                memmove( EndVbyte, h->s, h->lnth );
[f450f2f]1081                obase = h->s;
1082                h->s = EndVbyte;
1083                nbase = h->s;
1084                EndVbyte += h->lnth;
1085                limit = obase + h->lnth;
1086                h = h->flink;
1087               
1088                // check if any substrings are allocated within a string
1089               
[9ca5e56]1090                for () {
[f450f2f]1091                        if ( h == &Header ) break;                      // end of header list ?
1092                        if ( h->s >= limit ) break;                     // outside of current string ?
1093                        h->s = nbase + (( uintptr_t )h->s - ( uintptr_t )obase );
1094                        h = h->flink;
1095                } // for
1096                if ( h == &Header ) break;                      // end of header list ?
1097    } // for
1098} // compaction
1099
1100
[08ed947]1101static double heap_expansion_freespace_threshold = 0.1;  // default inherited from prior work: expand heap when less than 10% "free" (i.e. garbage)
1102                                                         // probably an unreasonable default, but need to assess early-round tests on changing it
1103
1104void TUNING_set_string_heap_liveness_threshold( double val ) {
1105    heap_expansion_freespace_threshold = 1.0 - val;
1106}
1107
1108
[f450f2f]1109// Garbage determines the amount of free space left in the heap and then reduces, leave the same, or extends the size of
1110// the heap.  The heap is then compacted in the existing heap or into the newly allocated heap.
1111
[681e12f]1112void garbage(VbyteHeap & s, int minreq ) with(s) {
[f450f2f]1113#ifdef VbyteDebug
1114    serr | "enter:garbage";
1115    {
1116                serr | "HandleList:";
1117                for ( HandleNode *n = Header.flink; n != &Header; n = n->flink ) {
1118                        serr | nlOff;
1119                        serr | "\tnode:" | n | " lnth:" | n->lnth | " s:" | (void *)n->s | ",\"";
[9ca5e56]1120                        for ( i; n->lnth ) {
[f450f2f]1121                                serr | n->s[i];
1122                        } // for
1123                        serr | nlOn;
1124                        serr | "\" flink:" | n->flink | " blink:" | n->blink;
1125                } // for
1126    }
1127#endif // VbyteDebug
1128    int AmountUsed, AmountFree;
1129
1130    AmountUsed = 0;
1131    for ( HandleNode *i = Header.flink; i != &Header; i = i->flink ) { // calculate amount of byte area used
1132                AmountUsed += i->lnth;
1133    } // for
1134    AmountFree = ( uintptr_t )ExtVbyte - ( uintptr_t )StartVbyte - AmountUsed;
1135   
[08ed947]1136    if ( ( double ) AmountFree < ( CurrSize * heap_expansion_freespace_threshold ) || AmountFree < minreq ) {   // free space less than threshold or not enough to serve cur request
[f450f2f]1137
[681e12f]1138                extend( s, max( CurrSize, minreq ) );                           // extend the heap
[f450f2f]1139
1140                        //  Peter says, "This needs work before it should be used."
1141                        //  } else if ( AmountFree > CurrSize / 2 ) {           // free space greater than 3 times the initial allocation ?
1142                        //              reduce(( AmountFree / CurrSize - 3 ) * CurrSize ); // reduce the memory
1143
[97c215f]1144        // `extend` implies a `compaction` during the copy
1145
1146    } else {
[681e12f]1147        compaction(s);                                  // in-place
[97c215f]1148    }// if
[f450f2f]1149#ifdef VbyteDebug
1150    {
1151                serr | "HandleList:";
1152                for ( HandleNode *n = Header.flink; n != &Header; n = n->flink ) {
1153                        serr | nlOff;
1154                        serr | "\tnode:" | n | " lnth:" | n->lnth | " s:" | (void *)n->s | ",\"";
[9ca5e56]1155                        for ( i; n->lnth ) {
[f450f2f]1156                                serr | n->s[i];
1157                        } // for
1158                        serr | nlOn;
1159                        serr | "\" flink:" | n->flink | " blink:" | n->blink;
1160                } // for
1161    }
1162    serr | "exit:garbage";
1163#endif // VbyteDebug
1164} // garbage
1165
1166#undef VbyteDebug
1167
1168
1169
1170// Extend the size of the byte-string area by creating a new area and copying the old area into it. The old byte-string
1171// area is deleted.
1172
[681e12f]1173void extend( VbyteHeap & s, int size ) with (s) {
[f450f2f]1174#ifdef VbyteDebug
1175    serr | "enter:extend, size:" | size;
1176#endif // VbyteDebug
1177    char *OldStartVbyte;
1178
1179    NoOfExtensions += 1;
1180    OldStartVbyte = StartVbyte;                         // save previous byte area
1181   
1182    CurrSize += size > InitSize ? size : InitSize;      // minimum extension, initial size
[08ed947]1183    StartVbyte = EndVbyte = TEMP_ALLOC(char, CurrSize);
[f450f2f]1184    ExtVbyte = (void *)( StartVbyte + CurrSize );
[681e12f]1185    compaction(s);                                      // copy from old heap to new & adjust pointers to new heap
[7b0e8b7]1186    free( OldStartVbyte );                              // release old heap
[f450f2f]1187#ifdef VbyteDebug
1188    serr | "exit:extend, CurrSize:" | CurrSize;
1189#endif // VbyteDebug
1190} // extend
1191
[7b0e8b7]1192//WIP
1193#if 0
[f450f2f]1194
1195// Extend the size of the byte-string area by creating a new area and copying the old area into it. The old byte-string
1196// area is deleted.
1197
1198void VbyteHeap::reduce( int size ) {
1199#ifdef VbyteDebug
1200    serr | "enter:reduce, size:" | size;
1201#endif // VbyteDebug
1202    char *OldStartVbyte;
1203
1204    NoOfReductions += 1;
1205    OldStartVbyte = StartVbyte;                         // save previous byte area
1206   
1207    CurrSize -= size;
1208    StartVbyte = EndVbyte = new char[CurrSize];
1209    ExtVbyte = (void *)( StartVbyte + CurrSize );
1210    compaction();                                       // copy from old heap to new & adjust pointers to new heap
1211    delete  OldStartVbyte;                              // release old heap
1212#ifdef VbyteDebug
1213    serr | "exit:reduce, CurrSize:" | CurrSize;
1214#endif // VbyteDebug
1215} // reduce
1216
1217
1218#endif
Note: See TracBrowser for help on using the repository browser.