         return NSUTF8StringEncoding
     }
     
-    static func parseBOM(bytes: UnsafePointer<UInt8>, length: Int) -> NSStringEncoding? {
+    static func parseBOM(bytes: UnsafePointer<UInt8>, length: Int) -> (encoding: NSStringEncoding, skipLength: Int)? {
         if length >= 2 {
             switch (bytes[0], bytes[1]) {
             case (0xEF, 0xBB):
                 if length >= 3 && bytes[2] == 0xBF {
-                    return NSUTF8StringEncoding
+                    return (NSUTF8StringEncoding, 3)
                 }
             case (0x00, 0x00):
                 if length >= 4 && bytes[2] == 0xFE && bytes[3] == 0xFF {
-                    return NSUTF32BigEndianStringEncoding
+                    return (NSUTF32BigEndianStringEncoding, 4)
                 }
             case (0xFF, 0xFE):
                 if length >= 4 && bytes[2] == 0 && bytes[3] == 0 {
-                    return NSUTF32LittleEndianStringEncoding
-                }
-                return NSUTF16LittleEndianStringEncoding
+                    return (NSUTF32LittleEndianStringEncoding, 4)
+                }
+                return (NSUTF16LittleEndianStringEncoding, 2)
             case (0xFE, 0xFF):
-                return NSUTF16BigEndianStringEncoding
+                return (NSUTF16BigEndianStringEncoding, 2)
             default:
                 break
             }

}

//MARK: - JSONDeserializer
private struct JSONDeserializer {
    
    struct UnicodeParser {
        let view: String.UnicodeScalarView
        let index: String.UnicodeScalarIndex
        
        init(view: String.UnicodeScalarView, index: String.UnicodeScalarIndex) {
            self.view = view
            self.index = index
        }
        
        init(viewSkippingBOM view: String.UnicodeScalarView) {
            if view.startIndex < view.endIndex && view[view.startIndex] == UnicodeScalar(0xFEFF) {
                self.init(view: view, index: view.startIndex.successor())
                return
            }
            self.init(view: view, index: view.startIndex)
        }
        
        func successor() -> UnicodeParser {
            return UnicodeParser(view: view, index: index.successor())
        }
        
        var distanceFromStart: String.UnicodeScalarIndex.Distance {
            return view.startIndex.distanceTo(index)
        }
    }

    static let whitespaceScalars = [
        UnicodeScalar(0x09), // Horizontal tab
        UnicodeScalar(0x0A), // Line feed or New line
        UnicodeScalar(0x0D), // Carriage return
        UnicodeScalar(0x20), // Space
    ]

    static func consumeWhitespace(parser: UnicodeParser) -> UnicodeParser? {
        var index = parser.index
        let view = parser.view
        let endIndex = view.endIndex
        while index < endIndex && whitespaceScalars.contains(view[index]) {
            index = index.successor()
        }
        return UnicodeParser(view: view, index: index)
    }
    
    struct StructureScalar {
        static let BeginArray: UnicodeScalar     = "["
        static let EndArray: UnicodeScalar       = "]"
        static let BeginObject: UnicodeScalar    = "{"
        static let EndObject: UnicodeScalar      = "}"
        static let NameSeparator: UnicodeScalar  = ":"
        static let ValueSeparator: UnicodeScalar = ","
    }
    
    static func consumeStructure(scalar: UnicodeScalar, input: UnicodeParser) throws -> UnicodeParser? {
        return try consumeWhitespace(input).flatMap(consumeScalar(scalar)).flatMap(consumeWhitespace)
    }
    
    static func consumeScalar(scalar: UnicodeScalar) -> (UnicodeParser) throws -> UnicodeParser? {
        return { (parser: UnicodeParser) throws -> UnicodeParser? in
            switch takeScalar(parser) {
            case nil:
                throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [
                    "NSDebugDescription" : "Unexpected end of file during JSON parse."
                ])
            case let (taken, parser)? where taken == scalar:
                return parser
            default:
                return nil
            }
        }
    }
    
    static func consumeSequence(sequence: String, input: UnicodeParser) throws -> UnicodeParser? {
        var parser = input
        for scalar in sequence.unicodeScalars {
            guard let newParser = try consumeScalar(scalar)(parser) else {
                return nil
            }
            parser = newParser
        }
        return parser
    }
    
    static func takeScalar(input: UnicodeParser) -> (UnicodeScalar, UnicodeParser)? {
        guard input.index < input.view.endIndex else {
            return nil
        }
        return (input.view[input.index], input.successor())
    }
    
    static func takeMatching(match: (UnicodeScalar) -> Bool) -> (String, UnicodeParser) -> (String, UnicodeParser)? {
        return { input, parser in
            guard let (scalar, parser) = takeScalar(parser) where match(scalar) else {
                return nil
            }
            return (input + String(scalar), parser)
        }
    }

    //MARK: - String Parsing
    struct StringScalar{
        static let QuotationMark: UnicodeScalar = "\""
        static let Escape: UnicodeScalar        = "\\"
    }
    
    static func parseString(input: UnicodeParser) throws -> (String, UnicodeParser)? {
        guard let begin = try consumeScalar(StringScalar.QuotationMark)(input) else {
            return nil
        }
        let view = begin.view
        let endIndex = view.endIndex
        var index = begin.index
        var value = String.UnicodeScalarView()
        while index < endIndex {
            let scalar = view[index]
            index = index.successor()
            
            switch scalar {
            case StringScalar.QuotationMark:
                return (String(value), UnicodeParser(view: view, index: index))
            case StringScalar.Escape:
                let parser = UnicodeParser(view: view, index: index)
                if let (escaped, newParser) = try parseEscapeSequence(parser) {
                    value.append(escaped)
                    index = newParser.index
                }
                else {
                    throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [
                        "NSDebugDescription" : "Invalid unicode escape sequence at position \(parser.distanceFromStart - 1)"
                    ])
                }
            default:
                value.append(scalar)
            }
        }
        throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [
            "NSDebugDescription" : "Unexpected end of file during string parse."
        ])
    }
    
    static func parseEscapeSequence(input: UnicodeParser) throws -> (UnicodeScalar, UnicodeParser)? {
        guard let (scalar, parser) = takeScalar(input) else {
            throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [
                "NSDebugDescription" : "Early end of unicode escape sequence around character"
            ])
        }
        switch scalar {
        case "\"", "\\", "/":
            return (scalar, parser)
        case "b":
            return (UnicodeScalar(0x08), parser)
        case "f":
            return (UnicodeScalar(0x0C), parser)
        case "n":
            return (UnicodeScalar(0x0A), parser)
        case "r":
            return (UnicodeScalar(0x0D), parser)
        case "t":
            return (UnicodeScalar(0x09), parser)
        case "u":
            return try parseUnicodeSequence(parser)
        default:
            return nil
        }
    }
    
    static func parseUnicodeSequence(input: UnicodeParser) throws -> (UnicodeScalar, UnicodeParser)? {
        
        guard let (codeUnit, parser) = parseCodeUnit(input) else {
            return nil
        }
        
        if !UTF16.isLeadSurrogate(codeUnit) {
            return (UnicodeScalar(codeUnit), parser)
        }
        
        guard let (trailCodeUnit, finalParser) = try consumeSequence("\\u", input: parser).flatMap(parseCodeUnit) where UTF16.isTrailSurrogate(trailCodeUnit) else {
            throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.PropertyListReadCorruptError.rawValue, userInfo: [
                "NSDebugDescription" : "Unable to convert unicode escape sequence (no low-surrogate code point) to UTF8-encoded character at position \(parser.distanceFromStart)"
            ])
        }
        
        let highValue = (UInt32(codeUnit  - 0xD800) << 10)
        let lowValue  =  UInt32(trailCodeUnit - 0xDC00)
        return (UnicodeScalar(highValue + lowValue + 0x10000), finalParser)
    }
    
    static let hexScalars = [
        UnicodeScalar(0x30), UnicodeScalar(0x31), // 0, 1
        UnicodeScalar(0x32), UnicodeScalar(0x33), // 2, 3
        UnicodeScalar(0x34), UnicodeScalar(0x35), // 4, 5
        UnicodeScalar(0x36), UnicodeScalar(0x37), // 6, 7
        UnicodeScalar(0x38), UnicodeScalar(0x39), // 8, 9
        UnicodeScalar(0x41), UnicodeScalar(0x61), // A, a
        UnicodeScalar(0x42), UnicodeScalar(0x62), // B, b
        UnicodeScalar(0x43), UnicodeScalar(0x63), // C, c
        UnicodeScalar(0x44), UnicodeScalar(0x64), // D, d
        UnicodeScalar(0x45), UnicodeScalar(0x65), // E, e
        UnicodeScalar(0x46), UnicodeScalar(0x66), // F, f
    ]
    static func parseCodeUnit(input: UnicodeParser) -> (UTF16.CodeUnit, UnicodeParser)? {
        let hexParser = takeMatching(hexScalars.contains)
        guard let (result, parser) = hexParser("", input).flatMap(hexParser).flatMap(hexParser).flatMap(hexParser),
            let value = Int(result, radix: 16) else {
                return nil
        }
        return (UTF16.CodeUnit(value), parser)
    }
    
    //MARK: - Number parsing
    static let numberScalars = [
        UnicodeScalar(0x2B), // +
        UnicodeScalar(0x2D), // -
        UnicodeScalar(0x2E), // .
        UnicodeScalar(0x30), // 0
        UnicodeScalar(0x31), // 1
        UnicodeScalar(0x32), // 2
        UnicodeScalar(0x33), // 3
        UnicodeScalar(0x34), // 4
        UnicodeScalar(0x35), // 5
        UnicodeScalar(0x36), // 6
        UnicodeScalar(0x37), // 7
        UnicodeScalar(0x38), // 8
        UnicodeScalar(0x39), // 9
        UnicodeScalar(0x45), // E
        UnicodeScalar(0x65), // e
    ]
    static func parseNumber(input: UnicodeParser) throws -> (Double, UnicodeParser)? {
        let view = input.view
        let endIndex = view.endIndex
        var index = input.index
        var value = String.UnicodeScalarView()
        while index < endIndex && numberScalars.contains(view[index]) {
            value.append(view[index])
            index = index.successor()
        }
        guard value.count > 0, let result = Double(String(value)) else {
            return nil
        }
        return (result, UnicodeParser(view: view, index: index))
    }

    //MARK: - Value parsing
    static func parseValue(input: UnicodeParser) throws -> (Any, UnicodeParser)? {
        if let (value, parser) = try parseString(input) {
            return (value, parser)
        }
        else if let parser = try consumeSequence("true", input: input) {
            return (true, parser)
        }
        else if let parser = try consumeSequence("false", input: input) {
            return (false, parser)
        }
        else if let parser = try consumeSequence("null", input: input) {
            return (NSNull(), parser)
        }
        else if let (object, parser) = try parseObject(input) {

    }
}

//MARK: - Encoding Detection

internal extension NSJSONSerialization {
    
    /// Detect the encoding format of the NSData contents
    class func detectEncoding(bytes: UnsafePointer<UInt8>, _ length: Int) -> NSStringEncoding {

        if length >= 4 {
            switch (bytes[0], bytes[1], bytes[2], bytes[3]) {
            case (0, 0, 0, _):
