mirror of
https://github.com/apple/swift-collections
synced 2026-11-27 04:54:21 +00:00
[BigString] Fix accidentally quadratic BigString.init
When ingesting a `String` instance, `BigString` assumes that the input string has a reasonably efficient UTF-8 view. Unfortunately, that is very much not the case when the input happens to be backed by a bridged NSString object — it appears that in this case, the ingester loop invokes some operation(s) with linear complexity in the size of the entire input, rendering the ingester’s overall complexity quadratic. The BigString ingester is only expected to operate within a single chunk at the time. It’s unclear precisely which operation triggers the quadratic behavior; ideally we should figure it out and resolve it with a more targeted fix. In the meantime, a blunt stopgap fix is to force-transcode the input string to UTF-8 at the time the ingester is initialized. This unnecessarily wastes some (temporary) memory on holding the transcoded string, but it avoids the quadratic cliff.
This commit is contained in:
3 files changed
+118
-3
No files matched your search
@@ -39,13 +39,19 @@ extension BigString {
|
||||
var state: _CharacterRecognizer
|
||||
|
||||
init(_ input: Substring) {
|
||||
self.input = input
|
||||
self.start = input.startIndex
|
||||
self.state = _CharacterRecognizer()
|
||||
self.init(input, startState: _CharacterRecognizer())
|
||||
}
|
||||
|
||||
init(_ input: Substring, startState: __owned _CharacterRecognizer) {
|
||||
self.input = input
|
||||
// Prevent accidentally quadratic operation by ensuring that we have
|
||||
// a native UTF-8 string.
|
||||
// FIXME: This is wasteful: if `input` happens to be a bridged
|
||||
// FIXME: NSString instance, then it temporarily allocates a full
|
||||
// FIXME: copy of the (transcoded) input string, only to then copy
|
||||
// FIXME: its pieces into the tree later.
|
||||
// FIXME: We should have a direct ingester path for native UTF-16 data.
|
||||
self.input.makeContiguousUTF8()
|
||||
self.start = input.startIndex
|
||||
self.state = startState
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user