PureXML/Sources/Parsing/ByteStorage.swift
Mihaela Mihaljevic 72eaeeb439 perf(parsing): byte-backed Reader and bulk content runs
String input copies its UTF-8 once into owned storage (an unsafe
pointer encapsulated in a class lifetime, never escaping the parser)
and scalars decode straight off the pointer, eliminating the
per-character closure chain; ASCII literals match and consume at the
byte level; and plain-ASCII character data scans as a single byte run
with one String built per run. Parse drops 32 percent cumulative
(0.49 s to 0.34 s on the 4.2 MB corpus, libxml2 ratio 30x to 20x).
The W3C suite caught one boundary (a run starting with '>' could
swallow the ]]> check after the character path consumed ]]); the run
scanner leaves a leading '>' to the character path, pinned as a unit
regression. All conformance suites, Linux, and WASM verified.
2026-06-10 18:48:57 +02:00

27 lines
957 B
Swift

extension PureXML.Parsing {
/// Owned contiguous UTF-8 storage for the Reader's fast path: one copy
/// of the input, read through an unsafe cursor with no per-byte bounds
/// or retain traffic. The bytes come from a Swift String, so they are
/// valid UTF-8 by construction. The pointer never escapes the parser;
/// deallocation rides the class lifetime.
final class ByteStorage {
let pointer: UnsafeMutablePointer<UInt8>
let count: Int
init(_ bytes: [UInt8]) {
count = bytes.count
pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: max(count, 1))
bytes.withUnsafeBufferPointer { buffer in
if let base = buffer.baseAddress {
pointer.initialize(from: base, count: count)
}
}
}
deinit {
pointer.deinitialize(count: count)
pointer.deallocate()
}
}
}