Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Commit

Permalink
Merge pull request #107 from vapor/hex
Browse files Browse the repository at this point in the history
add hexEncoded + lossless data
  • Loading branch information
tanner0101 authored Mar 23, 2018
2 parents b1aef57 + f8ed048 commit 6179ee2
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Sources/Core/CoreError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
public struct CoreError: Debuggable, Error {
public var identifier: String
public var reason: String
public init(identifier: String, reason: String) {
self.identifier = identifier
self.reason = reason
}
}
16 changes: 16 additions & 0 deletions Sources/Core/Data+Hex.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
extension Data {
public func hexEncodedString() -> String {
var bytes = Data()
bytes.reserveCapacity(self.count * 2)

for byte in self {
bytes.append(radix16table[Int(byte / 16)])
bytes.append(radix16table[Int(byte % 16)])
}

return String(bytes: bytes, encoding: .utf8)!
}
}


fileprivate let radix16table: [UInt8] = [0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66]
49 changes: 49 additions & 0 deletions Sources/Core/LosslessDataConvertible.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/// A type that can be represented as Data in a lossless, unambiguous way.
public protocol LosslessDataConvertible {
/// Losslessly converts this type to `Data`.
func convertToData() throws -> Data

/// Losslessly converts `Data` to this type.
static func convertFromData(_ data: Data) throws -> Self
}

extension String: LosslessDataConvertible {
/// Converts this `String` to data using `.utf8`.
public func convertToData() -> Data {
return Data(utf8)
}

/// Converts `Data` to a `utf8` encoded String.
///
/// - throws: Error if String is not UTF8 encoded.
public static func convertFromData(_ data: Data) throws -> String {
guard let string = String(data: data, encoding: .utf8) else {
throw CoreError(identifier: "stringData", reason: "String not UTF-8 encoded")
}
return string
}
}

extension Array: LosslessDataConvertible where Element == UInt8 {
/// Converts this `[UInt8]` to `Data`.
public func convertToData() -> Data {
return Data(bytes: self)
}

/// Converts `Data` to `[UInt8]`.
public static func convertFromData(_ data: Data) -> Array<UInt8> {
return .init(data)
}
}

extension Data: LosslessDataConvertible {
/// `LosslessDataConvertible` conformance.
public func convertToData() throws -> Data {
return self
}

/// `LosslessDataConvertible` conformance.
public static func convertFromData(_ data: Data) -> Data {
return data
}
}

0 comments on commit 6179ee2

Please sign in to comment.