From e5f3c18e89048961156f3cb3af7f662979a2d0a9 Mon Sep 17 00:00:00 2001 From: Joannis Orlandos Date: Fri, 17 Jun 2022 11:47:31 +0200 Subject: [PATCH] Fix crashing on parsing ObjectId as String in Swift 5.7 --- Sources/BSON/Helpers/PointerHelpers.swift | 9 --------- Sources/BSON/Types/ObjectId.swift | 13 ++++--------- 2 files changed, 4 insertions(+), 18 deletions(-) delete mode 100644 Sources/BSON/Helpers/PointerHelpers.swift diff --git a/Sources/BSON/Helpers/PointerHelpers.swift b/Sources/BSON/Helpers/PointerHelpers.swift deleted file mode 100644 index d8eff41..0000000 --- a/Sources/BSON/Helpers/PointerHelpers.swift +++ /dev/null @@ -1,9 +0,0 @@ -extension UnsafePointer { - var int32: Int32 { - return self.withMemoryRebound(to: Int32.self, capacity: 1) { $0.pointee } - } - - var int64: Int64 { - return self.withMemoryRebound(to: Int64.self, capacity: 1) { $0.pointee } - } -} diff --git a/Sources/BSON/Types/ObjectId.swift b/Sources/BSON/Types/ObjectId.swift index 5aace32..a4e9400 100644 --- a/Sources/BSON/Types/ObjectId.swift +++ b/Sources/BSON/Types/ObjectId.swift @@ -31,10 +31,7 @@ public struct ObjectId: Sendable { /// Decodes the ObjectID from the provided (24 character) hexString public init?(_ hex: String) { - let storage = UnsafeMutablePointer.allocate(capacity: 12) - defer { - storage.deallocate() - } + var buffer = ByteBufferAllocator().buffer(capacity: 12) let cString = hex.utf8CString @@ -44,7 +41,6 @@ public struct ObjectId: Sendable { } var input = 0 - var output = 0 while input < 23 { guard let c1 = cString[input].hexDecoded(), @@ -53,14 +49,13 @@ public struct ObjectId: Sendable { return nil } - storage[output] = UInt8(bitPattern: c1 << 4) | UInt8(bitPattern: c2) + buffer.writeInteger(UInt8(bitPattern: c1 << 4) | UInt8(bitPattern: c2)) input = input &+ 2 - output = output &+ 1 } - _timestamp = storage.withMemoryRebound(to: UInt32.self, capacity: 1) { $0.pointee.bigEndian } - _random = storage.advanced(by: 4).withMemoryRebound(to: UInt64.self, capacity: 1) { $0.pointee.bigEndian } + _timestamp = buffer.readInteger()! + _random = buffer.readInteger()! } /// The 12 bytes represented as 24-character hex-string