source: doc/theses/mike_brooks_MMath/string.tex@ 5faa3a5

Last change on this file since 5faa3a5 was 9c12dd0, checked in by Michael Brooks <mlbrooks@…>, 34 hours ago

Apply document-level formatting and rearrange the array-in-struct discussion.

Formatting:

  • add visual separation of figures from text
  • prevent "formula"-style code fragments from page breaking
  • (thereby prevent code formula broken at end of page from mistakenly restarting the reader in a code figure at the top of the next page)
  • give short+long figure captions
  • assure descriptive captions
  • remove Title-Like Captialization in Captions
  • turn a couple figures into tables where the figure visual separator looks bad

Array-in-struct

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