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

Last change on this file since d2e6f84 was 780727f, checked in by Peter A. Buhr <pabuhr@…>, 7 days ago

harmonize user manual string discussion with string chapter

  • Property mode set to 100644
File size: 94.2 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 the 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 & @==@, @!=@, @<@, @<=@, @>@, @>=@ \\
26@strlen@ & @length@, @size@ & @length@ & @size@ \\
27@[ ]@ & @[ ]@ & @charAt@ & @[ ]@ \\
28@strncpy@ & @substr@ & @substring@ & @( )@, on RHS of @=@ \\
29@strncpy@ & @replace@ & @replace@ & @( )@, on LHS of @=@ \\
30@strstr@ & @find@ & @indexOf@ & @find@ \\
31@strcspn@ & @find_first_of@ & @matches@ & @exclude@ \\
32@strspn@ & @find_first_not_of@ & @matches@ & @include@ \\
33N/A & @c_str@, @data@ & N/A & @strcpy@, @strncpy@ \\
34\end{tabular}
35\end{cquote}
36\caption{Language comparison of string API}
37\label{f:StrApiCompare}
38\end{figure}
39
40As mentioned in \VRef{s:String}, a C string uses null termination rather than a length, which leads to explicit storage management;
41hence, most of its group operations are error prone and expensive due to copying.
42Most high-level string libraries use a separate length field and specialized storage management to implement group operations.
43Interestingly, \CC strings retain null termination in case it is needed to interface with C library functions.
44\begin{cfa}
45int open( @const char * pathname@, int flags );
46string fname{ "test.cc" );
47open( fname.@c_str()@, O_RDONLY ); // null terminated value of string
48\end{cfa}
49Here, 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{
50C functions like \lstinline{strdup} do return allocated storage that must be freed by the caller.}
51% Instead, each \CC string is null terminated just in case it might be needed for this purpose.
52Providing this backwards compatibility with C has a ubiquitous performance and storage cost.
53
54
55\section{\CFA \lstinline{string} Type}
56\label{s:stringType}
57
58The \CFA string type is for manipulation of dynamically-sized character-strings versus C @char *@ type for manipulation of statically-sized null-terminated character-strings.
59Therefore, 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.
60As a result, a @string@ declaration does not specify a maximum length, where a C string array does.
61For \CFA, as a @string@ dynamically grows and shrinks in size, so does its underlying storage.
62For C, as a string dynamically grows and shrinks in size, but its underlying storage does not.
63The maximum storage for a \CFA @string@ value is @size_t@ characters, which is $2^{32}$ or $2^{64}$ respectively.
64A \CFA string manages its length separately from the string, so there is no null (@'\0'@) terminating value at the end of a string value.
65Hence, a \CFA string cannot be passed to a C string manipulation function, such as @strcat@.
66Like 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.
67\begin{cquote}
68\rm
69\begin{tabular}{@{}rrrrll@{}}
70\small\tt "a & \small\tt b & \small\tt c & \small\tt d & \small\tt e" \\
710 & 1 & 2 & 3 & 4 & left to right index \\
72-5 & -4 & -3 & -2 & -1 & right to left index
73\end{tabular}
74\end{cquote}
75The following operations manipulate an instance of type @string@, where the discussion assumes the following declarations.
76\begin{cfa}
77#include @<string.hfa>@
78@string@ s = "abcde", name = "MIKE", digit = "0123456789";
79const char cs[$\,$] = "abc";
80int i;
81\end{cfa}
82Note, the include file @<string.hfa>@ to access type @string@.
83
84
85\subsection{Implicit String Conversions}
86
87The ability to convert from internal (machine) to external (human) format is useful in situations other than I/O.
88Hence, the basic types @char@, @char *@, @int@, @double@, @_Complex@, including any signness and size variations, implicitly convert to type @string@ (as in Java).
89\begin{cquote}
90\begin{tabular}{@{}l|ll|l@{}}
91\begin{cfa}
92string s = 5;
93s = 'x';
94s = "abc";
95s = 42hh; /* signed char */
96s = 42h; /* short int */
97s = 0xff;
98\end{cfa}
99&
100\begin{cfa}
101"5"
102"x"
103"abc"
104"42"
105"42"
106"255"
107\end{cfa}
108&
109\begin{cfa}
110s = (ssize_t)MIN;
111s = (size_t)MAX;
112s = 5.5;
113s = 5.5L;
114s = 5.5+3.4i;
115s = 5.5L+3.4Li;
116\end{cfa}
117&
118\begin{cfa}
119"-9223372036854775808"
120"18446744073709551615"
121"5.5"
122"5.5"
123"5.5+3.4i"
124"5.5+3.4i"
125\end{cfa}
126\end{tabular}
127\end{cquote}
128Conversions can be explicitly specified using a compound literal.
129\begin{cfa}
130s = (string){ 5 }; s = (string){ "abc" }; s = (string){ 5.5 };
131\end{cfa}
132
133Conversions from @string@ to @char *@ attempt to be safe.
134The @strncpy@ conversion requires the maximum length for the pointer's target buffer.
135The assignment operator and constructor both allocate the buffer and return its address, meaning the programmer must free it.
136Note, a C string is always null terminated, implying storage is always necessary for the null.
137\begin{cquote}
138\begin{tabular}{@{}l|l@{}}
139\begin{cfa}
140string s = "abcde";
141char cs[4];
142strncpy( cs, s, sizeof(cs) );
143char * cp = s; // ownership
144delete( cp );
145cp = s + ' ' + s; // ownership
146delete( cp );
147\end{cfa}
148&
149\begin{cfa}
150
151
152"abc\0", in place
153"abcde\0", malloc
154
155"abcde abcde\0", malloc
156
157\end{cfa}
158\end{tabular}
159\end{cquote}
160
161
162\subsection{Length}
163
164The @len@ operation (short for @strlen@) returns the length of a C or \CFA string.
165For compatibility, @strlen@ also works with \CFA strings.
166\begin{cquote}
167\begin{tabular}{@{}l|l@{}}
168\begin{cfa}
169i = len( "" );
170i = len( "abc" );
171i = len( cs );
172i = strlen( cs );
173i = len( name );
174i = strlen( name );
175\end{cfa}
176&
177\begin{cfa}
1780
1793
1803
1813
1824
1834
184\end{cfa}
185\end{tabular}
186\end{cquote}
187
188
189\subsection{Comparison Operators}
190
191The binary relational, @<@, @<=@, @>@, @>=@, and equality, @==@, @!=@, operators compare \CFA strings using lexicographical ordering, where longer strings are greater than shorter strings.
192In C, these operators compare the C string pointer not its value, which does not match programmer expectation.
193C strings use function @strcmp@ to lexicographically compare the string value.
194Java has the same issue with @==@ and @.equals@.
195
196
197\subsection{Concatenation}
198
199The binary operators @+@ and @+=@ concatenate C @char@, @char *@ and \CFA strings, creating the sum of the characters.
200\begin{cquote}
201\begin{tabular}{@{}l|l@{\hspace{15pt}}l|l@{\hspace{15pt}}l|l@{}}
202\begin{cfa}
203s = "";
204s = 'a' + 'b';
205s = 'a' + "b";
206s = "a" + 'b';
207s = "a" + "b";
208\end{cfa}
209&
210\begin{cfa}
211
212"ab"
213"ab"
214"ab"
215"ab"
216\end{cfa}
217&
218\begin{cfa}
219s = "";
220s = 'a' + 'b' + s;
221s = 'a' + 'b' + s;
222s = 'a' + "b" + s;
223s = "a" + 'b' + s;
224\end{cfa}
225&
226\begin{cfa}
227
228"ab"
229"abab"
230"ababab"
231"abababab"
232\end{cfa}
233&
234\begin{cfa}
235s = "";
236s = s + 'a' + 'b';
237s = s + 'a' + "b";
238s = s + "a" + 'b';
239s = s + "a" + "b";
240\end{cfa}
241&
242\begin{cfa}
243
244"ab"
245"abab"
246"ababab"
247"abababab"
248\end{cfa}
249\end{tabular}
250\end{cquote}
251However, 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.}
252For example, subtracting characters or pointers has valid use-cases:
253\begin{cfa}
254ch - '0' $\C[2in]{// find character offset}$
255cs - cs2; $\C{// find pointer offset}\CRT$
256\end{cfa}
257addition is less obvious
258\begin{cfa}
259ch + 'b' $\C[2in]{// add character values}$
260cs + 'a'; $\C{// move pointer cs['a']}\CRT$
261\end{cfa}
262There are legitimate use cases for arithmetic with @signed@/@unsigned@ characters (bytes), and these types are treated differently from @char@ in \CC and \CFA.
263However, backwards compatibility makes it impossible to restrict or remove addition on type @char@.
264Similarly, it is impossible to restrict or remove addition on type @char *@ because (unfortunately) it is subscripting: @cs + 'a'@ implies @cs['a']@ or @'a'[cs]@.
265
266The prior \CFA concatenation examples show complex mixed-mode interactions among @char@, @char *@, and @string@ constants work correctly (variables are the same).
267The reason is that the \CFA type-system handles this kind of overloading well using the left-hand assignment-type and complex conversion costs.
268Hence, the type system correctly handles all uses of addition (explicit or implicit) for @char *@.
269\begin{cfa}
270printf( "%s %s %s %c %c\n", "abc", cs, cs + 3, cs['a'], 'a'[cs] );
271\end{cfa}
272Only @char@ addition can result in ambiguities, and only when there is no left-hand information.
273\begin{cfa}
274ch = ch + 'b'; $\C[2in]{// LHS disambiguate, add character values}$
275s = 'a' + 'b'; $\C{// LHS disambiguate, concatenate characters}$
276printf( "%c\n", @'a' + 'b'@ ); $\C{// no LHS information, ambiguous}$
277printf( "%c\n", @(return char)@('a' + 'b') ); $\C{// disambiguate with ascription cast}\CRT$
278\end{cfa}
279The ascription cast, @(return T)@, disambiguates by stating a (LHS) type to use during expression resolution (not a conversion).
280Fortunately, character addition without LHS information is rare in C/\CFA programs, so repurposing the operator @+@ for @string@ types is not a problem.
281Note, other programming languages that repurpose @+@ for concatenation, can have similar ambiguity issues.
282
283Interestingly, \CC cannot support this generality because it does not use the left-hand side of assignment in expression resolution.
284While it can special case some combinations:
285\begin{c++}
286s = 'a' + s; $\C[2in]{// compiles in C++}$
287s = "a" + s;
288\end{c++}
289it cannot generalize to any number of steps:
290\begin{c++}
291s = 'a' + 'b' + s; $\C{// does not compile in C++}\CRT$
292s = "a" + "b" + s;
293\end{c++}
294
295
296\subsection{Repetition}
297
298The binary operators @*@ and @*=@ repeat a string $N$ times.
299If $N = 0$, a zero length string, @""@, is returned.
300\begin{cquote}
301\begin{tabular}{@{}l|l@{}}
302\begin{cfa}
303s = 'x' * 0;
304s = 'x' * 3;
305s = "abc" * 3;
306s = ("MIKE" + ' ') * 3;
307\end{cfa}
308&
309\begin{cfa}
310""
311"xxx"
312"abcabcabc"
313"MIKE MIKE MIKE "
314\end{cfa}
315\end{tabular}
316\end{cquote}
317Like concatenation, there is a potential ambiguity with multiplication of characters;
318multiplication of pointers does not exist in C.
319\begin{cfa}
320ch = ch * 3; $\C[2in]{// LHS disambiguate, multiply character values}$
321s = 'a' * 3; $\C{// LHS disambiguate, concatenate characters}$
322printf( "%c\n", @'a' * 3@ ); $\C{// no LHS information, ambiguous}$
323printf( "%c\n", @(return char)@('a' * 3) ); $\C{// disambiguate with ascription cast}\CRT$
324\end{cfa}
325Fortunately, character multiplication without LHS information is even rarer than addition, so repurposing the operator @*@ for @string@ types is not a problem.
326
327
328\subsection{Substring}
329
330The substring operation returns a subset of a string starting at a position in the string and traversing a length, or matching a pattern string.
331\begin{cquote}
332\setlength{\tabcolsep}{10pt}
333\begin{tabular}{@{}l|ll|l@{}}
334\multicolumn{2}{@{}c}{\textbf{length}} & \multicolumn{2}{c@{}}{\textbf{pattern}} \\
335\multicolumn{4}{@{}l}{\lstinline{string name = "PETER"}} \\
336\begin{cfa}
337s = name( 0, 4 );
338s = name( 1, 4 );
339s = name( 2, 4 );
340s = name( 4, -2 );
341s = name( 8, 2 );
342s = name( 0, -2 );
343s = name( -1, -2 );
344s = name( -3 );
345\end{cfa}
346&
347\begin{cfa}
348"PETE"
349"ETER"
350"TER" // clip length to 3
351"ER"
352"" // beyond string to right, clip to null
353"" // beyond string to left, clip to null
354"ER"
355"TER" // to end of string
356\end{cfa}
357&
358\begin{cfa}
359s = name( "ET" );
360s = name( "WW" );
361
362
363
364
365
366
367\end{cfa}
368&
369\begin{cfa}
370"ET"
371"" // does not occur
372
373
374
375
376
377
378\end{cfa}
379\end{tabular}
380\end{cquote}
381For the length form, a negative starting position is a specification from the right end of the string.
382A negative length means that characters are selected in the opposite (right to left) direction from the starting position.
383If the substring request extends beyond the beginning or end of the string, it is clipped (shortened) to the bounds of the string.
384If the substring request is completely outside of the original string, a null string is returned.
385For the pattern-form, it returns the pattern string if the pattern matches or a null string if the pattern does not match.
386The usefulness of this mechanism is discussed next.
387
388The substring operation can appear on the left side of assignment, where it defines a replacement substring.
389The length of the right string may be shorter, the same, or longer than the length of left string.
390Hence, the left string may decrease, stay the same, or increase in length.
391\begin{cquote}
392\begin{tabular}{@{}l|l@{}}
393\begin{cfa}[escapechar={}]
394digit( 3, 3 ) = "";
395digit( 4, 3 ) = "xyz";
396digit( 7, 0 ) = "***";
397digit(-4, 3 ) = "$$$";
398digit( 5 ) = "LLL";
399\end{cfa}
400&
401\begin{cfa}[escapechar={}]
402"0126789"
403"0126xyz"
404"0126xyz"
405"012$$$z"
406"012$$LLL"
407\end{cfa}
408\end{tabular}
409\end{cquote}
410Now substring pattern matching is useful on the left-hand side of assignment.
411\begin{cquote}
412\begin{tabular}{@{}l|l@{}}
413\begin{cfa}[escapechar={}]
414digit( "$$" ) = "345";
415digit( "LLL") = "6789";
416\end{cfa}
417&
418\begin{cfa}
419"012345LLL"
420"0123456789"
421\end{cfa}
422\end{tabular}
423\end{cquote}
424Extending the pattern to a regular expression is a possible extension.
425
426The replace operation extends substring to substitute all occurrences.
427\begin{cquote}
428\begin{tabular}{@{}l|l@{}}
429\begin{cfa}
430s = replace( "PETER", "E", "XX" );
431s = replace( "PETER", "ET", "XX" );
432s = replace( "PETER", "W", "XX" );
433\end{cfa}
434&
435\begin{cfa}
436"PXXTXXR"
437"PXXER"
438"PETER"
439\end{cfa}
440\end{tabular}
441\end{cquote}
442The replacement is done left-to-right and substituted text is not examined for replacement.
443
444
445\subsection{Searching}
446
447The @find@ operation returns the position of the first occurrence of a key in a string.
448If the key does not appear in the string, the length of the string is returned.
449\begin{cquote}
450\begin{tabular}{@{}l|l@{}}
451\begin{cfa}
452i = find( digit, '3' );
453i = find( digit, "45" );
454i = find( digit, "abc" );
455\end{cfa}
456&
457\begin{cfa}
4583
4594
46010
461\end{cfa}
462\end{tabular}
463\end{cquote}
464
465A character-class operation indicates if a string is composed completely of a particular class of characters, \eg, alphabetic, numeric, vowels, \etc.
466\begin{cquote}
467\begin{tabular}{@{}l|l@{}}
468\begin{cfa}
469charclass vowels{ "aeiouy" };
470i = include( "aaeiuyoo", vowels );
471i = include( "aabiuyoo", vowels );
472\end{cfa}
473&
474\begin{cfa}
475
4768 // compliant
4772 // b non-compliant
478\end{cfa}
479\end{tabular}
480\end{cquote}
481@vowels@ defines a character class and function @include@ checks if all characters in the string appear in the class (compliance).
482The position of the last character is returned if the string is compliant or the position of the first non-compliant character.
483There is no relationship between the order of characters in the two strings.
484Function @exclude@ is the reverse of @include@, checking if all characters in the string are excluded from the class (compliance).
485\begin{cquote}
486\begin{tabular}{@{}l|l@{}}
487\begin{cfa}
488i = exclude( "cdbfghmk", vowels );
489i = exclude( "cdyfghmk", vowels );
490\end{cfa}
491&
492\begin{cfa}
4938 // compliant
4942 // y non-compliant
495\end{cfa}
496\end{tabular}
497\end{cquote}
498Both forms can return the longest substring of compliant characters.
499\begin{cquote}
500\begin{tabular}{@{}l|l@{}}
501\begin{cfa}
502s = include( "aaeiuyoo", vowels );
503s = include( "aabiuyoo", vowels );
504s = exclude( "cdbfghmk", vowels );
505s = exclude( "cdyfghmk", vowels );
506\end{cfa}
507&
508\begin{cfa}
509"aaeiuyoo"
510"aa"
511"cdbfghmk"
512"cd"
513\end{cfa}
514\end{tabular}
515\end{cquote}
516
517There are also versions of @include@ and @exclude@, returning a position or string, taking a validation function, like one of the C character-class functions.\footnote{It is part of the hereditary of C that these function take and return an \lstinline{int} rather than a \lstinline{bool}, which affects the function type.}
518\begin{cquote}
519\begin{tabular}{@{}l|l@{}}
520\begin{cfa}
521i = include( "1FeC34aB", @isxdigit@ );
522i = include( ".,;'!\"", @ispunct@ );
523i = include( "XXXx", @isupper@ );
524\end{cfa}
525&
526\begin{cfa}
5278 // compliant
5286 // compliant
5293 // non-compliant
530\end{cfa}
531\end{tabular}
532\end{cquote}
533These operations perform an \emph{apply} of the validation function to each character, where the function returns a boolean indicating a stopping condition for the search.
534The position of the last character is returned if the string is compliant or the position of the first non-compliant character.
535
536The translate operation returns a string with each character transformed by one of the C character transformation functions.
537\begin{cquote}
538\begin{tabular}{@{}l|l@{}}
539\begin{cfa}
540s = translate( "abc", @toupper@ );
541s = translate( "ABC", @tolower@ );
542int tospace( int c ) { return isspace( c ) ? ' ' : c; }
543s = translate( "X X\tX\nX", @tospace@ );
544\end{cfa}
545&
546\begin{cfa}
547"ABC"
548"abc"
549
550"X X X X"
551\end{cfa}
552\end{tabular}
553\end{cquote}
554
555
556\subsection{Returning N on Search Failure}
557
558Some 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.
559However, string search can fail, which is reported as an alternate search outcome, possibly an exception.
560Many string libraries use a return code to indicate search failure, with a failure value of @0@ or @-1@ (PL/I~\cite{PLI} returns @0@).
561This semantics leads to the awkward pattern, which can appear many times in a string library or user code.
562\begin{cfa}
563i = exclude( s, alpha );
564if ( i != -1 ) return s( 0, i );
565else return "";
566\end{cfa}
567
568\CFA 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).
569This semantics allows many search and substring functions to be written without conditions, \eg:
570\begin{cfa}
571string include( const string & s, int (*f)( int ) ) { return @s( 0, include( s, f ) )@; }
572string exclude( const string & s, int (*f)( int ) ) { return @s( 0, exclude( s, f ) )@; }
573\end{cfa}
574In string systems with an $O(1)$ length operator, checking for failure is low cost.
575\begin{cfa}
576if ( include( line, alpha ) == len( line ) ) ... // not found, 0 origin
577\end{cfa}
578\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.
579The \CFA code is simpler solely because of the choice for indicating search failure.
580(A simplification of the \CC version is to concatenate a sentinel character at the end of the line so the call to @find_first_not_of@ does not fail.)
581
582\begin{figure}
583\begin{cquote}
584\begin{tabular}{@{}l|l@{}}
585\multicolumn{1}{c}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\CFA}} \\
586\begin{cfa}
587for ( ;; ) {
588 string::size_type posn = line.find_first_of( alpha );
589 if ( posn == string::npos ) break;
590 line = line.substr( posn );
591 posn = line.find_first_not_of( alpha );
592 if ( posn != string::npos ) {
593 cout << line.substr( 0, posn ) << endl;
594 line = line.substr( posn );
595 } else {
596 cout << line << endl;
597 line = "";
598 }
599}
600\end{cfa}
601&
602\begin{cfa}
603for () {
604 size_t posn = exclude( line, alpha );
605 if ( posn == len( line ) ) break;
606 line = line( posn );
607 posn = include( line, alpha );
608
609 sout | line( 0, posn );
610 line = line( posn );
611
612
613
614
615}
616\end{cfa}
617\end{tabular}
618\end{cquote}
619\caption{Extracting Words from Line of Text}
620\label{f:ExtractingWordsText}
621\end{figure}
622
623
624\subsection{C Compatibility}
625
626To ease conversion from C to \CFA, \CFA provides companion C @string@ functions.
627Hence, it is possible to convert a block of C string operations to \CFA strings just by changing the type @char *@ to @string@.
628\begin{cquote}
629\begin{tabular}{@{}ll@{}}
630\begin{cfa}
631char s[32]; // string s;
632strlen( s );
633strnlen( s, 3 );
634strcmp( s, "abc" );
635strncmp( s, "abc", 3 );
636\end{cfa}
637&
638\begin{cfa}
639
640strcpy( s, "abc" );
641strncpy( s, "abcdef", 3 );
642strcat( s, "xyz" );
643strncat( s, "uvwxyz", 3 );
644\end{cfa}
645\end{tabular}
646\end{cquote}
647However, the conversion fails with I/O because @printf@ cannot print a @string@ using format code @%s@ because \CFA strings are not null terminated.
648Nevertheless, this capability does provide a useful starting point for conversion to safer \CFA strings.
649
650
651\subsection{I/O Operators}
652
653The ability to input and output strings is as essential as for any other type.
654The goal for character I/O is to also work with groups rather than individual characters.
655A comparison with \CC string I/O is presented as a counterpoint to \CFA string I/O.
656
657The \CC output @<<@ and input @>>@ operators are defined on type @string@.
658\CC output for @char@, @char *@, and @string@ are similar.
659The \CC manipulators are @setw@, and its associated width controls @left@, @right@ and @setfill@.
660\begin{cquote}
661\begin{tabular}{@{}l|l@{}}
662\begin{c++}
663string s = "abc";
664cout << setw(10) << left << setfill( 'x' ) << s << endl;
665\end{c++}
666&
667\begin{c++}
668
669"abcxxxxxxx"
670\end{c++}
671\end{tabular}
672\end{cquote}
673
674The \CFA input/output operator @|@ is defined on type @string@.
675\CFA output for @char@, @char *@, and @string@ are similar.
676The \CFA manipulators are @bin@, @oct@, @hex@, @wd@, and its associated width control and @left@.
677\begin{cquote}
678\begin{tabular}{@{}l|l@{}}
679\begin{cfa}
680string s = "abc";
681sout | bin( s ) | nl
682 | oct( s ) | nl
683 | hex( s ) | nl
684 | wd( 10, s ) | nl
685 | wd( 10, 2, s ) | nl
686 | left( wd( 10, s ) );
687\end{cfa}
688&
689\begin{cfa}
690
691"0b1100001 0b1100010 0b1100011"
692"0141 0142 0143"
693"0x61 0x62 0x63"
694" abc"
695" ab"
696"abc "
697\end{cfa}
698\end{tabular}
699\end{cquote}
700\CC @setfill@ is not considered an important string manipulator.
701
702\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.
703The \CC manipulator is @setw@ to restrict the size.
704Reading 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.
705\begin{cquote}
706\begin{tabular}{@{}l|l@{}}
707\begin{c++}
708char ch, c[10];
709string s;
710cin >> ch >> setw( 5 ) >> c >> s;
711@abcde fg@
712\end{c++}
713&
714\begin{c++}
715
716
717'a' "bcde" "fg"
718
719\end{c++}
720\end{tabular}
721\end{cquote}
722Input text can be \emph{gulped}, including whitespace, from the current point to an arbitrary delimiter character using @getline@.
723
724The \CFA philosophy for input is that, for every constant type in C, these constants should be usable as input.
725For example, the complex constant @3.5+4.1i@ can appear as input to a complex variable.
726\CFA input matching for @char@, @char *@, and @string@ are similar.
727C-strings may only be read with a width field, which should match the string size.
728Certain input manipulators support a scanset, which is a simple regular expression from @printf@.
729The \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@.
730\begin{cquote}
731\setlength{\tabcolsep}{10pt}
732\begin{tabular}{@{}l|l@{}}
733\begin{c++}
734char ch, c[10];
735string s;
736sin | ch | wdi( 5, c ) | s;
737@abcde fg@
738sin | quote( ch ) | quote( wdi( sizeof(c), c ) ) | quote( s, '[', ']' ) | nl;
739@'a' "bcde" [fg]@
740sin | incl( "a-zA-Z0-9 ?!&\n", s ) | nl;
741@x?&000xyz TOM !.@
742sin | excl( "a-zA-Z0-9 ?!&\n", s );
743@<>{}{}STOP@
744\end{c++}
745&
746\begin{c++}
747
748
749'a' "bcde" "fg"
750
751'a' "bcde" "fg"
752
753"x?&000xyz TOM !"
754
755"<>{}{}"
756
757\end{c++}
758\end{tabular}
759\end{cquote}
760Note, the ability to read in quoted strings with whitespace to match with program string constants.
761The @nl@ at the end of an input ignores the rest of the line.
762
763
764\subsection{Assignment}
765
766While \VRef[Figure]{f:StrApiCompare} emphasizes cross-language similarities, it elides many specific operational differences.
767For 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.
768\CC modifies the mutable receiver object, replacing by position (zero origin) and length.
769\begin{cquote}
770\begin{tabular}{@{}l|l@{}}
771\begin{c++}
772string s1 = "abcde";
773s1.replace( 2, 3, "xy" );
774\end{c++}
775&
776\begin{c++}
777
778"abxy"
779\end{c++}
780\end{tabular}
781\end{cquote}
782Java cannot modify the receiver (immutable strings) so it returns a new string, replacing by text.
783\label{p:JavaReplace}
784\begin{cquote}
785\begin{tabular}{@{}l|l@{}}
786\begin{java}
787String s = "abcde";
788String r = s.replace( "cde", "xy" );
789\end{java}
790&
791\begin{java}
792
793"abxy"
794\end{java}
795\end{tabular}
796\end{cquote}
797Java also provides a mutable @StringBuffer@, replacing by position (zero origin) and length.
798\begin{cquote}
799\begin{tabular}{@{}l|l@{}}
800\begin{java}
801StringBuffer sb = new StringBuffer( "abcde" );
802sb.replace( 2, 5, "xy" );
803\end{java}
804&
805\begin{java}
806
807"abxy"
808\end{java}
809\end{tabular}
810\end{cquote}
811However, there are anomalies.
812@StringBuffer@'s @substring@ returns a @String@ copy that is immutable rather than modifying the receiver.
813As well, the operations are asymmetric, \eg @String@ has @replace@ by text but not replace by position and vice versa for @StringBuffer@.
814
815More significant operational differences relate to storage management, often appearing through assignment (@target = source@), and are summarized in \VRef[Figure]{f:StrSemanticCompare}, which defines properties type abstraction, state, symmetry, and referent.
816The following discussion justifies the figure's yes/no entries per language.
817
818\begin{figure}
819\setlength{\extrarowheight}{2pt}
820\begin{tabularx}{\textwidth}{@{}p{0.6in}XXcccc@{}}
821 & & & \multicolumn{4}{@{}c@{}}{\underline{Supports Helpful?}} \\
822 & Required & Helpful & C & \CC & Java & \CFA \\
823\hline
824Type abst'n
825 & Low-level: The string type is a varying amount of text communicated via a parameter or return.
826 & High-level: The string-typed relieves the user of managing memory for the text.
827 & no & yes & yes & yes \\
828\hline
829State
830 & \multirow{2}{2in}
831 {Fast Initialize: The target receives the characters of the source without copying the characters, resulting in an Alias or Snapshot.}
832 & Alias: The target variable names the source text; changes made in either variable are visible in both.
833 & yes & yes & no & yes \\
834\cline{3-7}
835 &
836 & Snapshot: Subsequent operations on either the source or target variable do not affect the other.
837 & no & no & yes & yes \\
838\hline
839Symmetry
840 & Laxed: The target's type is anything string-like; it may have a different status concerning ownership.
841 & Strict: The target's type is the same as the source; both strings are equivalent peers concerning ownership.
842 & N/A & no & yes & yes \\
843\hline
844Referent
845 & Variable-Constrained: The target can accept the entire text of the source.
846 & Fragment: The target can accept an arbitrary substring of the source.
847 & no & no & yes & yes
848\end{tabularx}
849
850\noindent
851Notes
852\begin{itemize}[parsep=0pt]
853\item
854 All languages support Required in all criteria.
855\item
856 A language gets ``Supports Helpful'' in one criterion if it can do so without sacrificing the Required achievement on all other criteria.
857\item
858 The C ``string'' is @char *@, under the conventions of @<string.h>@. Because this type does not manage a text allocation, symmetry does not apply.
859\item
860 The Java @String@ class is analyzed; its @StringBuffer@ class behaves similarly to \CC.
861\end{itemize}
862\caption{Comparison of languages' strings, storage management perspective.}
863\label{f:StrSemanticCompare}
864\end{figure}
865
866In C, these declarations are very different.
867\begin{cfa}
868char x[$\,$] = "abcde";
869char * y = "abcde";
870\end{cfa}
871Both associate the declared name with the fixed, six contiguous bytes: @{'a', 'b', 'c', 'd', 'e', 0}@.
872But @x@ is allocated on the stack (with values filled at the declaration), while @y@ refers to the executable's read-only data-section.
873With @x@ representing an allocation, it offers information in @sizeof(x)@ that @y@ does not.
874But this extra information is second-class, as it can only be used in the immediate lexical context, \ie it cannot be passed to string operations or user functions.
875Only pointers to text buffers are first-class, and discussed further.
876\begin{cfa}
877char * s = "abcde";
878char * s1 = s; $\C[2.25in]{// alias state, N/A symmetry, variable-constrained referent}$
879char * s2 = &s[1]; $\C{// alias state, N/A symmetry, variable-constrained referent}$
880char * s3 = &s2[1]; $\C{// alias state, N/A symmetry, variable-constrained referent}\CRT$
881printf( "%s %s %s %s\n", s, s1, s2, s3 );
882$\texttt{\small abcde abcde bcde cde}$
883\end{cfa}
884Note, all of these aliased strings rely on the single null termination character at the end of @s@.
885The issue of symmetry does not apply to a low-level API because no management of a text buffer is provided.
886With the @char *@ type not managing the text storage, there is no ownership question, \ie operations on @s1@ or @s2@ never lead to their memory becoming reusable.
887While @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.
888
889In \CC, @string@ offers a high-level abstraction.
890\begin{cfa}
891string s = "abcde";
892string & s1 = s; $\C[2.25in]{// alias state, lax symmetry, variable-constrained referent}$
893string s2 = s; $\C{// no fast-initialize (strict symmetry, variable-constrained referent)}$
894string s3 = s.substr( 1, 2 ); $\C{// no fast-initialize (strict symmetry, fragment referent)}$
895string s4 = s3.substr( 1, 1 ); $\C{// no fast-initialize (strict symmetry, fragment referent)}$
896cout << s << ' ' << s1 << ' ' << s2 << ' ' << s3 << ' ' << s4 << endl;
897$\texttt{\small abcde abcde abcde bc c}$
898string & s5 = s.substr(2,4); $\C{// error: cannot point to temporary}\CRT$
899\end{cfa}
900The @s1@ lax symmetry reflects how its validity depends on the lifetime of @s@.
901It is common practice in \CC to use the @s1@-style for a by-reference function parameter.
902Doing so assumes that the callee only uses the referenced string for the duration of the call, \ie no storing the parameter (as a reference) for later.
903So, when the called function is a constructor, its definition typically uses an @s2@-style copy-initialization.
904Exceptions to this pattern are possible, but require the programmer to assure safety where the type system does not.
905The @s3@ initialization must copy the substring to support a subsequent @c_str@ call, which provides null-termination, generally at a different position than the source string's.
906@s2@ assignment could be made fast, by reference-counting the text area and using copy-on-write, but would require an implementation upgrade.
907
908In Java, @String@ also offers a high-level abstraction:
909\begin{java}
910String s = "abcde";
911String s1 = s; $\C[2.25in]{// snapshot state, strict symmetry, variable-constrained referent}$
912String s2 = s.substring( 1, 3 ); $\C{// snapshot state (possible), strict symmetry, fragment referent}$
913String s3 = s2.substring( 1, 2 ); $\C{// snapshot state (possible), strict symmetry, fragment referent}\CRT$
914System.out.println( s + ' ' + s1 + ' ' + s2 + ' ' + s3 );
915System.out.println( (s == s1) + " " + (s == s2) + " " + (s2 == s3) );
916$\texttt{\small abcde abcde bc c}$
917$\texttt{\small true false false}$
918\end{java}
919Note, Java's @substring@ takes a start and end position, rather than a start position and length.
920Here, facts about Java's implicit pointers and pointer equality can over complicate the picture, and so are ignored.
921Furthermore, Java's string immutability means string variables behave as simple values.
922The result in @s1@ is the pointer in @s@, and their pointer equality confirm no time is spent copying characters.
923With @s2@, the case for fast-copy is more subtle.
924Certainly, its value is not pointer-equal to @s@, implying at least a further allocation.
925But because Java is \emph{not} constrained to use a null-terminated representation, a standard-library implementation is free to refer to the source characters in-place.
926Java does not meet the aliasing requirement because immutability makes it impossible to modify.
927Java'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@;
928as a result, @StringBuffer@ scores as \CC.
929The easy symmetry that the Java string enjoys is aided by Java's garbage collection; Java's @s1@ is doing effectively the operation of \CC's @s1@, though without the consequence of complicating memory management.
930
931% former \PAB{What complex storage management is going on here?}
932% answer: the variable names in the sentence were out of date; fixed
933
934Finally, in \CFA, @string@ also offers a high-level abstraction:
935\begin{cfa}
936string s = "abcde";
937string & s1 = s; $\C[2.25in]{// alias state, lax symmetry, variable-constrained referent}$
938string s2 = s; $\C{// snapshot state, strict symmetry, variable-constrained referent}$
939string s3 = s`share; $\C{// alias state, strict symmetry, variable-constrained referent}$
940string s4 = s( 1, 2 ); $\C{// snapshot state, strict symmetry, fragment referent}$
941string s5 = s4( 1, 1 )`share'; $\C{// alias state, strict symmetry, fragment referent}\CRT$
942sout | s | s1 | s2 | s3 | s4 | s5;
943$\texttt{\small abcde abcde abcde abcde bc c}$
944\end{cfa}
945% all helpful criteria of \VRef[Figure]{f:StrSemanticCompare} are satisfied.
946The \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).
947The @s1@ case is the same in \CFA as in \CC.
948But the \CFA @s2@ delivers a fast snapshot, while the \CC @s2@ does not.
949\CFA offers the snapshot-vs-alias choice in @s2@-vs-@s3@ and @s4@-vs-@s5@.
950Regardless of snapshot-vs-alias and fragment-vs-whole, the target is always of the same @string@ type.
951
952% former \PAB{Need to discuss the example, as for the other languages.}
953% answer: done
954
955
956\subsection{Logical Overlap}
957
958It may be unfamiliar to combine \VRef[Figure]{f:StrSemanticCompare}'s alias state and fragment referent in one API, or at the same time.
959This section shows the capability in action.
960
961\begin{comment}
962The metaphor of a GUI text-editor is used to illustrate combining these features.
963Most editors allow selecting a consecutive block of text (highlighted) to define an aliased substring within a document.
964Typing in this area overwrites the prior text, replacing the selected text with less, same, or more text.
965Importantly, the document also changes size, not just the selection.
966%This alias model is assigning to an aliased substring for two strings overlapping by total containment: one is the selected string, the other is the document.
967Extend the metaphor to two selected areas, where one area can be drag-and-dropped into another, changing the text in the drop area and correspondingly changing the document.
968When the selected areas are independent, the semantics of the drag-and-drop are straightforward.
969However, for overlapping selections, either partial or full, there are multiple useful semantics.
970For example, two areas overlap at the top, or bottom, or a block at a corner, where one areas is dropped into the other.
971For selecting a smaller area within a larger, and dropping the smaller area into the larger to replace it.
972In both cases, meaningful semantics must be constructed or the operation precluded.
973However, without this advanced capability, certain operations become multi-step, possible requiring explicit temporaries.
974\end{comment}
975
976A GUI text-editor provides a metaphor.
977Selecting a block of text using the mouse defines an aliased substring within a document.
978Typing in this area overwrites what was there, replacing the originally selected text with more or less text.
979But the \emph{containing document} also grows or shrinks, not just the selection.
980This action models assigning to an aliased substring when one string is completely contained in the other.
981
982Extend the metaphor to a multi-user editor.
983If Alice selects a range of text at the bottom, while Bob is rewriting a paragraph at the top, Alice's selection holds onto the characters initially selected, unaffected by Bob making the document grow/shrink even though Alice's start index in the document is changing.
984This action models assigning to an aliased substring when the two strings do not overlap.
985
986Logically, Alice's and Bob's actions on the whole document are like two single-user-edit cases, giving the semantics of the individual edits flowing into a whole.
987But, there is no need to have two separate document strings.
988Even if a third selection removes all the text, both Alice's and Bob's strings remain.
989The independence of their selections assumes that the editor API does not allow the selection to be enlarged, \ie adding text from the containing environment, which may have disappeared.
990
991This leaves the ``Venn-diagram overlap'' cases, where Alice's and Bob's selections overlap at the top, bottom, or corner.
992In this case, the selection areas are dependent, and so, changes in content and size in one may have an affect in the other.
993There are multiple possible semantics for this case.
994The remainder of this section shows the chosen semantics for all of the cases.
995
996String sharing is expressed using the @`share@ marker to indicate aliasing (mutations shared) \vs snapshot (not quite an immutable result, but one with subsequent mutations isolated).
997This aliasing relationship is a sticky property established at initialization.
998For example, here strings @s1@ and @s1a@ are in an aliasing relationship, while @s2@ is in a copy relationship.
999\input{sharing1.tex}
1000Here, the aliasing (@`share@) causes partial changes (subscripting) to flow in both directions.
1001(In the following examples, note how @s1@ and @s1a@ change together, and @s2@ is independent.)
1002\input{sharing2.tex}
1003Similarly for complete changes.
1004\input{sharing3.tex}
1005Because string assignment copies the value, RHS aliasing is irrelevant.
1006Hence, aliasing of the LHS is unaffected.
1007\input{sharing4.tex}
1008
1009Now, consider string @s1_mid@ being an alias in the middle of @s1@, along with @s2@, made by a copy from the middle of @s1@.
1010\input{sharing5.tex}
1011Again, @`share@ passes changes in both directions; copy does not.
1012As 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"@.
1013This alternate positioning also applies to subscripting.
1014\input{sharing6.tex}
1015
1016Finally, assignment flows through the aliasing relationship without affecting its structure.
1017\input{sharing7.tex}
1018In the @"ff"@ assignment, the result is straightforward to accept because the flow direction is from contained (small) to containing (large).
1019The following rules explain aliasing substrings that flow in the opposite direction, large to small.
1020
1021Growth and shrinkage are natural extensions, as for the text-editor analogy, where an empty substring is as real as an empty string.
1022\input{sharing8.tex}
1023
1024Multiple portions of a string can be aliased.
1025% When there are several aliasing substrings at once, the text editor analogy becomes an online multi-user editor.
1026%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.
1027\input{sharing9.tex}
1028When @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,
1029
1030When changes happen on an aliasing substring that overlap.
1031\input{sharing10.tex}
1032Strings @s1_crs@ and @s1_mid@ overlap at character 4, @j@, because the substrings are 3,2 and 4,2.
1033When @s1_crs@'s size increases by 1, @s1_mid@'s starting location moves from 4 to 5, but the overlapping character remains, changing to @'+'@.
1034
1035\PAB{TODO: finish typesetting the demo}
1036
1037%\input{sharing-demo.tex}
1038
1039\VRef[Figure]{f:ParameterPassing} shows similar relationships when passing the results of substring operations by reference and by value to a subprogram.
1040Again, notice the side-effects to other reference parameters as one is modified.
1041
1042\begin{figure}
1043\begin{cfa}
1044// x, a, b, c, & d are substring results passed by reference
1045// e is a substring result passed by value
1046void test( string & x, string & a, string & b, string & c, string & d, string e ) {
1047\end{cfa}
1048\begin{cquote}
1049\setlength{\tabcolsep}{2pt}
1050\begin{tabular}{@{}ll@{}}
1051\begin{cfa}
1052
1053 a( 0, 2 ) = "aaa";
1054 b( 1, 12 ) = "bbb";
1055 c( 4, 5 ) = "ccc";
1056 c = "yyy";
1057 d( 0, 3 ) = "ddd";
1058 e( 0, 3 ) = "eee";
1059 x = e;
1060}
1061\end{cfa}
1062&
1063\sf
1064\setlength{\extrarowheight}{-0.5pt}
1065\begin{tabular}{@{}llllll@{}}
1066x & a & b & c & d & e \\
1067@"aaaxxxxxxxxx"@ & @"aaax"@ & @"xxx"@ & @"xxxxx"@ & @"xxx"@ & @"xxx"@ \\
1068@"aaaxbbbxxxxxx"@ & @"aaax"@ & @"xbbb"@ & @"xxxx"@ & @"xxx"@ & @"xxx"@ \\
1069@"aaaxbbbxxxcccxx"@ & @"aaax"@ & @"xbbb"@ & @"xxxccc"@& @"cccxx"@ & @"xxx"@ \\
1070@"aaaxbbbyyyxx"@ & @"aaax"@ & @"aaab"@ & @"yyy"@ & @"xx"@ & @"xxx"@ \\
1071@"aaaxbbbyyyddd"@ & @"aaax"@ & @"xbbb"@ & @"yyy"@ & @"ddd"@ & @"xxx"@ \\
1072@"aaaxbbbyyyddd"@ & @"aaax"@ & @"xbbb"@ & @"yyy"@ & @"ddd"@ & @"eee"@ \\
1073@"eee"@ & @""@ & @""@ & @""@ & @"eee"@ \\
1074 & \\
1075\end{tabular}
1076\end{tabular}
1077\end{cquote}
1078\begin{cfa}
1079int main() {
1080 string x = "xxxxxxxxxxx";
1081 test( x, x(0, 3), x(2, 3), x(4, 5), x(8, 5), x(8, 5) );
1082}
1083\end{cfa}
1084\caption{Parameter Passing}
1085\label{f:ParameterPassing}
1086\end{figure}
1087
1088
1089\section{Storage Management}
1090
1091This section discusses issues related to storage management of strings.
1092Specifically, it is common for strings to logically overlap partially or completely.
1093\begin{cfa}
1094string s1 = "abcdef";
1095string s2 = s1; $\C{// complete overlap, s2 == "abcdef"}$
1096string s3 = s1.substr( 0, 3 ); $\C{// partial overlap, s3 == "abc"}$
1097\end{cfa}
1098This raises the question of how strings behave when an overlapping component is changed,
1099\begin{cfa}
1100s3[1] = 'w'; $\C{// what happens to s1 and s2?}$
1101\end{cfa}
1102which is restricted by a string's mutable or immutable property.
1103For example, Java's immutable strings require copy-on-write when any overlapping string changes.
1104Note, the notion of underlying string mutability is not specified by @const@; \eg in \CC:
1105\begin{cfa}
1106const string s1 = "abc";
1107\end{cfa}
1108@const@ applies to the @s1@ pointer to @"abc"@, and @"abc"@ is an immutable constant that is \emph{copied} into the string's storage.
1109Hence, @s1@ is not pointing at an immutable constant and its underlying string is mutable, unless some other designation is specified, such as Java's global immutable rule.
1110
1111
1112\subsection{General Implementation}
1113\label{string-general-impl}
1114
1115A centrepiece of the string module is its memory manager.
1116The management scheme defines a shared buffer for string text.
1117Allocation in this buffer is always via a bump-pointer;
1118the buffer is compacted and/or relocated (to grow) when it fills.
1119A string is a smart pointer into this buffer.
1120
1121This cycle of frequent cheap allocations, interspersed with infrequent expensive compactions, has obvious similarities to a general-purpose memory-manager based on garbage collection (GC).
1122A few differences are noteworthy.
1123First, in a general purpose manager, the allocated objects may contain pointers to other objects, making the transitive reachability of these objects a crucial property.
1124Here, the allocations are text, so one allocation never keeps another alive.
1125Second, in a general purpose manager, the handle that keeps an allocation alive is a bare pointer.
1126For strings, a fatter representation is acceptable because this pseudo-pointer is only used for entry into the string-heap, not for general data-substructure linking around the general heap.
1127
1128\begin{figure}
1129\includegraphics{memmgr-basic.pdf}
1130\caption{String memory-management data structures}
1131\label{f:memmgr-basic}
1132\end{figure}
1133
1134\VRef[Figure]{f:memmgr-basic} shows the representation.
1135The heap header and text buffer define a sharing context.
1136Normally, one global context is appropriate for an entire program;
1137concurrency is discussed in \VRef{s:ControllingImplicitSharing}.
1138A string is a handle to a node in a linked list containing a information about a string text in the buffer.
1139The list is doubly linked for $O(1)$ insertion and removal at any location.
1140Strings are ordered in the list by text start address.
1141The heap header maintains a next-allocation pointer, @alloc@, pointing to the last live allocation in the buffer.
1142No external references point into the buffer and the management procedure relocates the text allocations as needed.
1143A string handle references a containing string, while its string is contiguous and not null terminated.
1144The length sets an upper limit on the string size, but is large (4 or 8 bytes).
1145String handles can be allocated in the stack or heap, and represent the string variables in a program.
1146Normal C life-time rules apply to guarantee correctness of the string linked-list.
1147The text buffer is large enough with good management so that often only one dynamic allocation is necessary during program execution, but not so large as to cause program bloat.
1148% During this period, strings can vary in size dynamically.
1149
1150When the text buffer fills, \ie the next new string allocation causes @alloc@ to point beyond the end of the buffer, the strings are compacted.
1151The linked handles define all live strings in the buffer, which indirectly defines the allocated and free space in the buffer.
1152The string handles are maintained in sorted order, so the handle list can be traversed, copying the first live text to the start of the buffer, and subsequent strings after each other.
1153After compaction, if free storage is still be less than the new string allocation, a larger text buffer is heap-allocated, the current buffer is copied into the new buffer, and the original buffer is freed.
1154Note, the list of string handles is structurally unaffected during a compaction;
1155only the text pointers in the handles are modified to new buffer locations.
1156
1157Object lifecycle events are the \emph{subscription-management} triggers in such a service.
1158There are two fundamental string-creation functions: importing external text like a C-string or reading a string, and initialization from an existing \CFA string.
1159When importing, storage comes from the end of the buffer, into which the text is copied.
1160The new string handle is inserted at the end of the handle list because the new text is at the end of the buffer.
1161When initializing from text already in the buffer, the new handle is a second reference into the original run of characters.
1162In this case, the new handle's linked-list position is after the original handle.
1163Both string initialization styles preserve the string module's internal invariant that the linked-list order matches the buffer order.
1164For string destruction, handles are removed from the list.
1165Once the last handle using a run of buffer characters is destroyed, that buffer space is excluded from use until the next compaction.
1166
1167Certain string operations result in a substring of another string.
1168The resulting handle is then placed in the correct sorted position in the list, possible requiring a short linear search to locate the position.
1169For string operations resulting in a new string, that string is allocated at the end of the buffer.
1170For shared-edit strings, handles that originally referenced containing locations need to see the new value at the new buffer location.
1171These strings are moved to appropriate locations at the end of the list \see{details in \VRef{sharing-impl}}.
1172For nonshared-edit strings, a containing string can be moved and the other strings can remain in the same position.
1173String assignment works similarly to string initialization, maintaining the invariant of linked-list order matching buffer order.
1174
1175At the level of the memory manager, these modifications can always be explained as assignment and appendment.
1176For example, an append is an assignment into the empty substring at the end of the buffer.
1177Favourable 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.
1178One notable example of favourable conditions occurs because the most recently written string is often the last in the buffer, after which a large amount of free space occurs.
1179So, repeated appends often occur without copying previously accumulated characters.
1180However, 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.
1181
1182
1183\subsection{RAII Limitations}
1184\label{string-raii-limit}
1185
1186Earlier work on \CFA~\cite[ch.~2]{Schluntz17} implemented object constructors and destructors for all types (basic and user defined).
1187A constructor is a user-defined function run implicitly \emph{after} an object's storage is allocated, and a destructor is a user-defined function run \emph{before} an object's storage is deallocated.
1188This feature, called Resource Acquisition Is Initialization (RAII)~\cite[p.~389]{Stroustrup94}, helps guarantee invariants for users before accessing an object and for the programming environment after an object terminates.
1189
1190The purposes of these invariants goes beyond ensuring authentic values inside an object.
1191Invariants can also track data about managed objects in other data structures.
1192Reference counting is an example application of an invariant outside of the immediate data value.
1193With a reference-counting smart-pointer, the constructor and destructor \emph{of a pointer type} track the lifecycle of the object it points to.
1194Both \CC and \CFA RAII systems are powerful enough to achieve reference counting.
1195
1196In 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.
1197\begin{cfa}
1198struct S { int * ip; };
1199void ?{}( S & @this@ ) { this.ip = new(); } $\C[3in]{// default constructor}$
1200void ?{}( S & @this@, int i ) { (this){}; *this.ip = i; } $\C{// initializing constructor}$
1201void ?{}( S & @this@, S s ) { (this){*s.ip}; } $\C{// copy constructor}$
1202void ^?{}( S & @this@ ) { delete( this.ip ); } $\C{// destructor}\CRT$
1203\end{cfa}
1204Such basic examples use the @this@ address only to gain access to the values being managed.
1205But the lifecycle logic can use the pointer generally, too.
1206For example, they can add @this@ object to a collection at creation and remove it at destruction.
1207\begin{cfa}
1208// header
1209struct T {
1210 // private
1211 inline dlink(T);
1212};
1213void ?{}( T & ); $\C[3in]{// default constructor}$
1214void ^?{}( T & ); $\C{// destructor}\CRT$
1215// implementation
1216static dlist(T) @all_T@;
1217void ?{}( T & this ) { insert_last(all_T, @this@) }
1218void ^?{}( T & this ) { remove(this); }
1219\end{cfa}
1220A module providing the @T@ type can traverse @all_T@ at relevant times, to keep the objects ``good.''
1221Hence, declaring a @T@ not only ensures that it begins with an initially ``good'' value, but it also provides an implicit subscription to a service that keeps the value ``good'' during its lifetime.
1222Again, both \CFA and \CC support this usage style.
1223
1224A third capability concerns \emph{implicitly} requested copies.
1225When stack-allocated objects are used as parameter and return values, a sender's version exists in one stack frame and a receiver's version exists in another.
1226In the parameter direction, the language's function-call handling must arrange for a copy-constructor call to happen, at a time near the control transfer into the callee. %, with the source as the caller's (sender's) version and the target as the callee's (receiver's) version.
1227In the return direction, the roles are reversed and the copy-constructor call happens near the return of control.
1228\CC supports this capability.% without qualification.
1229\CFA offers limited support;
1230simple examples work, but implicit copying does not combine successfully with the other RAII capabilities discussed.
1231
1232\CC also offers move constructors and return-value optimization~\cite{RVO20}.
1233These features help reduce unhelpful copy-constructor calls, which, for types like the @S@ example, would lead to extra memory allocations.
1234\CFA does not currently have these features; adding similarly-intended features to \CFA is desirable.
1235However, this section is about a problem in the realization of features that \CFA already supports.
1236Hence, the comparison continues with the classic version of \CC that treated such copy-constructor calls as necessary.
1237
1238To summarize the unsupported combinations, the relevant features are:
1239\begin{enumerate}
1240\item
1241 Object provider implements lifecycle functions to manage a resource outside of the object.
1242\item
1243 Object provider implements lifecycle functions to store references back to the object, often originating from outside of it.
1244\item
1245 Object user expects to pass (in either direction) an object by value for function calls.
1246\end{enumerate}
1247\CC supports all three simultaneously. \CFA does not currently support \#2 and \#3 on the same object, though \#1 works along with either one of \#2 or \#3. \CFA needs to be fixed to support all three simultaneously.
1248
1249The reason that \CFA does not support \#2 with \#3 is a holdover from how \CFA function calls lowered to C, before \CFA got references and RAII.
1250At that time, adhering to a principal of minimal intervention, this code could always be treated as passthrough:
1251\begin{cfa}
1252struct U { ... };
1253// RAII to go here
1254void f( U u ) { F_BODY(u) }
1255U x;
1256f( x );
1257\end{cfa}
1258But adding custom RAII (at ``...go here'') changes things.
1259The common \CC lowering~\cite[Sec. 3.1.2.3]{cxx:raii-abi} proceeds differently than the present \CFA lowering.
1260\begin{cquote}
1261\begin{tabular}{@{}l|l@{}}
1262\begin{cfa}
1263$\C[0.0in]{// \CC, \CFA future}\CRT$
1264struct U {...};
1265// RAII elided
1266void f( U * __u_orig ) {
1267 U u = * __u_orig; // call copy ctor
1268 F_BODY( u );
1269 // call dtor, u
1270}
1271U x; // call default ctor
1272
1273
1274f( &x ) ;
1275
1276
1277// call dtor, x
1278\end{cfa}
1279&
1280\begin{cfa}
1281$\C[0.0in]{// \CFA today}\CRT$
1282struct U {...};
1283// RAII elided
1284void f( U u ) {
1285
1286 F_BODY( u );
1287
1288}
1289U x; // call default ctor
1290{
1291 U __u_for_f = x; // call copy ctor
1292 f( __u_for_f );
1293 // call dtor, __u_for_f
1294}
1295// call dtor, x
1296\end{cfa}
1297\end{tabular}
1298\end{cquote}
1299The current \CFA scheme is still using a by-value C call.
1300C does a @memcpy@ on structures passed by value.
1301And so, @F_BODY@ sees the bits of @__u_for_f@ occurring at an address that has never been presented to the @U@ lifecycle functions.
1302If @U@ is trying to have a style-\#2 invariant, it shows up broken in @F_BODY@: references supposedly to @u@ are actually to @__u_for_f@.
1303The \CC scheme does not have this problem because it constructs the for @f@ copy in the correct location within @f@.
1304
1305Yet, the current \CFA scheme is sufficient to deliver style-\#1 invariants (in this style-\#3 use case) because this scheme still does the correct number of lifecycle calls, using correct values, at correct times.
1306So, reference-counting or simple ownership applications get their invariants respected under call/return-by-value.
1307
1308% [Mike is not currently seeing how distinguishing initialization from assignment is relevant]
1309% as opposed to assignment where sender and receiver are in the same stack frame.
1310% What 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.
1311% To provide this knowledge, languages differentiate between initialization and assignment to a left-hand side.
1312% \begin{cfa}
1313% Obj obj2 = obj1; $\C[1.5in]{// initialization, obj2 is initialized}$
1314% obj2 = obj1; $\C{// assignment, obj2 must be initialized for management to work}\CRT$
1315% \end{cfa}
1316% Initialization occurs at declaration by value, parameter by argument, return temporary by function call.
1317% Hence, it is necessary to have two kinds of constructors: by value or object.
1318% \begin{cfa}
1319% Obj obj1{ 1, 2, 3 }; $\C[1.5in]{// by value, management is initialized}$
1320% Obj obj2 = obj1; $\C{// by obj, management is updated}\CRT$
1321% \end{cfa}
1322% When no object management is required, initialization copies the right-hand value.
1323% Hence, the calling convention remains uniform, where the unmanaged case uses @memcpy@ as the initialization constructor and managed uses the specified initialization constructor.
1324
1325% [Mike is currently seeing RVO as orthogonal, addressed with the footnote]
1326% to a temporary.
1327% For example, in \CC:
1328% \begin{c++}
1329% struct S {...};
1330% S identity( S s ) { return s; }
1331% S s;
1332% s = identity( s ); // S temp = identity( s ); s = temp;
1333% \end{c++}
1334% the generated code for the function call created a temporary with initialization from the function call, and then assigns the temporary to the object.
1335% This two step approach means extra storage for the temporary and two copies to get the result into the object variable.
1336% \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''.
1337% \CFA uses C semantics for function return giving direct value-assignment, which eliminates unnecessary code, but skips an essential feature needed by lifetime management.
1338% The following discusses the consequences of this semantics with respect to lifetime management of \CFA strings.
1339
1340The string API offers style \#3's pass-by-value in, \eg in the return of @"a" + "b"@.
1341Its implementation uses the style-\#2 invariant of the string handles being linked to each other, helping to achieve high performance.
1342Since these two RAII styles cannot coexist, a workaround splits the API into two layers: one that provides pass-by-value, built upon the other with inter-linked handles.
1343The layer with pass-by-value incurs a performance penalty, while the layer without delivers the desired runtime performance.
1344The slower, friendlier High Level API (HL, type @string@) wraps the faster, more primitive Low Level API (LL, type @string_res@, abbreviating ``resource'').
1345Both APIs present the same features, up to return-by-value operations being unavailable in LL and implemented via the workaround in HL.
1346The intention is for most future code to target HL.
1347When the RAII issue is fixed, the full HL feature set will be achievable using the LL-style lifetime management.
1348Then, HL will be removed;
1349LL's type will be renamed @string@ and programs written for current HL will run faster.
1350In the meantime, performance-critical sections of applications must use LL.
1351Subsequent performance experiments \see{\VRef{s:PerformanceAssessment}} use the LL API when comparing \CFA to other languages.
1352This measurement gives a fair estimate of the goal state for \CFA.
1353A separate measure of the HL overhead is also included.
1354hence, \VRef[Section]{string-general-impl} us describing the goal state for \CFA.
1355In present state, the type @string_res@ replaces its mention of @string@ as inter-linked handle.
1356
1357To use LL, a programmer rewrites invocations using pass-by-value APIs into invocations where resourcing is more explicit.
1358Many invocations are unaffected, notably assignment and comparison.
1359Of the capabilities listed in \VRef[Figure]{f:StrApiCompare}, only the following three cases need revisions.
1360\begin{cquote}
1361\begin{tabular}{ll}
1362HL & LL \\
1363\hline
1364\begin{cfa}
1365
1366string s = "a" + "b";
1367\end{cfa}
1368&
1369\begin{cfa}
1370string_res sr = "a";
1371sr += b;
1372\end{cfa}
1373\\
1374\hline
1375\begin{cfa}
1376string s = "abcde";
1377string s2 = s(2, 3); // s2 == "cde"
1378
1379s(2,3) = "x"; // s == "abx" && s2 == "cde"
1380\end{cfa}
1381&
1382\begin{cfa}
1383string_res sr = "abcde";
1384string_res sr2 = {sr, 2, 3}; // sr2 == "cde"
1385string_res sr_mid = { sr, 2, 3, SHARE };
1386sr_mid = "x"; // sr == "abx" && sr2 == "cde"
1387\end{cfa}
1388\\
1389\hline
1390\begin{cfa}
1391string s = "abcde";
1392
1393s[2] = "xxx"; // s == "abxxxde"
1394\end{cfa}
1395&
1396\begin{cfa}
1397string_res sr = "abcde";
1398string_res sr_mid = { sr, 2, 1, SHARE };
1399mid = "xxx"; // sr == "abxxxde"
1400\end{cfa}
1401\end{tabular}
1402\end{cquote}
1403The actual HL workaround is having @string@ wrap a pointer to a uniquely owned, heap-allocated @string_res@. This arrangement has @string@ being style-\#1 RAII, which is compatible with pass-by-value.
1404
1405
1406\subsection{Sharing Implementation}
1407\label{sharing-impl}
1408
1409The \CFA string module has two mechanisms to deal with string handles sharing text.
1410In the first type of sharing, the user requests that both string handles be views of the same logical, modifiable string.
1411This state is typically produced by the substring operation.
1412\begin{cfa}
1413string s = "abcde";
1414string s1 = s( 1, 2 )@`share@; $\C[2.25in]{// explicit sharing}$
1415s[1] = 'x'; $\C{// change s and s1}\CRT$
1416sout | s | s1;
1417$\texttt{\small axcde xc}$
1418\end{cfa}
1419Here, the source string-handle is referencing an entire string, and the resulting, newly made, string handle is referencing a contained portion of the original.
1420In this state, a modification made in the overlapping area is visible in both strings.
1421
1422The 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.
1423This state is typically produced by constructing a new string, using an original string as its initialization source.
1424\begin{cfa}
1425string s = "abcde";
1426string s1 = s( 1, 2 )@@; $\C[2.25in]{// no sharing}$
1427s[1] = 'x'; $\C{// copy-on-write s1}\CRT$
1428sout | s | s1;
1429$\texttt{\small axcde bc}$
1430\end{cfa}
1431In 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.
1432
1433A further abstraction helps distinguish the two senses of sharing.
1434A 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'' option given.
1435The SES is represented by a second linked list among the handles.
1436A string that shares edits with no other is in a SES by itself.
1437Inside a SES, a logical modification of one substring portion may change the logical value in another substring portion, depending on whether the two actually overlap.
1438Conversely, no logical value change can flow outside of a SES.
1439Even 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.
1440
1441
1442\subsection{Controlling Implicit Sharing}
1443\label{s:ControllingImplicitSharing}
1444
1445There are tradeoffs associated with sharing and its implicit copy-on-write mechanism.
1446Several qualitative matters are detailed in \VRef{s:PerformanceAssessment}.
1447In 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.''
1448Therefore, it is useful to toggle this capability on or off when it is not providing any application benefit.
1449
1450The \CFA string library provides the type @string_sharectx@ to control an ambient sharing context.
1451It allows two adjustments: to opt out of sharing entirely or to begin sharing within a private context.
1452Running with sharing disabled can be thought of as a \CC STL-emulation mode, where each string is dynamically allocated.
1453The 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.
1454\VRef[Figure]{fig:string-sharectx} illustrates this behaviour by showing the stack frames of a program in execution.
1455In this example, the single-letter functions are called in alphabetic order.
1456The functions @a@, @b@ and @g@ share string character ranges with each other, because they occupy a common sharing-enabled context.
1457The 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).
1458The functions @c@, @d@ and @f@ never share anything, because they are in a sharing-disabled context.
1459Executing the example does not produce an interesting outcome, but the comments in the picture indicate when the logical copy operation runs with
1460\begin{description}
1461 \item[share:] the copy being deferred, as described through the rest of this section (fast), or
1462 \item[copy:] the copy performed eagerly (slow).
1463\end{description}
1464Only eager copies can cross @string_sharectx@ boundaries.
1465The 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.
1466
1467\begin{figure}
1468 \begin{tabular}{ll}
1469 \lstinputlisting[language=CFA, firstline=10, lastline=55]{sharectx.run.cfa}
1470 &
1471 \raisebox{-0.17\totalheight}{\includegraphics{string-sharectx.pdf}} % lower
1472 \end{tabular}
1473 \caption{Controlling copying vs sharing of strings using \lstinline{string_sharectx}.}
1474 \label{fig:string-sharectx}
1475\end{figure}
1476
1477
1478\subsection{Sharing and Threading}
1479
1480The \CFA string library provides no thread safety, the same as \CC string, providing similar performance goals.
1481Threads 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.
1482A positive consequence of this approach is that independent threads can use the sharing buffer without locking overhead.
1483When 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.
1484Finally, concurrent users of string objects can provide their own mutual exclusion.
1485
1486
1487\subsection{Short-String Optimization}
1488
1489\CC implements a short-string ($\le$16) optimization (SSO).
1490As a string header contains a pointer to the string text, this pointer can be tagged and used to contain a short string, removing a dynamic memory allocation/deallocation.
1491\begin{c++}
1492class string {
1493 union {
1494 struct { $\C{// long string, text in heap}$
1495 size_t size;
1496 char * strptr;
1497 } lstr;
1498 char sstr[sizeof(lstr)]; $\C{// short string <16 characters, text in situ}$
1499 };
1500 // some tagging for short or long strings
1501};
1502\end{c++}
1503However, there is now a conditional check required on the fast-path to switch between short and long string operations.
1504
1505It might be possible to pack 16- or 32-bit Unicode characters within the same string buffer as 8-bit characters.
1506Again, locations for identification flags must be found and checked along the fast path to select the correct actions.
1507Handling utf8 (variable length), is more problematic because simple pointer arithmetic cannot be used to stride through the variable-length characters.
1508Trying 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.
1509
1510
1511\section{Performance Assessment}
1512\label{s:PerformanceAssessment}
1513
1514I assessed the \CFA string library's speed and memory usage against strings in \CC STL.
1515Overall, this analysis shows that adding support for the features shown earlier in the chapter comes at no substantial cost in the performance of features common to both APIs.
1516
1517Moreover, the results support the \CFA string's position as a high-level enabler of simplified text processing.
1518STL makes its user think about memory management.
1519When the user does, and is successful, STL's performance can be very good.
1520But when the user fails to think through the consequences of the STL representation, performance becomes poor.
1521The \CFA string lets the user work at the level of just putting the right text into the right variables, with corresponding performance degradations reduced or eliminated.
1522
1523% The final test shows the overall win of the \CFA text-sharing mechanism.
1524% It exercises several operations together, showing \CFA enabling clean user code to achieve performance that STL requires less-clean user code to achieve.
1525
1526
1527\subsection{Methodology}
1528
1529These tests use a \emph{corpus} of strings.
1530Their lengths are important; the specific characters occurring in them are immaterial.
1531In a result graph, a corpus's mean string length is often the independent variable shown on the X axis.
1532
1533When a corpus contains strings of different lengths, the lengths are drawn from a lognormal distribution.
1534Therefore, strings much longer than the mean occur less often and strings slightly shorter than the mean occur most often.
1535A corpus's string sizes are one of:
1536\begin{description}
1537 \item [Fixed-size] all string lengths are of the stated size.
1538 \item [Varying 1 and up] the string lengths are drawn from the lognormal distribution with a stated mean and all lengths occur.
1539 \item [Varying 16 and up] string lengths are drawn from the lognormal distribution with the stated mean, but only lengths 16 and above occur; thus, the stated mean is above 16.
1540\end{description}
1541The special treatment of length 16 deals with the SSO in STL @string@, currently not implemented in \CFA.
1542A fixed-size or from-16 distribution ensures that \CC's extra-optimized cases are isolated within, or removed from, the comparison.
1543In all experiments that use a corpus, its text is generated and loaded into the system under test before the timed phase begins.
1544To ensure comparable results, a common memory allocator is used for \CFA and \CC.
1545\CFA runs the llheap allocator~\cite{Zulfiqar22}, which is also plugged into \CC.
1546
1547The operations being measured take dozens of nanoseconds, so a succession of many invocations is run and timed as a group.
1548The experiments run for a fixed duration (5 seconds), as determined by re-checking @clock()@ every 10,000 invocations, which is never more often than once per 80 ms.
1549Timing outcomes report mean nanoseconds per invocation, which includes harness overhead and the targeted string API execution.
1550
1551As discussed in \VRef[Section]{string-raii-limit}, general performance comparisons are made using \CFA's faster, low-level string API, named @string_res@.
1552\VRef{s:ControllingImplicitSharing} presents an operational mode where \CFA string sharing is turned off.
1553In this mode, the \CFA string operates similarly to \CC's, by using a heap allocation for string text.
1554Some experiments include measurements in this mode for baselining purposes, called ``\CC emulation mode'' or ``nosharing''.
1555
1556See~\VRef{s:ExperimentalEnvironment} for a description of the hardware environment.
1557
1558
1559\subsection{Test: Append}
1560
1561These tests measure the speed of appending strings from the corpus onto a larger, growing string.
1562They show \CFA performing comparably to \CC overall, though with penalties for simple API misuses.
1563The basic harness is:
1564\begin{cfa}
1565// set alarm duration
1566for ( ... ) { $\C[1.5in]{// loop for duration}$
1567 for ( i; N ) { $\C{// perform multiple appends (concatenations)}$
1568 accum += corpus[ f( i ) ];
1569 }
1570 count += N; $\C{// count number of appends}\CRT$
1571}
1572\end{cfa}
1573The harness's outer loop executes for the experiment duration.
1574The string is reset to empty before appending (not shown).
1575The inner loop builds up a growing-length string with successive appends.
1576Each run targets a specific (mean) corpus string length and produces one data point on the result graph.
1577Three specific comparisons are made with this harness.
1578Each picks its own independent-variable basis of comparison.
1579All three comparisons use the varying-from-1 corpus construction, \ie they allow the STL to show its advantage for SSO.
1580
1581
1582\subsubsection{Fresh vs Reuse in \CC, Emulation Baseline}
1583
1584The first experiment compares \CFA with \CC, with \CFA operating in nosharing mode and \CC having no other mode, hence both string package are using @malloc@/@free@.
1585% This experiment establishes a baseline for other experiments.
1586This experiment also introduces the first \CC coding pitfall, which the next experiment shows is helped by turning on \CFA sharing.
1587% This pitfall shows, a \CC programmer must pay attention to string variable reuse.
1588In the following, both programs are doing the same thing: start with @accum@ empty and build it up by appending @N@ strings (type @string@ in \CC and the faster @string_res@ in \CFA).
1589\begin{cquote}
1590\setlength{\tabcolsep}{40pt}
1591\begin{tabular}{@{}ll@{}}
1592% \multicolumn{1}{c}{\textbf{fresh}} & \multicolumn{1}{c}{\textbf{reuse}} \\
1593\begin{cfa}
1594
1595for ( ... ) {
1596 @string_res accum;@ $\C[1.5in]{// fresh}$
1597 for ( N )
1598 accum @+=@ ... $\C{// append}\CRT$
1599}
1600\end{cfa}
1601&
1602\begin{cfa}
1603string_res accum;
1604for ( ... ) {
1605 @accum = "";@ $\C[1.5in]{// reuse}$
1606 for ( N )
1607 accum @+=@ ... $\C{// append}\CRT$
1608}
1609\end{cfa}
1610\end{tabular}
1611\end{cquote}
1612The difference is creating a new or reusing an existing string variable.
1613The pitfall is that most programmers do not consider this difference.
1614However, creating a new variable implies deallocating the previous string storage and allocating new empty storage.
1615As the string grows, further deallocations/allocations are required to release the previous and extend the current string storage.
1616So, the fresh version is constantly restarting with zero string storage, while the reuse version benefits from having its prior large storage from the last append sequence.
1617
1618\begin{figure}
1619\centering
1620 \includegraphics{plot-string-peq-cppemu.pdf}
1621% \includegraphics[width=\textwidth]{string-graph-peq-cppemu.png}
1622 \caption{Fresh vs Reuse in \CC, Emulation Baseline.
1623 Average time per iteration with one \lstinline{x += y} invocation (lower is better).
1624 Comparing \CFA's STL emulation mode with STL implementations, and comparing the fresh with reused reset styles.}
1625 \label{fig:string-graph-peq-cppemu}
1626 \bigskip
1627 \bigskip
1628 \includegraphics{plot-string-peq-sharing.pdf}
1629% \includegraphics[width=\textwidth]{string-graph-peq-sharing.png}
1630 \caption{\CFA Compromise for Fresh \vs Reuse.
1631 Average time per iteration with one \lstinline{x += y} invocation (lower is better).
1632 Comparing \CFA's sharing mode with STL, and comparing the fresh with reused reset styles.
1633 The \CC results are repeated from \VRef[Figure]{fig:string-graph-peq-cppemu}.}
1634 \label{fig:string-graph-peq-sharing}
1635\end{figure}
1636
1637\VRef[Figure]{fig:string-graph-peq-cppemu} shows the resulting performance.
1638The two fresh (solid) lines and the two reuse (dash) lines are identical, except for lengths $\le$10, where the \CC SSO has a 40\% average and minimally 24\% advantage.
1639The gap between the fresh and reuse lines is the removal of the dynamic memory allocates and reuse of prior storage, \eg 100M allocations for fresh \vs 100 allocations for reuse across all experiments.
1640While allocation reduction is huge, data copying dominates the cost, so the lines are still reasonably close together.
1641
1642
1643\subsubsection{\CFA's Sharing Mode}
1644
1645This comparison is the same as the last one, except the \CFA implementation is using sharing mode.
1646Hence, both \CFA's fresh and reuse versions have no memory allocations, and as before, only for reuse does \CC have no memory allocations.
1647\VRef[Figure]{fig:string-graph-peq-sharing} shows the resulting performance.
1648For fresh at append lengths 5 and above, \CFA is now closer to the \CC reuse performance, because of removing the dynamic allocations.
1649However, for reuse, \CFA has slowed down slightly, to performance matching the new fresh version, as the two versions are now implemented virtually the same.
1650The reason for the \CFA reuse slow-down is the overhead of managing the sharing scheme (primarily maintaining the list of handles), without gaining any benefit.
1651
1652\begin{comment}
1653FIND A HOME!!!
1654The potential benefits of the sharing scheme do not give \CFA an edge over \CC when appending onto a reused string, though the first one helps \CFA win at going onto a fresh string. These abilities are:
1655\begin{itemize}
1656\item
1657To grow a text allocation repeatedly without copying it elsewhere.
1658This ability is enabled by \CFA's most-recently modified string being located immediately before the text buffer's \emph{shared} bump-pointer area, \ie often a very large greenfield, relative to the \emph{individual} string being grown.
1659With \CC-reuse, this benefit is already reaped by the user's reuse of a pre-stretched allocation.
1660Yet \CC-fresh pays the higher cost because its room to grow for free is at most a constant times the original string's length.
1661\item
1662To share an individual text allocation across multiple related strings.
1663This ability is not applicable to appending with @+=@.
1664It in play in [xref sub-experiment pta] and [xref experiment pbv].
1665\item
1666To share a text arena across unrelated strings, sourcing disparate allocations from a common place.
1667That is, always allocating from a bump pointer, and never maintaining free lists.
1668This ability is not relevant to running any append scenario on \CFA with sharing, because appending modifies an existing allocation and is not driving several allocations.
1669This ability is assessed in [xref experiment allocn].
1670\end{itemize}
1671This cost, of slowing down append-with-reuse, is \CFA paying the piper for other scenarios done well.
1672\CFA prioritizes the fresh use case because it is more natural.
1673The \emph{user-invoked} reuse scheme is an unnatural programming act because it deliberately misuses lexical scope: a variable (@accum@) gets its lifetime extended beyond the scope in which it is used.
1674
1675A \CFA user needing the best performance on an append scenario can still access the \CC-like speed by invoking noshare.
1676This (indirect) resource management is memory-safe, as compared to that required in \CC to use @string&@, where knowledge of another string's lifetime comes into play.
1677This abstraction opt-out is also different from invoking the LL API-level option.
1678In fact, these considerations are orthogonal.
1679But the key difference is that invoking the LL API would be a temporary measure, to use a workaround of a known \CFA language issue; choosing to exempt a string from sharing is a permanent act of program tuning.
1680Beyond these comparisons, opting for noshare actually provides program ``eye candy,'' indicating that under-the-hood thinking is becoming relevant here.
1681\end{comment}
1682
1683
1684\subsubsection{Misusing Concatenation}
1685
1686A further pitfall occurs writing the apparently equivalent @x = x + y@ \vs @x += y@.
1687For numeric types, the generated code is equivalent, giving identical performance.
1688However, for string types there can be a significant difference.
1689This pitfall is a particularly likely for beginners.
1690
1691In earlier experiments, the choice of \CFA API among HL and LL had no impact on the functionality being tested.
1692Here, however, the @+@ operation, which returns its result by value, is only available in HL.
1693The \CFA @+@ number was obtained by inlining the HL implementation of @+@, which is done using LL's @+=@, into the test harness, while omitting the HL-inherent extra dynamic allocation. The HL-upon-LL @+@ implementation, is:
1694\begin{cfa}
1695struct string {
1696 string_res * inner; // RAII manages malloc/free, simple ownership
1697};
1698void ?+=?( string & s, string s2 ) {
1699 (*s.inner) += (*s2.inner);
1700}
1701string @?+?@( string lhs, string rhs ) {
1702 string ret = lhs;
1703 ret @+=@ rhs;
1704 return ret;
1705}
1706\end{cfa}
1707This @+@ implementation is also the goal implementation of @+@ once the HL/LL workaround is no longer needed. Inlining the induced LL steps into the test harness gives:
1708\begin{cquote}
1709\setlength{\tabcolsep}{20pt}
1710\begin{tabular}{@{}ll@{}}
1711\multicolumn{1}{c}{\textbf{Goal}} & \multicolumn{1}{c}{\textbf{Measured}} \\
1712\begin{cfa}
1713
1714for ( ... ) {
1715 string accum;
1716 for ( ... ) {
1717 accum = @accum + ...@
1718
1719
1720 }
1721}
1722\end{cfa}
1723&
1724\begin{cfa}
1725string_res pta_ll_temp;
1726for ( ... ) {
1727 string_res accum;
1728 for ( ... ) {
1729 pta_ll_temp = @accum@;
1730 pta_ll_temp @+= ...@;
1731 accum = pta_ll_temp;
1732 }
1733}
1734\end{cfa}
1735\end{tabular}
1736\end{cquote}
1737Note, the goal code functions today in HL but with slower performance.
1738
1739\begin{figure}
1740\centering
1741 \includegraphics{plot-string-pta-sharing.pdf}
1742% \includegraphics[width=\textwidth]{string-graph-pta-sharing.png}
1743 \caption{CFA's low overhead for misusing concatenation. Average time per iteration with one \lstinline{x += y} invocation (lower is better). Comparing \CFA (having implicit sharing activated) with STL, and comparing the \lstinline{+}-then-\lstinline{=} with the \lstinline{+=} append styles. The \lstinline{+=} results are repeated from \VRef[Figure]{fig:string-graph-peq-sharing}.}
1744 \label{fig:string-graph-pta-sharing}
1745\end{figure}
1746
1747\VRef[Figure]{fig:string-graph-pta-sharing} gives the outcome, where the Y-axis is log scale because of the large differences.
1748The STL's penalty is $8 \times$ while \CFA's is only $2 \times$, averaged across the cases shown here.
1749Moreover, the STL's gap increases with string size, while \CFA's converges.
1750So again, \CFA helps users who just want to treat strings as values, and not think about the resource management under the covers.
1751
1752While not a design goal, and not graphed, \CFA in STL-emulation mode outperformed STL in this case.
1753User-managed allocation reuse did not affect either implementation in this case; only ``fresh'' results are shown.
1754
1755
1756\subsection{Test: Pass Argument}
1757
1758STL has a penalty for passing a string by value, which forces users to think about memory management when communicating values with a function.
1759The key \CFA value-add is that a user can think of a string simply as a value; this test shows that \CC charges a stiff penalty for thinking this way, while \CFA does not.
1760This test illustrates a main advantage of the \CFA sharing algorithm (in one case).
1761It shows STL's SSO providing a successful mitigation (in the other case).
1762
1763The basic operation considered is:
1764\begin{cfa}
1765void foo( string s );
1766string s = "abc";
1767foo( s );
1768\end{cfa}
1769With implicit sharing active, \CFA treats this operation as normal and supported.
1770
1771Again, an HL-LL difference requires an LL mockup. This time, the fact to integrate into the test harness is that LL does not directly support pass-by-value.
1772\begin{cquote}
1773\setlength{\tabcolsep}{20pt}
1774\begin{tabular}{@{}ll@{}}
1775\multicolumn{1}{c}{\textbf{Goal}} & \multicolumn{1}{c}{\textbf{Measured}} \\
1776\begin{cfa}
1777void helper( string q ) {
1778
1779}
1780for ( ... ) { // loop for duration
1781 helper( corpus[ f( i ) ] );
1782 count += 1;
1783}
1784\end{cfa}
1785&
1786\begin{cfa}
1787void helper( string_res & qref ) {
1788 string_res q = { qref, COPY_VALUE };
1789}
1790
1791
1792
1793
1794\end{cfa}
1795\end{tabular}
1796\end{cquote}
1797The goal (HL) version gives the modified test harness, with a single loop.
1798Each iteration uses a corpus item as the argument to the function call.
1799These corpus items were imported to the string heap before beginning the timed run.
1800
1801\begin{figure}
1802\centering
1803 \includegraphics{plot-string-pbv.pdf}
1804% \includegraphics[width=\textwidth]{string-graph-pbv.png}
1805 \begin{tabularx}{\linewidth}{>{\centering\arraybackslash}X >{\centering\arraybackslash}X} (a) & (b) \end{tabularx}
1806 \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.
1807(a) With \emph{Varying 1 and up} corpus construction, in which the STL-only benefit of SSO optimization occurs, in varying degrees, at all string sizes.
1808(b) With \emph{Fixed-size} corpus construction, in which this benefit applies exactly to strings with length below 16.}
1809 \label{fig:string-graph-pbv}
1810\end{figure}
1811
1812\VRef[Figure]{fig:string-graph-pbv} shows the costs for calling a function that receives a string argument by value.
1813STL's performance worsens uniformly as string length increases, while \CFA has the same performance at all sizes.
1814Although the STL is better than \CFA until string length 10 because of the SSO.
1815While improved, the \CFA cost to pass a string is still nontrivial.
1816The contributor is adding and removing the callee's string handle from the global list.
1817This cost is $1.5 \times$ to $2 \times$ over STL's when SSO applies, but is avoidable once \CFA realizes this optimization.
1818At the larger sizes, the STL runs more than $3 \times$ slower, because it has to allocation/deallocate storage for the parameter and copy the argument string to the parameter.
1819If the \CC string is passed by reference, the results are better and flat across string lengths like \CFA.
1820
1821
1822\subsection{Test: Allocate}
1823
1824This test directly compares the allocation schemes of the \CFA string (sharing active), with the STL string.
1825It treats the \CFA scheme as a form of garbage collection (GC), and the STL scheme as an application of malloc-free.
1826The test shows that \CFA enables faster speed in exchange for greater memory usage.
1827
1828A precise garbage-collector, which knows all pointers and may modify them, often runs faster than malloc-free in an amortized analysis, even though it must occasionally stop to collect (latency issues).
1829The speedup happens indirectly because GC is able to move objects.
1830(In the case of the mini-allocator powering the \CFA string library, objects are runs of text.)
1831Moving objects creates a large contiguous store of available memory;
1832fresh allocations consume from this area using light-weight \emph{bump-allocation}.
1833A malloc-free implementation cannot move objects because the location of allocated objects is unknown;
1834hence, free-space management is more complex managing linked structures of freed allocations and possibly coalescing freed blocks.
1835
1836GC occurs lazily, so the lifetime of unreachable allocations is unknown, \eg GC may never be triggered.
1837A garbage collector can minimize the memory footprint for unreachable allocations by collecting eagerly.
1838However, this approach can negate GC's speed advantage.
1839Alternatively, collecting infrequently can consume large amounts of resident and virtual memory.
1840In contrast, a program using malloc-free tries to release an allocation as soon as it is unreachable.
1841This approach reduces the memory footprint (depending on the allocator), but has a per allocation cost for each free.
1842% [TODO: find citations for the above knowledge]
1843Therefore, a speed \vs memory tradeoff is a good comparator for \CFA--STL string allocations.
1844%The test verifies that it is so and quantifies the returns available.
1845
1846These tests manipulate a tuning knob that controls how much extra space to use.
1847Specific values of this knob are not user-visible and are not presented in the results.
1848Instead, its two effects (amount of space used and time per operation) are shown.
1849The independent variable is the liveness target, which is the fraction of the text buffer in use at the end of a collection.
1850The allocator expands its text buffer during a collection if the actual live fraction exceeds this target.
1851
1852\begin{figure}
1853\centering
1854 \includegraphics{string-perf-alloc.pdf}
1855 \caption{Memory-allocation test's harness and its resulting pattern of memory usage under a bump-pointer-only scheme.}
1856 \label{fig:string-perf-alloc}
1857\end{figure}
1858
1859\VRef[Figure]{fig:string-perf-alloc} shows the memory-allocation pattern that the test harness drives.
1860Note how this pattern creates few long-lived strings and many short-lived strings.
1861To extend this pattern to the scale of a performance test, the harness is actually recursive, to achieve the nesting (three levels in the figure), and iterative, to achieve the fan-out (factor two / binary tree in the figure).
1862\begin{cfa}
1863void f( int depth ) {
1864 if (depth == 0) return;
1865 string_res x = corpus[...]; // importing from char * here
1866 COUNT_ONE_OP_DONE
1867 for ( fanOut ) {
1868 // elided: terminate fixed-duration experiment
1869 f( depth - 1 );
1870 }
1871}
1872START_TIMER
1873f( launchDepth );
1874STOP_TIMER
1875\end{cfa}
1876The runs presented use 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.
1877This sizing keeps an average of 836 strings live and keeps the amounts of consumed memory within the machine's last-level cache.
1878The time measurement is nanoseconds per @f@-call, for internal or leaf strings.
1879
1880% String lifetime (measured in number of subsequent string allocations) is ?? distributed, because each node in the call tree survives as long as its descendent calls.
1881
1882
1883\begin{figure}
1884\centering
1885 \includegraphics{plot-string-allocn.pdf}
1886 \begin{tabularx}{\linewidth}{>{\centering\arraybackslash}X >{\centering\arraybackslash}X} (a) Vertical, Lower is better. \\ Horizontal, leftward is better. & (b) \hspace*{5pt} STL CFA \hspace*{20pt} STL \hspace*{10pt} CFA \hspace*{10pt} \end{tabularx}
1887 \caption{Space and time performance, under varying fraction-live targets, for the five string lengths shown, at \emph{Varying 16 and up} corpus construction.}
1888 \label{fig:string-graph-allocn}
1889\end{figure}
1890
1891\VRef[Figure]{fig:string-graph-allocn} shows the experimental results.
1892In plot (a), there is one labeled curve for each of the five chosen string sizes, 20, 50, 100, 200, 500.
1893A labeled curve shows the \CFA speed and space combinations achievable by varying the fraction-live tuning parameter.
1894Stepping along the curve from top-left toward bottom-right means the string library has a smaller fraction of its heap remain live after collection, \ie it doubles its size more often.
1895Hence, memory approximately doubles between points.
1896The additional memory means less time is spent collecting, so the curve shows lower (better) times per operation (y-axis).
1897This doubling benefit diminishes, so the curves begin to flatten.
1898
1899The point chosen as \CFA's default liveness threshold (20\%) is marked with a circle.
1900For most string lengths, this point occurs as the doubling benefit becomes subjectively negligible.
1901At len-500, the amount of space needed to achieve 20\% liveness is so much that last-level cache misses begin occurring generating a further slowdown.
1902This effect is an anomaly of the experimental setup trying to compare such varied sizes in one view;
1903the len-500 default point is included only to provide a holistic picture of the STL comparisons (discussed next).
1904
1905Staying within plot (a), each \emph{tradeoff} line (green) connects the default-tuned \CFA performance point with its length-equivalent STL performance point.
1906STL always uses less memory (occurs to the left of) than its \CFA equivalent.
1907Ideally, \CFA results would be faster (STL occurs above it);
1908however, this inversion only occurs for smaller string lengths.
1909That is, the STL-to-\CFA tradeoff line goes down and to the right for small strings, but for longer strings, it goes up and to the right.
1910
1911Plot (b) offers insight into why larger lengths are not currently showing the anticipated tradeoff, and suggests possible remedies.
1912This plot breaks down the time spent, comparing STL--\CFA tradeoffs, at successful len-50 with unsuccessful len-200.
1913Data are sourced from running the experiment under \emph{perf}, recording samples of the call stack, and imposing a mutually-exclusive classification on these call stacks.
1914Reading a stacked bar from the top down, \emph{text import} captures samples where a routine like @memcpy@ is running, so that the string library is copying characters from the corpus source into its allocated working space.
1915\emph{Malloc-free} means literally one of those routines (taking nontrivial time only for STL), while \emph{gc} is the direct \CFA(-only) equivalent.
1916All of the attributions so far occur while a string is live; further time spent in a string's lifecycle management functions is attributed \emph{ctor-dtor}.
1917Skipping to the bottom-most attribution, \emph{harness-leaf} represents samples where the youngest live stack frame is simply the recursive @helper@ routine of \VRef[Figure]{fig:string-perf-alloc}.
1918The skipped attribution \emph{Other} has samples that meet none of the criteria above.
1919
1920\PAB{From Mike: need to add the sep-comp side bar to the graph.}
1921
1922Beside \CFA's principal bars, a bar for separate-compilation overhead (\emph{sep.\ comp.}) shows the benefit that STL enjoys by using monolithic compilation.
1923\CFA currently forgoes this benefit.
1924This overhead figure was obtained by hacking a version of the \CFA string library to have a header-only implementation and measuring the resulting speed.
1925The difference between separately compiled (normal) and header-only (hacked) versions is the reported overhead.
1926It represents how much \CFA could speed up if it switched to a header-only implementation to match STL.
1927The difference jumps noticeably between the different string sizes, but has little correlation with string size ($r=0.3$).
1928Associating this potential improvement with the \emph{other} attribution is a stylistic choice.
1929
1930Analyzing the stacked bars from the bottom up, the first two categories, \emph{harness-leaf} and \emph{other} both give baseline times that should not be matters of STL-\CFA difference.
1931The \emph{harness-leaf} category is called out as a quality check; this attribution is equal across all four setups, ruling out mysterious ``everything is X\% slower'' effects.
1932But with the \emph{other} attribution, STL beats \CFA by an amount that matches the STL's benefit from avoiding separate compilation.
1933In the \emph{ctor-dtor} category, \CFA is spending more time than STL to inter-link its string handles.
1934Comparing STL's \emph{malloc-free} with \CFA's \emph{gc}, \CFA's is considerably shorter, in spite of its copying, because \emph{gc} only spends time on live strings, while \emph{malloc-free} works on all strings.
1935Most of the every-string bookkeeping occurs under STL's \emph{malloc-free} and \CFA's \emph{ctor-dtor}.
1936So the critical comparison is STL's $(\textit{ctor-dtor} + \textit{malloc-free})$ \vs \CFA's $(\textit{ctor-dtor} + \textit{gc})$.
1937Here, \CFA is a clear winner.
1938Moreover, the discussion so far holds for both the successful and unsuccessful string lengths, albeit with the length-correlated duration of \emph{gc} (due to copying) encroaching on \CFA's advantage, though not eliminating it.
1939The total attributions so far see \CFA ahead, possibly by more than is shown, depending on how one views the separate-compilation difference.
1940Under a \CFA-generous separate-compilation stance, \CFA is equal or ahead in every important category so far.
1941
1942The remaining attribution, \emph{text-import}, is thus a major reason that \CFA is currently unsuccessful at delivering improved speed with long strings. \PAB{From Mike: need to finish this point.}
1943
1944% \subsection{Test: Normalize}
1945
1946% This test is more applied than the earlier ones.
1947% It combines the effects of several operations.
1948% It 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.
1949
1950% To motivate: edits being rare
1951
1952% The program is doing a specialized find-replace operation on a large body of text.
1953% In the program under test, the replacement is just to erase a magic character.
1954% But in the larger software problem represented, the rewrite logic belongs to a module that was originally intended to operate on simple, modest-length strings.
1955% The challenge is to apply this packaged function across chunks taken from the large body.
1956% Using the \CFA string library, the most natural way to write the helper module's function also works well in the adapted context.
1957% Using 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.
1958
1959\begin{lstlisting}
1960void processItem( string & item ) {
1961 // find issues in item and fix them
1962}
1963\end{lstlisting}
Note: See TracBrowser for help on using the repository browser.