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 #108 from vapor/data-coders
Browse files Browse the repository at this point in the history
data coders
  • Loading branch information
tanner0101 committed Mar 24, 2018
2 parents 6179ee2 + 3762c60 commit 9238f27
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions Sources/Core/DataCoders.swift
@@ -0,0 +1,63 @@
/// A type capable of decoding `Decodable` types from `Data`.
///
/// print(data) /// Data
/// let user = try JSONDecoder().decode(User.self, from: data)
/// print(user) /// User
///
public protocol DataDecoder {
/// Decodes an instance of the supplied `Decodable` type from `Data`.
///
/// print(data) /// Data
/// let user = try JSONDecoder().decode(User.self, from: data)
/// print(user) /// User
///
/// - parameters:
/// - decodable: Generic `Decodable` type (`D`) to decode.
/// - from: `Data` to decode a `D` from.
/// - returns: An instance of the `Decodable` type (`D`).
/// - throws: Any error that may occur while attempting to decode the specified type.
func decode<D>(_ decodable: D.Type, from data: Data) throws -> D where D: Decodable
}

extension DataDecoder {
/// Convenience method for decoding a `Decodable` type from something `LosslessDataConvertible`.
///
///
/// print(data) /// LosslessDataConvertible
/// let user = try JSONDecoder().decode(User.self, from: data)
/// print(user) /// User
///
/// - parameters:
/// - decodable: Generic `Decodable` type (`D`) to decode.
/// - from: `LosslessDataConvertible` to decode a `D` from.
/// - returns: An instance of the `Decodable` type (`D`).
/// - throws: Any error that may occur while attempting to decode the specified type.
public func decode<D>(_ decodable: D.Type, from data: LosslessDataConvertible) throws -> D where D: Decodable {
return try decode(D.self, from: data.convertToData())
}
}

/// A type capable of encoding `Encodable` objects to `Data`.
///
/// print(user) /// User
/// let data = try JSONEncoder().encode(user)
/// print(data) /// Data
///
public protocol DataEncoder {
/// Encodes the supplied `Encodable` object to `Data`.
///
/// print(user) /// User
/// let data = try JSONEncoder().encode(user)
/// print(data) /// Data
///
/// - parameters:
/// - encodable: Generic `Encodable` object (`E`) to encode.
/// - returns: Encoded `Data`
/// - throws: Any error taht may occur while attempting to encode the specified type.
func encode<E>(_ encodable: E) throws -> Data where E: Encodable
}

/// MARK: Default Conformances

extension JSONDecoder: DataDecoder { }
extension JSONEncoder: DataEncoder { }

0 comments on commit 9238f27

Please sign in to comment.