Merge pull request #1136 from moiseev/integers-revised

Reflect changes to the integer types
diff --git a/CoreFoundation/NumberDate.subproj/CFTimeZone.c b/CoreFoundation/NumberDate.subproj/CFTimeZone.c
index 434203a..427a3b1 100644
--- a/CoreFoundation/NumberDate.subproj/CFTimeZone.c
+++ b/CoreFoundation/NumberDate.subproj/CFTimeZone.c
@@ -33,9 +33,12 @@
 #endif
 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
 #include <tzfile.h>
+#define MACOS_TZDIR1 "/usr/share/zoneinfo/"          // 10.12 and earlier
+#define MACOS_TZDIR2 "/var/db/timezone/zoneinfo/"    // 10.13 onwards
+
 #elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
 #ifndef TZDIR
-#define TZDIR	"/usr/share/zoneinfo" /* Time zone object file directory */
+#define TZDIR	"/usr/share/zoneinfo/" /* Time zone object file directory */
 #endif /* !defined TZDIR */
 
 #ifndef TZDEFAULT
@@ -56,16 +59,9 @@
 
 #include <time.h>
 
-#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
-#define TZZONELINK	TZDEFAULT
-#define TZZONEINFO	TZDIR "/"
-#elif DEPLOYMENT_TARGET_WINDOWS
 static CFStringRef __tzZoneInfo = NULL;
 static char *__tzDir = NULL;
 static void __InitTZStrings(void);
-#else
-#error Unknown or unspecified DEPLOYMENT_TARGET
-#endif
 
 CONST_STRING_DECL(kCFTimeZoneSystemTimeZoneDidChangeNotification, "kCFTimeZoneSystemTimeZoneDidChangeNotification")
 
@@ -147,13 +143,9 @@
 #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
 static CFMutableArrayRef __CFCopyRecursiveDirectoryList() {
     CFMutableArrayRef result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks);
-#if DEPLOYMENT_TARGET_WINDOWS
     if (!__tzDir) __InitTZStrings();
     if (!__tzDir) return result;
     int fd = open(__tzDir, O_RDONLY);
-#else
-    int fd = open(TZDIR "/zone.tab", O_RDONLY);
-#endif
 
     for (; 0 <= fd;) {
         uint8_t buffer[4096];
@@ -686,7 +678,7 @@
 }
 
 extern CFStringRef _CFGetWindowsAppleSystemLibraryDirectory(void);
-void __InitTZStrings(void) {
+static void __InitTZStrings(void) {
     static CFLock_t __CFTZDirLock = CFLockInit;
     __CFLock(&__CFTZDirLock);
     if (!__tzZoneInfo) {
@@ -704,6 +696,50 @@
     }
     __CFUnlock(&__CFTZDirLock);
 }
+
+#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
+static void __InitTZStrings(void) {
+    static dispatch_once_t initOnce = 0;
+
+    dispatch_once(&initOnce, ^{
+        unsigned int major = 0, minor = 0, patch = 0;
+
+        CFDictionaryRef dict = _CFCopySystemVersionDictionary();
+        if (dict) {
+            CFStringRef version = CFDictionaryGetValue(dict, _kCFSystemVersionProductVersionKey);
+            if (version) {
+                const char *cStr = CFStringGetCStringPtr(version, kCFStringEncodingASCII);
+                if (cStr) {
+                    if (sscanf(cStr, "%u.%u.%u", &major, &minor, &patch) != 3) {
+                        major = 0;
+                        minor = 0;
+                        patch = 0;
+                    }
+                }
+            }
+            CFRelease(dict);
+        }
+
+        // Timezone files moved in High Sierra(10.13)
+        if (major == 10 && minor < 13) {
+            // older versions
+            __tzZoneInfo = CFSTR(MACOS_TZDIR1);
+            __tzDir = MACOS_TZDIR1 "zone.tab";
+        } else {
+            __tzZoneInfo = CFSTR(MACOS_TZDIR2);
+            __tzDir = MACOS_TZDIR2 "zone.tab";
+        }
+    });
+}
+
+#elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
+static void __InitTZStrings(void) {
+    __tzZoneInfo = CFSTR(TZDIR);
+    __tzDir = TZDIR "zone.tab";
+}
+
+#else
+#error Unknown or unspecified DEPLOYMENT_TARGET
 #endif
 
 static CFTimeZoneRef __CFTimeZoneCreateSystem(void) {
@@ -748,11 +784,16 @@
         CFRelease(name);
         if (result) return result;
     }
-    ret = readlink(TZZONELINK, linkbuf, sizeof(linkbuf));
-    if (0 < ret) {
+
+    if (!__tzZoneInfo) __InitTZStrings();
+    ret = readlink(TZDEFAULT, linkbuf, sizeof(linkbuf));
+    if (__tzZoneInfo && (0 < ret)) {
         linkbuf[ret] = '\0';
-        if (strncmp(linkbuf, TZZONEINFO, sizeof(TZZONEINFO) - 1) == 0) {
-            name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf + sizeof(TZZONEINFO) - 1, strlen(linkbuf) - sizeof(TZZONEINFO) + 1, kCFStringEncodingUTF8, false);
+        const char *tzZoneInfo = CFStringGetCStringPtr(__tzZoneInfo, kCFStringEncodingASCII);
+        size_t zoneInfoDirLen = CFStringGetLength(__tzZoneInfo);
+        if (strncmp(linkbuf, tzZoneInfo, zoneInfoDirLen) == 0) {
+            name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf + zoneInfoDirLen,
+                                           strlen(linkbuf) - zoneInfoDirLen + 2, kCFStringEncodingUTF8, false);
         } else {
             name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf, strlen(linkbuf), kCFStringEncodingUTF8, false);
         }
@@ -1133,12 +1174,12 @@
             CFIndex length;
             Boolean result = false;
             
-#if DEPLOYMENT_TARGET_WINDOWS
             if (!__tzZoneInfo) __InitTZStrings();
             if (!__tzZoneInfo) return NULL;
+#if DEPLOYMENT_TARGET_WINDOWS
             baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true);
 #else
-            baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, CFSTR(TZZONEINFO), kCFURLPOSIXPathStyle, true);
+            baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true);
 #endif
             if (tryAbbrev) {
                 CFDictionaryRef abbrevs = CFTimeZoneCopyAbbreviationDictionary();
@@ -1159,15 +1200,9 @@
                 CFStringRef mapping = CFDictionaryGetValue(dict, name);
                 if (mapping) {
                     name = mapping;
-#if DEPLOYMENT_TARGET_WINDOWS
                 } else if (CFStringHasPrefix(name, __tzZoneInfo)) {
                     CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name);
                     CFStringDelete(unprefixed, CFRangeMake(0, CFStringGetLength(__tzZoneInfo)));
-#else
-                } else if (CFStringHasPrefix(name, CFSTR(TZZONEINFO))) {
-                    CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name);
-                    CFStringDelete(unprefixed, CFRangeMake(0, sizeof(TZZONEINFO)));
-#endif
                     mapping = CFDictionaryGetValue(dict, unprefixed);
                     if (mapping) {
                         name = mapping;
@@ -1340,12 +1375,12 @@
     void *bytes;
     CFIndex length;
 
-#if DEPLOYMENT_TARGET_WINDOWS
     if (!__tzZoneInfo) __InitTZStrings();
     if (!__tzZoneInfo) return NULL;
+#if DEPLOYMENT_TARGET_WINDOWS
     baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true);
 #else
