Skip to content

Commit 54b22fe

Browse files
Simplify the current parser context management
1 parent fe0e1d0 commit 54b22fe

File tree

1 file changed

+7
-30
lines changed

1 file changed

+7
-30
lines changed

Sources/FoundationXML/XMLParser.swift

+7-30
Original file line numberDiff line numberDiff line change
@@ -462,24 +462,16 @@ open class XMLParser : NSObject {
462462

463463
open var allowedExternalEntityURLs: Set<URL>?
464464

465-
/// The current parser context for the current thread.
466-
private class _CurrentParserContext {
467-
var _stack: [XMLParser] = []
468-
var _current: XMLParser? {
469-
return _stack.last
470-
}
471-
}
472-
473465
#if os(WASI)
474466
/// The current parser associated with the current thread. (assuming no multi-threading)
475467
/// FIXME: Unify the implementation with the other platforms once we unlock `threadDictionary`
476468
/// or migrate to `FoundationEssentials._ThreadLocal`.
477-
private static nonisolated(unsafe) var _currentParserContext: _CurrentParserContext?
469+
private static nonisolated(unsafe) var _currentParser: XMLParser? = nil
478470
#else
479471
/// The current parser associated with the current thread.
480-
private static var _currentParserContext: _CurrentParserContext? {
472+
private static var _currentParser: XMLParser? {
481473
get {
482-
return Thread.current.threadDictionary["__CurrentNSXMLParser"] as? _CurrentParserContext
474+
return Thread.current.threadDictionary["__CurrentNSXMLParser"] as? XMLParser
483475
}
484476
set {
485477
Thread.current.threadDictionary["__CurrentNSXMLParser"] = newValue
@@ -489,29 +481,14 @@ open class XMLParser : NSObject {
489481

490482
/// The current parser associated with the current thread.
491483
internal static func currentParser() -> XMLParser? {
492-
if let ctx = _currentParserContext {
493-
return ctx._current
494-
}
495-
return nil
484+
return _currentParser
496485
}
497486

498487
/// Execute the given closure with the current parser set to the given parser.
499488
internal static func withCurrentParser<R>(_ parser: XMLParser, _ body: () -> R) -> R {
500-
var ctx: _CurrentParserContext
501-
if let current = _currentParserContext {
502-
// Use the existing context if it exists
503-
ctx = current
504-
} else {
505-
// Create a new context in TLS
506-
ctx = _CurrentParserContext()
507-
_currentParserContext = ctx
508-
}
509-
// Push the parser onto the stack
510-
ctx._stack.append(parser)
511-
defer {
512-
// Pop the parser off the stack
513-
ctx._stack.removeLast()
514-
}
489+
let oldParser = _currentParser
490+
_currentParser = parser
491+
defer { _currentParser = oldParser }
515492
return body()
516493
}
517494

0 commit comments

Comments
 (0)