Files
SWCompression/Sources/Extensions.swift
T
2017-05-20 22:09:28 +03:00

65 lines
1.3 KiB
Swift

//
// DataExtension.swift
// SWCompression
//
// Created by Timofey Solomko on 19.09.16.
// Copyright © 2017 Timofey Solomko. All rights reserved.
//
import Foundation
extension Data {
func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.pointee }
}
func toArray<T>(type: T.Type) -> [T] {
return self.withUnsafeBytes {
[T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.size))
}
}
}
extension UInt8 {
func toInt() -> Int {
return Int(bitPattern: UInt(self))
}
}
extension Int {
func toUInt8() -> UInt8 {
return UInt8(truncatingBitPattern: UInt(self))
}
func reverseBytes() -> Int {
var result = 0
for i in 0..<4 {
let byte = ((self & (0xFF << (i * 8))) >> (i * 8))
result += byte << (8 * (3 - i))
}
return result
}
}
extension String {
subscript (index: Int) -> Character {
let charIndex = self.index(self.startIndex, offsetBy: index)
return self[charIndex]
}
subscript (range: Range<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(startIndex, offsetBy: range.count)
return self[startIndex..<endIndex]
}
}