-    baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, CFSTR(TZZONEINFO), kCFURLPOSIXPathStyle, true);
+    baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true);
 #endif
     if (tryAbbrev) {
 	CFDictionaryRef abbrevs = CFTimeZoneCopyAbbreviationDictionary();
@@ -1366,15 +1401,9 @@
 	CFStringRef mapping = CFDictionaryGetValue(dict, name);
 	if (mapping) {
 	    name = mapping;
-#if DEPLOYMENT_TARGET_WINDOWS
 	} else if (CFStringHasPrefix(name, __tzZoneInfo)) {
 	    CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name);
 	    CFStringDelete(unprefixed, CFRangeMake(0, CFStringGetLength(__tzZoneInfo)));
-#else
-	} else if (CFStringHasPrefix(name, CFSTR(TZZONEINFO))) {
-	    CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name);
-	    CFStringDelete(unprefixed, CFRangeMake(0, sizeof(TZZONEINFO)));
-#endif
 	    mapping = CFDictionaryGetValue(dict, unprefixed);
 	    if (mapping) {
 		name = mapping;
@@ -1549,6 +1578,4 @@
     return dict;
 }
 
-#undef TZZONEINFO
-#undef TZZONELINK
 
diff --git a/Foundation/CharacterSet.swift b/Foundation/CharacterSet.swift
index 79948ec..84fa74c 100644
--- a/Foundation/CharacterSet.swift
+++ b/Foundation/CharacterSet.swift
@@ -94,6 +94,12 @@
     override func isSuperset(of other: CharacterSet) -> Bool {
         return _mapUnmanaged { $0.isSuperset(of: other) }
     }
