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

Last change on this file since cefaa2df was 931f1b4, checked in by Peter A. Buhr <pabuhr@…>, 6 months ago

more proofreading string chapter

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