Merge pull request #940 from ffried/master

diff --git a/CoreFoundation/Base.subproj/CFInternal.h b/CoreFoundation/Base.subproj/CFInternal.h
index a716f90..59106bd 100644
--- a/CoreFoundation/Base.subproj/CFInternal.h
+++ b/CoreFoundation/Base.subproj/CFInternal.h
@@ -341,6 +341,12 @@
 
 CF_EXPORT void *__CFConstantStringClassReference[];
 
+#if __CF_BIG_ENDIAN__
+#define CF_CONST_STRING_INFO {0x00, 0x00, 0x07, 0xc8}
+#elif __CF_LITTLE_ENDIAN__
+#define CF_CONST_STRING_INFO {0xc8, 0x07, 0x00, 0x00}
+#endif
+
 #if DEPLOYMENT_TARGET_LINUX
 #define CONST_STRING_SECTION __attribute__((section(".cfstr.data")))
 #else
@@ -348,11 +354,11 @@
 #endif
 
 #define CONST_STRING_DECL(S, V) \
-const struct __CFConstStr __##S CONST_STRING_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0, {0xc8, 0x07, 0x00, 0x00}}, (uint8_t *)(V), sizeof(V) - 1}; \
+const struct __CFConstStr __##S CONST_STRING_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0, CF_CONST_STRING_INFO}, (uint8_t *)(V), sizeof(V) - 1}; \
 const CFStringRef S = (CFStringRef)&__##S;
 
 #define PE_CONST_STRING_DECL(S, V) \
-const static struct __CFConstStr __##S CONST_STRING_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0, {0xc8, 0x07, 0x00, 0x00}}, (uint8_t *)(V), sizeof(V) - 1}; \
+const static struct __CFConstStr __##S CONST_STRING_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0, CF_CONST_STRING_INFO}, (uint8_t *)(V), sizeof(V) - 1}; \
 CF_PRIVATE const CFStringRef S = (CFStringRef)&__##S;
 
 
@@ -366,33 +372,24 @@
 struct CF_CONST_STRING {
     CFRuntimeBase _base;
     uint8_t *_ptr;
-    uint32_t _length;
+#if defined(__LP64__) && defined(__BIG_ENDIAN__)
+	uint64_t _length;
+#else
+	uint32_t _length;
+#endif
 };
 
 CF_EXPORT int __CFConstantStringClassReference[];
 
 /* CFNetwork also has a copy of the CONST_STRING_DECL macro (for use on platforms without constant string support in cc); please warn cfnetwork-core@group.apple.com of any necessary changes to this macro. -- REW, 1/28/2002 */
 
-#if __CF_BIG_ENDIAN__
-
 #define CONST_STRING_DECL(S, V)			\
-static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0x00, 0x00, 0x07, 0xc8}}, (uint8_t *)V, sizeof(V) - 1}; \
+static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, CF_CONST_STRING_INFO}, (uint8_t *)V, sizeof(V) - 1}; \
 const CFStringRef S = (CFStringRef) & __ ## S ## __;
 #define PE_CONST_STRING_DECL(S, V)			\
-static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0x00, 0x00, 0x07, 0xc8}}, (uint8_t *)V, sizeof(V) - 1}; \
+static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, CF_CONST_STRING_INFO}, (uint8_t *)V, sizeof(V) - 1}; \
 CF_PRIVATE const CFStringRef S = (CFStringRef) & __ ## S ## __;
 
-#elif __CF_LITTLE_ENDIAN__
-
-#define CONST_STRING_DECL(S, V)			\
-static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0xc8, 0x07, 0x00, 0x00}}, (uint8_t *)(V), sizeof(V) - 1}; \
-const CFStringRef S = (CFStringRef) & __ ## S ## __;
-#define PE_CONST_STRING_DECL(S, V)			\
-static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0xc8, 0x07, 0x00, 0x00}}, (uint8_t *)(V), sizeof(V) - 1}; \
-CF_PRIVATE const CFStringRef S = (CFStringRef) & __ ## S ## __;
-
-#endif
-
 #endif // __CONSTANT_CFSTRINGS__
 
 CF_EXPORT bool __CFOASafe;