+
+    override var _cfObject: CFType {
+        // We cannot inherit super's unsafeBitCast(self, to: CFType.self) here, because layout of _SwiftNSCharacterSet
+        // is not compatible with CFCharacterSet. We need to bitcast the underlying NSCharacterSet instead.
+        return _mapUnmanaged { unsafeBitCast($0, to: CFType.self) }
+    }
 }
 
 /**
@@ -469,7 +475,7 @@
     
     /// Returns true if the two `CharacterSet`s are equal.
     public static func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool {
-        return lhs._wrapped.isEqual(rhs._bridgeToObjectiveC()) // TODO: mlehew - as  NSCharacterSet
+        return lhs._mapUnmanaged { $0.isEqual(rhs) }
     }
 }
 
@@ -503,3 +509,20 @@
     }
     
 }
+
+extension CharacterSet : Codable {
+    private enum CodingKeys : Int, CodingKey {
+        case bitmap
+    }
+    
+    public init(from decoder: Decoder) throws {
+        let container = try decoder.container(keyedBy: CodingKeys.self)
+        let bitmap = try container.decode(Data.self, forKey: .bitmap)
+        self.init(bitmapRepresentation: bitmap)
+    }
+    
+    public func encode(to encoder: Encoder) throws {
+        var container = encoder.container(keyedBy: CodingKeys.self)
+        try container.encode(self.bitmapRepresentation, forKey: .bitmap)
+    }
+}
diff --git a/Foundation/ExtraStringAPIs.swift b/Foundation/ExtraStringAPIs.swift
index 2c737c6..2f5d4f1 100644
--- a/Foundation/ExtraStringAPIs.swift
+++ b/Foundation/ExtraStringAPIs.swift
@@ -29,6 +29,4 @@
     }
 }
 
-extension String.UTF16View : RandomAccessCollection {}
-extension String.UTF16View.Indices : RandomAccessCollection {}
 
diff --git a/Foundation/FileHandle.swift b/Foundation/FileHandle.swift
index 645dc5d..28bf722 100644
--- a/Foundation/FileHandle.swift
+++ b/Foundation/FileHandle.swift
@@ -76,7 +76,7 @@
                 fatalError("Unable to fetch current file offset")
             }
             if off_t(statbuf.st_size) > offset {
-                var remaining = size_t(statbuf.st_size - offset)
+                var remaining = size_t(off_t(statbuf.st_size) - offset)
                 remaining = min(remaining, size_t(length))
                 
                 dynamicBuffer = malloc(remaining)
diff --git a/Foundation/NSError.swift b/Foundation/NSError.swift
index 14d05cc..abec7fa 100644
--- a/Foundation/NSError.swift
+++ b/Foundation/NSError.swift
@@ -274,6 +274,37 @@
     var errorUserInfo: [String : Any] { get }
 }
 
+public extension CustomNSError {
+    /// Default domain of the error.
+    static var errorDomain: String {
+        return String(reflecting: self)
+    }
+
+    /// The error code within the given domain.
+    var errorCode: Int {
+        return _swift_getDefaultErrorCode(self)
+    }
+
+    /// The default user-info dictionary.
+    var errorUserInfo: [String : Any] {
+        return [:]
+    }
+}
+
+extension CustomNSError where Self: RawRepresentable, Self.RawValue: SignedInteger {
+    // The error code of Error with integral raw values is the raw value.
+    public var errorCode: Int {
+        return numericCast(self.rawValue)
+    }
+}
+
+extension CustomNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger {
+    // The error code of Error with integral raw values is the raw value.
+    public var errorCode: Int {
+        return numericCast(self.rawValue)
+    }
+}
+
 public extension Error where Self : CustomNSError {
     /// Default implementation for customized NSErrors.
     var _domain: String { return Self.errorDomain }
@@ -282,6 +313,16 @@
     var _code: Int { return self.errorCode }
 }
 
+public extension Error where Self: CustomNSError, Self: RawRepresentable, Self.RawValue: SignedInteger {
+    /// Default implementation for customized NSErrors.
+    var _code: Int { return self.errorCode }
+}
+
+public extension Error where Self: CustomNSError, Self: RawRepresentable, Self.RawValue: UnsignedInteger {
+    /// Default implementation for customized NSErrors.
+    var _code: Int { return self.errorCode }
+}
+
 public extension Error {
     /// Retrieve the localized description for this error.
     var localizedDescription: String {
diff --git a/Foundation/NSGeometry.swift b/Foundation/NSGeometry.swift
index 454014a..80c8d25 100644
--- a/Foundation/NSGeometry.swift
+++ b/Foundation/NSGeometry.swift
@@ -25,6 +25,20 @@
     }
 }
 
+extension CGPoint {
+    public static var zero: CGPoint {
+        return CGPoint(x: CGFloat(0), y: CGFloat(0))
+    }
+    
+    public init(x: Int, y: Int) {
+        self.init(x: CGFloat(x), y: CGFloat(y))
+    }
+    
+    public init(x: Double, y: Double) {
+        self.init(x: CGFloat(x), y: CGFloat(y))
+    }
+}
+
 extension CGPoint: Equatable {
     public static func ==(lhs: CGPoint, rhs: CGPoint) -> Bool {
         return lhs.x == rhs.x && lhs.y == rhs.y
@@ -76,6 +90,21 @@
     }
 }
 
+extension CGPoint : Codable {
+    public init(from decoder: Decoder) throws {
+        var container = try decoder.unkeyedContainer()
+        let x = try container.decode(CGFloat.self)
+        let y = try container.decode(CGFloat.self)
+        self.init(x: x, y: y)
+    }
+    
+    public func encode(to encoder: Encoder) throws {
+        var container = encoder.unkeyedContainer()
+        try container.encode(x)
+        try container.encode(y)
+    }
+}
+
 public struct CGSize {
     public var width: CGFloat
     public var height: CGFloat
@@ -88,6 +117,20 @@
     }
 }
 
+extension CGSize {
+    public static var zero: CGSize {
+        return CGSize(width: CGFloat(0), height: CGFloat(0))
+    }
+    
+    public init(width: Int, height: Int) {
+        self.init(width: CGFloat(width), height: CGFloat(height))
+    }
+    
+    public init(width: Double, height: Double) {
+        self.init(width: CGFloat(width), height: CGFloat(height))
+    }
+}
+
 extension CGSize: Equatable {
     public static func ==(lhs: CGSize, rhs: CGSize) -> Bool {
         return lhs.width == rhs.width && lhs.height == rhs.height
@@ -139,6 +182,21 @@
     }
 }
 
+extension CGSize : Codable {
+    public init(from decoder: Decoder) throws {
+        var container = try decoder.unkeyedContainer()
+        let width = try container.decode(CGFloat.self)
+        let height = try container.decode(CGFloat.self)
+        self.init(width: width, height: height)
+    }
+    
+    public func encode(to encoder: Encoder) throws {
+        var container = encoder.unkeyedContainer()
+        try container.encode(width)
+        try container.encode(height)
+    }
+}
+
 public struct CGRect {
     public var origin: CGPoint
     public var size: CGSize
@@ -151,12 +209,57 @@
     }
 }
 
+extension CGRect {
+    public static var zero: CGRect {
+        return CGRect(origin: CGPoint(), size: CGSize())
+    }
+    
+    public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
+        self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height))
+    }
+    
+    public init(x: Double, y: Double, width: Double, height: Double) {
+        self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height))
+    }
+    
+    public init(x: Int, y: Int, width: Int, height: Int) {
+        self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height))
+    }
+}
+
+extension CGRect {
+    public static let null = CGRect(x: CGFloat.infinity,
+                                    y: CGFloat.infinity,
+                                    width: CGFloat(0),
+                                    height: CGFloat(0))
+    
+    public static let infinite = CGRect(x: -CGFloat.greatestFiniteMagnitude / 2,
+                                        y: -CGFloat.greatestFiniteMagnitude / 2,
+                                        width: CGFloat.greatestFiniteMagnitude,
+                                        height: CGFloat.greatestFiniteMagnitude)
+}
+
 extension CGRect: Equatable {
     public static func ==(lhs: CGRect, rhs: CGRect) -> Bool {
         return lhs.origin == rhs.origin && lhs.size == rhs.size
     }
 }
 
+extension CGRect : Codable {
+    public init(from decoder: Decoder) throws {
+        var container = try decoder.unkeyedContainer()
+        let origin = try container.decode(CGPoint.self)
+        let size = try container.decode(CGSize.self)
+        self.init(origin: origin, size: size)
+    }
+    
+    public func encode(to encoder: Encoder) throws {
+        var container = encoder.unkeyedContainer()
+        try container.encode(origin)
+        try container.encode(size)
+    }
+}
+
 public typealias NSPoint = CGPoint
 
 public typealias NSPointPointer = UnsafeMutablePointer<NSPoint>
diff --git a/Foundation/NSSortDescriptor.swift b/Foundation/NSSortDescriptor.swift
index 52d83a8..9bd70d8 100644
--- a/Foundation/NSSortDescriptor.swift
+++ b/Foundation/NSSortDescriptor.swift
@@ -35,13 +35,13 @@
     
     open var key: String? { NSUnimplemented() }
     open var ascending: Bool { NSUnimplemented() }
-    var keyPath: AnyKeyPath? { NSUnimplemented() }
+    public var keyPath: AnyKeyPath? { NSUnimplemented() }
     
     open func allowEvaluation() { NSUnimplemented() } // Force a sort descriptor which was securely decoded to allow evaluation
     
     public init(key: String?, ascending: Bool, comparator cmptr: Comparator) { NSUnimplemented() }
-    convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool) { NSUnimplemented() }
-    convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool, comparator cmptr: @escaping Comparator) { NSUnimplemented() }
+    public convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool) { NSUnimplemented() }
+    public convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool, comparator cmptr: @escaping Comparator) { NSUnimplemented() }
     
     open var comparator: Comparator { NSUnimplemented() }
     
diff --git a/Foundation/NSString.swift b/Foundation/NSString.swift
index 97212d5..5b43cf5 100644
--- a/Foundation/NSString.swift
+++ b/Foundation/NSString.swift
@@ -346,49 +346,7 @@
             let start = _storage.utf16.startIndex
             let min = start.advanced(by: range.location)
             let max = start.advanced(by: range.location + range.length)
-            if let substr = String(_storage.utf16[min..<max]) {
-                return substr
-            }
-            //If we come here, then the range has created unpaired surrogates on either end.
-            //An unpaired surrogate is replaced by OXFFFD - the Unicode Replacement Character.
-            //The CRLF ("\r\n") sequence is also treated like a surrogate pair, but its constinuent
-            //characters "\r" and "\n" can exist outside the pair!
-
-            let replacementCharacter = String(describing: UnicodeScalar(0xFFFD)!)
-            let CR: UInt16 = 13  //carriage return
-            let LF: UInt16 = 10  //new line
-
-            //make sure the range is of non-zero length
-            guard range.length > 0 else { return "" }
-
-            //if the range is pointing to a single unpaired surrogate
-            if range.length == 1 {
-                switch _storage.utf16[min] {
-                case CR: return "\r"
-                case LF: return "\n"
-                default: return replacementCharacter
-                }
-            }
-
-            //set the prefix and suffix characters
-            let prefix = _storage.utf16[min] == LF ? "\n" : replacementCharacter
-            let suffix = _storage.utf16[max.advanced(by: -1)] == CR ? "\r" : replacementCharacter
-
-            //if the range breaks a surrogate pair at the beginning of the string
-            if let substrSuffix = String(_storage.utf16[min.advanced(by: 1)..<max]) {
-                return prefix + substrSuffix
-            }
-
-            //if the range breaks a surrogate pair at the end of the string
-            if let substrPrefix = String(_storage.utf16[min..<max.advanced(by: -1)]) {
-                return substrPrefix + suffix
-            }
-
-            //the range probably breaks surrogate pairs at both the ends
-            guard min.advanced(by: 1) <= max.advanced(by: -1) else { return prefix + suffix }
-
-            let substr =  String(_storage.utf16[min.advanced(by: 1)..<max.advanced(by: -1)])!
-            return prefix + substr + suffix
+            return String(decoding: _storage.utf16[min..<max], as: UTF16.self)
         } else {
             let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length)
             getCharacters(buff, range: range)
diff --git a/Foundation/NSURLSession/NSURLSessionTask.swift b/Foundation/NSURLSession/NSURLSessionTask.swift
index 2b28de4..f819ff0 100644
--- a/Foundation/NSURLSession/NSURLSessionTask.swift
+++ b/Foundation/NSURLSession/NSURLSessionTask.swift
@@ -546,13 +546,12 @@
         guard let task = `protocol`.task else { fatalError() }
         guard let session = task.session as? URLSession else { fatalError() }
         switch session.behaviour(for: task) {
-        case .taskDelegate(let delegate) where delegate is URLSessionDownloadDelegate:
-            let downloadDelegate = delegate as! URLSessionDownloadDelegate
-            let downloadTask = task as! URLSessionDownloadTask
-            session.delegateQueue.addOperation {
-                downloadDelegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: `protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as! URL)
-            }
         case .taskDelegate(let delegate):
+            if let downloadDelegate = delegate as? URLSessionDownloadDelegate, let downloadTask = task as? URLSessionDownloadTask {
+                session.delegateQueue.addOperation {
+                    downloadDelegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: `protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as! URL)
+                }
+            }
             session.delegateQueue.addOperation {
                 delegate.urlSession(session, task: task, didCompleteWithError: nil)
                 task.state = .completed
diff --git a/Foundation/NSURLSession/http/HTTPMessage.swift b/Foundation/NSURLSession/http/HTTPMessage.swift
index 8b82fb3..f8bff6f 100644
--- a/Foundation/NSURLSession/http/HTTPMessage.swift
+++ b/Foundation/NSURLSession/http/HTTPMessage.swift
@@ -222,7 +222,7 @@
     /// Split a request line into its 3 parts: *Method*, *Request-URI*, and *HTTP-Version*.
     /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-5.1
     func splitRequestLine() -> (String, String, String)? {
-        let scalars = self.unicodeScalars
+        let scalars = self.unicodeScalars[...]
         guard let firstSpace = scalars.rangeOfSpace else { return nil }
         let remainingRange = firstSpace.upperBound..<scalars.endIndex
         let remainder = scalars[remainingRange]
@@ -285,7 +285,7 @@
         // recipient MAY replace any linear white space with a single SP before
         // interpreting the field value or forwarding the message downstream.
         guard let (head, tail) = lines.decompose else { return nil }
-        let headView = head.unicodeScalars
+        let headView = head.unicodeScalars[...]
         guard let nameRange = headView.rangeOfTokenPrefix else { return nil }
         guard headView.index(after: nameRange.upperBound) <= headView.endIndex && headView[nameRange.upperBound] == _HTTPCharacters.Colon else { return nil }
         let name = String(headView[nameRange])
@@ -302,10 +302,10 @@
         }
         do {
             var t = tail
-            while t.first?.unicodeScalars.hasSPHTPrefix ?? false {
+            while t.first?.unicodeScalars[...].hasSPHTPrefix ?? false {
                 guard let (h2, t2) = t.decompose else { return nil }
                 t = t2
-                guard let v = h2.unicodeScalars.trimSPHTPrefix else { return nil }
+                guard let v = h2.unicodeScalars[...].trimSPHTPrefix else { return nil }
                 let valuePart = String(v)
                 value = value.map { $0 + " " + valuePart } ?? valuePart
             }
@@ -321,7 +321,7 @@
         return (head, tail)
     }
 }
-private extension String.UnicodeScalarView {
+private extension String.UnicodeScalarView.SubSequence {
     /// The range of *Token* characters as specified by RFC 2616.
     var rangeOfTokenPrefix: Range<Index>? {
         var end = startIndex
@@ -344,7 +344,7 @@
     }
     /// Unicode scalars after removing the leading spaces (SP) and horizontal tabs (HT).
     /// Returns `nil` if the unicode scalars do not start with a SP or HT.
-    var trimSPHTPrefix: String.UnicodeScalarView? {
+    var trimSPHTPrefix: SubSequence? {
         guard !isEmpty else { return nil }
         var idx = startIndex
         while idx < endIndex {
diff --git a/Foundation/NSURLSession/http/HTTPURLProtocol.swift b/Foundation/NSURLSession/http/HTTPURLProtocol.swift
index 0186bf2..b105b15 100644
--- a/Foundation/NSURLSession/http/HTTPURLProtocol.swift
+++ b/Foundation/NSURLSession/http/HTTPURLProtocol.swift
@@ -14,6 +14,8 @@
 
     fileprivate var easyHandle: _EasyHandle!
     fileprivate var totalDownloaded = 0
+    fileprivate var totalUploaded: Int64 = 0
+    fileprivate var requestBodyLength: Int64 = 0
     fileprivate var tempFileURL: URL
 
     public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
@@ -127,6 +129,7 @@
                 set(requestBodyLength: .noBody)
             case (_, .some(let length)):
                 set(requestBodyLength: .length(length))
+                requestBodyLength = Int64(length)
             case (_, .none):
                 set(requestBodyLength: .unknown)
             }
@@ -495,6 +498,16 @@
         }
     }
 
+    fileprivate func notifyDelegate(aboutUploadedData count: Int64) {
+        let session = self.task?.session as! URLSession
+        guard case .taskDelegate(let delegate) = session.behaviour(for: self.task!), self.task is URLSessionUploadTask else { return }
+        totalUploaded += count
+        session.delegateQueue.addOperation {
+            delegate.urlSession(session, task: self.task!, didSendBodyData: count,
+                totalBytesSent: self.totalUploaded, totalBytesExpectedToSend: self.requestBodyLength)
+        }
+    }
+
     func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
         guard case .transferInProgress(let ts) = internalState else { fatalError("Requested to fill write buffer, but transfer isn't in progress.") }
         guard let source = ts.requestBodySource else { fatalError("Requested to fill write buffer, but transfer state has no body source.") }
@@ -503,6 +516,7 @@
             copyDispatchData(data, infoBuffer: buffer)
             let count = data.count
             assert(count > 0)
+            notifyDelegate(aboutUploadedData: Int64(count))
             return .bytes(count)
         case .done:
             return .bytes(0)
diff --git a/Foundation/Process.swift b/Foundation/Process.swift
index d104183..07a958e 100644
--- a/Foundation/Process.swift
+++ b/Foundation/Process.swift
@@ -387,11 +387,30 @@
             posix(posix_spawn_file_actions_addclose(&fileActions, fd))
         }
 
+        let fileManager = FileManager()
+        let previousDirectoryPath = fileManager.currentDirectoryPath
+        if !fileManager.changeCurrentDirectoryPath(currentDirectoryPath) {
+            // Foundation throws an NSException when changing the working directory fails,
+            // and unfortunately launch() is not marked `throws`, so we get away with a
+            // fatalError.
+            switch errno {
+            case ENOENT:
+                fatalError("Process: The specified working directory does not exist.")
+            case EACCES:
+                fatalError("Process: The specified working directory cannot be accessed.")
+            default:
+                fatalError("Process: The specified working directory cannot be set.")
+            }
+        }
+
         // Launch
 
         var pid = pid_t()
         posix(posix_spawn(&pid, launchPath, &fileActions, nil, argv, envp))
 
+        // Reset the previous working directory path.
+        fileManager.changeCurrentDirectoryPath(previousDirectoryPath)
+
         // Close the write end of the input and output pipes.
         if let pipe = standardInput as? Pipe {
             pipe.fileHandleForReading.closeFile()
diff --git a/TestFoundation/HTTPServer.swift b/TestFoundation/HTTPServer.swift
index 6485523..b129f74 100644
--- a/TestFoundation/HTTPServer.swift
+++ b/TestFoundation/HTTPServer.swift
@@ -330,7 +330,7 @@
     }
 
     func process(request: _HTTPRequest) -> _HTTPResponse {
-        if request.method == .GET || request.method == .POST {
+        if request.method == .GET || request.method == .POST || request.method == .PUT {
             return getResponse(request: request)
         } else {
             fatalError("Unsupported method!")
@@ -339,14 +339,20 @@
 
     func getResponse(request: _HTTPRequest) -> _HTTPResponse {
         let uri = request.uri
+
+        if uri == "/upload" {
+            let text = "Upload completed!"
+            return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
+        }
+
         if uri == "/country.txt" {
             let text = capitals[String(uri.characters.dropFirst())]!
-            return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
+            return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
         }
 
         if uri == "/requestHeaders" {
             let text = request.getCommaSeparatedHeaders()
-            return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
+            return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
         }
 
 	if uri == "/UnitedStates" {
diff --git a/TestFoundation/TestCodable.swift b/TestFoundation/TestCodable.swift
index 23650d1..0ff8297 100644
--- a/TestFoundation/TestCodable.swift
+++ b/TestFoundation/TestCodable.swift
@@ -52,12 +52,21 @@
 }
 
 func expectRoundTripEqualityThroughJSON<T : Codable>(for value: T) where T : Equatable {
+    let inf = "INF", negInf = "-INF", nan = "NaN"
     let encode = { (_ value: T) throws -> Data in
-        return try JSONEncoder().encode(value)
+        let encoder = JSONEncoder()
+        encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: inf,
+                                                                      negativeInfinity: negInf,
+                                                                      nan: nan)
+        return try encoder.encode(value)
     }
 
     let decode = { (_ data: Data) throws -> T in
-        return try JSONDecoder().decode(T.self, from: data)
+        let decoder = JSONDecoder()
+        decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: inf,
+                                                                        negativeInfinity: negInf,
+                                                                        nan: nan)
+        return try decoder.decode(T.self, from: data)
     }
 
     expectRoundTripEquality(of: value, encode: encode, decode: decode)
@@ -220,6 +229,81 @@
             expectRoundTripEqualityThroughJSON(for: decimal)
         }
     }
+    
+    // MARK: - CGPoint
+    lazy var cgpointValues: [CGPoint] = [
+        CGPoint(),
+        CGPoint.zero,
+        CGPoint(x: 10, y: 20),
+        CGPoint(x: -10, y: -20),
+        // Disabled due to limit on magnitude in JSON. See SR-5346
+        // CGPoint(x: .greatestFiniteMagnitude, y: .greatestFiniteMagnitude),
+    ]
+    
+    func test_CGPoint_JSON() {
+        for point in cgpointValues {
+            expectRoundTripEqualityThroughJSON(for: point)
+        }
+    }
+    
+    // MARK: - CGSize
+    lazy var cgsizeValues: [CGSize] = [
+        CGSize(),
+        CGSize.zero,
+        CGSize(width: 30, height: 40),
+        CGSize(width: -30, height: -40),
+        // Disabled due to limit on magnitude in JSON. See SR-5346
+        // CGSize(width: .greatestFiniteMagnitude, height: .greatestFiniteMagnitude),
+    ]
+    
+    func test_CGSize_JSON() {
+        for size in cgsizeValues {
+            expectRoundTripEqualityThroughJSON(for: size)
+        }
+    }
+    
+    // MARK: - CGRect
+    lazy var cgrectValues: [CGRect] = [
+        CGRect(),
+        CGRect.zero,
+        CGRect(origin: CGPoint(x: 10, y: 20), size: CGSize(width: 30, height: 40)),
+        CGRect(origin: CGPoint(x: -10, y: -20), size: CGSize(width: -30, height: -40)),
+        CGRect.null,
+        // Disabled due to limit on magnitude in JSON. See SR-5346
+        // CGRect.infinite
+    ]
+    
+    func test_CGRect_JSON() {
+        for rect in cgrectValues {
+            expectRoundTripEqualityThroughJSON(for: rect)
+        }
+    }
+    
+    // MARK: - CharacterSet
+    lazy var characterSetValues: [CharacterSet] = [
+        CharacterSet.controlCharacters,
+        CharacterSet.whitespaces,
+        CharacterSet.whitespacesAndNewlines,
+        CharacterSet.decimalDigits,
+        CharacterSet.letters,
+        CharacterSet.lowercaseLetters,
+        CharacterSet.uppercaseLetters,
+        CharacterSet.nonBaseCharacters,
+        CharacterSet.alphanumerics,
+        CharacterSet.decomposables,
+        CharacterSet.illegalCharacters,
+        CharacterSet.punctuationCharacters,
+        CharacterSet.capitalizedLetters,
+        CharacterSet.symbols,
+        CharacterSet.newlines,
+        CharacterSet(charactersIn: "abcd")
+    ]
+    
+    func test_CharacterSet_JSON() {
+        for characterSet in characterSetValues {
+            expectRoundTripEqualityThroughJSON(for: characterSet)
+        }
+    }
 
 }
 
@@ -235,6 +319,10 @@
             ("test_IndexPath_JSON", test_IndexPath_JSON),
             ("test_AffineTransform_JSON", test_AffineTransform_JSON),
             ("test_Decimal_JSON", test_Decimal_JSON),
+            ("test_CGPoint_JSON", test_CGPoint_JSON),
+            ("test_CGSize_JSON", test_CGSize_JSON),
+            ("test_CGRect_JSON", test_CGRect_JSON),
+            ("test_CharacterSet_JSON", test_CharacterSet_JSON),
         ]
     }
 }
diff --git a/TestFoundation/TestNSCharacterSet.swift b/TestFoundation/TestNSCharacterSet.swift
index 51378ae..c56da0d 100644
--- a/TestFoundation/TestNSCharacterSet.swift
+++ b/TestFoundation/TestNSCharacterSet.swift
@@ -1,4 +1,4 @@
-  // This source file is part of the Swift.org open source project
+// This source file is part of the Swift.org open source project
 //
 // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
 // Licensed under Apache License v2.0 with Runtime Library Exception
@@ -7,8 +7,6 @@
 // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 //
 
-
-
 #if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
 import Foundation
 import XCTest
@@ -17,7 +15,47 @@
 import SwiftXCTest
 #endif
 
+private struct Box: Equatable {
+    private let ns: NSCharacterSet
+    private let swift: CharacterSet
+    
+    private init(ns: NSCharacterSet, swift: CharacterSet) {
+        self.ns = ns
+        self.swift = swift
+    }
+    
+    init(charactersIn string: String) {
+        self.ns = NSCharacterSet(charactersIn: string)
+        self.swift = CharacterSet(charactersIn: string)
+    }
+    
+    static var alphanumerics: Box {
+        return Box(ns: NSCharacterSet.alphanumerics._bridgeToObjectiveC(),
+                   swift: CharacterSet.alphanumerics)
+    }
+    
+    static var decimalDigits: Box {
+        return Box(ns: NSCharacterSet.decimalDigits._bridgeToObjectiveC(),
+                   swift: CharacterSet.decimalDigits)
+    }
 
+    // MARK: Equatable
+
+    static func ==(lhs: Box, rhs: Box) -> Bool {
+        return lhs.ns == rhs.ns
+            && lhs.swift == rhs.swift
+            && lhs.ns._bridgeToSwift() == rhs.ns._bridgeToSwift()
+            && lhs.swift._bridgeToObjectiveC() == rhs.swift._bridgeToObjectiveC()
+            && lhs.ns.isEqual(rhs.ns)
+            && lhs.ns.isEqual(rhs.swift)
+            && lhs.ns.isEqual(rhs.ns._bridgeToSwift())
+            && lhs.ns.isEqual(rhs.swift._bridgeToObjectiveC())
+            && lhs.swift._bridgeToObjectiveC().isEqual(rhs.ns)
+            && lhs.swift._bridgeToObjectiveC().isEqual(rhs.swift)
+            && lhs.swift._bridgeToObjectiveC().isEqual(rhs.ns._bridgeToSwift())
+            && lhs.swift._bridgeToObjectiveC().isEqual(rhs.swift._bridgeToObjectiveC())
+    }
+}
 
 class TestNSCharacterSet : XCTestCase {
     
@@ -283,28 +321,36 @@
         let expected = CharacterSet(charactersIn: "abc")
         XCTAssertEqual(expected, symmetricDifference)
     }
-
+    
     func test_Equatable() {
-        XCTAssertEqual(NSCharacterSet(charactersIn: ""), NSCharacterSet(charactersIn: ""))
-        XCTAssertEqual(NSCharacterSet(charactersIn: "a"), NSCharacterSet(charactersIn: "a"))
-        XCTAssertEqual(NSCharacterSet(charactersIn: "ab"), NSCharacterSet(charactersIn: "ab"))
-
-        XCTAssertNotEqual(NSCharacterSet(charactersIn: "abc"), NSCharacterSet(charactersIn: "123"))
-        XCTAssertNotEqual(NSCharacterSet(charactersIn: "123"), NSCharacterSet(charactersIn: "abc"))
-
-        XCTAssertNotEqual(NSCharacterSet(charactersIn: ""), nil)
-
+        let equalPairs = [
+            ("", ""),
+            ("a", "a"),
+            ("abcde", "abcde"),
+            ("12345", "12345")
+        ]
+        
         /*
          Tests disabled due to CoreFoundation bug?
          These NSCharacterSet pairs are (wrongly?) evaluated to be equal. Same behaviour can be observed on macOS 10.12.
          Interestingly, on iOS 11 Simulator, they are evaluted to be _not_ equal,
          while on iOS 10.3.1 Simulator, they are evaluted to be equal.
          */
