Skip to content

Commit

Permalink
#161 Use DataContainer in integer extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
colemancda committed Nov 7, 2024
1 parent 6208f2e commit 971d850
Showing 1 changed file with 15 additions and 43 deletions.
58 changes: 15 additions & 43 deletions Sources/Bluetooth/Extensions/Integer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
// Copyright © 2015 PureSwift. All rights reserved.
//

#if canImport(Foundation)
import Foundation
#endif

internal extension UInt16 {

/// Initializes value from two bytes.
Expand Down Expand Up @@ -49,6 +45,15 @@ internal extension UInt64 {
}
}

internal extension BinaryInteger {

@inlinable
var bytes: [UInt8] {
var mutableValueCopy = self
return withUnsafeBytes(of: &mutableValueCopy) { Array($0) }
}
}

internal extension UInt8 {

/// Initialize a byte from 2 bit enums.
Expand All @@ -67,74 +72,41 @@ internal extension UInt8 {
}
}

internal extension BinaryInteger {

@inlinable
var bytes: [UInt8] {
var mutableValueCopy = self
return withUnsafeBytes(of: &mutableValueCopy) { Array($0) }
}
}

#if canImport(Foundation)
internal extension UInt64 {

/// The value of the characteristic is a bit mask implemented as an array of unsigned 8 bit integers.
init?(bitmaskArray data: Data) {
init?<Data: DataContainer>(bitmaskArray data: Data) {

if data.count == MemoryLayout<UInt64>.size {

self = UInt64(littleEndian: UInt64(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])))

} else if data.count >= MemoryLayout<UInt32>.size {

let rawValue = UInt32(littleEndian: UInt32(bytes: (data[0], data[1], data[2], data[3])))

self = UInt64(rawValue)

} else if data.count >= MemoryLayout<UInt16>.size {

let rawValue = UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))

self = UInt64(rawValue)

} else if data.count >= MemoryLayout<UInt8>.size {

let rawValue = data[0]

self = UInt64(rawValue)

} else {

return nil
}
}

/// The value of the characteristic is a bit mask implemented as an array of unsigned 8 bit integers.
var bitmaskArray: Data {
var bitmaskArray: [UInt8] {

if self <= numericCast(UInt8.max) {

return Data([UInt8(self)])

return [UInt8]([UInt8(self)])
} else if self <= numericCast(UInt16.max) {

let bytes = UInt16(self).littleEndian.bytes

return Data([bytes.0, bytes.1])

return [UInt8]([bytes.0, bytes.1])
} else if self <= numericCast(UInt32.max) {

let bytes = UInt32(self).littleEndian.bytes

return Data([bytes.0, bytes.1, bytes.2, bytes.3])

return [UInt8]([bytes.0, bytes.1, bytes.2, bytes.3])
} else {

let bytes = self.littleEndian.bytes

return Data([bytes.0, bytes.1, bytes.2, bytes.3, bytes.4, bytes.5, bytes.6, bytes.7])
return [UInt8]([bytes.0, bytes.1, bytes.2, bytes.3, bytes.4, bytes.5, bytes.6, bytes.7])
}
}
}
#endif

0 comments on commit 971d850

Please sign in to comment.