Skip to content

JSONEncoder implementation #1048

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Foundation.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
231503DB1D8AEE5D0061694D /* TestNSDecimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231503DA1D8AEE5D0061694D /* TestNSDecimal.swift */; };
294E3C1D1CC5E19300E4F44C /* TestNSAttributedString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */; };
2EBE67A51C77BF0E006583D5 /* TestDateFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EBE67A31C77BF05006583D5 /* TestDateFormatter.swift */; };
3EA9D6701EF0532D00B362D6 /* TestJSONEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EA9D66F1EF0532D00B362D6 /* TestJSONEncoder.swift */; };
3EDCE50C1EF04D8100C2EC04 /* Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDCE5051EF04D8100C2EC04 /* Codable.swift */; };
3EDCE5101EF04D8100C2EC04 /* JSONEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDCE5091EF04D8100C2EC04 /* JSONEncoder.swift */; };
528776141BF2629700CB0090 /* FoundationErrors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 522C253A1BF16E1600804FC6 /* FoundationErrors.swift */; };
528776191BF27D9500CB0090 /* Test.plist in Resources */ = {isa = PBXBuildFile; fileRef = 528776181BF27D9500CB0090 /* Test.plist */; };
555683BD1C1250E70041D4C6 /* TestNSUserDefaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = 555683BC1C1250E70041D4C6 /* TestNSUserDefaults.swift */; };
Expand Down Expand Up @@ -482,6 +485,9 @@
231503DA1D8AEE5D0061694D /* TestNSDecimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDecimal.swift; sourceTree = "<group>"; };
294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSAttributedString.swift; sourceTree = "<group>"; };
2EBE67A31C77BF05006583D5 /* TestDateFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestDateFormatter.swift; sourceTree = "<group>"; };
3EA9D66F1EF0532D00B362D6 /* TestJSONEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestJSONEncoder.swift; sourceTree = "<group>"; };
3EDCE5051EF04D8100C2EC04 /* Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Codable.swift; sourceTree = "<group>"; };
3EDCE5091EF04D8100C2EC04 /* JSONEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONEncoder.swift; sourceTree = "<group>"; };
400E22641C1A4E58007C5933 /* TestProcessInfo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestProcessInfo.swift; sourceTree = "<group>"; };
4AE109261C17CCBF007367B5 /* TestNSIndexPath.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSIndexPath.swift; sourceTree = "<group>"; };
4DC1D07F1C12EEEF00B5948A /* TestNSPipe.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSPipe.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -959,6 +965,15 @@
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
3EDCE5121EF04D8600C2EC04 /* JSONEncoder */ = {
isa = PBXGroup;
children = (
3EDCE5051EF04D8100C2EC04 /* Codable.swift */,
3EDCE5091EF04D8100C2EC04 /* JSONEncoder.swift */,
);
name = JSONEncoder;
sourceTree = "<group>";
};
5B1FD9C71D6D162D0080E83C /* Session */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -1405,6 +1420,9 @@
BD8042151E09857800487EB8 /* TestLengthFormatter.swift */,
A058C2011E529CF100B07AA1 /* TestMassFormatter.swift */,
BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */,
3EA9D66F1EF0532D00B362D6 /* TestJSONEncoder.swift */,
159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */,
D4FE895A1D703D1100DA7986 /* TestURLRequest.swift */,
C93559281C12C49F009FD6A9 /* TestNSAffineTransform.swift */,
EA66F63C1BF1619600136161 /* TestNSArray.swift */,
294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */,
Expand Down Expand Up @@ -1593,6 +1611,7 @@
EAB57B6C1BD1A852004AC5C5 /* Serialization */ = {
isa = PBXGroup;
children = (
3EDCE5121EF04D8600C2EC04 /* JSONEncoder */,
EADE0B641BD15DFF00C49C64 /* NSJSONSerialization.swift */,
EADE0B651BD15DFF00C49C64 /* NSKeyedArchiver.swift */,
D3BCEB9F1C2F6DDB00295652 /* NSKeyedCoderOldStyleArray.swift */,
Expand Down Expand Up @@ -2141,6 +2160,7 @@
D3E8D6D11C367AB600295652 /* NSSpecialValue.swift in Sources */,
EAB57B721BD1C7A5004AC5C5 /* NSPortMessage.swift in Sources */,
5BD31D201D5CE8C400563814 /* Bridging.swift in Sources */,
3EDCE50C1EF04D8100C2EC04 /* Codable.swift in Sources */,
EADE0BBB1BD15E0000C49C64 /* NSURLAuthenticationChallenge.swift in Sources */,
EADE0BA11BD15DFF00C49C64 /* NSIndexSet.swift in Sources */,
5BF7AEA91BCD51F9008F214A /* NSDate.swift in Sources */,
Expand All @@ -2156,6 +2176,7 @@
5BD31D411D5D1BC300563814 /* Set.swift in Sources */,
5BD31D241D5CECC400563814 /* Array.swift in Sources */,
5BF7AEBC1BCD51F9008F214A /* Thread.swift in Sources */,
3EDCE5101EF04D8100C2EC04 /* JSONEncoder.swift in Sources */,
D31302011C30CEA900295652 /* NSConcreteValue.swift in Sources */,
5BF7AEA81BCD51F9008F214A /* NSData.swift in Sources */,
5B424C761D0B6E5B007B39C8 /* IndexPath.swift in Sources */,
Expand Down Expand Up @@ -2396,6 +2417,7 @@
5B13B3371C582D4C00651CE2 /* TestNSNotificationCenter.swift in Sources */,
5B13B3251C582D4700651CE2 /* main.swift in Sources */,
5B1FD9E31D6D17B80080E83C /* TestNSURLSession.swift in Sources */,
3EA9D6701EF0532D00B362D6 /* TestJSONEncoder.swift in Sources */,
D512D17C1CD883F00032E6A5 /* TestFileHandle.swift in Sources */,
D4FE895B1D703D1100DA7986 /* TestURLRequest.swift in Sources */,
5B13B33A1C582D4C00651CE2 /* TestNSNumber.swift in Sources */,
Expand Down
105 changes: 105 additions & 0 deletions Foundation/Codable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

//===----------------------------------------------------------------------===//
// Errors
//===----------------------------------------------------------------------===//

// Adding the following extensions to EncodingError and DecodingError allows them to bridge to NSErrors implicitly.

fileprivate let NSCodingPathErrorKey = "NSCodingPath"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we don't have error bridging in Linux, I think this whole section (short of the helper methods on DecodingError) can be removed.

fileprivate let NSDebugDescriptionErrorKey = "NSDebugDescription"

extension EncodingError : CustomNSError {
public static var errorDomain: String = NSCocoaErrorDomain

public var errorCode: Int {
switch self {
case .invalidValue(_, _): return CocoaError.coderInvalidValue.rawValue
}
}

public var errorUserInfo: [String : Any] {
let context: Context
switch self {
case .invalidValue(_, let c): context = c
}

return [NSCodingPathErrorKey: context.codingPath,
NSDebugDescriptionErrorKey: context.debugDescription]
}
}

extension DecodingError : CustomNSError {
public static var errorDomain: String = NSCocoaErrorDomain

public var errorCode: Int {
switch self {
case .valueNotFound(_, _): fallthrough
case .keyNotFound(_, _):
return CocoaError.coderValueNotFound.rawValue

case .typeMismatch(_, _): fallthrough
case .dataCorrupted(_):
return CocoaError.coderReadCorrupt.rawValue
}
}

public var errorUserInfo: [String : Any] {
let context: Context
switch self {
case .typeMismatch(_, let c): context = c
case .valueNotFound(_, let c): context = c
case .keyNotFound(_, let c): context = c
case .dataCorrupted(let c): context = c
}

return [NSCodingPathErrorKey: context.codingPath,
NSDebugDescriptionErrorKey: context.debugDescription]
}
}

//===----------------------------------------------------------------------===//
// Error Utilities
//===----------------------------------------------------------------------===//

internal extension DecodingError {
/// Returns a `.typeMismatch` error describing the expected type.
///
/// - parameter path: The path of `CodingKey`s taken to decode a value of this type.
/// - parameter expectation: The type expected to be encountered.
/// - parameter reality: The value that was encountered instead of the expected type.
/// - returns: A `DecodingError` with the appropriate path and debug description.
internal static func _typeMismatch(at path: [CodingKey?], expectation: Any.Type, reality: Any) -> DecodingError {
let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead."
return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
}

/// Returns a description of the type of `value` appropriate for an error message.
///
/// - parameter value: The value whose type to describe.
/// - returns: A string describing `value`.
/// - precondition: `value` is one of the types below.
fileprivate static func _typeDescription(of value: Any) -> String {
if value is NSNull {
return "a null value"
} else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ {
return "a number"
} else if value is String {
return "a string/data"
} else if value is [Any] {
return "an array"
} else if value is [String : Any] {
return "a dictionary"
} else {
// This should never happen -- we somehow have a non-JSON type here.
preconditionFailure("Invalid storage type \(type(of: value)).")
}
}
}
13 changes: 13 additions & 0 deletions Foundation/Date.swift
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,16 @@ extension Date : CustomPlaygroundQuickLookable {
return .text(summary)
}
}

extension Date : Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let timestamp = try container.decode(Double.self)
self.init(timeIntervalSinceReferenceDate: timestamp)
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.timeIntervalSinceReferenceDate)
}
}
Loading