-//        XCTAssertNotEqual(NSCharacterSet(charactersIn: "ab"), NSCharacterSet(charactersIn: "abc"))
-//        XCTAssertNotEqual(NSCharacterSet(charactersIn: "abc"), NSCharacterSet(charactersIn: "ab"))
-//        XCTAssertNotEqual(NSCharacterSet(charactersIn: "abc"), NSCharacterSet(charactersIn: ""))
-//        XCTAssertNotEqual(NSCharacterSet(charactersIn: ""), NSCharacterSet(charactersIn: "abc"))
+        let notEqualPairs = [
+            ("abc", "123"),
+//            ("ab", "abc"),
+//            ("abc", "")
+        ]
+        
+        for pair in equalPairs {
+            XCTAssertEqual(Box(charactersIn: pair.0), Box(charactersIn: pair.1))
+        }
+        XCTAssertEqual(Box.alphanumerics, Box.alphanumerics)
+        
+        for pair in notEqualPairs {
+            XCTAssertNotEqual(Box(charactersIn: pair.0), Box(charactersIn: pair.1))
+        }
+        XCTAssertNotEqual(Box.alphanumerics, Box.decimalDigits)
     }
 
 }
-
diff --git a/TestFoundation/TestNSDecimal.swift b/TestFoundation/TestNSDecimal.swift
index 6599281..9cacc4e 100644
--- a/TestFoundation/TestNSDecimal.swift
+++ b/TestFoundation/TestNSDecimal.swift
@@ -185,7 +185,7 @@
             _length: 0xff,
             _isNegative: 3,
             _isCompact: 4,