diff --git a/CoreFoundation/Base.subproj/CFRuntime.c b/CoreFoundation/Base.subproj/CFRuntime.c
index 8a01c0f..defb761 100644
--- a/CoreFoundation/Base.subproj/CFRuntime.c
+++ b/CoreFoundation/Base.subproj/CFRuntime.c
@@ -1284,6 +1284,7 @@
 
 #if DEPLOYMENT_RUNTIME_SWIFT
 extern void swift_retain(void *);
+extern void swift_release(void *);
 #endif
 
 // For "tryR==true", a return of NULL means "failed".
@@ -1399,7 +1400,6 @@
 static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) {
 #if DEPLOYMENT_RUNTIME_SWIFT
     // We always call through to swift_release, since all CFTypeRefs are at least _NSCFType objects
-    extern void swift_release(void *);
     swift_release((void *)cf);
 #else
 
diff --git a/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h b/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h
index 0f0adb8..5397533 100644
--- a/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h
+++ b/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h
@@ -259,17 +259,17 @@
 typedef __cf_uuid _cf_uuid_t;
 typedef __cf_uuid_string _cf_uuid_string_t;
 
-CF_EXPORT void _cf_uuid_clear(_cf_uuid_t uu);
-CF_EXPORT int _cf_uuid_compare(const _cf_uuid_t uu1, const _cf_uuid_t uu2);
-CF_EXPORT void _cf_uuid_copy(_cf_uuid_t dst, const _cf_uuid_t src);
-CF_EXPORT void _cf_uuid_generate(_cf_uuid_t out);
-CF_EXPORT void _cf_uuid_generate_random(_cf_uuid_t out);
-CF_EXPORT void _cf_uuid_generate_time(_cf_uuid_t out);
-CF_EXPORT int _cf_uuid_is_null(const _cf_uuid_t uu);
-CF_EXPORT int _cf_uuid_parse(const _cf_uuid_string_t in, _cf_uuid_t uu);
-CF_EXPORT void _cf_uuid_unparse(const _cf_uuid_t uu, _cf_uuid_string_t out);
-CF_EXPORT void _cf_uuid_unparse_lower(const _cf_uuid_t uu, _cf_uuid_string_t out);
-CF_EXPORT void _cf_uuid_unparse_upper(const _cf_uuid_t uu, _cf_uuid_string_t out);
+CF_EXPORT void _cf_uuid_clear(_cf_uuid_t _Nonnull uu);
+CF_EXPORT int _cf_uuid_compare(const _cf_uuid_t _Nonnull uu1, const _cf_uuid_t _Nonnull uu2);
+CF_EXPORT void _cf_uuid_copy(_cf_uuid_t _Nonnull dst, const _cf_uuid_t _Nonnull src);
+CF_EXPORT void _cf_uuid_generate(_cf_uuid_t _Nonnull out);
+CF_EXPORT void _cf_uuid_generate_random(_cf_uuid_t _Nonnull out);
+CF_EXPORT void _cf_uuid_generate_time(_cf_uuid_t _Nonnull out);
+CF_EXPORT int _cf_uuid_is_null(const _cf_uuid_t _Nonnull uu);
+CF_EXPORT int _cf_uuid_parse(const _cf_uuid_string_t _Nonnull in, _cf_uuid_t _Nonnull uu);
+CF_EXPORT void _cf_uuid_unparse(const _cf_uuid_t _Nonnull uu, _cf_uuid_string_t _Nonnull out);
+CF_EXPORT void _cf_uuid_unparse_lower(const _cf_uuid_t _Nonnull uu, _cf_uuid_string_t _Nonnull out);
+CF_EXPORT void _cf_uuid_unparse_upper(const _cf_uuid_t _Nonnull uu, _cf_uuid_string_t _Nonnull out);
 
 
 extern CFWriteStreamRef _CFWriteStreamCreateFromFileDescriptor(CFAllocatorRef alloc, int fd);
diff --git a/CoreFoundation/URL.subproj/CFURLComponents.c b/CoreFoundation/URL.subproj/CFURLComponents.c
index c1732e4..5756ea8 100644
--- a/CoreFoundation/URL.subproj/CFURLComponents.c
+++ b/CoreFoundation/URL.subproj/CFURLComponents.c
@@ -74,6 +74,7 @@
     if (instance->_userComponent) CFRelease(instance->_userComponent);
     if (instance->_passwordComponent) CFRelease(instance->_passwordComponent);
     if (instance->_hostComponent) CFRelease(instance->_hostComponent);
+    if (instance->_portComponent) CFRelease(instance->_portComponent);
     if (instance->_pathComponent) CFRelease(instance->_pathComponent);
     if (instance->_queryComponent) CFRelease(instance->_queryComponent);
     if (instance->_fragmentComponent) CFRelease(instance->_fragmentComponent);
@@ -197,10 +198,12 @@
     __CFLock(&components->_lock);
     memory->_lock = CFLockInit;
     memory->_urlString = components->_urlString ? CFStringCreateCopy(alloc, components->_urlString) : NULL;
+    memory->_parseInfo = components->_parseInfo;
     
     memory->_schemeComponentValid = components->_schemeComponentValid;
     memory->_userComponentValid = components->_userComponentValid;
     memory->_hostComponentValid = components->_hostComponentValid;
+    memory->_passwordComponentValid = components->_passwordComponentValid;
     memory->_portComponentValid = components->_portComponentValid;
     memory->_pathComponentValid = components->_pathComponentValid;
     memory->_queryComponentValid = components->_queryComponentValid;
@@ -305,7 +308,9 @@
 CF_EXPORT CFURLRef _CFURLComponentsCopyURLRelativeToURL(CFURLComponentsRef components, CFURLRef relativeToURL) {
     CFStringRef urlString = _CFURLComponentsCopyString(components);
     if (urlString) {
-        return CFURLCreateWithString(kCFAllocatorSystemDefault, urlString, relativeToURL);
+        CFURLRef url = CFURLCreateWithString(kCFAllocatorSystemDefault, urlString, relativeToURL);
+        CFRelease(urlString);
+        return url;
     } else {
         return NULL;
     }
@@ -1135,6 +1140,7 @@
                 CFArrayAppendValue(intermediateResult, entry);
                 CFRelease(entry);
                 CFRelease(nameString);
+                CFRelease(valueString);
             }
             else {
                 // at end of query while parsing the name string
diff --git a/Foundation/Measurement.swift b/Foundation/Measurement.swift
index 12486ec..99f6904 100644
--- a/Foundation/Measurement.swift
+++ b/Foundation/Measurement.swift
@@ -75,7 +75,7 @@
 /// Add two measurements of the same Unit.
 /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
 /// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
-public func +<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
+public func +<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
     if lhs.unit.isEqual(rhs.unit) {
         return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
     } else {
@@ -100,7 +100,7 @@
 /// Subtract two measurements of the same Unit.
 /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
 /// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
-public func -<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
+public func -<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
     if lhs.unit.isEqual(rhs.unit) {
         return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
     } else {
@@ -124,31 +124,31 @@
 
 /// Multiply a measurement by a scalar value.
 /// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
-public func *<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
+public func *<UnitType>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
     return Measurement(value: lhs.value * rhs, unit: lhs.unit)
 }
 
 /// Multiply a scalar value by a measurement.
 /// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
-public func *<UnitType : Unit>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
+public func *<UnitType>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
     return Measurement(value: lhs * rhs.value, unit: rhs.unit)
 }
 
 /// Divide a measurement by a scalar value.
 /// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
-public func /<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
+public func /<UnitType>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
     return Measurement(value: lhs.value / rhs, unit: lhs.unit)
 }
 
 /// Divide a scalar value by a measurement.
 /// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
-public func /<UnitType : Unit>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
+public func /<UnitType>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
     return Measurement(value: lhs / rhs.value, unit: rhs.unit)
 }
 
 /// Compare two measurements of the same `Unit`.
 /// - returns: `true` if `lhs.value == rhs.value && lhs.unit == rhs.unit`.
