From a215ff0245fa67d0610f8772eadf30c1e5852a8b Mon Sep 17 00:00:00 2001 From: Ayushi Tiwari Date: Wed, 8 May 2024 20:51:32 -0400 Subject: [PATCH] feat: Implement Copy-On-Write (CoW) behavior for Logger struct --- Sources/Logging/Logging.swift | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/Sources/Logging/Logging.swift b/Sources/Logging/Logging.swift index 590d57a5..190abd53 100644 --- a/Sources/Logging/Logging.swift +++ b/Sources/Logging/Logging.swift @@ -39,20 +39,41 @@ import WASILibc /// logger.info("Hello World!") /// ``` public struct Logger { - @usableFromInline - var handler: LogHandler + /// A private property to hold the boxed `LogHandler`. + private var _handler: Box /// An identifier of the creator of this `Logger`. public let label: String + + /// A computed property to access the `LogHandler`. + public var handler: LogHandler { + get { + return _handler.value + } + set { + if !(isKnownUniquelyReferenced(&_handler)) { + _handler = Box(value: newValue) + } else { + _handler.value = newValue + } + } + } /// The metadata provider this logger was created with. public var metadataProvider: Logger.MetadataProvider? { - return self.handler.metadataProvider + return handler.metadataProvider } internal init(label: String, _ handler: LogHandler) { self.label = label - self.handler = handler + self._handler = Box(value: handler) + } +} + +private final class Box { + var value: T + init(value: T) { + self.value = value } }