-            _reserved: UInt32(1<<18 + 1<<17 + 1),
+            _reserved: 1<<18 + 1<<17 + 1,
             _mantissa: (6, 7, 8, 9, 10, 11, 12, 13)
         )
         XCTAssertEqual(0x7f, explicit._exponent)
diff --git a/TestFoundation/TestNSError.swift b/TestFoundation/TestNSError.swift
index 43c9a47..8960aa6 100644
--- a/TestFoundation/TestNSError.swift
+++ b/TestFoundation/TestNSError.swift
@@ -16,6 +16,8 @@
     import SwiftXCTest
 #endif
 
+struct SwiftCustomNSError: Error, CustomNSError {
+}
 
 class TestNSError : XCTestCase {
     
@@ -23,6 +25,11 @@
         return [
             ("test_LocalizedError_errorDescription", test_LocalizedError_errorDescription),
             ("test_NSErrorAsError_localizedDescription", test_NSErrorAsError_localizedDescription),
+            ("test_CustomNSError_domain", test_CustomNSError_domain),
+            ("test_CustomNSError_userInfo", test_CustomNSError_userInfo),
+            ("test_CustomNSError_errorCode", test_CustomNSError_errorCode),
+            ("test_CustomNSError_errorCodeRawInt", test_CustomNSError_errorCodeRawInt),
+            ("test_CustomNSError_errorCodeRawUInt", test_CustomNSError_errorCodeRawUInt),
         ]
     }
     
