Skip to content

Commit fa936fc

Browse files
committed
[Core] makes 'SDLObject' public (temporarily)
1 parent 33acbc2 commit fa936fc

File tree

6 files changed

+57
-39
lines changed

6 files changed

+57
-39
lines changed

Samples/SwiftSDL-TestBench/Sources/Games/Sandbox.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ extension SDL.Games {
1515
private var scene: Scene!
1616

1717
func onReady(window: any SwiftSDL.Window) throws(SwiftSDL.SDL_Error) {
18-
try SDL_Init(.gamepad)
1918
scene = Scene(size: try window.size(as: Float.self), bgColor: .gray)
2019
}
2120

Sources/SwiftSDL/GPUDevice.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ extension GPUDevice {
4646
}
4747

4848
public func render(_ commandBuffer: some CommandBuffer, pass: (OpaquePointer) throws -> Void) throws(SDL_Error) -> some GPUDevice {
49-
SDL_BeginGPURenderPass(commandBuffer.pointer, nil , 0 , nil )
49+
SDL_BeginGPURenderPass(commandBuffer.pointer, nil , 0 , nil )
5050
return self
5151
}
5252
}
@@ -82,7 +82,7 @@ public enum SDL_GPUShaderFormat: RawRepresentable, Decodable, CaseIterable {
8282
default: self = .invalid
8383
}
8484
}
85-
85+
8686
public var rawValue: UInt32 {
8787
switch self {
8888
case .invalid: return UInt32(SDL_GPU_SHADERFORMAT_INVALID)

Sources/SwiftSDL/ObjectProtocol.swift

Lines changed: 47 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,41 @@ public protocol SDLObjectProtocol: AnyObject {
33
var pointer: Pointer { get }
44
}
55

6-
/*
7-
Explore this
8-
https://github.com/swiftlang/swift/blob/main/docs/OptimizationTips.rst#advice-use-unmanaged-references-to-avoid-reference-counting-overhead
9-
*/
106

117
public final class SDLObject<Pointer: Hashable>: SDLObjectProtocol, @unchecked Sendable {
12-
enum Tag {
8+
/// Used for associating a tag with an SDLObject instance, primarily for debugging and memory-allocation tracking.
9+
@available(*, deprecated, message: "Will be removed in a future release")
10+
public enum Tag {
11+
/// A user-defined string for debugging purposes.
1312
case custom(String)
13+
14+
/// A default, no-tag state.
15+
case empty
1416
}
1517

18+
/// The underlying resource reference managed by this object.
1619
public let pointer: Pointer
1720

21+
/// A callback invoked during deinitialization to clean up the resource.
1822
private let destroy: (Pointer) -> Void
23+
24+
/// A debugging or tracking tag for the instance.
1925
private let tag: Tag
2026

21-
required init(_ pointer: Pointer, tag: Tag, destroy: @escaping (Pointer) -> Void = { _ in }) {
27+
28+
/// Creates an instance of an SDL object from an underlying pointer reference.
29+
/// - Parameters:
30+
/// - pointer: The resource pointer being managed.
31+
/// - tag: A debugging or memory-allocation tag (default: .empty).
32+
/// - destroy: A closure invoked during deinitialization to clean up the resource (default: a no-op closure).
33+
public required init(_ pointer: Pointer, tag: Tag = .empty, destroy: @escaping (Pointer) -> Void = { _ in }) {
2234
// print("\(type(of: Pointer.self)): \(#function), \(tag)")
2335
self.destroy = destroy
2436
self.pointer = pointer
2537
self.tag = tag
2638
}
2739

40+
/// Ensures the destroy callback is called with the managed pointer when the SDLObject instance is deallocated.
2841
deinit {
2942
/*
3043
#if DEBUG
@@ -35,16 +48,6 @@ public final class SDLObject<Pointer: Hashable>: SDLObjectProtocol, @unchecked S
3548
}
3649
}
3750

38-
public func SDL_BufferPointer<Value>(_ allocate: (UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Value>?) throws(SDL_Error) -> [Value] {
39-
var count: Int32 = 0
40-
guard let pointer = allocate(&count) else {
41-
throw .error
42-
}
43-
defer { SDL_free(pointer) }
44-
let bufferPtr = UnsafeMutableBufferPointer.init(start: pointer, count: Int(count))
45-
return Array(bufferPtr)
46-
}
47-
4851
extension SDLObjectProtocol {
4952
@discardableResult
5053
@inlinable
@@ -82,3 +85,31 @@ extension SDLObjectProtocol {
8285
return .success(self)
8386
}
8487
}
88+
89+
/**
90+
This function facilitates the allocation and conversion of a buffer pointer
91+
to an array of values, handling resource cleanup and error management seamlessly.
92+
93+
**Example:**
94+
95+
```
96+
let joysticks = try SDL_BufferPointer(SDL_GetJoysticks)
97+
```
98+
99+
The closure is responsible for:
100+
- Modifying the Int32 pointer to indicate the number of elements allocated.
101+
- Returning a pointer to the allocated buffer or nil on failure.
102+
103+
- parameter allocate: A closure that takes an `UnsafeMutablePointer<Int32>` and returns an optional `UnsafeMutablePointer<Value>`.
104+
- returns: A Swift array containing the elements of the allocated buffer.
105+
- throws: Throw `SDL_Error.error` when the allocate closure fails to return a valid pointer.
106+
*/
107+
public func SDL_BufferPointer<Value>(_ allocate: (UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Value>?) throws(SDL_Error) -> [Value] {
108+
var count: Int32 = 0
109+
guard let pointer = allocate(&count) else {
110+
throw .error
111+
}
112+
defer { SDL_free(pointer) }
113+
let bufferPtr = UnsafeMutableBufferPointer.init(start: pointer, count: Int(count))
114+
return Array(bufferPtr)
115+
}

Sources/SwiftSDL/Renderer.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ public protocol Renderer: SDLObjectProtocol, Sendable where Pointer == OpaquePoi
44
extension SDLObject<OpaquePointer>: Renderer { }
55

66
// MARK: - Create Renderer
7-
public func SDL_CreateRenderer<P: PropertyValue>(with properties: (String, value: P)..., window: (any Window)? = nil) throws(SDL_Error) -> some Renderer {
7+
public func SDL_CreateRenderer<P: PropertyValue>(with properties: (String, value: P)..., window: (some Window)? = nil) throws(SDL_Error) -> some Renderer {
88
try SDL_CreateRenderer(with: properties, window: window)
99
}
1010

11-
public func SDL_CreateRenderer<P: PropertyValue>(with properties: [(String, value: P)], window: (any Window)? = nil) throws(SDL_Error) -> some Renderer {
11+
public func SDL_CreateRenderer<P: PropertyValue>(with properties: [(String, value: P)], window: (some Window)? = nil) throws(SDL_Error) -> some Renderer {
1212
let rendererProperties = SDL_CreateProperties()
1313
defer { rendererProperties.destroy() }
1414

@@ -155,7 +155,7 @@ extension Renderer {
155155
}
156156

157157
@discardableResult
158-
public func pass(to callback: ((_ renderer: Self) throws -> Void)?) throws(SDL_Error) -> any Renderer {
158+
public func pass(to callback: ((_ renderer: Self) throws -> Void)?) throws(SDL_Error) -> Self {
159159
do {
160160
try callback?(self)
161161
return self
@@ -169,7 +169,7 @@ extension Renderer {
169169
}
170170

171171
@discardableResult
172-
public func pass<each Argument>(to callback: (_ renderer: Self, repeat each Argument) throws(SDL_Error) -> Void, _ argument: repeat each Argument) throws(SDL_Error) -> any Renderer {
172+
public func pass<each Argument>(to callback: (_ renderer: Self, repeat each Argument) throws(SDL_Error) -> Void, _ argument: repeat each Argument) throws(SDL_Error) -> Self {
173173
try callback(self, repeat each argument)
174174
return self
175175
}

Sources/SwiftSDL/Surface.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ extension Surface {
7979

8080
// MARK: - Load Bitmaps
8181
@discardableResult
82-
public func SDL_Load(bitmap file: String, relativePath: String? = nil) throws(SDL_Error) -> any Surface {
82+
public func SDL_Load(bitmap file: String, relativePath: String? = nil) throws(SDL_Error) -> some Surface {
8383
guard let pointer = SDL_LoadBMP(file) else {
8484
throw .error
8585
}
@@ -91,7 +91,7 @@ public func SDL_Load(bitmap file: String, relativePath: String? = nil) throws(SD
9191
public func SDL_Load(
9292
bitmap file: String,
9393
searchingBundles bundles: [Bundle] = Bundle.resourceBundles(),
94-
inDirectory directory: String? = nil) throws(SDL_Error) -> any Surface
94+
inDirectory directory: String? = nil) throws(SDL_Error) -> some Surface
9595
{
9696
guard let filePath = bundles.compactMap({ bundle in
9797
bundle.path(

Sources/SwiftSDL/Window.swift

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -221,19 +221,7 @@ public func SDL_CreateWindow(_ title: String, size: Size<Int32>, flags: SDL_Wind
221221

222222
@discardableResult
223223
public func SDL_GetWindows() throws(SDL_Error) -> [any Window] {
224-
var count: UInt32 = 0
225-
guard let windows = SDL_GetWindows(&count) else {
226-
throw .error
227-
}
228-
229-
defer { SDL_free(windows) }
230-
231-
return Array<OpaquePointer?>.init(unsafeUninitializedCapacity: Int(count)) { buffer, initializedCount in
232-
initializedCount = Int(count)
233-
for i in 0..<initializedCount {
234-
buffer[i] = windows[i]
235-
}
236-
}
224+
try SDL_BufferPointer(SDL_GetWindows)
237225
.compactMap(\.self)
238-
.map({ SDLObject($0, tag: .custom("tag"), destroy: SDL_DestroyWindow) })
226+
.map({ SDLObject($0) as! (any Window) })
239227
}

0 commit comments

Comments
 (0)