diff --git a/Sources/PlaydateKit/Core/System.swift b/Sources/PlaydateKit/Core/System.swift index d4d40c93..d44110b1 100644 --- a/Sources/PlaydateKit/Core/System.swift +++ b/Sources/PlaydateKit/Core/System.swift @@ -200,6 +200,18 @@ public enum System { } } + /// Returns the number of seconds elapsed since midnight (hour 0), January 1, 2000. + public static var secondsSinceEpoch: CUnsignedInt { + system.getSecondsSinceEpoch.unsafelyUnwrapped(nil) + } + + /// Returns the number of milliseconds elapsed since midnight (hour 0), January 1, 2000. + public static var millisecondsSinceEpoch: CUnsignedInt { + var ms: CUnsignedInt = 0 + _ = system.getSecondsSinceEpoch.unsafelyUnwrapped(&ms) + return ms + } + // MARK: - Memory allocation /// Allocates heap space if `pointer` is nil, else reallocates the given pointer. If `size` is zero, frees the given pointer. @@ -436,11 +448,6 @@ public enum System { menuItems = [] } - /// Returns the number of seconds (and sets milliseconds if not NULL) elapsed since midnight (hour 0), January 1, 2000. - public static func getSecondsSinceEpoch(milliseconds: UnsafeMutablePointer? = nil) -> CUnsignedInt { - system.getSecondsSinceEpoch.unsafelyUnwrapped(milliseconds) - } - /// Resets the high-resolution timer. public static func resetElapsedTime() { system.resetElapsedTime.unsafelyUnwrapped() diff --git a/Sources/PlaydateKit/Playdate.swift b/Sources/PlaydateKit/Playdate.swift index b5fd918c..b64aac7d 100644 --- a/Sources/PlaydateKit/Playdate.swift +++ b/Sources/PlaydateKit/Playdate.swift @@ -22,6 +22,7 @@ public enum Playdate { public static func initialize(with pointer: UnsafeMutableRawPointer) { _playdateAPI = pointer.bindMemory(to: PlaydateAPI.self, capacity: 1).pointee + arc4random_seed = System.millisecondsSinceEpoch System.setUpdateCallback(update: { _ in (System.updateCallback?() ?? false) ? 1 : 0 }, userdata: nil) @@ -32,7 +33,7 @@ public enum Playdate { private nonisolated(unsafe) static var _playdateAPI: PlaydateAPI? } -/// Implement `posix_memalign(3)`, which is required by the Swift runtime but is +/// Implement `posix_memalign(3)`, which is required by the Embedded Swift runtime but is /// not provided by the Playdate C library. @_documentation(visibility: internal) @_cdecl("posix_memalign") public func posix_memalign( @@ -46,3 +47,22 @@ public enum Playdate { memptr.pointee = allocation return 0 } + +/// Implement `arc4random_buf` which is required by the Embedded Swift runtime for Hashable, Set, Dictionary, +/// and random-number generating APIs but is not provided by the Playdate C library. +nonisolated(unsafe) var arc4random_seed: CUnsignedInt = 0 +@_cdecl("arc4random") public func arc4random() -> UInt32 { + arc4random_seed = 1664525 &* arc4random_seed &+ 1013904223 + return arc4random_seed +} + +@_cdecl("arc4random_buf") public func arc4random_buf(buf: UnsafeMutableRawPointer, nbytes: Int) { + var r = arc4random() + for i in 0..>= 8 + } +}