From 9fc4fa84d295abf7bf8778f19c0be3e002aa49a0 Mon Sep 17 00:00:00 2001 From: Elijah Semyonov Date: Tue, 24 Sep 2024 23:13:49 +0200 Subject: [PATCH] Fix the leak --- Sources/SwiftGodot/Variant.swift | 7 ++++++- Tests/SwiftGodotTests/MemoryLeakTests.swift | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Sources/SwiftGodot/Variant.swift b/Sources/SwiftGodot/Variant.swift index 93b3f15c3..2cbbb006a 100644 --- a/Sources/SwiftGodot/Variant.swift +++ b/Sources/SwiftGodot/Variant.swift @@ -73,6 +73,11 @@ public class Variant: Hashable, Equatable, CustomDebugStringConvertible { gi.variant_new_copy(&content, src) } } + + /// Initializes using `ContentType` and assuming that this `Variant` is sole owner of this content now. + init(takingOver other: ContentType) { + self.content = other + } deinit { if experimentalDisableVariantUnref { return } @@ -229,7 +234,7 @@ public class Variant: Hashable, Equatable, CustomDebugStringConvertible { return .failure(toCallErrorType(err.error)) } - return .success(Variant(copying: result)) + return .success(Variant(takingOver: result)) } /// Errors raised by the variant subscript diff --git a/Tests/SwiftGodotTests/MemoryLeakTests.swift b/Tests/SwiftGodotTests/MemoryLeakTests.swift index c66957153..6035427ad 100644 --- a/Tests/SwiftGodotTests/MemoryLeakTests.swift +++ b/Tests/SwiftGodotTests/MemoryLeakTests.swift @@ -59,5 +59,22 @@ final class MemoryLeakTests: GodotTestCase { XCTAssertEqual(before, after, "Leaked \(Int((after - before) / Double(count))) bytes per iteration.") } + + func test_544_leak() { + let string = "Hello, World!" + let variant = Variant(string) + // https://docs.godotengine.org/en/stable/classes/class_string.html#class-string-method-left + let methodName = StringName("left") + + let before = Performance.getMonitor(.memoryStatic) + + for _ in 0 ..< 2000 { + let _ = variant.call(method: methodName, Variant(2)) + } + + let after = Performance.getMonitor(.memoryStatic) + + XCTAssertEqual(before, after, "Leaked \(Int(after - before)) bytes") + } }