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