-public func ==<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
+public func ==<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
     return lhs.value == rhs.value && lhs.unit == rhs.unit
 }
 
@@ -168,7 +168,7 @@
 /// Compare two measurements of the same `Unit`.
 /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
 /// - returns: `lhs.value < rhs.value`
-public func <<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
+public func <<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
     return lhs.value < rhs.value
 }
 
@@ -188,7 +188,7 @@
 /// Compare two measurements of the same `Unit`.
 /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
 /// - returns: `lhs.value > rhs.value`
-public func ><UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
+public func ><UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
     return lhs.value > rhs.value
 }
 
@@ -208,7 +208,7 @@
 /// Compare two measurements of the same `Unit`.
 /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
 /// - returns: `lhs.value <= rhs.value`
-public func <=<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
+public func <=<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
     return lhs.value <= rhs.value
 }
 
@@ -228,7 +228,7 @@
 /// Compare two measurements of the same `Unit`.
 /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
 /// - returns: `lhs.value >= rhs.value`
-public func >=<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
+public func >=<UnitType>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
     return lhs.value >= rhs.value
 }
 
diff --git a/Foundation/NSHTTPCookie.swift b/Foundation/NSHTTPCookie.swift
index b2c629f..358b3df 100644
--- a/Foundation/NSHTTPCookie.swift
+++ b/Foundation/NSHTTPCookie.swift
@@ -184,10 +184,8 @@
     /// <tr>
     ///     <td>HTTPCookiePropertyKey.path</td>
     ///     <td>NSString</td>
