source: libcfa/src/collections/string_res.cfa@ 3c1e432

Last change on this file since 3c1e432 was 768d091, checked in by Peter A. Buhr <pabuhr@…>, 9 months ago

rename I/O function "clear" to "clearerr"

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