Skip to content

Commit

Permalink
Added methods for typecasting single values to Data
Browse files Browse the repository at this point in the history
  • Loading branch information
peterb180369 committed Oct 19, 2018
1 parent e9ffde7 commit 6bdde3a
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion BXSwiftUtils/Data/Data+TypeCasting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,24 @@ import Foundation
public extension Data
{

/// Wraps a value of type T in Data object WITHOUT copying the underlying memory
/// - parameter value: The value or object to be wrapped

init<T>(usingMemoryOf value: inout T)
{
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}


/// Converts a Data object to a value WITHOUT copying the underlying memory
/// - parameter type: The type of the value

func `as`<T>(type: T.Type) -> T
{
return self.withUnsafeBytes { $0.pointee }
}


/// Wraps an Array in a Data object WITHOUT copying the underlying memory
/// - parameter array: An array of values of type T

Expand All @@ -30,7 +48,7 @@ public extension Data
/// Converts a Data object to an Array WITHOUT copying the underlying memory
/// - parameter type: The type of the array elements

func asArray<T>(ofType type: T.Type) -> [T]
func asArray<T>(ofType: T.Type) -> [T]
{
let count = self.count / MemoryLayout<T>.stride

Expand Down

0 comments on commit 6bdde3a

Please sign in to comment.