-    ///     <td>NO</td>
-    ///     <td>Path for the cookie. Inferred from the value for
-    ///     HTTPCookiePropertyKey.originURL if not provided. Default is "/".
-    ///     </td>
+    ///     <td>YES</td>
+    ///     <td>Path for the cookie</td>
     /// </tr>
     /// <tr>
     ///     <td>HTTPCookiePropertyKey.port</td>
diff --git a/Foundation/NSJSONSerialization.swift b/Foundation/NSJSONSerialization.swift
index 36120e3..5aff5b2 100644
--- a/Foundation/NSJSONSerialization.swift
+++ b/Foundation/NSJSONSerialization.swift
@@ -284,6 +284,8 @@
 //MARK: - JSONSerializer
 private struct JSONWriter {
     
+    private let maxUIntLength = String(describing: UInt.max).characters.count
+    private let maxIntLength = String(describing: Int.max).characters.count
     var indent = 0
     let pretty: Bool
     let writer: (String?) -> Void
@@ -309,6 +311,10 @@
             try serializeString(str)
         case let boolValue as Bool:
             serializeBool(boolValue)
+        case let num as Int:
+            try serializeInt(value: num)
+        case let num as UInt:
+            try serializeUInt(value: num)
         case let array as Array<Any>:
             try serializeArray(array)
         case let dict as Dictionary<AnyHashable, Any>:
@@ -322,6 +328,92 @@
         }
     }
 
