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

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

more string API updates

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