Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port _CShims UUID to Swift #129

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 35 additions & 28 deletions Sources/FoundationEssentials/UUID.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@
//
//===----------------------------------------------------------------------===//

#if FOUNDATION_FRAMEWORK
@_implementationOnly import _CShims // uuid.h
#else
package import _CShims // uuid.h
#endif

public typealias uuid_t = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
public typealias uuid_string_t = (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)

Expand All @@ -23,26 +17,41 @@ public typealias uuid_string_t = (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8
public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable {
public private(set) var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

public enum Version {
case v4
}

/* Create a new UUID with RFC 4122 version 4 random bytes */
public init() {
withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
uuid_generate_random($0)
}
self.init(version: .v4)
}

/* Create a new UUID with RFC 4122 version 4 random bytes */
public init(version: Version) {
switch version {
case .v4:
self.uuid = Self.v4_generatedRandom()
}
}

/// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
///
/// Returns nil for invalid strings.
public init?(uuidString string: __shared String) {
let res = withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
return uuid_parse(string, $0)
}
}
if res != 0 {
return nil
self.init(version: .v4, uuidString: string)
}

/// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
///
/// Returns nil for invalid strings.
public init?(version: Version, uuidString string: __shared String) {
switch version {
case .v4:
guard let parsedResult = Self.v4_parse(uuidString: uuidString) else {
return nil
}

self.uuid = parsedResult
}
}

Expand All @@ -53,17 +62,7 @@ public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable {

/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
public var uuidString: String {
var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
return withUnsafePointer(to: uuid) { valPtr in
valPtr.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) { val in
withUnsafeMutablePointer(to: &bytes) { strPtr in
strPtr.withMemoryRebound(to: CChar.self, capacity: MemoryLayout<uuid_string_t>.size) { str in
uuid_unparse_upper(val, str)
return String(cString: str)
}
}
}
}
"\(Self.formatToHexString(uuid.0))\(Self.formatToHexString(uuid.1))\(Self.formatToHexString(uuid.2))\(Self.formatToHexString(uuid.3))-\(Self.formatToHexString(uuid.4))\(Self.formatToHexString(uuid.5))-\(Self.formatToHexString(uuid.6))\(Self.formatToHexString(uuid.7))-\(Self.formatToHexString(uuid.8))\(Self.formatToHexString(uuid.9))-\(Self.formatToHexString(uuid.10))\(Self.formatToHexString(uuid.11))\(Self.formatToHexString(uuid.12))\(Self.formatToHexString(uuid.13))\(Self.formatToHexString(uuid.14))\(Self.formatToHexString(uuid.15))"
}

public func hash(into hasher: inout Hasher) {
Expand Down Expand Up @@ -98,6 +97,14 @@ public struct UUID : Hashable, Equatable, CustomStringConvertible, Sendable {
lhs.uuid.14 == rhs.uuid.14 &&
lhs.uuid.15 == rhs.uuid.15
}

private static func formatToHexString(_ value: UInt8) -> String {
var result = String(value, radix: 16, uppercase: true)
if result.count == 1 {
result = "0" + result
}
return result
}
}

@available(macOS 10.8, iOS 6.0, tvOS 9.0, watchOS 2.0, *)
Expand Down
52 changes: 52 additions & 0 deletions Sources/FoundationEssentials/UUIDv4.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

extension UUID {
static func v4_generatedRandom() -> uuid_t {
var randomBits = (0 ... 15).map { _ in UInt8.random(in: .min ... .max) }
randomBits[6] = (randomBits[6] & 0x0F) | 0x40
randomBits[8] = (randomBits[8] & 0x3F) | 0x80

return randomBits.withUnsafeBytes { buffer in
return buffer.bindMemory(to: uuid_t.self)[0]
}
}

static func v4_parse(uuidString string: __shared String) -> uuid_t? {
let components = string

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on #129 (comment), one obvious optimization we can do here is to guard against string.count. However, both String.count and String.UTF8View.count is not O(1), so I guess we should parse the string manually and throw if it’s malformed, including too short or too long?

.replacing("-", with: "")
.split(by: 2)
.compactMap { UInt8($0, radix: 16) }

guard components.count == 16 else {
return nil
}

return components.withUnsafeBytes { buffer in
return buffer.bindMemory(to: uuid_t.self)[0]
}
}
}

private extension String {
func split(by length: Int) -> [String] {
var startIndex = self.startIndex
var results = [Substring]()

while startIndex < self.endIndex {
let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
results.append(self[startIndex..<endIndex])
startIndex = endIndex
}

return results.map { String($0) }
}
}
85 changes: 0 additions & 85 deletions Sources/_CShims/include/uuid.h

This file was deleted.