+    private func serializeUInt(value: UInt) throws {
+        if value == 0 {
+            writer("0")
+            return
+        }
+        var array: [UInt] = []
+        var stringResult = ""
+        //Maximum length of an UInt
+        array.reserveCapacity(maxUIntLength)
+        stringResult.reserveCapacity(maxUIntLength)
+        var number = value
+        
+        while number != 0 {
+            array.append(number % 10)
+            number /= 10
+        }
+        
+        /*
+         Step backwards through the array and append the values to the string. This way the values are appended in the correct order.
+         */
+        var counter = array.count
+        while counter > 0 {
+            counter -= 1
+            let digit: UInt = array[counter]
+            switch digit {
+            case 0: stringResult.append("0")
+            case 1: stringResult.append("1")
+            case 2: stringResult.append("2")
+            case 3: stringResult.append("3")
+            case 4: stringResult.append("4")
+            case 5: stringResult.append("5")
+            case 6: stringResult.append("6")
+            case 7: stringResult.append("7")
+            case 8: stringResult.append("8")
+            case 9: stringResult.append("9")
+            default: fatalError()
+            }
+        }
+        
+        writer(stringResult)
+    }
+    
+    private func serializeInt(value: Int) throws {
+        if value == 0 {
+            writer("0")
+            return
+        }
+        var array: [Int] = []
+        var stringResult = ""
+        array.reserveCapacity(maxIntLength)
+        //Account for a negative sign
+        stringResult.reserveCapacity(maxIntLength + 1)
+        var number = value
+        
+        while number != 0 {
+            array.append(number % 10)
+            number /= 10
+        }
+        //If negative add minus sign before adding any values
+        if value < 0 {
+            stringResult.append("-")
+        }
+        /*
+         Step backwards through the array and append the values to the string. This way the values are appended in the correct order.
+         */
+        var counter = array.count
+        while counter > 0 {
+            counter -= 1
+            let digit = array[counter]
+            switch digit {
+            case 0: stringResult.append("0")
+            case 1, -1: stringResult.append("1")
+            case 2, -2: stringResult.append("2")
+            case 3, -3: stringResult.append("3")
+            case 4, -4: stringResult.append("4")
+            case 5, -5: stringResult.append("5")
+            case 6, -6: stringResult.append("6")
+            case 7, -7: stringResult.append("7")
+            case 8, -8: stringResult.append("8")
+            case 9, -9: stringResult.append("9")
+            default: fatalError()
+            }
+        }
+        writer(stringResult)
+    }
+    
     func serializeString(_ str: String) throws {
         writer("\"")
         for scalar in str.unicodeScalars {
diff --git a/Foundation/NSKeyedArchiver.swift b/Foundation/NSKeyedArchiver.swift
index ccf7ad8..40fc5a5 100644
--- a/Foundation/NSKeyedArchiver.swift
+++ b/Foundation/NSKeyedArchiver.swift
@@ -376,7 +376,7 @@
         if objv == nil {
             return true // always have a null reference
         } else {
-            return self._objRefMap[_SwiftValue.store(objv)] != nil
+            return self._objRefMap[_SwiftValue.store(objv!)] != nil
         }
     }
     
@@ -612,7 +612,7 @@
 
             if _isContainer(object) {
                 guard let codable = object as? NSCoding else {
-                    fatalError("Object \(object) does not conform to NSCoding")
+                    fatalError("Object \(String(describing: object)) does not conform to NSCoding")
                 }
 
                 let innerEncodingContext = EncodingContext()
diff --git a/Foundation/NSKeyedUnarchiver.swift b/Foundation/NSKeyedUnarchiver.swift
index e29bed7..c8feeb5 100644
--- a/Foundation/NSKeyedUnarchiver.swift
+++ b/Foundation/NSKeyedUnarchiver.swift
@@ -387,7 +387,7 @@
         }
         
         // check replacement cache
-        object = self._replacementMap[_SwiftValue.store(decodedObject)]
+        object = self._replacementMap[_SwiftValue.store(decodedObject!)]
         if object != nil {
             return object
         }
@@ -454,7 +454,7 @@
 
                 guard let classReference = innerDecodingContext.dict["$class"] as? _NSKeyedArchiverUID else {
                     throw _decodingError(CocoaError.coderReadCorrupt,
-                                         withDescription: "Invalid class reference \(innerDecodingContext.dict["$class"]). The data may be corrupt.")
+                                         withDescription: "Invalid class reference \(String(describing: innerDecodingContext.dict["$class"])). The data may be corrupt.")
                 }
 
                 var classToConstruct : AnyClass? = try _validateAndMapClassReference(classReference,
diff --git a/Foundation/NSLocale.swift b/Foundation/NSLocale.swift
index 52becd1..6bc7873 100644
--- a/Foundation/NSLocale.swift
+++ b/Foundation/NSLocale.swift
@@ -97,7 +97,7 @@
     open class var availableLocaleIdentifiers: [String] {
         var identifiers = Array<String>()
         for obj in CFLocaleCopyAvailableLocaleIdentifiers()._nsObject {
-            identifiers.append((obj as! NSString)._swiftObject)
+            identifiers.append(obj as! String)
         }
         return identifiers
     }
diff --git a/Foundation/NSMeasurementFormatter.swift b/Foundation/NSMeasurementFormatter.swift
index cf0d89a..8fc04d5 100644
--- a/Foundation/NSMeasurementFormatter.swift
+++ b/Foundation/NSMeasurementFormatter.swift
@@ -79,5 +79,5 @@
 }
 
 extension MeasurementFormatter {
-    public func string<UnitType : Unit>(from measurement: Measurement<UnitType>) -> String { NSUnimplemented() }
+    public func string<UnitType>(from measurement: Measurement<UnitType>) -> String { NSUnimplemented() }
 }
