The design goals for the new StringObject class are
- Fixed-width strings with fixed widths of 8, 16 and 32 bits. Widths are either automatic (based on constructor arguments), or manual (as requested).
- 8-bit strings contain the first 256 Unicode characters. UTF-8 is not supported in strings.
- 16-bit strings are UTF-16, including surrogate pairs.
- String contents may be based upon static data.
- String APIs should be as close to SpiderMonkey string APIs as possible to make ActionMonkey implementation easy.
- Preferred access to characters is via a charAt() method that returns 32-bit characters regardless of the underlying implementation.
There are three types of strings:
- Direct strings, where the character data immediately follows the instance data. Memory is allocated via low-level calls to GC-Alloc() with an in-place constructor call.
- Static strings, where the character data is kept elsewhere. This data must be guaranteed to exist longer than the String instance itself. C character constants are good candidates. ABC data is also be a good candidate as long as the unload of the ABC data does not cause the data in these strings to become invalid.
- Dependent strings, where a DRC'ed pointer keeps a reference to the master string, and the string contains a pointer to the start of the character data, and a length count.
Out-of-memory conditions will be handled by the allocator in a future version. The String class uses checks for NULL, and returns NULL for new strings whose allocation failed.
UTF-8, UTF-16 and UTF-32
The String class ignores all Unicode encoding related issues. A string is just an array of characters. For Unicode conformant processing, a StringUtils class exists with a number of static methods:
- Widening and narrowing with surrogate pair processing for 16-bit and 32-bit strings
- Creating a string out of UTF-8 data
- Creating an UTF-8 data buffer out of a string
These layers will catch the following:
- Invalid UTF-8 character sequences
- Single 16-bit and 32-bit characters that have a value between 0xD800 and 0xDFFF
- 32-bit characters with a value > 0x10FFFF
- Any other conditions that Unicode 5 considers to be ill-formed.
Strings may either be created with 8, 16, or 32 bit data. A UTF-8 version of the StringUtils::create() method processes UTF-8 data, which results in the smallest width that can hold the data, or a desired width that may cause the creation method to return NULL if the UTF-8 string contains characters that cannot be represented in the desired width. This is the case for 8-bit strings with UTF-8 character values greater then 0x00FF, for 16-bit strings with UTF-8 character values greater than 0xFFFF, and for 32-bit strings with UTF-8 character values greater than 0x10FFFF.
Strings are never zero-terminated. Zero-characters are legal as part of a string.
Strings are created using static creator functions. This allows the implementation to use raw memory allocation and in-place constructor calls to avoid having to do two memory allocations, one for the instance, and the other for the data. Strings created that way contain the data right behind the instance data.
The maximum string width determines the way strings are created. It is an optional argument to the string constructors.
- 8 bits: If the source data contains 16 or 32 bit data, the return value is NULL.
- 16 bits: If the source data contains 32 bit values, surrogate pairs are created. If a character is > 0x10FFFF, NULL is returned.
- 32 bits: If a character is > 0x10FFFF, NULL is returned.
This allows implementers to define the maximum width of strings; they can choose to use 8, 16 or 32 bits only, or they can choose to go with whatever width that fits best. If they choose best-fit widths, String creation methods do not create UTF-16 surrogate pairs. Use the StringUtils class to process surrogate pairs.
It would not be a good idea to create a new, flat string every time two strings are concatenated. Consider this loop:
var s = ""; for (var i = 32; i <= 1024; i++) s += String.fromCharCode (i);
If a new, flat string would be created on every iteration, this would lead to a almost 1000 copy operations, with a growing string buffer.
The concatenating operation uses a different approach called in-place concatenation. A memory allocator like MMgc usually aligns memory on fixed boundaries. MMgc uses 16-byte boundaries. On Windows, if you allocate a string of 2 characters, MMgc allocates 6 extra bytes, which usually is wasted memory.
This example deals with 8-bit characters. For other widths, divide the number of bytes by the character withs to get the number of characters.
So, the string "Hi" looks in memory as follows. Note that the character "¤" is used to show unused characters.
The concatenation of "Hi" and " world" would not create a new string containing "Hi world", but rather fill the buffer with the second string, and then create a dependent string pointing to the result.
For the VM, the original string has not changed because its length did not change:
The dependent string, however, keeps a reference to its master, and spans the entire string:
|pointer to master|
If another concatenation would cause the same string "Hi" (which actually is "Hi world") and a space character, the buffer can even be reused, and a new dependent string could be created:
|pointer to master|
If the string would not be " world", but, say, " Jonathan", the buffer would be too small for the append operation. Therefore, the result of such a concatenation is a new string, containing "Hi Jonathan". To accommodate loops where strings are appended to a base string, the concatenation allocates extra characters at the end that correspond to the length of the new string. The new string length would be 11, with extra 11 bytes (remember that we are talking about 8-bit characters in this example), making 22 bytes. MMgc would add two more bytes, resulting in a total character buffer length of 24 bytes:
As a result, the new string can be used to concatenate 13 extra characters in-place. If the string again grows beyound the buffer capacity, a new string is again allocated with an even bigger room for extra characters etc. To inhibit excessive growth and memory consumption, the maximum number of extra bytes is limited to 64 KBytes. So even for large strings, a copy operation is only forced every 64 KBytes.
In-place concatenation is only possible if the right-hand string width is smaller or equal to the the left-hand string width. If it is wider, a new string is created that contains the widened left-hand string concatenated with the right-hand string.
A first implementation used a tree-based approach on top of in-place concatenation. Unfortunately, this resulted in large trees that held references to all right-hand-side strings, and the resulting flatten operation was highly recursive, which is not desirable for small devices. The current approach is a good compromise between low memory usage and a low number of string copy operations. Also, it reduces the number of objects that need to be marked during a GC operation.
A substring is a dependent string, as above, that holds a reference to its master, the start and the length of the data. A substring of a substring does not reference a dependent string, but rather the master string itself.
Consider the above example:
substr (3, 5) would create this dependent string, pointing to "world":
|pointer to master|
substr (3, 5).substr (0, 1) would then create this dependent string, where the master still is the original string:
|pointer to master|
Static string data
Strings can be created using static character data. This data must, of course, stay alive as long as the strings stay alive. C string constants are a great candidate. ABC data can be unloaded, so ABC data is currently not usable as static data. It should be, though, since ABC strings can be used directly if they are ASCII, which they most often are. We need to come up with a locking mechanism that locks ABC string data in memory as long as there are String instances that point to ABC string data. A possible approach would be to restrict these strings to interned strings. On unload, the strings in that table could either be freed, or the data could be copied to the heap, and the pointer could be replaced.
Since strings are immutable, they are by definition thread safe. The only unsafe operation is the in-place concatenation operation. Currently, TT is not thread safe, so the sensible code is clearly marked with a TODO comment until a global threading solution for TT is available.
- The SM API offers the registration of string finalizers. Strings can be created with custom buffers that the finalizer takes care of deallocating. The String code is prepared to handle these finalizers, but the code is currently commented out (and incomplete). All finalizers are stored in a global table with a fixed maximum size. The registration of a finalizer returns an index value into this table. Finalizer indexes correspond to string type enumerators (see last section). The size of that array is limited to 16. The table should be able to store a JSContext pointer together with the finalizer.
- JS_GetStringChars() returns a pointer to UTF-16 characters, and JS_GetStringBytes() returns a pointer to UTF-8 characters. Both buffers are guaranteed to live as long as the string instance lives. SM maintains a separate cache for this purpose, where string buffers are garbage-collected. Other encodings may be requested as well.
This TT helper class was used to wrap a String instance (which contained UTF-8 data) into a class providing direct access to the string buffer. The new String code offers a stack-based StUTF8String containing UTF-8 data and provides access to that data. The pcre code needs this class and another class StIndexableUTF8String class, since pcre is UTF-8 based. This leads to a performance slowdown that could be avoided if a regular expression parser was used that worked with UTF-16 data.