@@ -40,4 +47,45 @@
         let error = nsError as Error
         XCTAssertEqual(error.localizedDescription, "Localized!")
     }
+
+    func test_CustomNSError_domain() {
+        XCTAssertEqual(SwiftCustomNSError.errorDomain, "TestFoundation.SwiftCustomNSError")
+    }
+
+    func test_CustomNSError_userInfo() {
+        let userInfo = SwiftCustomNSError().errorUserInfo
+        XCTAssertTrue(userInfo.isEmpty)
+    }
+
+    func test_CustomNSError_errorCode() {
+        enum SwiftError : Error, CustomNSError {
+            case zero
+            case one
+            case two
+        }
+
+        XCTAssertEqual(SwiftCustomNSError().errorCode, 1)
+
+        XCTAssertEqual(SwiftError.zero.errorCode, 0)
+        XCTAssertEqual(SwiftError.one.errorCode,  1)
+        XCTAssertEqual(SwiftError.two.errorCode,  2)
+    }
+
+    func test_CustomNSError_errorCodeRawInt() {
+        enum SwiftError : Int, Error, CustomNSError {
+            case minusOne  = -1
+            case fortyTwo = 42
+        }
+
+        XCTAssertEqual(SwiftError.minusOne.errorCode,  -1)
+        XCTAssertEqual(SwiftError.fortyTwo.errorCode, 42)
+    }
+
+    func test_CustomNSError_errorCodeRawUInt() {
+        enum SwiftError : UInt, Error, CustomNSError {
+            case fortyTwo = 42
+        }
+
+        XCTAssertEqual(SwiftError.fortyTwo.errorCode, 42)
+    }
 }