diff --git a/Foundation/NSString.swift b/Foundation/NSString.swift
index 7f2d181..48d766d 100644
--- a/Foundation/NSString.swift
+++ b/Foundation/NSString.swift
@@ -286,7 +286,7 @@
     internal var _fastContents: UnsafePointer<UniChar>? {
         if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
             if !_storage._core.isASCII {
-                return unsafeBitCast(_storage._core.startUTF16, to: UnsafePointer<UniChar>.self)
+                return UnsafePointer<UniChar>(_storage._core.startUTF16)
             }
         }
         return nil
diff --git a/Foundation/ReferenceConvertible.swift b/Foundation/ReferenceConvertible.swift
index f0916bf..b640056 100644
--- a/Foundation/ReferenceConvertible.swift
+++ b/Foundation/ReferenceConvertible.swift
@@ -11,7 +11,7 @@
 /// Decorates types which are backed by a Foundation reference type.
 ///
 /// All `ReferenceConvertible` types are hashable, equatable, and provide description functions.
-public protocol ReferenceConvertible : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable {
+public protocol ReferenceConvertible : CustomStringConvertible, CustomDebugStringConvertible, Hashable {
     associatedtype ReferenceType : NSObject, NSCopying
 }
 
diff --git a/Foundation/UUID.swift b/Foundation/UUID.swift
index a794744..269a9a2 100644
--- a/Foundation/UUID.swift
+++ b/Foundation/UUID.swift
@@ -24,14 +24,18 @@
     /* Create a new UUID with RFC 4122 version 4 random bytes */
     public init() {
         withUnsafeMutablePointer(to: &uuid) {
-            _cf_uuid_generate_random(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self))
+            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
+                _cf_uuid_generate_random($0)
+            }
         }
     }
     
     fileprivate init(reference: NSUUID) {
         var bytes: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
         withUnsafeMutablePointer(to: &bytes) {
-            reference.getBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self))
+            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
+                reference.getBytes($0)
+            }
         }
         uuid = bytes
     }
@@ -41,7 +45,9 @@
     /// Returns nil for invalid strings.
     public init?(uuidString string: String) {
         let res = withUnsafeMutablePointer(to: &uuid) {
-            return _cf_uuid_parse(string, unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self))
+            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
+                return _cf_uuid_parse(string, $0)
+            }
         }
         if res != 0 {
             return nil
@@ -57,10 +63,14 @@
     public var uuidString: String {
         var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
         var localValue = uuid
-        return withUnsafeMutablePointer(to: &localValue) { val in
-            withUnsafeMutablePointer(to: &bytes) { str in
-                _cf_uuid_unparse(unsafeBitCast(val, to: UnsafePointer<UInt8>.self), unsafeBitCast(str, to: UnsafeMutablePointer<Int8>.self))
-                return String(cString: unsafeBitCast(str, to: UnsafePointer<CChar>.self), encoding: .utf8)!
+        return withUnsafeMutablePointer(to: &localValue) { valPtr in
+            valPtr.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) { val in
+                withUnsafeMutablePointer(to: &bytes) { strPtr in
+                    strPtr.withMemoryRebound(to: CChar.self, capacity: MemoryLayout<uuid_string_t>.size) { str in
+                        _cf_uuid_unparse(val, str)
+                        return String(cString: str, encoding: .utf8)!
+                    }
+                }
             }
         }
     }
@@ -68,7 +78,9 @@
     public var hashValue: Int {
         var localValue = uuid
         return withUnsafeMutablePointer(to: &localValue) {
-            return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(MemoryLayout<uuid_t>.size)))
+            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
+                return Int(bitPattern: CFHashBytes($0, CFIndex(MemoryLayout<uuid_t>.size)))
+            }
         }
     }
     
