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

Last change on this file since f945fa7 was 1955fac, checked in by Peter A. Buhr <pabuhr@…>, 4 weeks ago

fix sense of assert condition

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