diff --git a/TestFoundation/TestNSGeometry.swift b/TestFoundation/TestNSGeometry.swift
index edd9d37..9367431 100644
--- a/TestFoundation/TestNSGeometry.swift
+++ b/TestFoundation/TestNSGeometry.swift
@@ -27,8 +27,12 @@
             ("test_CGFloat_LessThanOrEqual", test_CGFloat_LessThanOrEqual),
             ("test_CGFloat_GreaterThanOrEqual", test_CGFloat_GreaterThanOrEqual),
             ("test_CGPoint_BasicConstruction", test_CGPoint_BasicConstruction),
+            ("test_CGPoint_ExtendedConstruction", test_CGPoint_ExtendedConstruction),
             ("test_CGSize_BasicConstruction", test_CGSize_BasicConstruction),
+            ("test_CGSize_ExtendedConstruction", test_CGSize_ExtendedConstruction),
             ("test_CGRect_BasicConstruction", test_CGRect_BasicConstruction),
+            ("test_CGRect_ExtendedConstruction", test_CGRect_ExtendedConstruction),
+            ("test_CGRect_SpecialValues", test_CGRect_SpecialValues),
             ("test_NSEdgeInsets_BasicConstruction", test_NSEdgeInsets_BasicConstruction),
             ("test_NSEdgeInsetsEqual", test_NSEdgeInsetsEqual),
             ("test_NSMakePoint", test_NSMakePoint),
@@ -112,6 +116,20 @@
         XCTAssertEqual(p2.x, CGFloat(3.6))
         XCTAssertEqual(p2.y, CGFloat(4.5))
     }
+    
+    func test_CGPoint_ExtendedConstruction() {
+        let p1 = CGPoint.zero
+        XCTAssertEqual(p1.x, CGFloat(0))
+        XCTAssertEqual(p1.y, CGFloat(0))
+        
+        let p2 = CGPoint(x: Int(3), y: Int(4))
+        XCTAssertEqual(p2.x, CGFloat(3))
+        XCTAssertEqual(p2.y, CGFloat(4))
+        
+        let p3 = CGPoint(x: Double(3.6), y: Double(4.5))
+        XCTAssertEqual(p3.x, CGFloat(3.6))
+        XCTAssertEqual(p3.y, CGFloat(4.5))
+    }
 
     func test_CGSize_BasicConstruction() {
         let s1 = CGSize()
@@ -122,6 +140,20 @@
         XCTAssertEqual(s2.width, CGFloat(3.6))
         XCTAssertEqual(s2.height, CGFloat(4.5))
     }
+    
+    func test_CGSize_ExtendedConstruction() {
+        let s1 = CGSize.zero
+        XCTAssertEqual(s1.width, CGFloat(0))
+        XCTAssertEqual(s1.height, CGFloat(0))
+        
+        let s2 = CGSize(width: Int(3), height: Int(4))
+        XCTAssertEqual(s2.width, CGFloat(3))
+        XCTAssertEqual(s2.height, CGFloat(4))
+        
+        let s3 = CGSize(width: Double(3.6), height: Double(4.5))
+        XCTAssertEqual(s3.width, CGFloat(3.6))
+        XCTAssertEqual(s3.height, CGFloat(4.5))
+    }
 
     func test_CGRect_BasicConstruction() {
         let r1 = CGRect()
@@ -138,6 +170,46 @@
         XCTAssertEqual(r2.size.width, s.width)
         XCTAssertEqual(r2.size.height, s.height)
     }
+    
+    func test_CGRect_ExtendedConstruction() {
+        let r1 = CGRect.zero
+        XCTAssertEqual(r1.origin.x, CGFloat(0.0))
+        XCTAssertEqual(r1.origin.y, CGFloat(0.0))
+        XCTAssertEqual(r1.size.width, CGFloat(0.0))
+        XCTAssertEqual(r1.size.height, CGFloat(0.0))
+        
+        let r2 = CGRect(x: CGFloat(1.2), y: CGFloat(2.3), width: CGFloat(3.4), height: CGFloat(4.5))
+        XCTAssertEqual(r2.origin.x, CGFloat(1.2))
+        XCTAssertEqual(r2.origin.y, CGFloat(2.3))
+        XCTAssertEqual(r2.size.width, CGFloat(3.4))
+        XCTAssertEqual(r2.size.height, CGFloat(4.5))
+        
+        let r3 = CGRect(x: Double(1.2), y: Double(2.3), width: Double(3.4), height: Double(4.5))
+        XCTAssertEqual(r3.origin.x, CGFloat(1.2))
+        XCTAssertEqual(r3.origin.y, CGFloat(2.3))
+        XCTAssertEqual(r3.size.width, CGFloat(3.4))
+        XCTAssertEqual(r3.size.height, CGFloat(4.5))
+        
+        let r4 = CGRect(x: Int(1), y: Int(2), width: Int(3), height: Int(4))
+        XCTAssertEqual(r4.origin.x, CGFloat(1))
+        XCTAssertEqual(r4.origin.y, CGFloat(2))
+        XCTAssertEqual(r4.size.width, CGFloat(3))
+        XCTAssertEqual(r4.size.height, CGFloat(4))
+    }
+    
+    func test_CGRect_SpecialValues() {
+        let r1 = CGRect.null
+        XCTAssertEqual(r1.origin.x, CGFloat.infinity)
+        XCTAssertEqual(r1.origin.y, CGFloat.infinity)
+        XCTAssertEqual(r1.size.width, CGFloat(0.0))
+        XCTAssertEqual(r1.size.height, CGFloat(0.0))
+        
+        let r2 = CGRect.infinite
+        XCTAssertEqual(r2.origin.x, -CGFloat.greatestFiniteMagnitude / 2)
+        XCTAssertEqual(r2.origin.y, -CGFloat.greatestFiniteMagnitude / 2)
+        XCTAssertEqual(r2.size.width, CGFloat.greatestFiniteMagnitude)
+        XCTAssertEqual(r2.size.height, CGFloat.greatestFiniteMagnitude)
+    }
 
     func test_NSEdgeInsets_BasicConstruction() {
         let i1 = NSEdgeInsets()
diff --git a/TestFoundation/TestNSString.swift b/TestFoundation/TestNSString.swift
index 58a1c8a..85dac2a 100644
--- a/TestFoundation/TestNSString.swift
+++ b/TestFoundation/TestNSString.swift
@@ -1134,6 +1134,10 @@
 
         let s5 = NSString(string: "\r\ncats😺")
         XCTAssertEqual(s5.substring(with: NSMakeRange(1,6)), "\ncats�")
+
+        // SR-3363
+        let s6 = NSString(string: "Beyonce\u{301} and Tay")
+        XCTAssertEqual(s6.substring(with: NSMakeRange(7, 9)), "\u{301} and Tay")
     }
 }
 