@@ -85,7 +97,9 @@
     fileprivate var reference: NSUUID {
         var bytes = uuid
         return withUnsafePointer(to: &bytes) {
-            return NSUUID(uuidBytes: unsafeBitCast($0, to: UnsafePointer<UInt8>.self))
+            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
+                return NSUUID(uuidBytes: $0)
+            }
         }
     }
     
diff --git a/TestFoundation/TestNSJSONSerialization.swift b/TestFoundation/TestNSJSONSerialization.swift
index 0e4e09f..86616f9 100644
--- a/TestFoundation/TestNSJSONSerialization.swift
+++ b/TestFoundation/TestNSJSONSerialization.swift
@@ -863,6 +863,10 @@
             ("test_nested_array", test_nested_array),
             ("test_nested_dictionary", test_nested_dictionary),
             ("test_serialize_number", test_serialize_number),
+            ("test_serialize_IntMax", test_serialize_IntMax),
+            ("test_serialize_IntMin", test_serialize_IntMin),
+            ("test_serialize_UIntMax", test_serialize_UIntMax),
+            ("test_serialize_UIntMin", test_serialize_UIntMin),
             ("test_serialize_stringEscaping", test_serialize_stringEscaping),
             ("test_jsonReadingOffTheEndOfBuffers", test_jsonReadingOffTheEndOfBuffers),
             ("test_jsonObjectToOutputStreamBuffer", test_jsonObjectToOutputStreamBuffer),
@@ -1054,6 +1058,26 @@
         XCTAssertEqual(try trySerialize(json), "[false,true]")
     }
     
+    func test_serialize_IntMax() {
+        let json: [Any] = [Int.max]
+        XCTAssertEqual(try trySerialize(json), "[\(Int.max)]")
+    }
+    
+    func test_serialize_IntMin() {
+        let json: [Any] = [Int.min]
+        XCTAssertEqual(try trySerialize(json), "[\(Int.min)]")
+    }
+    
+    func test_serialize_UIntMax() {
+        let json: [Any] = [UInt.max]
+        XCTAssertEqual(try trySerialize(json), "[\(UInt.max)]")
+    }
+    
+    func test_serialize_UIntMin() {
+        let json: [Any] = [UInt.min]
+        XCTAssertEqual(try trySerialize(json), "[\(UInt.min)]")
+    }
+    
     func test_serialize_stringEscaping() {
         var json = ["foo"]
         XCTAssertEqual(try trySerialize(json), "[\"foo\"]")
diff --git a/TestFoundation/TestNSLocale.swift b/TestFoundation/TestNSLocale.swift
index a061c03..bfd69ad 100644
--- a/TestFoundation/TestNSLocale.swift
+++ b/TestFoundation/TestNSLocale.swift
@@ -20,7 +20,8 @@
         return [
             ("test_constants", test_constants),
             ("test_Identifier", test_Identifier),
-            ("test_copy", test_copy)
+            ("test_copy", test_copy),
+            ("test_availableIdentifiers", test_availableIdentifiers),
         ]
     }
 
@@ -107,4 +108,8 @@
 
         XCTAssertTrue(locale == localeCopy)
     }
+
+     func test_availableIdentifiers() {
+        XCTAssertNoThrow(Locale.availableIdentifiers)
+    }
 }
