source: doc/theses/mike_brooks_MMath/string.tex@ b0296dba

Last change on this file since b0296dba was b0296dba, checked in by Peter A. Buhr <pabuhr@…>, 5 months ago

more proofreading of string chapter

  • Property mode set to 100644
File size: 71.6 KB
Line 
1\chapter{String}
2
3\vspace*{-20pt}
4This chapter presents my work on designing and building a modern string type in \CFA.
5The discussion starts with an overview of string API, then a number of interesting string problems, followed by how these issues are resolved in this work.
6
7
8\section{String Operations}
9
10% https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)
11
12\VRef[Figure]{f:StrApiCompare} shows a general comparison of string APIs for C, \CC, Java and \CFA.
13It provides a classic ``cheat sheet'', summarizing the names of the most-common closely-equivalent operations.
14The over-arching commonality is that operations work on groups of characters for assigning, copying, scanning, and updating.
15
16\begin{figure}[h]
17\begin{cquote}
18\begin{tabular}{@{}l|l|l|l@{}}
19C @char [ ]@ & \CC @string@ & Java @String@ & \CFA @string@ \\
20\hline
21@strcpy@, @strncpy@ & @=@ & @=@ & @=@ \\
22@strcat@, @strncat@ & @+@ & @+@ & @+@ \\
23@strcmp@, @strncmp@ & @==@, @!=@, @<@, @<=@, @>@, @>=@
24 & @equals@, @compareTo@ & @==@, @!=@, @<@, @<=@, @>@, @>=@ \\
25@strlen@ & @length@, @size@ & @length@ & @size@ \\
26@[ ]@ & @[ ]@ & @charAt@ & @[ ]@ \\
27@strncpy@ & @substr@ & @substring@ & @( )@ RHS @=@ \\
28@strncpy@ & @replace@ & @replace@ & @( )@ LHS @=@ \\
29@strstr@ & @find@ & @indexOf@ & @find@ \\
30@strcspn@ & @find_first_of@ & @matches@ & @include@ \\
31@strspn@ & @find_first_not_of@ & @matches@ & @exclude@ \\
32n/a & @c_str@, @data@ & n/a & @strcpy@, @strncpy@ \\
33\end{tabular}
34\end{cquote}
35\caption{Language comparison of string API}
36\label{f:StrApiCompare}
37\end{figure}
38
39As mentioned in \VRef{s:String}, a C string uses null termination rather than a length, which leads to explicit storage management;
40hence, most of its group operations are error prone and expensive due to copying.
41Most high-level string libraries use a separate length field and specialized storage management to implement group operations.
42Interestingly, \CC strings retain null termination in case it is needed to interface with C library functions.
43\begin{cfa}
44int open( @const char * pathname@, int flags );
45string fname{ "test.cc" );
46open( fname.@c_str()@, O_RDONLY ); // null terminated value of string
47\end{cfa}
48Here, the \CC @c_str@ function does not create a new null-terminated C string from the \CC string, as that requires passing ownership of the C string to the caller for eventual deletion.\footnote{
49C functions like \lstinline{strdup} do return allocated storage that must be freed by the caller.}
50% Instead, each \CC string is null terminated just in case it might be needed for this purpose.
51Providing this backwards compatibility with C has a ubiquitous performance and storage cost.
52
53
54\section{\CFA \lstinline{string} type}
55\label{s:stringType}
56
57The \CFA string type is for manipulation of dynamically-sized character-strings versus C @char *@ type for manipulation of statically-sized null-terminated character-strings.
58Hence, the amount of storage for a \CFA string changes dynamically at runtime to fit the string size, whereas the amount of storage for a C string is fixed at compile time.
59As a result, a @string@ declaration does not specify a maximum length, where a C string must.
60The maximum storage for a \CFA @string@ value is @size_t@ characters, which is $2^{32}$ or $2^{64}$ respectively.
61A \CFA string manages its length separately from the string, so there is no null (@'\0'@) terminating value at the end of a string value.
62Hence, a \CFA string cannot be passed to a C string manipulation function, such as @strcat@.
63Like C strings, characters in a @string@ are numbered from the left starting at 0 (because subscripting is zero-origin), and in \CFA numbered from the right starting at -1.
64\begin{cquote}
65\rm
66\begin{tabular}{@{}rrrrll@{}}
67\small\tt "a & \small\tt b & \small\tt c & \small\tt d & \small\tt e" \\
680 & 1 & 2 & 3 & 4 & left to right index \\
69-5 & -4 & -3 & -2 & -1 & right to left index
70\end{tabular}
71\end{cquote}
72The following operations manipulate an instance of type @string@, where the discussion assumes the following declarations.
73\begin{cfa}
74#include @<string.hfa>@
75@string@ s = "abcde", name = "MIKE", digit = "0123456789";
76const char cs[$\,$] = "abc";
77int i;
78\end{cfa}
79Note, the include file @<string.hfa>@ to access type @string@.
80
81
82\subsection{Implicit String Conversions}
83
84The ability to convert from internal (machine) to external (human) format is useful in situations other than I/O.
85Hence, the basic types @char@, @char *@, @int@, @double@, @_Complex@, including any signness and size variations, implicitly convert to type @string@.
86\begin{cquote}
87\setlength{\tabcolsep}{15pt}
88\begin{tabular}{@{}l|ll|l@{}}
89\begin{cfa}
90string s;
91s = 'x';
92s = "abc";
93s = cs;
94s = 45hh;
95s = 45h;
96\end{cfa}
97&
98\begin{cfa}
99
100"x"
101"abc"
102"abc"
103"45"
104"45"
105\end{cfa}
106&
107\begin{cfa}
108 s = (ssize_t)MIN;
109 s = (size_t)MAX;
110 s = 5.5;
111 s = 5.5L;
112 s = 5.5+3.4i;
113 s = 5.5L+3.4Li;
114\end{cfa}
115&
116\begin{cfa}
117"-9223372036854775808"
118"18446744073709551615"
119"5.5"
120"5.5"
121"5.5+3.4i"
122"5.5+3.4i"
123\end{cfa}
124\end{tabular}
125\end{cquote}
126Conversions can be explicitly specified using a compound literal.
127\begin{cfa}
128s = (string){ "abc" }; $\C{// converts char * to string}$
129s = (string){ 5 }; $\C{// converts int to string}$
130s = (string){ 5.5 }; $\C{// converts double to string}$
131\end{cfa}
132
133Conversions from @string@ to @char *@ attempt to be safe:
134either by requiring the maximum length of the @char *@ storage (@strncpy@) or allocating the @char *@ storage for the string characters (ownership), meaning the programmer must free the storage.
135Note, a C string is always null terminated, implying a minimum size of 1 character.
136\begin{cquote}
137\setlength{\tabcolsep}{15pt}
138\begin{tabular}{@{}l|l@{}}
139\begin{cfa}
140strncpy( cs, s, sizeof(cs) );
141char * cp = s;
142delete( cp );
143cp = s + ' ' + s;
144delete( cp );
145\end{cfa}
146&
147\begin{cfa}
148"abc\0", in place
149"abcde\0", malloc
150ownership
151"abcde abcde\0", malloc
152ownership
153\end{cfa}
154\end{tabular}
155\end{cquote}
156
157
158\subsection{Length}
159
160The @len@ operation (short for @strlen@) returns the length of a C or \CFA string.
161For compatibility, @strlen@ also works with \CFA strings.
162\begin{cquote}
163\setlength{\tabcolsep}{15pt}
164\begin{tabular}{@{}l|l@{}}
165\begin{cfa}
166i = len( "" );
167i = len( "abc" );
168i = len( cs );
169i = strlen( cs );
170i = len( name );
171i = strlen( name );
172\end{cfa}
173&
174\begin{cfa}
1750
1763
1773
1783
1794
1804
181\end{cfa}
182\end{tabular}
183\end{cquote}
184
185
186\subsection{Comparison Operators}
187
188The binary relational, @<@, @<=@, @>@, @>=@, and equality, @==@, @!=@, operators compare \CFA string values using lexicographical ordering, where longer strings are greater than shorter strings.
189In C, these operators compare the C string pointer not its value, which does not match programmer expectation.
190C strings use function @strcmp@ to lexicographically compare the string value.
191
192
193\subsection{Concatenation}
194
195The binary operators @+@ and @+=@ concatenate C @char@, @char *@ and \CFA strings, creating the sum of the characters.
196\par\noindent
197\begin{tabular}{@{}l|l@{\hspace{15pt}}l|l@{\hspace{15pt}}l|l@{}}
198\begin{cfa}
199s = "";
200s = 'a' + 'b';
201s = 'a' + "b";
202s = "a" + 'b';
203s = "a" + "b";
204\end{cfa}
205&
206\begin{cfa}
207
208"ab"
209"ab"
210"ab"
211"ab"
212\end{cfa}
213&
214\begin{cfa}
215s = "";
216s = 'a' + 'b' + s;
217s = 'a' + 'b' + s;
218s = 'a' + "b" + s;
219s = "a" + 'b' + s;
220\end{cfa}
221&
222\begin{cfa}
223
224"ab"
225"abab"
226"ababab"
227"abababab"
228\end{cfa}
229&
230\begin{cfa}
231s = "";
232s = s + 'a' + 'b';
233s = s + 'a' + "b";
234s = s + "a" + 'b';
235s = s + "a" + "b";
236\end{cfa}
237&
238\begin{cfa}
239
240"ab"
241"abab"
242"ababab"
243"abababab"
244\end{cfa}
245\end{tabular}
246\par\noindent
247However, including @<string.hfa>@ can result in ambiguous uses of the overloaded @+@ operator.\footnote{Combining multiple packages in any programming language can result in name clashes or ambiguities.}
248While subtracting characters or pointers has a low-level use-case
249\begin{cfa}
250ch - '0' $\C[2in]{// find character offset}$
251cs - cs2; $\C{// find pointer offset}\CRT$
252\end{cfa}
253addition is less obvious
254\begin{cfa}
255ch + 'b' $\C[2in]{// add character values}$
256cs + 'a'; $\C{// move pointer cs['a']}\CRT$
257\end{cfa}
258There is a legitimate use case for arithmetic with @signed@/@unsigned@ characters (bytes), but these types are treated differently from @char@ in \CC and \CFA.
259However, backwards compatibility makes is impossible to restrict or remove addition on type @char@.
260Similarly, it is impossible to restrict or remove addition on type @char *@ because (unfortunately) it is subscripting: @cs + 'a'@ implies @cs['a']@ or @'a'[cs]@.
261
262Fortunately, the prior concatenation examples show complex mixed-mode interactions among @char@, @char *@, and @string@ (variables are the same as constants) work correctly.
263The reason is that the \CFA type-system handles this kind of overloading well using the left-hand assignment-type and complex conversion costs.
264Hence, the type system correctly handles all uses of addition (explicit or implicit) for @char *@.
265\begin{cfa}
266printf( "%s %s %s %c %c\n", "abc", cs, cs + 3, cs['a'], 'a'[cs] );
267\end{cfa}
268Only @char@ addition can result in ambiguities, and only when there is no left-hand information.
269\begin{cfa}
270ch = ch + 'b'; $\C[2in]{// LHS disambiguate, add character values}$
271s = 'a' + 'b'; $\C{// LHS disambiguate, concatenate characters}$
272printf( "%c\n", @'a' + 'b'@ ); $\C[2in]{// no LHS information, ambiguous}$
273printf( "%c\n", @(return char)@('a' + 'b') ); $\C{// disambiguate with ascription cast}$
274\end{cfa}
275The ascription cast, @(return T)@, disambiguates by stating a (LHS) type to use during expression resolution (not a conversion).
276Fortunately, character addition without LHS information is rare in C/\CFA programs, so repurposing the operator @+@ for @string@ types is not a problem.
277Note, other programming languages that repurpose @+@ for concatenation, could have a similar ambiguity issue.
278
279Interestingly, \CC cannot support this generality because it does not use the left-hand side of assignment in expression resolution.
280While it can special case some combinations:
281\begin{c++}
282s = 'a' + s; $\C[2in]{// compiles in C++}$
283s = "a" + s;
284\end{c++}
285it cannot generalize to any number of steps:
286\begin{c++}
287s = 'a' + 'b' + s; $\C{// does not compile in C++}\CRT$
288s = "a" + "b" + s;
289\end{c++}
290
291
292\subsection{Repetition}
293
294The binary operators @*@ and @*=@ repeat a string $N$ times.
295If $N = 0$, a zero length string, @""@, is returned.
296\begin{cquote}
297\setlength{\tabcolsep}{15pt}
298\begin{tabular}{@{}l|l@{}}
299\begin{cfa}
300s = 'x' * 0;
301s = 'x' * 3;
302s = "abc" * 3;
303s = (name + ' ') * 3;
304\end{cfa}
305&
306\begin{cfa}
307"
308"xxx"
309"abcabcabc"
310"MIKE MIKE MIKE "
311\end{cfa}
312\end{tabular}
313\end{cquote}
314Like concatenation, there is a potential ambiguity with multiplication of characters;
315multiplication for pointers does not exist in C.
316\begin{cfa}
317ch = ch * 3; $\C[2in]{// LHS disambiguate, multiply character values}$
318s = 'a' * 3; $\C{// LHS disambiguate, concatenate characters}$
319printf( "%c\n", @'a' * 3@ ); $\C[2in]{// no LHS information, ambiguous}$
320printf( "%c\n", @(return char)@('a' * 3) ); $\C{// disambiguate with ascription cast}$
321\end{cfa}
322Fortunately, character multiplication without LHS information is even rarer than addition, so repurposing the operator @*@ for @string@ types is not a problem.
323
324
325\subsection{Substring}
326The substring operation returns a subset of a string starting at a position in the string and traversing a length or matching a pattern string.
327\begin{cquote}
328\setlength{\tabcolsep}{10pt}
329\begin{tabular}{@{}l|ll|l@{}}
330\multicolumn{2}{c}{\textbf{length}} & \multicolumn{2}{c}{\textbf{pattern}} \\
331\begin{cfa}
332s = name( 2, 2 );
333s = name( 3, -2 );
334s = name( 2, 8 );
335s = name( 0, -1 );
336s = name( -1, -1 );
337s = name( -3 );
338\end{cfa}
339&
340\begin{cfa}
341"KE"
342"IK"
343"KE", clip length to 2
344"", beyond string clip to null
345"K"
346"IKE", to end of string
347\end{cfa}
348&
349\begin{cfa}
350s = name( "IK" );
351s = name( "WW" );
352
353
354
355
356\end{cfa}
357&
358\begin{cfa}
359"IK"
360""
361
362
363
364
365\end{cfa}
366\end{tabular}
367\end{cquote}
368A negative starting position is a specification from the right end of the string.
369A negative length means that characters are selected in the opposite (right to left) direction from the starting position.
370If the substring request extends beyond the beginning or end of the string, it is clipped (shortened) to the bounds of the string.
371If the substring request is completely outside of the original string, a null string is returned.
372The pattern-form either returns the pattern string is the pattern matches or a null string if the pattern does not match.
373The usefulness of this mechanism is discussed next.
374
375The substring operation can appear on the left side of assignment, where it defines a replacement substring.
376The length of the right string may be shorter, the same, or longer than the length of left string.
377Hence, the left string may decrease, stay the same, or increase in length.
378\begin{cquote}
379\setlength{\tabcolsep}{15pt}
380\begin{tabular}{@{}l|l@{}}
381\begin{cfa}[escapechar={}]
382digit( 3, 3 ) = "";
383digit( 4, 3 ) = "xyz";
384digit( 7, 0 ) = "***";
385digit(-4, 3 ) = "$$$";
386digit( 5 ) = "LLL";
387\end{cfa}
388&
389\begin{cfa}[escapechar={}]
390"0126789"
391"0126xyz"
392"0126xyz"
393"012$$$z"
394"012$$LLL"
395\end{cfa}
396\end{tabular}
397\end{cquote}
398Now pattern matching is useful on the left-hand side of assignment.
399\begin{cquote}
400\setlength{\tabcolsep}{15pt}
401\begin{tabular}{@{}l|l@{}}
402\begin{cfa}[escapechar={}]
403digit( "$$" ) = "345";
404digit( "LLL") = "6789";
405\end{cfa}
406&
407\begin{cfa}
408"012345LLL"
409"0123456789"
410\end{cfa}
411\end{tabular}
412\end{cquote}
413Extending the pattern to a regular expression is a possible extension.
414
415The replace operation extensions substring to substitute all occurrences.
416\begin{cquote}
417\setlength{\tabcolsep}{15pt}
418\begin{tabular}{@{}l|l@{}}
419\begin{cfa}
420s = replace( "PETER", "E", "XX" );
421s = replace( "PETER", "ET", "XX" );
422s = replace( "PETER", "W", "XX" );
423\end{cfa}
424&
425\begin{cfa}
426"PXXTXXR"
427"PXXER"
428"PETER"
429\end{cfa}
430\end{tabular}
431\end{cquote}
432The replacement is done left-to-right and substituted text is not examined for replacement.
433
434
435\subsection{Searching}
436
437The find operation returns the position of the first occurrence of a key in a string.
438If the key does not appear in the string, the length of the string is returned.
439\begin{cquote}
440\setlength{\tabcolsep}{15pt}
441\begin{tabular}{@{}l|l@{}}
442\begin{cfa}
443i = find( digit, '3' );
444i = find( digit, "45" );
445i = find( digit, "abc" );
446\end{cfa}
447&
448\begin{cfa}
4493
4504
45110
452\end{cfa}
453\end{tabular}
454\end{cquote}
455
456A character-class operation indicate if a string is composed completely of a particular class of characters, \eg, alphabetic, numeric, vowels, \etc.
457\begin{cquote}
458\setlength{\tabcolsep}{15pt}
459\begin{tabular}{@{}l|l@{}}
460\begin{cfa}
461charclass vowels{ "aeiouy" };
462i = include( "aaeiuyoo", vowels );
463i = include( "aabiuyoo", vowels );
464\end{cfa}
465&
466\begin{cfa}
467
4688 // compliant
4692 // b non-compliant
470\end{cfa}
471\end{tabular}
472\end{cquote}
473@vowels@ defines a character class and function @include@ checks if all characters in the string appear in the class (compliance).
474The position of the last character is returned if the string is compliant or the position of the first non-compliant character.
475There is no relationship between the order of characters in the two strings.
476Function @exclude@ is the reverse of @include@, checking if all characters in the string are excluded from the class (compliance).
477\begin{cquote}
478\setlength{\tabcolsep}{15pt}
479\begin{tabular}{@{}l|l@{}}
480\begin{cfa}
481i = exclude( "cdbfghmk", vowels );
482i = exclude( "cdyfghmk", vowels );
483\end{cfa}
484&
485\begin{cfa}
4868 // compliant
4872 // y non-compliant
488\end{cfa}
489\end{tabular}
490\end{cquote}
491Both forms can return the longest substring of compliant characters.
492\begin{cquote}
493\setlength{\tabcolsep}{15pt}
494\begin{tabular}{@{}l|l@{}}
495\begin{cfa}
496s = include( "aaeiuyoo", vowels );
497s = include( "aabiuyoo", vowels );
498s = exclude( "cdbfghmk", vowels );
499s = exclude( "cdyfghmk", vowels );
500\end{cfa}
501&
502\begin{cfa}
503"aaeiuyoo"
504"aa"
505"cdbfghmk"
506"cd"
507\end{cfa}
508\end{tabular}
509\end{cquote}
510
511There are versions of @include@ and @exclude@, returning a position or string, taking a validation function, like one of the C character-class routines.\footnote{It is part of the hereditary of C that these function take and return an \lstinline{int} rather than a \lstinline{char}, which affects the function type.}
512\begin{cquote}
513\setlength{\tabcolsep}{15pt}
514\begin{tabular}{@{}l|l@{}}
515\begin{cfa}
516i = include( "1FeC34aB", @isxdigit@ );
517i = include( ".,;'!\"", @ispunct@ );
518i = include( "XXXx", @isupper@ );
519\end{cfa}
520&
521\begin{cfa}
5228 // compliant
5236 // compliant
5243 // non-compliant
525\end{cfa}
526\end{tabular}
527\end{cquote}
528These operations perform an apply of the validation function to each character, and it returns a boolean indicating a stopping condition.
529The position of the last character is returned if the string is compliant or the position of the first non-compliant character.
530
531The translate operation returns a string with each character transformed by one of the C character transformation functions.
532\begin{cquote}
533\setlength{\tabcolsep}{15pt}
534\begin{tabular}{@{}l|l@{}}
535\begin{cfa}
536s = translate( "abc", @toupper@ );
537s = translate( "ABC", @tolower@ );
538int tospace( int c ) { return isspace( c ) ? ' ' : c; }
539s = translate( "X X\tX\nX", @tospace@ );
540\end{cfa}
541&
542\begin{cfa}
543"ABC"
544"abc"
545
546"X X X X"
547\end{cfa}
548\end{tabular}
549\end{cquote}
550
551
552\subsection{Returning N on Search Failure}
553
554Some of the prior string operations are composite, \eg string operations returning the longest substring of compliant characters (@include@) are built using a search and then substring the appropriate text.
555However, string search can fail, which is reported as an alternate search outcome, possibly an exception.
556Many string libraries use a return code to indicate search failure, with a failure value of @0@ or @-1@ (PL/I~\cite{PLI} returns @0@).
557This semantics leads to the awkward pattern, which can appear many times in a string library or user code.
558\begin{cfa}
559i = exclude( s, alpha );
560if ( i != -1 ) return s( 0, i );
561else return "";
562\end{cfa}
563
564\CFA also adopts a return code but the failure value is taken from the index-of function in APL~\cite{apl}, which returns the length of the target string $N$ (or $N+1$ for 1 origin).
565This semantics allows many search and substring functions to be written without conditions, \eg:
566\begin{cfa}
567string include( const string & s, int (*f)( int ) ) { return @s( 0, include( s, f ) )@; }
568string exclude( const string & s, int (*f)( int ) ) { return @s( 0, exclude( s, f ) )@; }
569\end{cfa}
570In string systems with an $O(1)$ length operator, checking for failure is low cost.
571\begin{cfa}
572if ( include( line, alpha ) == len( line ) ) ... // not found, 0 origin
573\end{cfa}
574\VRef[Figure]{f:ExtractingWordsText} compares \CC and \CFA string code for extracting words from a line of text, repeatedly removing non-word text and then a word until the line is empty.
575The \CFA code is simpler solely because of the choice for indicating search failure.
576(It is possible to simplify the \CC version by concatenating a sentinel character at the end of the line so the call to @find_first_not_of@ does not fail.)
577
578\begin{figure}
579\begin{cquote}
580\setlength{\tabcolsep}{15pt}
581\begin{tabular}{@{}l|l@{}}
582\multicolumn{1}{c}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\CFA}} \\
583\begin{cfa}
584for ( ;; ) {
585 string::size_type posn = line.find_first_of( alpha );
586 if ( posn == string::npos ) break;
587 line = line.substr( posn );
588 posn = line.find_first_not_of( alpha );
589 if ( posn != string::npos ) {
590 cout << line.substr( 0, posn ) << endl;
591 line = line.substr( posn );
592 } else {
593 cout << line << endl;
594 line = "";
595 }
596}
597\end{cfa}
598&
599\begin{cfa}
600for ( ;; ) {
601 size_t posn = exclude( line, alpha );
602 if ( posn == len( line ) ) break;
603 line = line( posn );
604 posn = include( line, alpha );
605
606 sout | line( 0, posn );
607 line = line( posn );
608
609
610
611
612}
613\end{cfa}
614\end{tabular}
615\end{cquote}
616\caption{Extracting Words from Line of Text}
617\label{f:ExtractingWordsText}
618\end{figure}
619
620
621\subsection{C Compatibility}
622
623To ease conversion from C to \CFA, \CFA provides companion C @string@ functions.
624Hence, it is possible to convert a block of C string operations to \CFA strings just by changing the type @char *@ to @string@.
625\begin{cfa}
626char s[32]; // string s;
627strlen( s );
628strnlen( s, 3 );
629strcmp( s, "abc" );
630strncmp( s, "abc", 3 );
631strcpy( s, "abc" );
632strncpy( s, "abcdef", 3 );
633strcat( s, "xyz" );
634strncat( s, "uvwxyz", 3 );
635\end{cfa}
636However, the conversion fails with I/O because @printf@ cannot print a @string@ using format code @%s@ because \CFA strings are not null terminated.
637Nevertheless, this capability does provide a useful starting point for conversion to safer \CFA strings.
638
639
640\subsection{I/O Operators}
641
642The ability to input and output strings is as essential as for any other type.
643The goal for character I/O is to also work with groups rather than individual characters.
644A comparison with \CC string I/O is presented as a counterpoint to \CFA string I/O.
645
646The \CC output @<<@ and input @>>@ operators are defined on type @string@.
647\CC output for @char@, @char *@, and @string@ are similar.
648The \CC manipulators are @setw@, and its associated width controls @left@, @right@ and @setfill@.
649\begin{cquote}
650\setlength{\tabcolsep}{15pt}
651\begin{tabular}{@{}l|l@{}}
652\begin{c++}
653string s = "abc";
654cout << setw(10) << left << setfill( 'x' ) << s << endl;
655\end{c++}
656&
657\begin{c++}
658
659"abcxxxxxxx"
660\end{c++}
661\end{tabular}
662\end{cquote}
663
664The \CFA input/output operator @|@ is defined on type @string@.
665\CFA output for @char@, @char *@, and @string@ are similar.
666The \CFA manipulators are @bin@, @oct@, @hex@, @wd@, and its associated width control and @left@.
667\begin{cquote}
668\setlength{\tabcolsep}{15pt}
669\begin{tabular}{@{}l|l@{}}
670\begin{cfa}
671string s = "abc";
672sout | bin( s ) | nl
673 | oct( s ) | nl
674 | hex( s ) | nl
675 | wd( 10, s ) | nl
676 | wd( 10, 2, s ) | nl
677 | left( wd( 10, s ) );
678\end{cfa}
679&
680\begin{cfa}
681
682"0b1100001 0b1100010 0b1100011"
683"0141 0142 0143"
684"0x61 0x62 0x63"
685" abc"
686" ab"
687"abc "
688\end{cfa}
689\end{tabular}
690\end{cquote}
691
692\CC input matching for @char@, @char *@, and @string@ are similar, where \emph{all} input characters are read from the current point in the input stream to the end of the type size, format width, whitespace, end of line (@'\n'@), or end of file.
693The \CC manipulator is @setw@ to restrict the size.
694Reading into a @char@ is safe as the size is 1, @char *@ is unsafe without using @setw@ to constraint the length (which includes @'\0'@), @string@ is safe as its grows dynamically as characters are read.
695\begin{cquote}
696\setlength{\tabcolsep}{15pt}
697\begin{tabular}{@{}l|l@{}}
698\begin{c++}
699char ch, c[10];
700string s;
701cin >> ch >> setw( 5 ) >> c >> s;
702@abcde fg@
703\end{c++}
704&
705\begin{c++}
706
707
708'a' "bcde" "fg"
709
710\end{c++}
711\end{tabular}
712\end{cquote}
713Input text can be gulped, including whitespace, from the current point to an arbitrary delimiter character using @getline@.
714
715The \CFA philosophy for input is that, for every constant type in C, these constants should be usable as input.
716For example, the complex constant @3.5+4.1i@ can appear as input to a complex variable.
717\CFA input matching for @char@, @char *@, and @string@ are similar.
718C-strings may only be read with a width field, which should match the string size.
719Certain input manipulators support a scanset, which is a simple regular expression from @printf@.
720The \CFA manipulators for these types are @wdi@,\footnote{Due to an overloading issue in the type-resolver, the input width name must be temporarily different from the output, \lstinline{wdi} versus \lstinline{wd}.} and its associated width control and @left@, @quote@, @incl@, @excl@, and @getline@.
721\begin{cquote}
722\setlength{\tabcolsep}{10pt}
723\begin{tabular}{@{}l|l@{}}
724\begin{c++}
725char ch, c[10];
726string s;
727sin | ch | wdi( 5, c ) | s;
728@abcde fg@
729sin | quote( ch ) | quote( wdi( sizeof(c), c ) ) | quote( s, '[', ']' ) | nl;
730@$'a' "bcde" [fg]$@
731sin | incl( "a-zA-Z0-9 ?!&\n", s ) | nl;
732@x?&000xyz TOM !.@
733sin | excl( "a-zA-Z0-9 ?!&\n", s );
734@<>{}{}STOP@
735\end{c++}
736&
737\begin{c++}
738
739
740'a' "bcde" "fg"
741
742'a' "bcde" "fg"
743
744"x?&000xyz TOM !"
745
746"<>{}{}"
747
748\end{c++}
749\end{tabular}
750\end{cquote}
751Note, the ability to read in quoted strings to match with program strings.
752The @nl@ at the end of an input ignores the rest of the line.
753
754
755\subsection{Assignment}
756
757While \VRef[Figure]{f:StrApiCompare} emphasizes cross-language similarities, it elides many specific operational differences.
758For example, the \CC @replace@ function selects a substring in the target and substitutes it with the source string, which can be smaller or larger than the substring.
759\CC modifies the mutable receiver object, replacing by position (zero origin) and length.
760\begin{cquote}
761\setlength{\tabcolsep}{15pt}
762\begin{tabular}{@{}l|l@{}}
763\begin{c++}
764string s1 = "abcde";
765s1.replace( 2, 3, "xy" );
766\end{c++}
767&
768\begin{c++}
769
770"abxy"
771\end{c++}
772\end{tabular}
773\end{cquote}
774Java cannot modify the receiver (immutable strings) so it returns a new string, replacing by text.
775\label{p:JavaReplace}
776\begin{cquote}
777\setlength{\tabcolsep}{15pt}
778\begin{tabular}{@{}l|l@{}}
779\begin{java}
780String s = "abcde";
781String r = s.replace( "cde", "xy" );
782\end{java}
783&
784\begin{java}
785
786"abxy"
787\end{java}
788\end{tabular}
789\end{cquote}
790Java also provides a mutable @StringBuffer@, replacing by position (zero origin) and length.
791\begin{cquote}
792\setlength{\tabcolsep}{15pt}
793\begin{tabular}{@{}l|l@{}}
794\begin{java}
795StringBuffer sb = new StringBuffer( "abcde" );
796sb.replace( 2, 5, "xy" );
797\end{java}
798&
799\begin{java}
800
801"abxy"
802\end{java}
803\end{tabular}
804\end{cquote}
805However, there are anomalies.
806@StringBuffer@'s @substring@ returns a @String@ copy that is immutable rather than modifying the receiver.
807As well, the operations are asymmetric, \eg @String@ has @replace@ by text but not replace by position and vice versa for @StringBuffer@.
808
809More significant operational differences relate to storage management, often appearing through assignment (@target = source@), and are summarized in \VRef[Figure]{f:StrSemanticCompare}, defining properties: type abstraction, state, symmetry, and referent.
810The following discussion justifies the figure's yes/no entries per language.
811
812\begin{figure}
813\setlength{\extrarowheight}{2pt}
814\begin{tabularx}{\textwidth}{@{}p{0.6in}XXcccc@{}}
815 & & & \multicolumn{4}{@{}c@{}}{\underline{Supports Helpful?}} \\
816 & Required & Helpful & C & \CC & Java & \CFA \\
817\hline
818Type abst'n
819 & Low-level: The string type is a varying amount of text communicated via a parameter or return.
820 & High-level: The string-typed relieves the user of managing memory for the text.
821 & no & yes & yes & yes \\
822\hline
823State
824 & \multirow{2}{2in}
825 {Fast Initialize: The target receives the characters of the source without copying the characters, resulting in an Alias or Snapshot.}
826 & Alias: The target name is within the source text; changes made in either variable are visible in both.
827 & yes & yes & no & yes \\
828\cline{3-7}
829 &
830 & Snapshot: The target is an alias within the source until the target changes (copy on write).
831 & no & no & yes & yes \\
832\hline
833Symmetry
834 & Laxed: The target's type is anything string-like; it may have a different status concerning ownership.
835 & Strict: The target's type is the same as the source; both strings are equivalent peers concerning ownership.
836 & N/A & no & yes & yes \\
837\hline
838Referent
839 & Variable-Constrained: The target can accept the entire text of the source.
840 & Fragment: The target can accept an arbitrary substring of the source.
841 & no & no & yes & yes
842\end{tabularx}
843
844\noindent
845Notes
846\begin{itemize}[parsep=0pt]
847\item
848 All languages support Required in all criteria.
849\item
850 A language gets ``Supports Helpful'' in one criterion if it can do so without sacrificing the Required achievement on all other criteria.
851\item
852 The C ``string'' is actually @char []@, under the conventions that @<string.h>@ requires. Hence, there is no actual string type in C, so symmetry does not apply.
853\item
854 The Java @String@ class is analyzed; its @StringBuffer@ class behaves similarly to @C++@.
855\end{itemize}
856\caption{Comparison of languages' strings, storage management perspective.}
857\label{f:StrSemanticCompare}
858\end{figure}
859
860In C, the declaration
861\begin{cfa}
862char s[$\,$] = "abcde";
863\end{cfa}
864creates a second-class fixed-sized string-variable, as it can only be used in its lexical context, \ie it cannot be passed by value to string operations or user functions.
865The reason is that there is no implicit mechanism to pass the string-length information to the function.
866Therefore, only pointers to strings are first-class, and discussed further.
867\begin{cfa}
868(const) char * s = "abcde"; $\C[2.25in]{// alias state, n/a symmetry, variable-constrained referent}$
869char * s1 = s; $\C{// alias state, n/a symmetry, variable-constrained referent}$
870char * s2 = s; $\C{// alias state, n/a symmetry, variable-constrained referent}$
871char * s3 = &s[1]; $\C{// alias state, n/a symmetry, variable-constrained referent}$
872char * s4 = &s3[1]; $\C{// alias state, n/a symmetry, variable-constrained referent}\CRT$
873printf( "%s %s %s %s %s\n", s, s1, s2, s3, s4 );
874$\texttt{\small abcde abcde abcde bcde cde}$
875\end{cfa}
876Note, all of these aliased strings rely on the single null termination character at the end of @s@.
877The issue of symmetry does not apply to C strings because the value and pointer strings are essentially different types, and so this feature is scored as not applicable for C.
878With the type not managing the text storage, there is no ownership question, \ie operations on @s1@ or @s2@ never leads to their memory becoming reusable.
879While @s3@ is a valid C-string that contains a proper substring of @s1@, the @s3@ technique does not constitute having a fragment referent because null termination implies the substring cannot be chosen arbitrarily; the technique works only for suffixes.
880
881In \CC, @string@ offers a high-level abstraction.
882\begin{cfa}
883string s = "abcde";
884string & s1 = s; $\C[2.25in]{// alias state, lax symmetry, variable-constrained referent}$
885string s2 = s; $\C{// copy (strict symmetry, variable-constrained referent)}$
886string s3 = s.substr( 1, 2 ); $\C{// copy (strict symmetry, fragment referent)}$
887string s4 = s3.substr( 1, 1 ); $\C{// copy (strict symmetry, fragment referent)}$
888cout << s << ' ' << s1 << ' ' << s2 << ' ' << s3 << ' ' << s4 << endl;
889$\texttt{\small abcde abcde abcde bc c}$
890string & s5 = s.substr(2,4); $\C{// error: cannot point to temporary}\CRT$
891\end{cfa}
892The lax symmetry reflects how the validity of @s1@ depends on the content and lifetime of @s@.
893It is common practice in \CC to use the @s1@-style pass by reference, with the understanding that the callee only uses the referenced string for the duration of the call, \ie no side-effect using the parameter.
894So, when the called function is a constructor, it is typical to use an @s2@-style copy-initialization.
895Exceptions to this pattern are possible, but require the programmer to assure safety where the type system does not.
896The @s3@ initialization is constrained to copy the substring because @c_str@ always provides a null-terminated character, which may be different from the source string.
897@s3@ assignment could be fast by reference counting the text area and using copy-on-write, but would require an implementation upgrade.
898
899In Java, @String@ also offers a high-level abstraction:
900\begin{java}
901String s = "abcde";
902String s1 = s; $\C[2.25in]{// snapshot state, strict symmetry, variable-constrained referent}$
903String s2 = s.substring( 1, 3 ); $\C{// snapshot state (possible), strict symmetry, fragment referent}$
904String s3 = s2.substring( 1, 2 ); $\C{// snapshot state (possible), strict symmetry, fragment referent}\CRT$
905System.out.println( s + ' ' + s1 + ' ' + s2 + ' ' + s3 );
906System.out.println( (s == s1) + " " + (s == s2) + " " + (s2 == s3) );
907$\texttt{\small abcde abcde bc c}$
908$\texttt{\small true false false}$
909\end{java}
910Note, @substring@ takes a start and end position, rather than a start position and length.
911Here, facts about Java's implicit pointers and pointer equality can over complicate the picture, and so are ignored.
912Furthermore, Java's string immutability means string variables behave as simple values.
913The result in @s1@ is the pointer in @s@, and their pointer equality confirm no time is spent copying characters.
914With @s2@, the case for fast-copy is more subtle.
915Certainly, its value is not pointer-equal to @s@, implying at least a further allocation.
916\PAB{TODO: finish the fast-copy case.}
917Java does not meet the aliasing requirement because immutability make it impossible to modify.
918Java's @StringBuffer@ provides aliasing (see @replace@ example on \VPageref{p:JavaReplace}), though without supporting symmetric treatment of a fragment referent, \eg @substring@ of a @StringBuffer@ is a @String@;
919as a result, @StringBuffer@ scores as \CC.
920The easy symmetry that the Java string enjoys is aided by Java's garbage collection; Java's @s2@ is doing effectively the operation of \CC's @s3@, though without the consequence of complicating memory management.
921\PAB{What complex storage management is going on here?}
922
923Finally, in \CFA, @string@ also offers a high-level abstraction:
924\begin{cfa}
925string s = "abcde";
926string & s1 = s; $\C[2.25in]{// alias state, strict symmetry, variable-constrained referent}$
927string s2 = s; $\C{// snapshot state, strict symmetry, variable-constrained referent}$
928string s3 = s`share; $\C{// alias state, strict symmetry, variable-constrained referent}\CRT$
929string s4 = s( 1, 2 );
930string s5 = s4( 1, 1 );
931sout | s | s1 | s2 | s3 | s4 | s5;
932$\texttt{\small abcde abcde abcde abcde bc c}$
933\end{cfa}
934% all helpful criteria of \VRef[Figure]{f:StrSemanticCompare} are satisfied.
935The \CFA string manages storage, handles all assignments, including those of fragment referents with fast initialization, provides the choice between snapshot and alias semantics, and does so symmetrically with one type (which assures text validity according to the lifecycles of the string variables).
936The intended metaphor for \CFA stings is similar to a GUI text-editor or web browser.
937Select a consecutive block of text using the mouse generates an aliased substring in the file/dialog-box.
938Typing into the selected area is like assigning to an aliased substring, where the highlighted text is replaced with more or less text;
939depending on the text entered, the file/dialog-box content grows or shrinks.
940\PAB{Need to discuss the example, as for the other languages.}
941
942The remainder of this chapter explains how the \CFA string achieves this usage style.
943
944
945\section{Storage Management}
946
947This section discusses issues related to storage management of strings.
948Specifically, it is common for strings to logically overlap partially or completely.
949\begin{cfa}
950string s1 = "abcdef";
951string s2 = s1; $\C{// complete overlap, s2 == "abcdef"}$
952string s3 = s1.substr( 0, 3 ); $\C{// partial overlap, s3 == "abc"}$
953\end{cfa}
954This raises the question of how strings behave when an overlapping component is changed,
955\begin{cfa}
956s3[1] = 'w'; $\C{// what happens to s1 and s2?}$
957\end{cfa}
958which is restricted by a string's mutable or immutable property.
959For example, Java's immutable strings require copy-on-write when any overlapping string changes.
960Note, the notion of underlying string mutability is not specified by @const@; \eg in \CC:
961\begin{cfa}
962const string s1 = "abc";
963\end{cfa}
964the @const@ applies to the @s1@ pointer to @"abc"@, and @"abc"@ is an immutable constant that is \emph{copied} into the string's storage.
965Hence, @s1@ is not pointing at an immutable constant, meaning its underlying string can be mutable, unless some other designation is specified, such as Java's global immutable rule.
966
967
968\subsection{Logical overlap}
969
970\CFA provides a dynamic mechanism to indicate mutable or immutable using the attribute @`share@.
971This aliasing relationship is a sticky-property established at initialization.
972For example, here strings @s1@ and @s1a@ are in an aliasing relationship, while @s2@ is in a copy relationship.
973\input{sharing1.tex}
974Here, the aliasing (@`share@) causes partial changes (subscripting) to flow in both directions.
975(In the following examples, watch how @s1@ and @s1a@ change together, and @s2@ is independent.)
976\input{sharing2.tex}
977Similarly for complete changes.
978\input{sharing3.tex}
979Because string assignment copies the value, RHS aliasing is irrelevant.
980Hence, aliasing of the LHS is unaffected.
981\input{sharing4.tex}
982
983Now, consider string @s1_mid@ being an alias in the middle of @s1@, along with @s2@, made by a simple copy from the middle of @s1@.
984\input{sharing5.tex}
985Again, @`share@ passes changes in both directions; copy does not.
986As a result, the index values for the position of @b@ are 1 in the longer string @"abcd"@ and 0 in the shorter aliased string @"bc"@.
987This alternate positioning also applies to subscripting.
988\input{sharing6.tex}
989
990Finally, assignment flows through the aliasing relationship without affecting its structure.
991\input{sharing7.tex}
992In the @"ff"@ assignment, the result is straightforward to accept because the flow direction is from contained (small) to containing (large).
993The following rules explain aliasing substrings that flow in the opposite direction, large to small.
994
995Growth and shrinkage are natural extensions, as for the text-editor example mentioned earlier, where an empty substring is as real as an empty string.
996\input{sharing8.tex}
997
998Multiple portions of a string can be aliased.
999% When there are several aliasing substrings at once, the text editor analogy becomes an online multi-user editor.
1000%I should be able to edit a paragraph in one place (changing the document's length), without my edits affecting which letters are within a mouse-selection that you had made previously, somewhere else.
1001\input{sharing9.tex}
1002When @s1_bgn@'s size increases by 3, @s1_mid@'s starting location moves from 1 to 4 and @s1_end@'s from 3 to 6,
1003
1004When changes happens on an aliasing substring that overlap.
1005\input{sharing10.tex}
1006Strings @s1_crs@ and @s1_mid@ overlap at character 4, @j@ because the substrings are 3,2 and 4,2.
1007When @s1_crs@'s size increases by 1, @s1_mid@'s starting location moves from 4 to 5, but the overlapping character remains, changing to @'+'@.
1008
1009\PAB{TODO: finish typesetting the demo}
1010
1011%\input{sharing-demo.tex}
1012
1013\VRef[Figure]{f:ParameterPassing} shows similar relationships when passing the results of substring operations by reference and by value to a subprogram.
1014Again, notice the side-effects to other reference parameters as one is modified.
1015
1016\begin{figure}
1017\begin{cfa}
1018// x, a, b, c, & d are substring results passed by reference
1019// e is a substring result passed by value
1020void test( string & x, string & a, string & b, string & c, string & d, string e ) {
1021\end{cfa}
1022\begin{cquote}
1023\setlength{\tabcolsep}{2pt}
1024\begin{tabular}{@{}ll@{}}
1025\begin{cfa}
1026
1027 a( 0, 2 ) = "aaa";
1028 b( 1, 12 ) = "bbb";
1029 c( 4, 5 ) = "ccc";
1030 c = "yyy";
1031 d( 0, 3 ) = "ddd";
1032 e( 0, 3 ) = "eee";
1033 x = e;
1034}
1035\end{cfa}
1036&
1037\sf
1038\setlength{\extrarowheight}{-0.5pt}
1039\begin{tabular}{@{}llllll@{}}
1040x & a & b & c & d & e \\
1041@"aaaxxxxxxxxx"@ & @"aaax"@ & @"xxx"@ & @"xxxxx"@ & @"xxx"@ & @"xxx"@ \\
1042@"aaaxbbbxxxxxx"@ & @"aaax"@ & @"xbbb"@ & @"xxxx"@ & @"xxx"@ & @"xxx"@ \\
1043@"aaaxbbbxxxcccxx"@ & @"aaax"@ & @"xbbb"@ & @"xxxccc"@& @"cccxx"@ & @"xxx"@ \\
1044@"aaaxbbbyyyxx"@ & @"aaax"@ & @"aaab"@ & @"yyy"@ & @"xx"@ & @"xxx"@ \\
1045@"aaaxbbbyyyddd"@ & @"aaax"@ & @"xbbb"@ & @"yyy"@ & @"ddd"@ & @"xxx"@ \\
1046@"aaaxbbbyyyddd"@ & @"aaax"@ & @"xbbb"@ & @"yyy"@ & @"ddd"@ & @"eee"@ \\
1047@"eee"@ & @""@ & @""@ & @""@ & @"eee"@ \\
1048 & \\
1049\end{tabular}
1050\end{tabular}
1051\end{cquote}
1052\begin{cfa}
1053int main() {
1054 string x = "xxxxxxxxxxx";
1055 test( x, x(0, 3), x(2, 3), x(4, 5), x(8, 5), x(8, 5) );
1056}
1057\end{cfa}
1058\caption{Parameter Passing}
1059\label{f:ParameterPassing}
1060\end{figure}
1061
1062
1063\subsection{RAII limitations}
1064
1065Earlier work on \CFA~\cite[ch.~2]{Schluntz17} implemented object constructors and destructors for all types (basic and user defined).
1066A constructor is a user-defined function run implicitly \emph{after} an object's declaration-storage is created, and a destructor is a user-defined function run \emph{before} an object's declaration-storage is deleted.
1067This feature, called RAII~\cite[p.~389]{Stroustrup94}, guarantees pre-invariants for users before accessing an object and post invariants for the programming environment after an object terminates.
1068
1069The purposes of these invariants goes beyond ensuring authentic values inside an object.
1070Invariants can also track occurrences of managed objects in other data structures.
1071For example, reference counting is a typical application of an invariant outside of the data values.
1072With a reference-counting smart-pointer, the constructor and destructor \emph{of a pointer type} tracks the life cycle of the object it points to.
1073Both \CC and \CFA RAII systems are powerful enough to achieve reference counting.
1074
1075In general, a lifecycle function has access to an object by location, \ie constructors and destructors receive a @this@ parameter providing an object's memory address.
1076\begin{cfa}
1077struct S { int * ip; };
1078void ?{}( S & @this@ ) { this.ip = new(); } $\C[3in]{// default constructor}$
1079void ?{}( S & @this@, int i ) { ?{}(this); *this.ip = i; } $\C{// initializing constructor}$
1080void ?{}( S & @this@, S s ) { this = s; } $\C{// copy constructor}$
1081void ^?{}( S & @this@ ) { delete( this.ip ); } $\C{// destructor}\CRT$
1082\end{cfa}
1083The lifecycle implementation can then add this object to a collection at creation and remove it at destruction.
1084A module providing lifecycle semantics can traverse the collection at relevant times to keep the objects ``good.''
1085Hence, declaring such an object not only ensures ``good'' authentic values, but also an implicit subscription to a service that keeps the value ``good'' across its lifetime.
1086
1087In many cases, the relationship between memory location and lifecycle is straightforward.
1088For example, stack-allocated objects being used as parameters and returns, with a sender version in one stack frame and a receiver version in another, as opposed to assignment where sender and receiver are in the same stack frame.
1089What is crucial for lifecycle management is knowing if the receiver is initialized or uninitialized, \ie an object is or is not currently associated with management.
1090To provide this knowledge, languages differentiate between initialization and assignment to a left-hand side.
1091\begin{cfa}
1092Obj obj2 = obj1; $\C[1.5in]{// initialization, obj2 is initialized}$
1093obj2 = obj1; $\C{// assignment, obj2 must be initialized for management to work}\CRT$
1094\end{cfa}
1095Initialization occurs at declaration by value, parameter by argument, return temporary by function call.
1096Hence, it is necessary to have two kinds of constructors: by value or object.
1097\begin{cfa}
1098Obj obj1{ 1, 2, 3 }; $\C[1.5in]{// by value, management is initialized}$
1099Obj obj2 = obj1; $\C{// by obj, management is updated}\CRT$
1100\end{cfa}
1101When no object management is required, initialization copies the right-hand value.
1102Hence, the calling convention remains uniform, where the unmanaged case uses @memcpy@ as the initialization constructor and managed uses the specified initialization constructor.
1103
1104The \CFA RAII system supports lifecycle functions, except for returning a value from a function to a temporary.
1105For example, in \CC:
1106\begin{c++}
1107struct S {...};
1108S identity( S s ) { return s; }
1109S s;
1110s = identity( s ); // S temp = identity( s ); s = temp;
1111\end{c++}
1112the generated code for the function call created a temporary with initialization from the function call, and then assigns the temporary to the object.
1113This two step approach means extra storage for the temporary and two copies to get the result into the object variable.
1114\CC{17} introduced return value-optimization (RVO)~\cite{RVO20} to ``avoid copying an object that a function returns as its value, including avoiding creation of a temporary object''.
1115\CFA uses C semantics for function return giving direct value-assignment, which eliminates unnecessary code, but skips an essential feature needed by lifetime management.
1116The following discusses the consequences of this semantics with respect to lifetime management of \CFA strings.
1117
1118The present string-API contribution provides lifetime management with initialization semantics on function return.
1119The workaround to achieve the full lifetime semantics does have a runtime performance penalty.
1120An alternative API sacrifices return initialization semantics to recover full runtime performance.
1121These APIs are layered, with the slower, friendlier High Level API (HL) wrapping the faster, more primitive Low Level API (LL).
1122Both API present the same features, up to lifecycle management, with return initialization being disabled in LL and implemented with the workaround in HL.
1123The intention is for most future code to target HL.
1124When \CFA becomes a full compiler, it can provide return initialization with RVO optimizations.
1125Then, programs written with the HL API will simply run faster.
1126In the meantime, performance-critical sections of applications use LL.
1127Subsequent performance experiments \see{\VRef{s:PerformanceAssessment}} with other string libraries has \CFA strings using the LL API.
1128These measurement gives a fair estimate of the goal state for \CFA.
1129
1130
1131\subsection{Memory management}
1132
1133A centrepiece of the string module is its memory manager.
1134The management scheme defines a shared buffer for string text.
1135Allocation in this buffer is via a bump-pointer;
1136the buffer is compacted and/or relocated with growth when it fills.
1137A string is a smart pointer into this buffer.
1138
1139This cycle of frequent cheap allocations, interspersed with infrequent expensive compactions, has obvious similarities to a general-purpose memory manager based on garbage collection (GC).
1140A few differences are noteworthy.
1141First, in a general purpose manager, the allocated objects may contain pointers to other objects, making the transitive reachability of these objects a crucial property.
1142Here, the allocations are text, so one allocation never keeps another alive.
1143Second, in a general purpose manager, the handle that keeps an allocation alive is just a lean pointer.
1144For strings, a fatter representation is acceptable because there are fewer string head pointers versus chained pointers within nodes as for linked containers.
1145
1146\begin{figure}
1147\includegraphics{memmgr-basic.pdf}
1148\caption{String memory-management data structures}
1149\label{f:memmgr-basic}
1150\end{figure}
1151
1152\VRef[Figure]{f:memmgr-basic} shows the representation.
1153The heap header and text buffer define a sharing context.
1154Normally, one global sharing context is appropriate for an entire program;
1155concurrent exceptions are discussed in \VRef{s:ControllingImplicitSharing}.
1156A string is a handle into the buffer and linked into a list.
1157The list is doubly linked for $O(1)$ insertion and removal at any location.
1158Strings are orders in the list by string-text address, where there is no overlapping, and approximately, where there is.
1159The header maintains a next-allocation pointer, @alloc@, pointing to the last live allocation in the buffer.
1160No external references point into the buffer and the management procedure relocates the text allocations as needed.
1161A string handle references a containing string, while its string is contiguous and not null terminated.
1162The length sets an upper limit on the string size, but is large (4 or 8 bytes).
1163String handles can be allocated in the stack or heap, and represent the string variables in a program.
1164Normal C life-time rules apply to guarantee correctness of the string linked-list.
1165The text buffer is large enough with good management so that often only one dynamic allocation is necessary during program execution.
1166% During this period, strings can vary in size dynamically.
1167
1168When the text buffer fills, \ie the next new string allocation causes @alloc@ to point beyond the end of the buffer, the strings are compacted.
1169The linked handles define all live strings in the buffer, which indirectly defines the allocated and free space in the buffer.
1170Since the string handles are in (roughly) sorted order, the handle list can be traversed copying the first text to the start of the buffer and subsequent strings after each over.
1171After compaction, if the amount of free storage is still less than the new string allocation, a larger text buffer is heap allocated, the current buffer is copies into the new buffer, and the original buffer is freed.
1172Note, the list of string handles is unaffected during a compaction;
1173only the string pointers in the handles are modified to new buffer locations.
1174
1175Object lifecycle events are the \emph{subscription-management} triggers in such a service.
1176There are two fundamental string-creation functions: importing external text like a C-string or reading a string, and initialization from an existing \CFA string.
1177When importing, storage comes from the end of the buffer, into which the text is copied.
1178The new string handle is inserted at the end of the handle list because the new text is at the end of the buffer.
1179When initializing from text already in the text buffer, the new handle is a second reference into the original run of characters.
1180In this case, the new handle's linked-list position is after the original handle.
1181Both string initialization styles preserve the string module's internal invariant that the linked-list order matches the buffer order.
1182For string destruction, handles are removed from the list.
1183
1184Certain string operations can results in a subset (substring) of another string.
1185The resulting handle is then placed in the correct sorted position in the list, possible with a short linear search to locate the position.
1186For string operations resulting in a new string, that string is allocated at the end of the buffer.
1187For shared-edit strings, handles that originally referenced containing locations need to see the new value at the new buffer location.
1188These strings are moved to appropriate locations at the end of the list \see{[xref: TBD]}.
1189For nonshared-edit strings, a containing string can be moved and the nonshared strings can remain in the same position.
1190String assignment words similarly to string initialization, maintain the invariant of linked-list order matching buffer order.
1191
1192At the level of the memory manager, these modifications can always be explained as assignments and appendment;
1193for example, an append is an assignment into the empty substring at the end of the buffer.
1194Favourable conditions allow for in-place editing: where there is room for the resulting value in the original buffer location, and where all handles referring to the original buffer location see the new value.
1195However, the general case requires a new buffer allocation: where the new value does not fit in the old place, or if other handles are still using the old value.
1196
1197
1198\subsection{Sharing implementation}
1199
1200The \CFA string module has two mechanisms to handle the case when string handles share a string of text.
1201
1202The first type of sharing is the user requests both string handles be views of the same logical, modifiable string.
1203This state is typically produced by the substring operation.
1204\begin{cfa}
1205string s = "abcde";
1206string s1 = s( 1, 2 )@`share@; $\C[2.25in]{// explicit sharing}$
1207s[1] = 'x'; $\C{// change s and s1}\CRT$
1208sout | s | s1;
1209$\texttt{\small axcde xc}$
1210\end{cfa}
1211In a typical substring call, the source string-handle is referencing an entire string, and the resulting, newly made, string handle is referencing a portion of the original.
1212In this state, a subsequent modification made by either is visible in both.
1213
1214The second type of sharing happens when the system implicitly delays the physical execution of a logical \emph{copy} operation, as part of its copy-on-write optimization.
1215This state is typically produced by constructing a new string, using an original string as its initialization source.
1216\begin{cfa}
1217string s = "abcde";
1218string s1 = s( 1, 2 )@@; $\C[2.25in]{// no sharing}$
1219s[1] = 'x'; $\C{// copy-on-write s1}\CRT$
1220sout | s | s1;
1221$\texttt{\small axcde bc}$
1222\end{cfa}
1223In this state, a subsequent modification done on one handle triggers the deferred copy action, leaving the handles referencing different text within the buffer, holding distinct values.
1224
1225A further abstraction, in the string module's implementation, helps distinguish the two senses of sharing.
1226A share-edit set (SES) is an equivalence class over string handles, being the reflexive, symmetric and transitive closure of the relationship of one string being constructed from another, with the ``share'' opt-in given.
1227The SES is represented by a second linked list among the handles.
1228A string that shares edits with no other is in a SES by itself.
1229Inside a SES, a logical modification of one substring portion may change the logical value in another, depending on whether the two actually overlap.
1230Conversely, no logical value change can flow outside of a SES.
1231Even if a modification on one string handle does not reveal itself \emph{logically} to anther handle in the same SES (because they do not overlap), if the modification is length-changing, completing the modification requires visiting the second handle to adjust its location in the sliding text.
1232
1233
1234\subsection{Controlling implicit sharing}
1235\label{s:ControllingImplicitSharing}
1236
1237There are tradeoffs associated with sharing and its implicit copy-on-write mechanism.
1238Several qualitative matters are detailed in \VRef{s:PerformanceAssessment}.
1239In detail, string sharing has inter-linked string handles, so managing one string is also managing the neighbouring strings, and from there, a data structure of the ``set of all strings.''
1240Therefore, it is useful to toggle this capability on or off when it is not providing any application benefit.
1241
1242\begin{figure}
1243 \begin{tabular}{ll}
1244 \lstinputlisting[language=CFA, firstline=10, lastline=55]{sharectx.run.cfa}
1245 &
1246 \raisebox{-0.17\totalheight}{\includegraphics{string-sharectx.pdf}} % lower
1247 \end{tabular}
1248 \caption{Controlling copying vs sharing of strings using \lstinline{string_sharectx}.}
1249 \label{fig:string-sharectx}
1250\end{figure}
1251
1252The \CFA string library provides the type @string_sharectx@ to control an ambient sharing context.
1253It allows two adjustments: to opt out of sharing entirely or to begin sharing within a private context.
1254Running with sharing disabled can be thought of as a \CC STL-emulation mode, where each string is dynamically allocated.
1255The chosen mode applies for the duration of the lifetime of the created @string_sharectx@ object, up to being suspended by child lifetimes of different contexts.
1256\VRef[Figure]{fig:string-sharectx} illustrates this behaviour by showing the stack frames of a program in execution.
1257In this example, the single-letter functions are called in alphabetic order.
1258The functions @a@, @b@ and @g@ share string character ranges with each other, because they occupy a common sharing-enabled context.
1259The function @e@ shares within itself (because its is in a sharing-enabled context), but not with the rest of the program (because its context is not occupied by any of the rest of the program).
1260The functions @c@, @d@ and @f@ never share anything, because they are in a sharing-disabled context.
1261Executing the example does not produce an interesting outcome, but the comments in the picture indicate when the logical copy operation runs with
1262\begin{description}
1263 \item[share:] the copy being deferred, as described through the rest of this section (fast), or
1264 \item[copy:] the copy performed eagerly (slow).
1265\end{description}
1266Only eager copies can cross @string_sharectx@ boundaries.
1267The intended use is with stack-managed lifetimes, in which the established context lasts until the current function returns, and affects all functions called that do not create their own contexts.
1268
1269[ TODO: true up with ``is thread local'' (implement that and expand this discussion to give a concurrent example, or adjust this wording) ]
1270
1271
1272\subsection{Sharing and threading}
1273
1274The \CFA string library provides no thread safety, the same as \CC string, providing similar performance goals.
1275Threads can create their own string buffers and avoid passing these strings to other threads, or require that shared strings be immutable, as concurrent reading is safe.
1276A positive consequence of this approach is that independent threads can use the sharing buffer without locking overhead.
1277When string sharing amongst threads is required, program-wide string-management can toggled to non-sharing using @malloc@/@free@, where the storage allocator is assumed to be thread-safe.
1278Finally, concurrent users of string objects can provide their own mutual exclusion.
1279
1280
1281\subsection{Future work}
1282
1283Implementing the small-string optimization is straightforward, as a string header contains a pointer to the string text in the buffer.
1284This pointer could be marked with a flag and contain a small string.
1285However, there is now a conditional check required on the fast-path to switch between small and large string operations.
1286
1287It might be possible to pack 16- or 32-bit Unicode characters within the same string buffer as 8-bit characters.
1288Again, locations for identification flags must be found and checked along the fast path to select the correct actions.
1289Handling utf8 (variable length), is more problematic because simple pointer arithmetic cannot be used to stride through the variable-length characters.
1290Trying to use a secondary array of fixed-sized pointers/offsets to the characters is possible, but raises the question of storage management for the utf8 characters themselves.
1291
1292
1293\section{Performance assessment}
1294\label{s:PerformanceAssessment}
1295
1296I assessed the \CFA string library's speed and memory usage against strings in \CC STL.
1297The results are presented in even equivalent cases, due to either micro-optimizations foregone, or fundamental costs of the added functionality.
1298They also show the benefits and tradeoffs, as >100\% effects, of switching to \CFA, with the tradeoff points quantified.
1299The final test shows the overall win of the \CFA text-sharing mechanism.
1300It exercises several operations together, showing \CFA enabling clean user code to achieve performance that STL requires less-clean user code to achieve.
1301
1302To discuss: general goal of ...
1303while STL makes you think about memory management, all the time, and if you do, your performance can be great ...
1304\CFA sacrifices this advantage modestly in exchange for big wins when you're not thinking about memory management.
1305[Does this position cover all of it?]
1306
1307To discuss: revisit HL v LL APIs
1308
1309To discuss: revisit no-sharing as STL emulation modes
1310
1311
1312\subsection{Methodology}
1313
1314These tests use a \emph{corpus} of strings (string content is immaterial).
1315For varying-length strings, the mean length comes from a geometric distribution, which implies that lengths much longer than the mean occur frequently.
1316The string sizes are:
1317\begin{description}
1318 \item [Fixed-size] all string lengths are of the stated size.
1319 \item [Varying from 1 to N] means the string lengths are drawn from the geometric distribution with a stated mean and all lengths occur.
1320 \item [Varying from 16 to N] means string lengths are drawn from the geometric distribution with the stated mean, but only lengths 16 and above occur; thus, the stated mean is above 16.
1321\end{description}
1322The means for the geometric distribution are the X-axis values in experiments.
1323The special treatment of length 16 deals with the short-string optimization (SSO) in STL @string@, currently not implemented in \CFA.
1324When an STL string can fit into a heap pointer, the optimization uses the pointer storage to eliminate using the heap.
1325\begin{c++}
1326class string {
1327 union {
1328 struct { $\C{// long string, string storage in heap}$
1329 size_t size;
1330 char * strptr;
1331 } lstr;
1332 char sstr[sizeof(lstr)]; $\C{// short string 8-16 characters, in situ}$
1333 };
1334 bool tag; $\C{// string kind, short or long}$
1335 ... $\C{// other storage}$
1336};
1337\end{c++}
1338
1339When success is illustrated, notwithstanding SSO, a fixed-size or from-16 distribution ensures that extra-optimized cases are not part of the mix on the STL side.
1340In all experiments that use a corpus, its text is generated and loaded into the system under test before the timed phase begins.
1341
1342To discuss: vocabulary for reused case variables
1343
1344To discuss: common approach to iteration and quoted rates
1345
1346To discuss: hardware and such
1347
1348To ensure comparable results, a common memory allocator is used for \CFA and \CC.
1349The llheap allocator~\cite{Zulfiqar22} is embedded into \CFA and is used standalone with \CC.
1350
1351
1352\subsection{Test: Append}
1353
1354This test measures the speed of appending randomly-size text onto a growing string.
1355\begin{cquote}
1356\setlength{\tabcolsep}{20pt}
1357\begin{tabular}{@{}ll@{}}
1358% \multicolumn{1}{c}{\textbf{fresh}} & \multicolumn{1}{c}{\textbf{reuse}} \\
1359\begin{cfa}
1360
1361for ( ... ) {
1362 @string x;@ // fresh
1363 for ( ... )
1364 x @+=@ ...
1365}
1366\end{cfa}
1367&
1368\begin{cfa}
1369string x;
1370for ( ... ) {
1371 @x = "";@ $\C[1in]{// reuse}$
1372 for ( ... )
1373 x @+=@ ... $\C{// append, alternative x = x + ...}\CRT$
1374}
1375\end{cfa}
1376\end{tabular}
1377\end{cquote}
1378The benchmark's outer loop executes ``until a sample-worthy amount of execution has happened'' and an inner loop for ``building up the desired-length string.''
1379Its subcases include,
1380\begin{enumerate}[leftmargin=*]
1381\item
1382\CFA nosharing/sharing \vs \CC nosharing.
1383\item
1384Difference between the logically equivalent operations @x += ...@ \vs @x = x + ...@.
1385For numeric types, the generated code is equivalence, giving identical performance.
1386However, for string types there can be a significant difference in performance, especially if this code appears in a loop iterating a large number of times.
1387This difference might not be intuitive to beginners.
1388\item
1389Coding practice where the user's logical allocation is fresh \vs reused.
1390Here, \emph{reusing a logical allocation}, means that the program variable, into which the user is concatenating, previously held a long string.
1391In general, a user should not have to care about this difference, yet the STL performs differently in these cases.
1392Furthermore, if a function takes a string by reference, if cannot use the fresh approach.
1393Concretely, both cases incur the cost of copying characters into the target string, but only the allocation-fresh case incurs a further reallocation cost, which is generally paid at points of doubling the length.
1394For the STL, this cost includes obtaining a fresh buffer from the memory allocator and copying older characters into the new buffer, while \CFA-sharing hides such a cost entirely.
1395%The fresh \vs reuse distinction is only relevant in the \emph{append} tests.
1396\end{enumerate}
1397
1398\begin{figure}
1399\centering
1400 \includegraphics{string-graph-peq-cppemu.pdf}
1401% \includegraphics[width=\textwidth]{string-graph-peq-cppemu.png}
1402 \caption{Average time per iteration (lower is better) with one \lstinline{x += y} invocation, comparing \CFA with STL implementations (given \CFA running in STL emulation mode), and comparing the ``fresh'' with ``reused'' reset styles, at various string sizes.}
1403 \label{fig:string-graph-peq-cppemu}
1404\end{figure}
1405
1406This tests use the varying-from-1 corpus construction, \ie it assumes the STL's advantage of small-string optimization.
1407\PAB{To discuss: any other case variables introduced in the performance intro}
1408\VRef[Figure]{fig:string-graph-peq-cppemu} shows this behaviour, by the STL and by \CFA in STL emulation mode.
1409\CFA reproduces STL's performance, up to a 15\% penalty averaged over the cases shown, diminishing with larger strings, and 50\% in the worst case.
1410This penalty characterizes the amount of implementation fine tuning done with STL and not done with \CFA in present state.
1411There is a larger penalty for redeclaring the string each loop iteration (fresh) versus hosting it out of the loop and reseting it to the null string (reuse).
1412The cost is 40\% averaged over the cases shown and minimally 24\%, and shows up consistently between the \CFA and STL implementations, and increases with larger strings.
1413
1414\begin{figure}
1415\centering
1416 \includegraphics{string-graph-peq-sharing.pdf}
1417% \includegraphics[width=\textwidth]{string-graph-peq-sharing.png}
1418 \caption{Average time per iteration (lower is better) with one \lstinline{x += y} invocation, comparing \CFA (having implicit sharing activated) with STL, and comparing the ``fresh'' with ``reused'' reset styles, at various string sizes.}
1419 \label{fig:string-graph-peq-sharing}
1420\end{figure}
1421
1422In sharing mode, \CFA makes the fresh/reuse difference disappear, as shown in \VRef[Figure]{fig:string-graph-peq-sharing}.
1423At append lengths 5 and above, \CFA not only splits the two baseline STL cases, but its slowdown of 16\% over (STL with user-managed reuse) is close to the \CFA-v-STL implementation difference seen with \CFA in STL-emulation mode.
1424
1425\begin{figure}
1426\centering
1427 \includegraphics{string-graph-pta-sharing.pdf}
1428% \includegraphics[width=\textwidth]{string-graph-pta-sharing.png}
1429 \caption{Average time per iteration (lower is better) with one \lstinline{x = x + y} invocation, comparing \CFA (having implicit sharing activated) with STL.
1430For context, the results from \VRef[Figure]{fig:string-graph-peq-sharing} are repeated as the bottom bands.
1431While not a design goal, and not graphed out, \CFA in STL-emulation mode outperformed STL in this case; user-managed allocation reuse did not affect any of the implementations in this case.}
1432 \label{fig:string-graph-pta-sharing}
1433\end{figure}
1434
1435When the user takes a further step beyond the STL's optimal zone, by running @x = x + y@, as in \VRef[Figure]{fig:string-graph-pta-sharing}, the STL's penalty is above $15 \times$ while \CFA's (with sharing) is under $2 \times$, averaged across the cases shown here.
1436Moreover, the STL's gap increases with string size, while \CFA's converges.
1437
1438
1439\subsubsection{Test: Pass argument}
1440
1441STL has a penalty for passing a string by value, which indirectly forces users to think about memory management when communicating values to a function.
1442\begin{cfa}
1443void foo( string s );
1444string s = "abc";
1445foo( s );
1446\end{cfa}
1447With implicit sharing active, \CFA treats this operation as normal and supported.
1448This test illustrates a main advantage of the \CFA sharing algorithm.
1449It also has a case in which STL's small-string optimization provides a successful mitigation.
1450
1451\begin{figure}
1452\centering
1453 \includegraphics{string-graph-pbv.pdf}
1454% \includegraphics[width=\textwidth]{string-graph-pbv.png}
1455 \caption{Average time per iteration (lower is better) with one call to a function that takes a by-value string argument, comparing \CFA (having implicit sharing activated) with STL.
1456(a) With \emph{Varying-from-1} corpus construction, in which the STL-only benefit of small-string optimization occurs, in varying degrees, at all string sizes.
1457(b) With \emph{Fixed-size} corpus construction, in which this benefit applies exactly to strings with length below 16.
1458[TODO: show version (b)]}
1459 \label{fig:string-graph-pbv}
1460\end{figure}
1461
1462\VRef[Figure]{fig:string-graph-pbv} shows the costs for calling a function that receives a string argument by value.
1463STL's performance worsens as string length increases, while \CFA has the same performance at all sizes.
1464
1465The \CFA cost to pass a string is nontrivial.
1466The contributor is adding and removing the callee's string handle from the global list.
1467This cost is $1.5 \times$ to $2 \times$ over STL's when small-string optimization applies, though this cost should be avoidable in the same case, given a \CFA realization of this optimization.
1468At the larger sizes, when STL has to manage storage for the string, STL runs more than $3 \times$ slower, mainly due to time spent in the general-purpose memory allocator.
1469
1470
1471\subsubsection{Test: Allocate}
1472
1473This test directly compares the allocation schemes of the \CFA string with sharing, compared with the STL string.
1474It treats the \CFA scheme as a form of garbage collection, and the STL scheme as an application of malloc-free.
1475The test shows that \CFA enables faster speed at a cost in memory usage.
1476
1477A garbage collector, afforded the freedom of managed memory, often runs faster than malloc-free (in an amortized analysis, even though it must occasionally stop to collect) because it is able to use its collection time to move objects.
1478(In the case of the mini-allocator powering the \CFA string library, objects are runs of text.) Moving objects lets fresh allocations consume from a large contiguous store of available memory; the ``bump pointer'' book-keeping for such a scheme is very light.
1479A malloc-free implementation without the freedom to move objects must, in the general case, allocate in the spaces between existing objects; doing so entails the heavier book-keeping to navigate and maintain a linked structure.
1480
1481A garbage collector keeps allocations around for longer than the using program can reach them.
1482By contrast, a program using malloc-free (correctly) releases allocations exactly when they are no longer reachable.
1483Therefore, the same harness will use more memory while running under garbage collection.
1484A garbage collector can minimize the memory overhead by searching for these dead allocations aggressively, that is, by collecting more often.
1485Tuned in this way, it spends a lot of time collecting, easily so much as to overwhelm its speed advantage from bump-pointer allocation.
1486If it is tuned to collect rarely, then it leaves a lot of garbage allocated (waiting to be collected) but gains the advantage of little time spent doing collection.
1487
1488[TODO: find citations for the above knowledge]
1489
1490The speed for memory tradeoff is, therefore, standard for comparisons like \CFA--STL string allocations.
1491The test verifies that it is so and quantifies the returns available.
1492
1493These tests manipulate a tuning knob that controls how much extra space to use.
1494Specific values of this knob are not user-visible and are not presented in the results here.
1495Instead, its two effects (amount of space used and time per operation) are shown.
1496The independent variable is the liveness target, which is the fraction of the text buffer that is in use at the end of a collection.
1497The allocator will expand its text buffer during a collection if the actual fraction live exceeds this target.
1498
1499This experiment's driver allocates strings by constructing a string handle as a local variable then looping over recursive calls.
1500The time measurement is of nanoseconds per such allocating call.
1501The arrangement of recursive calls and their fan-out (iterations per recursion level) makes some of the strings long-lived and some of them short-lived.
1502String lifetime (measured in number of subsequent string allocations) is ?? distributed, because each node in the call tree survives as long as its descendent calls.
1503The run presented in this section used a call depth of 1000 and a fan-out of 1.006, which means that approximately one call in 167 makes two recursive calls, while the rest make one.
1504This sizing was chosen to keep the amounts of consumed memory within the machine's last-level cache.
1505
1506\begin{figure}
1507\centering
1508 \includegraphics{string-graph-allocn.pdf}
1509% \includegraphics[width=\textwidth]{string-graph-allocn.png}
1510 \caption{Space and time performance, under varying fraction-live targets, for the five string lengths shown, at (\emph{Fixed-size} corpus construction.
1511[MISSING] The identified clusters are for the default fraction-live target, which is 30\%.
1512MISSING: STL results, typically just below the 0.5--0.9 \CFA segment.
1513All runs keep an average of 836 strings live, and the median string lifetime is ?? allocations.}
1514 \label{fig:string-graph-allocn}
1515\end{figure}
1516
1517\VRef[Figure]{fig:string-graph-allocn} shows the results of this experiment.
1518At all string sizes, varying the liveness threshold gives offers speed-for-space tradeoffs relative to STL.
1519At the default liveness threshold, all measured string sizes see a ??\%--??\% speedup for a ??\%--??\% increase in memory footprint.
1520
1521
1522\subsubsection{Test: Normalize}
1523
1524This test is more applied than the earlier ones.
1525It combines the effects of several operations.
1526It also demonstrates a case of the \CFA API allowing user code to perform well, while being written without overt memory management, while achieving similar performance in STL requires adding memory-management complexity.
1527
1528To motivate: edits being rare
1529
1530The program is doing a specialized find-replace operation on a large body of text.
1531In the program under test, the replacement is just to erase a magic character.
1532But in the larger software problem represented, the rewrite logic belongs to a module that was originally intended to operate on simple, modest-length strings.
1533The challenge is to apply this packaged function across chunks taken from the large body.
1534Using the \CFA string library, the most natural way to write the helper module's function also works well in the adapted context.
1535Using the STL string, the most natural ways to write the helper module's function, given its requirements in isolation, slow down when it is driven in the adapted context.
1536
1537\begin{lstlisting}
1538void processItem( string & item ) {
1539 // find issues in item and fix them
1540}
1541\end{lstlisting}
Note: See TracBrowser for help on using the repository browser.