diff --git a/TestFoundation/TestNSURLSession.swift b/TestFoundation/TestNSURLSession.swift
index 6571658..cf44ab6 100644
--- a/TestFoundation/TestNSURLSession.swift
+++ b/TestFoundation/TestNSURLSession.swift
@@ -41,6 +41,8 @@
             ("test_outOfRangeButCorrectlyFormattedHTTPCode", test_outOfRangeButCorrectlyFormattedHTTPCode),
             ("test_missingContentLengthButStillABody", test_missingContentLengthButStillABody),
             ("test_illegalHTTPServerResponses", test_illegalHTTPServerResponses),
+            ("test_dataTaskWithSharedDelegate", test_dataTaskWithSharedDelegate),
+            ("test_simpleUploadWithDelegate", test_simpleUploadWithDelegate),
         ]
     }
     
@@ -429,8 +431,52 @@
             waitForExpectations(timeout: 12)
         }
     }
+
+    func test_dataTaskWithSharedDelegate() {
+        let sharedDelegate = SharedDelegate()
+        let urlString0 = "http://127.0.0.1:\(TestURLSession.serverPort)/Nepal"
+        let session = URLSession(configuration: .default, delegate: sharedDelegate, delegateQueue: nil)
+
+        let dataRequest = URLRequest(url: URL(string: urlString0)!)
+        let dataTask = session.dataTask(with: dataRequest)
+
+        sharedDelegate.dataCompletionExpectation = expectation(description: "GET \(urlString0)")
+        dataTask.resume()
+        waitForExpectations(timeout: 20)
+    }
+
+    func test_simpleUploadWithDelegate() {
+        let delegate = HTTPUploadDelegate()
+        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
+        let urlString = "http://127.0.0.1:\(TestURLSession.serverPort)/upload"
+        var request = URLRequest(url: URL(string: urlString)!)
+        request.httpMethod = "PUT"
+
+        delegate.uploadCompletedExpectation = expectation(description: "PUT \(urlString): Upload data")
+
+        let fileData = Data(count: 16*1024)
+        let task = session.uploadTask(with: request, from: fileData)
+        task.resume()
+        waitForExpectations(timeout: 20)
+    }
 }
 
+class SharedDelegate: NSObject {
+    var dataCompletionExpectation: XCTestExpectation!
+}
+
+extension SharedDelegate: URLSessionDataDelegate {
+    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+        dataCompletionExpectation.fulfill()
+    }
+}
+
+extension SharedDelegate: URLSessionDownloadDelegate {
+    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+    }
+}
+
+
 class SessionDelegate: NSObject, URLSessionDelegate {
     let invalidateExpectation: XCTestExpectation
     init(invalidateExpectation: XCTestExpectation){
@@ -619,3 +665,21 @@
         completionHandler(request)
     }
 }
+
+class HTTPUploadDelegate: NSObject {
+    var uploadCompletedExpectation: XCTestExpectation!
+    var totalBytesSent: Int64 = 0
+}
+
+extension HTTPUploadDelegate: URLSessionTaskDelegate {
+    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
+        self.totalBytesSent = totalBytesSent
+    }
+}
+
+extension HTTPUploadDelegate: URLSessionDataDelegate {
+    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+        XCTAssertEqual(self.totalBytesSent, 16*1024)
+        uploadCompletedExpectation.fulfill()
+    }
+}
diff --git a/TestFoundation/TestProcess.swift b/TestFoundation/TestProcess.swift
index cbac7a9..163dc31 100644
--- a/TestFoundation/TestProcess.swift
+++ b/TestFoundation/TestProcess.swift
@@ -28,6 +28,7 @@
                    ("test_pipe_stdin", test_pipe_stdin),
                    ("test_pipe_stdout", test_pipe_stdout),
                    ("test_pipe_stderr", test_pipe_stderr),
+                   ("test_current_working_directory", test_current_working_directory),
                    // disabled for now
                    // ("test_pipe_stdout_and_stderr_same_pipe", test_pipe_stdout_and_stderr_same_pipe),
                    ("test_file_stdout", test_file_stdout),
@@ -262,6 +263,19 @@
             XCTFail("Test failed: \(error)")
         }
     }
+
+    func test_current_working_directory() {
+        do {
+            let previousWorkingDirectory = FileManager.default.currentDirectoryPath
+
+            // `bash` will not be found if the current working directory is not set correctly.
+            let _ = try runTask(["bash", "-c", "exit 0"], currentDirectoryPath: "/bin")
+
+            XCTAssertEqual(previousWorkingDirectory, FileManager.default.currentDirectoryPath)
+        } catch let error {
+            XCTFail("Test failed: \(error)")
+        }
+    }
 }
 
 private func mkstemp(template: String, body: (FileHandle) throws -> Void) rethrows {
@@ -284,7 +298,7 @@
     case InvalidEnvironmentVariable(String)
 }
 
-private func runTask(_ arguments: [String], environment: [String: String]? = nil) throws -> String {
+private func runTask(_ arguments: [String], environment: [String: String]? = nil, currentDirectoryPath: String? = nil) throws -> String {
     let process = Process()
 
     var arguments = arguments
@@ -292,6 +306,10 @@
     process.arguments = arguments
     process.environment = environment
 
+    if let directoryPath = currentDirectoryPath {
+        process.currentDirectoryPath = directoryPath
+    }
+
     let pipe = Pipe()
     process.standardOutput = pipe
     process.standardError = pipe