diff --git a/TestFoundation/TestNSURL.swift b/TestFoundation/TestNSURL.swift
index 02a0a35..92caef7 100644
--- a/TestFoundation/TestNSURL.swift
+++ b/TestFoundation/TestNSURL.swift
@@ -158,7 +158,7 @@
                         differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(testedValue)'")
                     }
                 } else {
-                    differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(got[key])'")
+                    differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(String(describing: got[key]))'")
                 }
             } else if let expectedValue = obj as? [String] {
                 if let testedValue = got[key] as? [String] {
@@ -166,7 +166,7 @@
                         differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(testedValue)'")
                     }
                 } else {
-                    differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(got[key])'")
+                    differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(String(describing: got[key]))'")
                 }
             } else if let expectedValue = obj as? Int {
                 if let testedValue = got[key] as? Int {
@@ -174,7 +174,7 @@
                         differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(testedValue)'")
                     }
                 } else {
-                    differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(got[key])'")
+                    differences.append(" \(key)  Expected = '\(expectedValue)',  Got = '\(String(describing: got[key]))'")
                 }
             }
             
diff --git a/TestFoundation/TestNSURLSession.swift b/TestFoundation/TestNSURLSession.swift
index 022c601..b8bca88 100644
--- a/TestFoundation/TestNSURLSession.swift
+++ b/TestFoundation/TestNSURLSession.swift
@@ -428,7 +428,7 @@
 
 extension DataTask : URLSessionTaskDelegate {
     public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
-         guard let e = error as? URLError else { return }
+         guard (error as? URLError) != nil else { return }
          dataTaskExpectation.fulfill()
          if let cancellation = cancelExpectation {
              cancellation.fulfill()
diff --git a/TestFoundation/TestNSXMLDocument.swift b/TestFoundation/TestNSXMLDocument.swift
index 2cac5cb..68e9bdb 100644
--- a/TestFoundation/TestNSXMLDocument.swift
+++ b/TestFoundation/TestNSXMLDocument.swift
@@ -36,8 +36,8 @@
                 ("test_processingInstruction", test_processingInstruction),
                 ("test_parseXMLString", test_parseXMLString),
                 ("test_prefixes", test_prefixes),
-                ("test_validation_success", test_validation_success),
-                ("test_validation_failure", test_validation_failure),
+                //                ("test_validation_success", test_validation_success),
+                //                ("test_validation_failure", test_validation_failure),
                 ("test_dtd", test_dtd),
                 ("test_documentWithDTD", test_documentWithDTD),
                 ("test_dtd_attributes", test_dtd_attributes)
@@ -56,7 +56,7 @@
                 ("test_processingInstruction", test_processingInstruction),
                 ("test_parseXMLString", test_parseXMLString),
                 ("test_prefixes", test_prefixes),
-                ("test_validation_success", test_validation_success),
+                //                ("test_validation_success", test_validation_success),
                 //                ("test_validation_failure", test_validation_failure),
                 ("test_dtd", test_dtd),
                 //                ("test_documentWithDTD", test_documentWithDTD),
@@ -67,9 +67,9 @@
 
     func test_basicCreation() {
         let doc = XMLDocument(rootElement: nil)
-        XCTAssert(doc.version == "1.0", "expected 1.0, got \(doc.version)")
+        XCTAssert(doc.version == "1.0", "expected 1.0, got \(String(describing: doc.version))")
         doc.version = "1.1"
-        XCTAssert(doc.version == "1.1", "expected 1.1, got \(doc.version)")
+        XCTAssert(doc.version == "1.1", "expected 1.1, got \(String(describing: doc.version))")
         let node = XMLElement(name: "Hello", uri: "http://www.example.com")
 
         doc.setRootElement(node)
@@ -289,6 +289,8 @@
         XCTAssertEqual(element.localName, "root")
     }
 
+    /*
+     * <rdar://31567922> Re-enable these tests in a way that does not depend on the internet.
     func test_validation_success() throws {
         let validString = "<?xml version=\"1.0\" standalone=\"yes\"?><!DOCTYPE foo [ <!ELEMENT foo (#PCDATA)> ]><foo>Hello world</foo>"
         do {
@@ -330,7 +332,7 @@
         } catch let error as NSError {
             XCTAssert((error.userInfo[NSLocalizedDescriptionKey] as! String).contains("Element true was declared EMPTY this one has content"))
         }
-    }
+    }*/
 
     func test_dtd() throws {
         let node = XMLNode.dtdNode(withXMLString:"<!ELEMENT foo (#PCDATA)>") as! XMLDTDNode