From 107fc89e86dde84e64ae9f40b06f21514490dc39 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Wed, 6 Nov 2024 21:52:20 -0500 Subject: [PATCH] #161 Add `DataConvertible` conformance to `BluetoothUUID` --- Sources/Bluetooth/BluetoothUUID.swift | 39 +++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/Sources/Bluetooth/BluetoothUUID.swift b/Sources/Bluetooth/BluetoothUUID.swift index 2aec2d72d..63b7c1e9b 100644 --- a/Sources/Bluetooth/BluetoothUUID.swift +++ b/Sources/Bluetooth/BluetoothUUID.swift @@ -92,9 +92,9 @@ extension BluetoothUUID: RawRepresentable { // MARK: - Data -public extension BluetoothUUID { +extension BluetoothUUID: DataConvertible { - init?(data: Data) { + public init?(data: Data) { guard let length = Length(rawValue: data.count) else { return nil } @@ -120,6 +120,41 @@ public extension BluetoothUUID { self = .bit128(value) } } + + public var dataLength: Int { + length.rawValue + } + + public func append(to data: inout Data) where Data : DataContainer { + switch self { + case let .bit16(value): + data += value + case let .bit32(value): + data += value + case let .bit128(value): + data += value + } + } +} + +internal extension BluetoothUUID { + + /// Number of bytes to represent Bluetooth UUID. + enum Length: Int { + + case bit16 = 2 + case bit32 = 4 + case bit128 = 16 + } + + private var length: Length { + + switch self { + case .bit16: return .bit16 + case .bit32: return .bit32 + case .bit128: return .bit128 + } + } } // MARK: - Codable