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

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

more proofreading of string chapter

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