diff --git a/.gitignore b/.gitignore index 79b16009..785f83b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ .DS_Store +*.lock +*.resolved +/build /.build /Packages /*.xcodeproj diff --git a/.swift-version b/.swift-version index 8c50098d..5186d070 100644 --- a/.swift-version +++ b/.swift-version @@ -1 +1 @@ -3.1 +4.0 diff --git a/.travis.yml b/.travis.yml index daa20f53..12c35dcc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,8 @@ os: - linux - - osx language: generic sudo: false dist: trusty -osx_image: xcode8.3 addons: apt: sources: diff --git a/Package.pins b/Package.pins deleted file mode 100644 index e0570d6a..00000000 --- a/Package.pins +++ /dev/null @@ -1,5 +0,0 @@ -{ - "autoPin": false, - "pins": [], - "version": 1 -} diff --git a/Package.swift b/Package.swift index 26c208c2..4341d25e 100644 --- a/Package.swift +++ b/Package.swift @@ -1,21 +1,31 @@ -// swift-tools-version:3.1 +// swift-tools-version:4.0 import PackageDescription let package = Package( name: "Zewo", - targets: [ - Target(name: "CYAJL"), - Target(name: "CHTTPParser"), - - Target(name: "Core"), - Target(name: "IO", dependencies: ["Core"]), - Target(name: "Content", dependencies: ["CYAJL", "Core"]), - Target(name: "HTTP", dependencies: ["Content", "IO", "CHTTPParser"]), + products: [ + .library(name: "Zewo", targets: ["CYAJL", "CHTTPParser", "Core", "IO", "Media", "HTTP", "Zewo"]) ], dependencies: [ - .Package(url: "https://github.com/Zewo/Venice.git", majorVersion: 0, minor: 19), - .Package(url: "https://github.com/Zewo/CBtls.git", majorVersion: 1), - .Package(url: "https://github.com/Zewo/CLibreSSL.git", majorVersion: 3), + .package(url: "https://github.com/Zewo/CLibdill.git", .branch("swift-4")), + .package(url: "https://github.com/Zewo/Venice.git", .branch("swift-4")), + .package(url: "https://github.com/Zewo/CBtls.git", .branch("swift-4")), + .package(url: "https://github.com/Zewo/CLibreSSL.git", .branch("swift-4")), + ], + targets: [ + .target(name: "CYAJL"), + .target(name: "CHTTPParser"), + + .target(name: "Core", dependencies: ["Venice"]), + .target(name: "IO", dependencies: ["Core"]), + .target(name: "Media", dependencies: ["Core", "CYAJL"]), + .target(name: "HTTP", dependencies: ["Media", "IO", "CHTTPParser"]), + .target(name: "Zewo", dependencies: ["Core", "IO", "Media", "HTTP"]), + + .testTarget(name: "CoreTests", dependencies: ["Core"]), + .testTarget(name: "IOTests", dependencies: ["IO"]), + .testTarget(name: "MediaTests", dependencies: ["Media"]), + .testTarget(name: "HTTPTests", dependencies: ["HTTP"]), ] ) diff --git a/README.md b/README.md index e8cf0cef..cca725b2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

- Swift + Swift License Slack Travis @@ -70,5 +70,4 @@ All **Zewo** modules are released under the MIT license. See [LICENSE](LICENSE) [slack-image]: http://s13.postimg.org/ybwy92ktf/Slack.png [slack-url]: http://slack.zewo.io -[codecov-url]: https://codecov.io/gh/Zewo/Zewo -[codecov-sunburst]: https://codecov.io/gh/Zewo/Zewo/branch/master/graphs/sunburst.svg + diff --git a/Sources/CHTTPParser/http_parser.c b/Sources/CHTTPParser/http_parser.c index 24b9f05b..50469a14 100755 --- a/Sources/CHTTPParser/http_parser.c +++ b/Sources/CHTTPParser/http_parser.c @@ -77,13 +77,13 @@ do { \ /* Run the notify callback FOR, returning ER if it fails */ -#define CALLBACK_NOTIFY_(FOR, ER) \ +#define CALLBACK_NOTIFY_(FOR, ER, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ if (LIKELY(settings->on_##FOR)) { \ parser->state = CURRENT_STATE(); \ - if (UNLIKELY(0 != settings->on_##FOR(parser))) { \ + if (UNLIKELY(0 != settings->on_##FOR(parser, (METHOD), (STATUS_CODE), (HTTP_MAJOR), (HTTP_MINOR)))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ UPDATE_STATE(parser->state); \ @@ -96,13 +96,13 @@ do { \ } while (0) /* Run the notify callback FOR and consume the current byte */ -#define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) +#define CALLBACK_NOTIFY(FOR, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) CALLBACK_NOTIFY_(FOR, p - data + 1, (METHOD), (STATUS_CODE), (HTTP_MAJOR), (HTTP_MINOR)) /* Run the notify callback FOR and don't consume the current byte */ -#define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) +#define CALLBACK_NOTIFY_NOADVANCE(FOR, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) CALLBACK_NOTIFY_(FOR, p - data, (METHOD), (STATUS_CODE), (HTTP_MAJOR), (HTTP_MINOR)) -/* Run data callback FOR with LEN bytes, returning ER if it fails */ -#define CALLBACK_DATA_(FOR, LEN, ER) \ +/* Run data callback FOR with LEN bytes, returning ER if it fails (long version)*/ +#define CALLBACK_DATA_(FOR, LEN, ER, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) \ do { \ assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ \ @@ -110,7 +110,7 @@ do { \ if (LIKELY(settings->on_##FOR)) { \ parser->state = CURRENT_STATE(); \ if (UNLIKELY(0 != \ - settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \ + settings->on_##FOR(parser, FOR##_mark, (LEN), (METHOD), (STATUS_CODE), (HTTP_MAJOR), (HTTP_MINOR)))) { \ SET_ERRNO(HPE_CB_##FOR); \ } \ UPDATE_STATE(parser->state); \ @@ -125,12 +125,12 @@ do { \ } while (0) /* Run the data callback FOR and consume the current byte */ -#define CALLBACK_DATA(FOR) \ - CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) +#define CALLBACK_DATA(FOR, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) \ +CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) /* Run the data callback FOR and don't consume the current byte */ -#define CALLBACK_DATA_NOADVANCE(FOR) \ - CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) +#define CALLBACK_DATA_NOADVANCE(FOR, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) \ +CALLBACK_DATA_(FOR, p - FOR##_mark, p - data, METHOD, STATUS_CODE, HTTP_MAJOR, HTTP_MINOR) /* Set the mark FOR; non-destructive if mark is already set */ #define MARK(FOR) \ @@ -658,7 +658,7 @@ size_t http_parser_execute (http_parser *parser, /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if * we got paused. */ - CALLBACK_NOTIFY_NOADVANCE(message_complete); + CALLBACK_NOTIFY_NOADVANCE(message_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); return 0; case s_dead: @@ -728,7 +728,7 @@ size_t http_parser_execute (http_parser *parser, if (ch == 'H') { UPDATE_STATE(s_res_or_resp_H); - CALLBACK_NOTIFY(message_begin); + CALLBACK_NOTIFY(message_begin, parser->method, parser->status_code, parser->http_major, parser->http_minor); } else { parser->type = HTTP_REQUEST; UPDATE_STATE(s_start_req); @@ -774,7 +774,7 @@ size_t http_parser_execute (http_parser *parser, goto error; } - CALLBACK_NOTIFY(message_begin); + CALLBACK_NOTIFY(message_begin, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } @@ -934,13 +934,13 @@ size_t http_parser_execute (http_parser *parser, case s_res_status: if (ch == CR) { UPDATE_STATE(s_res_line_almost_done); - CALLBACK_DATA(status); + CALLBACK_DATA(status, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } if (ch == LF) { UPDATE_STATE(s_header_field_start); - CALLBACK_DATA(status); + CALLBACK_DATA(status, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } @@ -989,7 +989,7 @@ size_t http_parser_execute (http_parser *parser, } UPDATE_STATE(s_req_method); - CALLBACK_NOTIFY(message_begin); + CALLBACK_NOTIFY(message_begin, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } @@ -1102,7 +1102,7 @@ size_t http_parser_execute (http_parser *parser, switch (ch) { case ' ': UPDATE_STATE(s_req_http_start); - CALLBACK_DATA(url); + CALLBACK_DATA(url, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; case CR: case LF: @@ -1111,7 +1111,7 @@ size_t http_parser_execute (http_parser *parser, UPDATE_STATE((ch == CR) ? s_req_line_almost_done : s_header_field_start); - CALLBACK_DATA(url); + CALLBACK_DATA(url, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; default: UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); @@ -1421,7 +1421,7 @@ size_t http_parser_execute (http_parser *parser, if (ch == ':') { UPDATE_STATE(s_header_value_discard_ws); - CALLBACK_DATA(header_field); + CALLBACK_DATA(header_field, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } @@ -1511,7 +1511,7 @@ size_t http_parser_execute (http_parser *parser, if (ch == CR) { UPDATE_STATE(s_header_almost_done); parser->header_state = h_state; - CALLBACK_DATA(header_value); + CALLBACK_DATA(header_value, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } @@ -1519,7 +1519,7 @@ size_t http_parser_execute (http_parser *parser, UPDATE_STATE(s_header_almost_done); COUNT_HEADER_SIZE(p - start); parser->header_state = h_state; - CALLBACK_DATA_NOADVANCE(header_value); + CALLBACK_DATA_NOADVANCE(header_value, parser->method, parser->status_code, parser->http_major, parser->http_minor); REEXECUTE(); } @@ -1766,7 +1766,7 @@ size_t http_parser_execute (http_parser *parser, /* header value was empty */ MARK(header_value); UPDATE_STATE(s_header_field_start); - CALLBACK_DATA_NOADVANCE(header_value); + CALLBACK_DATA_NOADVANCE(header_value, parser->method, parser->status_code, parser->http_major, parser->http_minor); REEXECUTE(); } } @@ -1778,7 +1778,7 @@ size_t http_parser_execute (http_parser *parser, if (parser->flags & F_TRAILING) { /* End of a chunked request */ UPDATE_STATE(s_message_done); - CALLBACK_NOTIFY_NOADVANCE(chunk_complete); + CALLBACK_NOTIFY_NOADVANCE(chunk_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); REEXECUTE(); } @@ -1808,7 +1808,7 @@ size_t http_parser_execute (http_parser *parser, * we have to simulate it by handling a change in errno below. */ if (settings->on_headers_complete) { - switch (settings->on_headers_complete(parser)) { + switch (settings->on_headers_complete(parser, parser->method, parser->status_code, parser->http_major, parser->http_minor)) { case 0: break; @@ -1842,13 +1842,13 @@ size_t http_parser_execute (http_parser *parser, (parser->flags & F_SKIPBODY) || !hasBody)) { /* Exit, the rest of the message is in a different protocol. */ UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); + CALLBACK_NOTIFY(message_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); RETURN((p - data) + 1); } if (parser->flags & F_SKIPBODY) { UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); + CALLBACK_NOTIFY(message_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); } else if (parser->flags & F_CHUNKED) { /* chunked encoding - ignore Content-Length header */ UPDATE_STATE(s_chunk_size_start); @@ -1856,7 +1856,7 @@ size_t http_parser_execute (http_parser *parser, if (parser->content_length == 0) { /* Content-Length header given but zero: Content-Length: 0\r\n */ UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); + CALLBACK_NOTIFY(message_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); } else if (parser->content_length != ULLONG_MAX) { /* Content-Length header given and non-zero */ UPDATE_STATE(s_body_identity); @@ -1864,7 +1864,7 @@ size_t http_parser_execute (http_parser *parser, if (!http_message_needs_eof(parser)) { /* Assume content-length 0 - read the next */ UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); + CALLBACK_NOTIFY(message_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); } else { /* Read body until EOF */ UPDATE_STATE(s_body_identity_eof); @@ -1904,7 +1904,7 @@ size_t http_parser_execute (http_parser *parser, * complete-on-length. It's not clear that this distinction is * important for applications, but let's keep it for now. */ - CALLBACK_DATA_(body, p - body_mark + 1, p - data); + CALLBACK_DATA_(body, p - body_mark + 1, p - data, parser->method, parser->status_code, parser->http_major, parser->http_minor); REEXECUTE(); } @@ -1920,7 +1920,7 @@ size_t http_parser_execute (http_parser *parser, case s_message_done: UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); + CALLBACK_NOTIFY(message_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); if (parser->upgrade) { /* Exit, the rest of the message is in a different protocol. */ RETURN((p - data) + 1); @@ -2004,7 +2004,7 @@ size_t http_parser_execute (http_parser *parser, } else { UPDATE_STATE(s_chunk_data); } - CALLBACK_NOTIFY(chunk_header); + CALLBACK_NOTIFY(chunk_header, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; } @@ -2036,7 +2036,7 @@ size_t http_parser_execute (http_parser *parser, assert(parser->content_length == 0); STRICT_CHECK(ch != CR); UPDATE_STATE(s_chunk_data_done); - CALLBACK_DATA(body); + CALLBACK_DATA(body, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; case s_chunk_data_done: @@ -2044,7 +2044,7 @@ size_t http_parser_execute (http_parser *parser, STRICT_CHECK(ch != LF); parser->nread = 0; UPDATE_STATE(s_chunk_size_start); - CALLBACK_NOTIFY(chunk_complete); + CALLBACK_NOTIFY(chunk_complete, parser->method, parser->status_code, parser->http_major, parser->http_minor); break; default: @@ -2070,11 +2070,11 @@ size_t http_parser_execute (http_parser *parser, (body_mark ? 1 : 0) + (status_mark ? 1 : 0)) <= 1); - CALLBACK_DATA_NOADVANCE(header_field); - CALLBACK_DATA_NOADVANCE(header_value); - CALLBACK_DATA_NOADVANCE(url); - CALLBACK_DATA_NOADVANCE(body); - CALLBACK_DATA_NOADVANCE(status); + CALLBACK_DATA_NOADVANCE(header_field, parser->method, parser->status_code, parser->http_major, parser->http_minor); + CALLBACK_DATA_NOADVANCE(header_value, parser->method, parser->status_code, parser->http_major, parser->http_minor); + CALLBACK_DATA_NOADVANCE(url, parser->method, parser->status_code, parser->http_major, parser->http_minor); + CALLBACK_DATA_NOADVANCE(body, parser->method, parser->status_code, parser->http_major, parser->http_minor); + CALLBACK_DATA_NOADVANCE(status, parser->method, parser->status_code, parser->http_major, parser->http_minor); RETURN(len); diff --git a/Sources/CHTTPParser/include/http_parser.h b/Sources/CHTTPParser/include/http_parser.h index a3350788..c7743aa3 100755 --- a/Sources/CHTTPParser/include/http_parser.h +++ b/Sources/CHTTPParser/include/http_parser.h @@ -81,8 +81,8 @@ typedef struct http_parser_settings http_parser_settings; * many times for each string. E.G. you might get 10 callbacks for "on_url" * each providing just a few characters more data. */ -typedef int (*http_data_cb) (http_parser*, const char *at, size_t length); -typedef int (*http_cb) (http_parser*); +typedef int (*http_data_cb) (http_parser*, const char *at, size_t length, int method, int status_code, short http_major, short http_minor); +typedef int (*http_cb) (http_parser*, int method, int status_code, short http_major, short http_minor); /* Request Methods */ diff --git a/Sources/Content/Content/Content.swift b/Sources/Content/Content/Content.swift deleted file mode 100644 index 2dd66386..00000000 --- a/Sources/Content/Content/Content.swift +++ /dev/null @@ -1,31 +0,0 @@ -import Venice -import Core - -// TODO: Improve this -public enum ContentError : Error { - case unsupportedType -} - -public protocol Content : ContentRepresentable { - static var mediaType: MediaType { get } - static func parse(from readable: Readable, deadline: Deadline) throws -> Self - func serialize(to writable: Writable, deadline: Deadline) throws -} - -extension Content { - public static func parse(_ buffer: UnsafeRawBufferPointer, deadline: Deadline) throws -> Self { - let readable = ReadableBuffer(buffer) - return try parse(from: readable, deadline: deadline) - } -} - -public protocol ContentInitializable { - static var supportedTypes: [Content.Type] { get } - init(content: Content) throws -} - -public protocol ContentRepresentable { - static var supportedTypes: [Content.Type] { get } - var content: Content { get } - func content(for mediaType: MediaType) throws -> Content -} diff --git a/Sources/Content/IndexPath/IndexPath.swift b/Sources/Content/IndexPath/IndexPath.swift deleted file mode 100644 index ba3632df..00000000 --- a/Sources/Content/IndexPath/IndexPath.swift +++ /dev/null @@ -1,38 +0,0 @@ -public enum IndexPathComponentValue { - case index(Int) - case key(String) -} - -extension IndexPathComponentValue : CustomStringConvertible { - public var description: String { - switch self { - case let .index(index): - return index.description - case let .key(key): - return key - } - } -} - -extension Array where Element == IndexPathComponentValue { - public var string: String { - return map({ $0.description }).joined(separator: ".") - } -} - -/// Can be represented as `IndexPathValue`. -public protocol IndexPathComponent { - var indexPathComponent: IndexPathComponentValue { get } -} - -extension Int : IndexPathComponent { - public var indexPathComponent: IndexPathComponentValue { - return .index(self) - } -} - -extension String : IndexPathComponent { - public var indexPathComponent: IndexPathComponentValue { - return .key(self) - } -} diff --git a/Sources/Content/JSON/JSONContent.swift b/Sources/Content/JSON/JSONContent.swift deleted file mode 100644 index 9b4e2857..00000000 --- a/Sources/Content/JSON/JSONContent.swift +++ /dev/null @@ -1,39 +0,0 @@ -import Venice -import Core - -extension JSON : Content { - public static var mediaType: MediaType = .json - - public static func parse(from readable: Readable, deadline: Deadline) throws -> JSON { - let parser = JSONParser() - let buffer = UnsafeMutableRawBufferPointer.allocate(count: 4096) - - defer { - buffer.deallocate() - } - - while true { - let read = try readable.read(buffer, deadline: deadline) - - guard !read.isEmpty else { - break - } - - guard let json = try parser.parse(read) else { - continue - } - - return json - } - - return try parser.finish() - } - - public func serialize(to writable: Writable, deadline: Deadline) throws { - let serializer = JSONSerializer() - - try serializer.serialize(self) { buffer in - try writable.write(buffer, deadline: deadline) - } - } -} diff --git a/Sources/Content/JSON/JSONConvertible.swift b/Sources/Content/JSON/JSONConvertible.swift deleted file mode 100644 index 2439261b..00000000 --- a/Sources/Content/JSON/JSONConvertible.swift +++ /dev/null @@ -1,192 +0,0 @@ -import struct Foundation.Data -import struct Foundation.UUID - -public protocol JSONInitializable : ContentInitializable { - init(json: JSON) throws -} - -extension JSONInitializable { - public static var supportedTypes: [Content.Type] { - return [JSON.self] - } -} - -extension JSONInitializable { - public init(content: Content) throws { - guard let json = content as? JSON else { - throw ContentError.unsupportedType - } - - try self.init(json: json) - } -} - -public protocol JSONRepresentable : ContentRepresentable { - func json() -> JSON -} - -extension JSONRepresentable { - public static var supportedTypes: [Content.Type] { - return [JSON.self] - } - - public var content: Content { - return json() - } - - public func content(for mediaType: MediaType) throws -> Content { - guard JSON.mediaType.matches(other: mediaType) else { - throw ContentError.unsupportedType - } - - return json() - } -} - -public protocol JSONConvertible : JSONInitializable, JSONRepresentable {} - -extension JSONConvertible { - public static var supportedTypes: [Content.Type] { - return [JSON.self] - } -} - -extension JSON : JSONConvertible { - public init(json: JSON) throws { - self = json - } - - public func json() -> JSON { - return self - } -} - -extension Int : JSONConvertible { - public init(json: JSON) throws { - guard case let .int(value) = json else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - self = value - } - - public func json() -> JSON { - return .int(self) - } -} - -extension Bool : JSONConvertible { - public init(json: JSON) throws { - guard case let .bool(value) = json else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - self = value - } - - public func json() -> JSON { - return .bool(self) - } -} - -extension String : JSONConvertible { - public init(json: JSON) throws { - guard case let .string(value) = json else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - self = value - } - - public func json() -> JSON { - return .string(self) - } -} - -extension Double : JSONConvertible { - public init(json: JSON) throws { - guard case let .double(value) = json else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - self = value - } - - public func json() -> JSON { - return .double(self) - } -} - -extension UUID : JSONConvertible { - public init(json: JSON) throws { - guard case let .string(value) = json, let uuid = UUID(uuidString: value) else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - self = uuid - } - - public func json() -> JSON { - return .string(uuidString) - } -} - -// TODO: Implement this with conditional conformance when Swift provides it. -extension Array : JSONInitializable { - public init(json: JSON) throws { - guard case let .array(array) = json else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - guard let initializable = Element.self as? JSONInitializable.Type else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - var this = Array() - this.reserveCapacity(array.count) - - for element in array { - if let value = try initializable.init(json: element) as? Element { - this.append(value) - } - } - - self = this - } -} - -protocol MapDictionaryKeyInitializable { - init(mapDictionaryKey: String) -} - -extension String : MapDictionaryKeyInitializable { - init(mapDictionaryKey: String) { - self = mapDictionaryKey - } -} - -extension Dictionary : JSONInitializable { - public init(json: JSON) throws { - guard case .object(let object) = json else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - guard let keyInitializable = Key.self as? MapDictionaryKeyInitializable.Type else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - guard let valueInitializable = Value.self as? JSONInitializable.Type else { - throw JSONError.cannotInitialize(type: type(of: self), json: json) - } - - var this = Dictionary(minimumCapacity: object.count) - - for (key, value) in object { - if let key = keyInitializable.init(mapDictionaryKey: key) as? Key { - this[key] = try valueInitializable.init(json: value) as? Value - } - } - - self = this - } -} diff --git a/Sources/Content/PlainText/PlainText.swift b/Sources/Content/PlainText/PlainText.swift deleted file mode 100644 index 9c3c6615..00000000 --- a/Sources/Content/PlainText/PlainText.swift +++ /dev/null @@ -1,94 +0,0 @@ -import Venice -import Core -import struct Foundation.Data - -public struct PlainText { - public let description: String - - public init(_ description: String) { - self.description = description - } -} - -public protocol PlainTextInitializable : ContentInitializable { - init(plainText: PlainText) throws -} - -extension PlainTextInitializable { - public init(content: Content) throws { - guard let plainText = content as? PlainText else { - throw ContentError.unsupportedType - } - - try self.init(plainText: plainText) - } -} - -public protocol PlainTextRepresentable : ContentRepresentable { - func plainText() -> PlainText -} - -extension PlainTextRepresentable { - public static var supportedTypes: [Content.Type] { - return [PlainText.self] - } - - public var content: Content { - return plainText() - } - - public func content(for mediaType: MediaType) throws -> Content { - guard PlainText.mediaType.matches(other: mediaType) else { - throw ContentError.unsupportedType - } - - return plainText() - } -} - -public protocol PlainTextConvertible : PlainTextInitializable, PlainTextRepresentable {} - -extension PlainText : PlainTextInitializable { - public init(plainText: PlainText) throws { - self = plainText - } -} - -extension PlainText : PlainTextRepresentable { - public func plainText() -> PlainText { - return self - } -} - -extension PlainText : CustomStringConvertible {} - -extension PlainText : Content { - public static var mediaType: MediaType = .plainText - - public static func parse(from readable: Readable, deadline: Deadline) throws -> PlainText { - var bytes: [UInt8] = [] - - let buffer = UnsafeMutableRawBufferPointer.allocate(count: 2048) - - defer { - buffer.deallocate() - } - - while true { - let read = try readable.read(buffer, deadline: deadline) - - guard !read.isEmpty else { - break - } - - bytes.append(contentsOf: read) - } - - bytes += [0] - return PlainText(String(cString: bytes)) - } - - public func serialize(to writable: Writable, deadline: Deadline) throws { - try writable.write(description, deadline: deadline) - } -} diff --git a/Sources/Content/XML/XML.swift b/Sources/Content/XML/XML.swift deleted file mode 100644 index 6234464b..00000000 --- a/Sources/Content/XML/XML.swift +++ /dev/null @@ -1,242 +0,0 @@ -public enum XMLError : Error { - case noContent(type: XMLInitializable.Type) - case cannotInitialize(type: XMLInitializable.Type, xml: XML) - case valueNotArray(indexPath: [IndexPathComponentValue], xml: XML) - case outOfBounds(indexPath: [IndexPathComponentValue], xml: XML) - case valueNotDictionary(indexPath: [IndexPathComponentValue], xml: XML) - case valueNotFound(indexPath: [IndexPathComponentValue], xml: XML) -} - -extension XMLError : CustomStringConvertible { - public var description: String { - switch self { - case let .noContent(type): - return "Cannot initialize type \"\(String(describing: type))\" with no content." - case let .cannotInitialize(type, xml): - return "Cannot initialize type \"\(String(describing: type))\" with xml \(xml)." - case let .valueNotArray(indexPath, content): - return "Cannot get xml element for index path \"\(indexPath.string)\". Element is not an array \(content)." - case let .outOfBounds(indexPath, content): - return "Cannot get xml element for index path \"\(indexPath.string)\". Index is out of bounds for element \(content)." - case let .valueNotDictionary(indexPath, content): - return "Cannot get xml element for index path \"\(indexPath.string)\". Element is not a dictionary \(content)." - case let .valueNotFound(indexPath, content): - return "Cannot get xml element for index path \"\(indexPath.string)\". Key is not present in element \(content)." - } - } -} - -extension Array where Element == XML { - public func withAttribute(_ name: String, equalTo value: String) -> XML? { - for element in self where (element.getAttribute(name) as String?) == value { - return element - } - - return nil - } -} - -public protocol XMLNodeRepresentable { - var xmlNode: XML.Node { get } -} - -extension XML : XMLNodeRepresentable { - public var xmlNode: XML.Node { - return .element(self) - } -} - -extension String : XMLNodeRepresentable { - public var xmlNode: XML.Node { - return .content(self) - } -} - -public final class XML { - public enum Node { - case element(XML) - case content(String) - } - - public let name: String - public let attributes: [String: String] - public internal(set) var children: [Node] - - init(name: String, attributes: [String: String] = [:], children: [XMLNodeRepresentable] = []) { - self.name = name - self.attributes = attributes - self.children = children.map({ $0.xmlNode }) - } - - public func getAttribute(_ name: String) throws -> String { - guard let attribute = attributes[name] else { - throw XMLError.valueNotFound(indexPath: [.key(name)], xml: self) - } - - return attribute - } - - public var contents: String { - var string = "" - - var contents: [String] = [] - - for child in children { - if case let .content(content) = child { - contents.append(content.description) - } - } - - for content in contents { - string += content - } - - return string - } - - public func get(_ indexPath: IndexPathComponent...) throws -> XML { - return try _get(indexPath as [IndexPathComponent]) - } - - public func get(_ indexPath: IndexPathComponent...) throws -> [XML] { - return try _get(indexPath as [IndexPathComponent]) - } - - internal func _get(_ indexPath: [IndexPathComponent]) throws -> XML { - let elements: [XML] = try _get(indexPath) - - guard elements.count == 1, let element = elements.first else { - throw XMLError.valueNotFound( - indexPath: indexPath.map({ $0.indexPathComponent }), - xml: self - ) - } - - return element - } - - internal func _get(_ indexPath: [IndexPathComponent]) throws -> [XML] { - var value = [self] - var single = true - var visited: [IndexPathComponentValue] = [] - - loop: for component in indexPath { - visited.append(component.indexPathComponent) - - switch component.indexPathComponent { - case let .index(index): - if single, value.count == 1, let element = value.first { - guard element.elements.indices.contains(index) else { - throw XMLError.outOfBounds(indexPath: visited, xml: self) - } - - value = [element.elements[index]] - single = true - continue loop - } - - guard value.indices.contains(index) else { - throw XMLError.outOfBounds(indexPath: visited, xml: self) - } - - value = [value[index]] - single = true - case let .key(key): - guard value.count == 1, let element = value.first else { - // More than one result - throw XMLError.valueNotFound(indexPath: visited, xml: self) - } - - value = element.getElements(named: key) - single = false - } - } - - return value - } - - func getElements(named name: String) -> [XML] { - var elements: [XML] = [] - - for element in self.elements where element.name == name { - elements.append(element) - } - - return elements - } - - var elements: [XML] { - var elements: [XML] = [] - - for child in children { - if case let .element(element) = child { - elements.append(element) - } - } - - return elements - } - - func addElement(_ element: XML) { - children.append(.element(element)) - } - - func addContent(_ content: String) { - children.append(.content(content)) - } -} - -extension XML : CustomStringConvertible { - public var description: String { - var attributes = "" - - for (offset: index, element: (key: key, value: value)) in self.attributes.enumerated() { - if index == 0 { - attributes += " " - } - - attributes += key - attributes += "=" - attributes += value - - if index < self.attributes.count - 1 { - attributes += " " - } - } - - if !children.isEmpty { - var string = "" - string += "<" - string += name - string += attributes - string += ">" - - for child in children { - string += child.description - } - - string += "" - return string - } - - guard !contents.isEmpty else { - return "<\(name)\(attributes)/>" - - } - - return "<\(name)\(attributes)>\(content)" - } -} - -extension XML.Node : CustomStringConvertible { - public var description: String { - switch self { - case let .element(element): - return element.description - case let .content(content): - return content - } - } -} diff --git a/Sources/Content/XML/XMLContent.swift b/Sources/Content/XML/XMLContent.swift deleted file mode 100644 index aa08aa3f..00000000 --- a/Sources/Content/XML/XMLContent.swift +++ /dev/null @@ -1,34 +0,0 @@ -import Venice -import Core - -extension XML : Content { - public static var mediaType: MediaType = .xml - - public static func parse(from readable: Readable, deadline: Deadline) throws -> XML { - return try XMLParser.parse(readable, bufferSize: 4096, deadline: deadline) - } - - public func serialize(to writable: Writable, deadline: Deadline) throws { - // TODO: Improve this - try writable.write(description, deadline: deadline) - } -} - -// TODO: Implement this in XMLRepresentable -extension XML { - public static var supportedTypes: [Content.Type] { - return [XML.self] - } - - public var content: Content { - return self - } - - public func content(for mediaType: MediaType) throws -> Content { - guard PlainText.mediaType.matches(other: mediaType) else { - throw ContentError.unsupportedType - } - - return self - } -} diff --git a/Sources/Content/XML/XMLConvertible.swift b/Sources/Content/XML/XMLConvertible.swift deleted file mode 100644 index 6f937f79..00000000 --- a/Sources/Content/XML/XMLConvertible.swift +++ /dev/null @@ -1,114 +0,0 @@ -import Foundation - -public enum XMLInitializableError : Error, CustomStringConvertible { - // TODO: Reavaliate these - case implementationIsMissing(method: String) - case nodeIsInvalid(node: XML) - case nodeHasNoValue - case typeConversionFailed(type: String, element: XML) - case attributeDoesNotExist(element: XML, attribute: String) - case attributeDeserializationFailed(type: String, attribute: String) - - public var description: String { - switch self { - case let .implementationIsMissing(method): - return "This deserialization method is not implemented: \(method)" - case let .nodeIsInvalid(node): - return "This node is invalid: \(node)" - case .nodeHasNoValue: - return "This node is empty" - case let .typeConversionFailed(type, node): - return "Can't convert node \(node) to value of type \(type)" - case let .attributeDoesNotExist(element, attribute): - return "element \(element) does not contain attribute: \(attribute)" - case let .attributeDeserializationFailed(type, attribute): - return "Can't convert attribute \(attribute) to value of type \(type)" - } - } -} - -public protocol XMLInitializable { - init(xml: XML) throws -} - -public extension XML { - public func getAttribute(_ name: String) throws -> A { - let attribute = try getAttribute(name) - - guard let value = A(attribute) else { - throw XMLInitializableError.attributeDeserializationFailed( - type: String(describing: A.self), - attribute: name - ) - } - - return value - } - - public func getAttribute(_ name: String) -> A? { - return try? getAttribute(name) - } - - func get(_ indexPath: IndexPathComponent...) throws -> T { - let element: XML = try _get(indexPath as [IndexPathComponent]) - return try T(xml: element) - } - - func get(_ indexPath: IndexPathComponent...) -> T? { - guard let element = try? _get(indexPath as [IndexPathComponent]) as XML else { - return nil - } - - return try? T(xml: element) - } - - func get(_ indexPath: IndexPathComponent...) throws -> [T] { - return try _get(indexPath as [IndexPathComponent]).map({ try T(xml: $0) }) - } -} - -extension String : XMLInitializable { - public init(xml: XML) throws { - self = xml.contents - } -} - -extension Int : XMLInitializable { - public init(xml: XML) throws { - guard let value = Int(xml.contents) else { - throw XMLInitializableError.typeConversionFailed(type: "Int", element: xml) - } - - self = value - } -} - -extension Double : XMLInitializable { - public init(xml: XML) throws { - guard let value = Double(xml.contents) else { - throw XMLInitializableError.typeConversionFailed(type: "Double", element: xml) - } - - self = value - } -} - -extension Float : XMLInitializable { - public init(xml: XML) throws { - guard let value = Float(xml.contents) else { - throw XMLInitializableError.typeConversionFailed(type: "Float", element: xml) - } - - self = value - } -} - -extension Bool : XMLInitializable { - public init(xml: XML) throws { - guard let value = Bool(xml.contents) else { - throw XMLInitializableError.typeConversionFailed(type: "Float", element: xml) - } - - self = value - } -} diff --git a/Sources/Core/Environment/Environment.swift b/Sources/Core/Environment/Environment.swift index b052ee2a..8484d055 100644 --- a/Sources/Core/Environment/Environment.swift +++ b/Sources/Core/Environment/Environment.swift @@ -1,13 +1,5 @@ import Foundation -#if os(macOS) -extension NSTextCheckingResult { - func range(at index: Int) -> NSRange { - return rangeAt(index) - } -} -#endif - public enum EnvironmentError : Error { case valueNotFound(key: String, variables: [String: String]) case cannotInitialize(type: LosslessStringConvertible.Type, variable: String) @@ -96,15 +88,14 @@ public struct Environment { guard let keyRange = match.range(at: 1).range(for: line) else { continue } - - let key = line.substring(with: keyRange) + let key = String(line[keyRange]) var value = "" if match.numberOfRanges == 3, let valueRange = match.range(at: 2).range(for: line) { - value = line.substring(with: valueRange) + value = String(line[valueRange]) } value = value.trimmingCharacters(in: .whitespaces) diff --git a/Sources/Core/Readable/Readable.swift b/Sources/Core/Readable/Readable.swift new file mode 100644 index 00000000..5db93c54 --- /dev/null +++ b/Sources/Core/Readable/Readable.swift @@ -0,0 +1,20 @@ +import Venice + +/// Representation of a type which binary data can be read from. +public protocol Readable { + /// Read binary data into `buffer` timing out at `deadline`. + func read( + _ buffer: UnsafeMutableRawBufferPointer, + deadline: Deadline + ) throws -> UnsafeRawBufferPointer +} + +extension Readable { + public func read( + _ buffer: UnsafeMutableRawBufferPointer, + deadline: Deadline + ) throws -> B { + let buffer = try read(buffer, deadline: deadline) + return B(buffer) + } +} diff --git a/Sources/Core/Stream/ReadableBuffer.swift b/Sources/Core/Readable/ReadableBuffer.swift similarity index 71% rename from Sources/Core/Stream/ReadableBuffer.swift rename to Sources/Core/Readable/ReadableBuffer.swift index 3bebced0..7ac72905 100644 --- a/Sources/Core/Stream/ReadableBuffer.swift +++ b/Sources/Core/Readable/ReadableBuffer.swift @@ -27,9 +27,16 @@ public final class ReadableBuffer : Readable { let readCount = min(buffer.count, self.buffer.count) memcpy(destination, origin, readCount) - let read = buffer.prefix(readCount) - self.buffer = self.buffer.suffix(from: readCount) - return UnsafeRawBufferPointer(read) + + #if swift(>=3.2) + let read = UnsafeRawBufferPointer(rebasing: buffer.prefix(readCount)) + self.buffer = UnsafeRawBufferPointer(rebasing: self.buffer.suffix(from: readCount)) + #else + let read = UnsafeRawBufferPointer(buffer.prefix(readCount)) + self.buffer = self.buffer.suffix(from: readCount) + #endif + + return read } } diff --git a/Sources/Core/Stream/BufferStream.swift b/Sources/Core/Stream/BufferStream.swift deleted file mode 100644 index 94e5efd8..00000000 --- a/Sources/Core/Stream/BufferStream.swift +++ /dev/null @@ -1,40 +0,0 @@ -#if os(Linux) - import Glibc -#else - import Darwin.C -#endif - -import Venice - -public final class BufferReadable : Readable { - var buffer: UnsafeRawBufferPointer - - public init(buffer: UnsafeRawBufferPointer) { - self.buffer = buffer - } - - public func read( - _ buffer: UnsafeMutableRawBufferPointer, - deadline: Deadline - ) throws -> UnsafeRawBufferPointer { - guard !buffer.isEmpty && !self.buffer.isEmpty else { - return UnsafeRawBufferPointer(start: nil, count: 0) - } - - guard let destination = buffer.baseAddress, let origin = self.buffer.baseAddress else { - return UnsafeRawBufferPointer(start: nil, count: 0) - } - - let readCount = min(buffer.count, self.buffer.count) - memcpy(destination, origin, readCount) - let read = self.buffer.prefix(readCount) - self.buffer = self.buffer.suffix(from: readCount) - return UnsafeRawBufferPointer(read) - } -} - -extension BufferReadable { - public static var empty: BufferReadable = BufferReadable( - buffer: UnsafeRawBufferPointer(start: nil, count: 0) - ) -} diff --git a/Sources/Core/Stream/Stream.swift b/Sources/Core/Stream/Stream.swift deleted file mode 100755 index abcbd1f3..00000000 --- a/Sources/Core/Stream/Stream.swift +++ /dev/null @@ -1,46 +0,0 @@ -import Venice - -/// Representation of a type which binary data can be read from. -public protocol Readable { - /// Read binary data into `buffer` timing out at `deadline`. - func read( - _ buffer: UnsafeMutableRawBufferPointer, - deadline: Deadline - ) throws -> UnsafeRawBufferPointer -} - -extension Readable { - public func read( - _ buffer: UnsafeMutableRawBufferPointer, - deadline: Deadline - ) throws -> B { - let buffer = try read(buffer, deadline: deadline) - return B(buffer) - } -} - -public protocol ReadableStream : Readable { - func open(deadline: Deadline) throws - func close(deadline: Deadline) throws -} - -/// Representation of a type which binary data can be written to. -public protocol Writable { - /// Read `buffer` timing out at `deadline`. - func write(_ buffer: UnsafeRawBufferPointer, deadline: Deadline) throws -} - -extension Writable { - public func write(_ buffer: BufferRepresentable, deadline: Deadline) throws { - try buffer.withBuffer { - try write($0, deadline: deadline) - } - } -} - -public protocol WritableStream : Writable { - func open(deadline: Deadline) throws - func close(deadline: Deadline) throws -} - -public protocol DuplexStream : ReadableStream, WritableStream {} diff --git a/Sources/Core/String/String.swift b/Sources/Core/String/String.swift index ae8c2240..b8d16643 100644 --- a/Sources/Core/String/String.swift +++ b/Sources/Core/String/String.swift @@ -1,5 +1,35 @@ import Foundation +extension Character { + public var isASCII: Bool { + return unicodeScalars.reduce(true, { $0 && $1.isASCII }) + } + + public var isAlphabetic: Bool { + return isLowercase || isUppercase + } + + public var isLowercase: Bool { + return ("a" ... "z").contains(self) + } + + public var isUppercase: Bool { + return ("A" ... "Z").contains(self) + } + + public var isDigit: Bool { + return ("0" ... "9").contains(self) + } +} + +extension String { + public func uppercasedFirstCharacter() -> String { + let first = String(characters.prefix(1)).capitalized + let other = String(characters.dropFirst()) + return first + other + } +} + extension CharacterSet { public static var urlAllowed: CharacterSet { let uppercaseAlpha = CharacterSet(charactersIn: "A" ... "Z") @@ -25,15 +55,52 @@ extension String { withTemplate: " " ).trimmingCharacters(in: .whitespaces) } -} - -extension Int : LosslessStringConvertible { - public init?(_ string: String) { - guard let int = Int(string, radix: 10) else { - return nil + + public func camelCaseSplit() -> [String] { + var entries: [String] = [] + var runes: [[Character]] = [] + var lastClass = 0 + var currentClass = 0 + + for character in self { + switch true { + case character.isLowercase: + currentClass = 1 + case character.isUppercase: + currentClass = 2 + case character.isDigit: + currentClass = 3 + default: + currentClass = 4 + } + + if currentClass == lastClass { + var rune = runes[runes.count - 1] + rune.append(character) + runes[runes.count - 1] = rune + } else { + runes.append([character]) + } + + lastClass = currentClass + } + + // handle upper case -> lower case sequences, e.g. + // "PDFL", "oader" -> "PDF", "Loader" + if runes.count >= 2 { + for i in 0 ..< runes.count - 1 { + if runes[i][0].isUppercase && runes[i + 1][0].isLowercase { + runes[i + 1] = [runes[i][runes[i].count - 1]] + runes[i + 1] + runes[i] = Array(runes[i][..<(runes[i].count - 1)]) + } + } + } + + for rune in runes where rune.count > 0 { + entries.append(String(rune)) } - self = int + return entries } } diff --git a/Sources/Core/Writable/Writable.swift b/Sources/Core/Writable/Writable.swift new file mode 100755 index 00000000..2faa1c6f --- /dev/null +++ b/Sources/Core/Writable/Writable.swift @@ -0,0 +1,15 @@ +import Venice + +/// Representation of a type which binary data can be written to. +public protocol Writable { + /// Read `buffer` timing out at `deadline`. + func write(_ buffer: UnsafeRawBufferPointer, deadline: Deadline) throws +} + +extension Writable { + public func write(_ buffer: BufferRepresentable, deadline: Deadline) throws { + try buffer.withBuffer { + try write($0, deadline: deadline) + } + } +} diff --git a/Sources/Core/Stream/WritableBuffer.swift b/Sources/Core/Writable/WritableBuffer.swift similarity index 100% rename from Sources/Core/Stream/WritableBuffer.swift rename to Sources/Core/Writable/WritableBuffer.swift diff --git a/Sources/HTTP/Client/Client.swift b/Sources/HTTP/Client/Client.swift index ce308b72..deace7a0 100644 --- a/Sources/HTTP/Client/Client.swift +++ b/Sources/HTTP/Client/Client.swift @@ -256,11 +256,11 @@ fileprivate class Pool { fileprivate var waitList: Channel fileprivate var waiting: Int = 0 - fileprivate let create: (Void) throws -> Client.Connection + fileprivate let create: () throws -> Client.Connection fileprivate init( size: ClosedRange, - _ create: @escaping (Void) throws -> Client.Connection + _ create: @escaping () throws -> Client.Connection ) throws { self.size = size self.create = create diff --git a/Sources/HTTP/Message/Body.swift b/Sources/HTTP/Message/Body.swift index 2d0407ef..c8ab44b5 100644 --- a/Sources/HTTP/Message/Body.swift +++ b/Sources/HTTP/Message/Body.swift @@ -93,8 +93,13 @@ fileprivate final class ReadableBytes : Readable { return } - let read = buffer.prefix(readCount) + #if swift(>=3.2) + let read = UnsafeRawBufferPointer(rebasing: buffer.prefix(readCount)) + #else + let read = UnsafeRawBufferPointer(buffer.prefix(readCount)) + #endif + self.buffer = self.buffer.suffix(from: readCount) - return UnsafeRawBufferPointer(read) + return read } } diff --git a/Sources/HTTP/Message/Message.swift b/Sources/HTTP/Message/Message.swift index 1d044bc0..378ec041 100755 --- a/Sources/HTTP/Message/Message.swift +++ b/Sources/HTTP/Message/Message.swift @@ -1,5 +1,5 @@ import Core -import Content +import Media import Venice // TODO: Make error CustomStringConvertible and ResponseRepresentable @@ -99,13 +99,10 @@ extension Message { return headers["Upgrade"] } - public func content(deadline: Deadline = 5.minutes.fromNow()) throws -> C { - return try _content(deadline: deadline) - } - - public func content( - deadline: Deadline = 5.minutes.fromNow() - ) throws -> C { + public func content( + deadline: Deadline = 5.minutes.fromNow(), + userInfo: [CodingUserInfoKey: Any] = [:] + ) throws -> Content { guard let mediaType = self.contentType else { throw MessageError.noContentTypeHeader } @@ -114,41 +111,18 @@ extension Message { throw MessageError.noReadableBody } - var lastError: Error = MessageError.unsupportedMediaType - - for contentType in C.supportedTypes where contentType.mediaType.matches(other: mediaType) { - let content = try contentType.parse(from: readable, deadline: deadline) - - do { - return try C(content: content) - } catch { - lastError = error - continue - } - } - - throw lastError - } - - public func content( - deadline: Deadline = 5.minutes.fromNow() - ) throws -> C { - return try _content() + let media = try Content.decodingMedia(for: mediaType) + return try media.decode(Content.self, from: readable, deadline: deadline, userInfo: userInfo) } - public func _content(deadline: Deadline = 5.minutes.fromNow()) throws -> C { - guard let mediaType = self.contentType else { - throw MessageError.noContentTypeHeader - } - - guard mediaType == C.mediaType else { - throw MessageError.unsupportedMediaType - } - + public func content( + deadline: Deadline = 5.minutes.fromNow(), + userInfo: [CodingUserInfoKey: Any] = [:] + ) throws -> Content { guard let readable = try? body.convertedToReadable() else { throw MessageError.noReadableBody } - return try C.parse(from: readable, deadline: deadline) + return try Content(from: readable, deadline: deadline) } } diff --git a/Sources/HTTP/Message/Version.swift b/Sources/HTTP/Message/Version.swift index 178dc1c0..cdc0964c 100755 --- a/Sources/HTTP/Message/Version.swift +++ b/Sources/HTTP/Message/Version.swift @@ -7,8 +7,8 @@ public struct Version { self.minor = minor } - internal static let oneDotZero = Version(major: 1, minor: 0) - internal static let oneDotOne = Version(major: 1, minor: 1) + public static let oneDotZero = Version(major: 1, minor: 0) + public static let oneDotOne = Version(major: 1, minor: 1) } extension Version : Hashable { diff --git a/Sources/HTTP/Parser/Parser.swift b/Sources/HTTP/Parser/Parser.swift index f103b825..01f33399 100644 --- a/Sources/HTTP/Parser/Parser.swift +++ b/Sources/HTTP/Parser/Parser.swift @@ -44,7 +44,12 @@ internal class Parser { let bytesRead = min(bodyBuffer.count, buffer.count) memcpy(baseAddress, bodyBaseAddress, bytesRead) - bodyBuffer = bodyBuffer.suffix(from: bytesRead) + + #if swift(>=3.2) + bodyBuffer = UnsafeRawBufferPointer(rebasing: bodyBuffer.suffix(from: bytesRead)) + #else + bodyBuffer = bodyBuffer.suffix(from: bytesRead) + #endif return UnsafeRawBufferPointer(start: baseAddress, count: bytesRead) } @@ -125,7 +130,7 @@ internal class Parser { buffer.deallocate() } - func headersComplete(context: Context, body: BodyStream) -> Bool { + func headersComplete(context: Context, body: BodyStream, method: Int32, http_major: Int16, http_minor: Int16) -> Bool { return false } @@ -167,14 +172,14 @@ internal class Parser { } } - fileprivate func process(state newState: State, data: UnsafeRawBufferPointer? = nil) -> Int32 { + fileprivate func process(state newState: State, data: UnsafeRawBufferPointer? = nil, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { if state != newState { switch state { case .ready, .messageBegin, .body, .messageComplete: break case .uri: guard let uri = bytes.withUnsafeBytes({ buffer in - return URI(buffer: buffer, isConnect: parser.method == HTTP_CONNECT.rawValue) + return URI(buffer: buffer, isConnect: method == HTTP_CONNECT.rawValue) }) else { return 1 } @@ -186,9 +191,9 @@ internal class Parser { let string = bytes.withUnsafeBufferPointer { (pointer: UnsafeBufferPointer) -> String in return String(cString: pointer.baseAddress!) } - context.status = Response.Status( - statusCode: Int(parser.status_code), + + statusCode: Int(status_code), reasonPhrase: string ) case .headerField: @@ -212,7 +217,7 @@ internal class Parser { let body = BodyStream(parser: self) context.bodyStream = body - if !headersComplete(context: context, body: body) { + if !headersComplete(context: context, body: body, method: method, http_major: http_major, http_minor: http_minor) { return 1 } } @@ -241,62 +246,62 @@ internal class Parser { } } -private func http_parser_on_message_begin(pointer: UnsafeMutablePointer?) -> Int32 { +private func http_parser_on_message_begin(pointer: UnsafeMutablePointer?, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .messageBegin) + return parser.process(state: .messageBegin, method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_url( pointer: UnsafeMutablePointer?, data: UnsafePointer?, - length: Int + length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .uri, data: UnsafeRawBufferPointer(start: data, count: length)) + return parser.process(state: .uri, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_status( pointer: UnsafeMutablePointer?, data: UnsafePointer?, - length: Int + length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .status, data: UnsafeRawBufferPointer(start: data, count: length)) + return parser.process(state: .status, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_header_field( pointer: UnsafeMutablePointer?, data: UnsafePointer?, - length: Int + length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .headerField, data: UnsafeRawBufferPointer(start: data, count: length)) + return parser.process(state: .headerField, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_header_value( pointer: UnsafeMutablePointer?, data: UnsafePointer?, - length: Int + length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .headerValue, data: UnsafeRawBufferPointer(start: data, count: length)) + return parser.process(state: .headerValue, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } -private func http_parser_on_headers_complete(pointer: UnsafeMutablePointer?) -> Int32 { +private func http_parser_on_headers_complete(pointer: UnsafeMutablePointer?, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .headersComplete) + return parser.process(state: .headersComplete, method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_body( pointer: UnsafeMutablePointer?, data: UnsafePointer?, - length: Int + length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .body, data: UnsafeRawBufferPointer(start: data, count: length)) + return parser.process(state: .body, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } -private func http_parser_on_message_complete(pointer: UnsafeMutablePointer?) -> Int32 { +private func http_parser_on_message_complete(pointer: UnsafeMutablePointer?, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { let parser = Unmanaged.fromOpaque(pointer!.pointee.data).takeUnretainedValue() - return parser.process(state: .messageComplete) + return parser.process(state: .messageComplete, method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } diff --git a/Sources/HTTP/Parser/RequestParser.swift b/Sources/HTTP/Parser/RequestParser.swift index 7e26096e..eeb9d6c8 100644 --- a/Sources/HTTP/Parser/RequestParser.swift +++ b/Sources/HTTP/Parser/RequestParser.swift @@ -168,16 +168,16 @@ internal final class RequestParser : Parser { } } - override func headersComplete(context: Parser.Context, body: Parser.BodyStream) -> Bool { + override func headersComplete(context: Parser.Context, body: Parser.BodyStream, method: Int32, http_major: Int16, http_minor: Int16) -> Bool { guard let uri = context.uri else { return false } let request = Request( - method: Request.Method(code: http_method(rawValue: parser.method)), + method: Request.Method(code: http_method(rawValue: UInt32(Int(method)) )), uri: uri, headers: context.headers, - version: Version(major: Int(parser.http_major), minor: Int(parser.http_minor)), + version: Version(major: Int(http_major), minor: Int(http_minor)), body: .readable(body) ) diff --git a/Sources/HTTP/Parser/ResponseParser.swift b/Sources/HTTP/Parser/ResponseParser.swift index 3b5df522..d984347e 100644 --- a/Sources/HTTP/Parser/ResponseParser.swift +++ b/Sources/HTTP/Parser/ResponseParser.swift @@ -20,7 +20,7 @@ internal final class ResponseParser : Parser { } } - override func headersComplete(context: Parser.Context, body: Parser.BodyStream) -> Bool { + override func headersComplete(context: Parser.Context, body: Parser.BodyStream, method: Int32, http_major: Int16, http_minor: Int16) -> Bool { guard let status = context.status else { return false } @@ -28,7 +28,7 @@ internal final class ResponseParser : Parser { let response = Response( status: status, headers: context.headers, - version: Version(major: Int(parser.http_major), minor: Int(parser.http_minor)), + version: Version(major: Int(http_major), minor: Int(http_minor)), body: .readable(body) ) diff --git a/Sources/HTTP/Request/Request.swift b/Sources/HTTP/Request/Request.swift index 2634f37a..6cd22cc3 100644 --- a/Sources/HTTP/Request/Request.swift +++ b/Sources/HTTP/Request/Request.swift @@ -1,5 +1,6 @@ import Core -import Content +import IO +import Media import Venice public final class Request : Message { @@ -12,7 +13,6 @@ public final class Request : Message { public var body: Body public var storage: Storage = [:] - public var upgradeConnection: UpgradeConnection? public init( @@ -114,7 +114,7 @@ extension Request { contentLength = buffer.bufferSize } - private convenience init( + public convenience init( method: Method, uri: String, headers: Headers = [:], @@ -126,72 +126,60 @@ extension Request { uri: uri, headers: headers, body: { writable in - try content.serialize(to: writable, deadline: timeout.fromNow()) + try content.encode(to: writable, deadline: timeout.fromNow()) } ) - self.contentType = type(of: content).mediaType + self.contentType = Content.mediaType self.contentLength = nil self.transferEncoding = "chunked" } - public convenience init( + public convenience init( method: Method, uri: String, headers: Headers = [:], - content representable: C, + content: Content, timeout: Duration = 5.minutes ) throws { + let media = try Content.defaultEncodingMedia() + try self.init( method: method, uri: uri, headers: headers, - content: representable.content, - timeout: timeout + body: { writable in + try media.encode(content, to: writable, deadline: timeout.fromNow()) + } ) + + self.contentType = media.mediaType + self.contentLength = nil + self.transferEncoding = "chunked" } - public convenience init( + public convenience init( method: Method, uri: String, headers: Headers = [:], - content: C, + content: Content, + contentType mediaType: MediaType, timeout: Duration = 5.minutes ) throws { + let media = try Content.encodingMedia(for: mediaType) + try self.init( method: method, uri: uri, headers: headers, - content: content as Content, - timeout: timeout - ) - } - - public convenience init( - method: Method, - uri: String, - headers: Headers = [:], - content representable: C, - contentType mediaType: MediaType, - timeout: Duration = 5.minutes - ) throws { - for contentType in C.supportedTypes where contentType.mediaType.matches(other: mediaType) { - guard let content = try? representable.content(for: mediaType) else { - continue + body: { writable in + try media.encode(content, to: writable, deadline: timeout.fromNow()) } - - try self.init( - method: method, - uri: uri, - headers: headers, - content: content, - timeout: timeout - ) - - return - } + ) - throw MessageError.unsupportedMediaType + self.contentType = media.mediaType + self.contentLength = nil + self.transferEncoding = "chunked" } } @@ -241,22 +229,6 @@ extension Request { } } -extension Request { - public func negotiate( - _ representable: C - ) throws -> Content { - for contentType in C.supportedTypes where contentType.mediaType.matches(any: accept) { - guard let content = try? representable.content(for: contentType.mediaType) else { - continue - } - - return content - } - - throw ContentError.unsupportedType - } -} - extension Request : CustomStringConvertible { /// :nodoc: public var requestLineDescription: String { diff --git a/Sources/HTTP/Response/Response.swift b/Sources/HTTP/Response/Response.swift index 5c332a5f..d4855f96 100644 --- a/Sources/HTTP/Response/Response.swift +++ b/Sources/HTTP/Response/Response.swift @@ -1,5 +1,6 @@ import Core -import Content +import IO +import Media import Venice public final class Response : Message { @@ -11,9 +12,7 @@ public final class Response : Message { public var body: Body public var storage: Storage = [:] - public var upgradeConnection: UpgradeConnection? - public var cookieHeaders: Set = [] public init( @@ -154,76 +153,66 @@ extension Response { contentLength = buffer.bufferSize } - public convenience init( + public convenience init( status: Status, headers: Headers = [:], content: Content, timeout: Duration = 5.minutes - ) { + ) throws { self.init( status: status, headers: headers, body: { writable in - try content.serialize(to: writable, deadline: timeout.fromNow()) + try content.encode(to: writable, deadline: timeout.fromNow()) } ) - self.contentType = type(of: content).mediaType + self.contentType = Content.mediaType self.contentLength = nil self.transferEncoding = "chunked" } - public convenience init( + public convenience init( status: Status, headers: Headers = [:], - content representable: C, + content: Content, timeout: Duration = 5.minutes - ) { + ) throws { + let media = try Content.defaultEncodingMedia() + self.init( status: status, headers: headers, - content: representable.content, - timeout: timeout + body: { writable in + try media.encode(content, to: writable, deadline: timeout.fromNow()) + } ) + + self.contentType = media.mediaType + self.contentLength = nil + self.transferEncoding = "chunked" } - public convenience init( + public convenience init( status: Status, headers: Headers = [:], - content: C, + content: Content, + contentType mediaType: MediaType, timeout: Duration = 5.minutes - ) { + ) throws { + let media = try Content.encodingMedia(for: mediaType) + self.init( status: status, headers: headers, - content: content as Content, - timeout: timeout - ) - } - - public convenience init( - status: Status, - headers: Headers = [:], - content representable: C, - contentType mediaType: MediaType, - timeout: Duration = 5.minutes - ) throws { - for contentType in C.supportedTypes where contentType.mediaType.matches(other: mediaType) { - guard let content = try? representable.content(for: mediaType) else { - continue + body: { writable in + try media.encode(content, to: writable, deadline: timeout.fromNow()) } - - self.init( - status: status, - headers: headers, - content: content, - timeout: timeout - ) - - return - } + ) - throw MessageError.unsupportedMediaType + self.contentType = media.mediaType + self.contentLength = nil + self.transferEncoding = "chunked" } } diff --git a/Sources/HTTP/Response/ResponseRepresentable.swift b/Sources/HTTP/Response/ResponseRepresentable.swift index fe2b5d93..3c68d9f7 100644 --- a/Sources/HTTP/Response/ResponseRepresentable.swift +++ b/Sources/HTTP/Response/ResponseRepresentable.swift @@ -1,17 +1,5 @@ -import Content +import Media public protocol ResponseRepresentable { var response: Response { get } } - -extension JSONError : ResponseRepresentable { - public var response: Response { - return Response(status: .badRequest, content: PlainText(description)) - } -} - -extension ParametersError : ResponseRepresentable { - public var response: Response { - return Response(status: .badRequest, content: PlainText(description)) - } -} diff --git a/Sources/HTTP/Serializer/Serializer.swift b/Sources/HTTP/Serializer/Serializer.swift index 512206eb..339aa101 100644 --- a/Sources/HTTP/Serializer/Serializer.swift +++ b/Sources/HTTP/Serializer/Serializer.swift @@ -88,8 +88,6 @@ internal class Serializer { if message.isChunkEncoded { try writeChunkEncodedBody(message, deadline: deadline) } - - try write(to: stream, body: message.body, deadline: deadline) } @inline(__always) diff --git a/Sources/HTTP/Server/Server.swift b/Sources/HTTP/Server/Server.swift index 138f4298..4c1d0bd3 100755 --- a/Sources/HTTP/Server/Server.swift +++ b/Sources/HTTP/Server/Server.swift @@ -27,7 +27,7 @@ public final class Server { header: String = defaultHeader, parserBufferSize: Int = 4096, serializerBufferSize: Int = 4096, - parseTimeout: Duration = 5.minutes, + parseTimeout: Duration = 10.seconds, serializeTimeout: Duration = 5.minutes, closeConnectionTimeout: Duration = 1.minute, respond: @escaping Respond @@ -101,7 +101,7 @@ public final class Server { group.cancel() } - private static var defaultHeader: String { + public static var defaultHeader: String { var header = "\n" header += " _____ \n" header += " _.-ˆˆ-._.-ˆˆ-._ /__ / ____ _ __ ____ \n" @@ -128,11 +128,14 @@ public final class Server { do { try self.process(stream) } catch SystemError.brokenPipe { + Logger.error("Broken pipe while processing connection.") return } catch SystemError.connectionResetByPeer { - return + Logger.error("Connection reset by peer while processing connection.") + return } catch VeniceError.canceledCoroutine { - return + Logger.error("Cancelled coroutine while processing connection.") + return } catch { Logger.error("Error while processing connection.", error: error) } diff --git a/Sources/IO/Stream.swift b/Sources/IO/Stream.swift new file mode 100644 index 00000000..d2af817f --- /dev/null +++ b/Sources/IO/Stream.swift @@ -0,0 +1,14 @@ +import Core +import Venice + +public protocol ReadableStream : Readable { + func open(deadline: Deadline) throws + func close(deadline: Deadline) throws +} + +public protocol WritableStream : Writable { + func open(deadline: Deadline) throws + func close(deadline: Deadline) throws +} + +public protocol DuplexStream : ReadableStream, WritableStream {} diff --git a/Sources/IO/TCPStream.swift b/Sources/IO/TCPStream.swift index 53ea32f7..db20bc47 100755 --- a/Sources/IO/TCPStream.swift +++ b/Sources/IO/TCPStream.swift @@ -69,7 +69,11 @@ public final class TCPStream : DuplexStream { } } - return UnsafeRawBufferPointer(buffer).prefix(upTo: result) + #if swift(>=3.2) + return UnsafeRawBufferPointer(rebasing: buffer.prefix(upTo: result)) + #else + return UnsafeRawBufferPointer(buffer.prefix(upTo: result)) + #endif } public func write(_ buffer: UnsafeRawBufferPointer, deadline: Deadline) throws { diff --git a/Sources/IO/TLSStream.swift b/Sources/IO/TLSStream.swift index bb11c76e..cd484ebb 100644 --- a/Sources/IO/TLSStream.swift +++ b/Sources/IO/TLSStream.swift @@ -97,7 +97,11 @@ public final class TLSStream : DuplexStream { } } - return UnsafeRawBufferPointer(buffer.prefix(result)) + #if swift(>=3.2) + return UnsafeRawBufferPointer(rebasing: buffer.prefix(upTo: result)) + #else + return UnsafeRawBufferPointer(buffer.prefix(upTo: result)) + #endif } public func write(_ buffer: UnsafeRawBufferPointer, deadline: Deadline) throws { diff --git a/Sources/Content/JSON/JSON.swift b/Sources/Media/JSON/JSON.swift similarity index 54% rename from Sources/Content/JSON/JSON.swift rename to Sources/Media/JSON/JSON.swift index 2552cdfb..51a58484 100644 --- a/Sources/Content/JSON/JSON.swift +++ b/Sources/Media/JSON/JSON.swift @@ -1,37 +1,5 @@ import Foundation -public enum JSONError : Error { - case noContent(type: Any.Type) - case cannotInitializeWithContent(type: Any.Type, content: Content.Type) - case cannotInitialize(type: Any.Type, json: JSON) - case valueNotArray(indexPath: [IndexPathComponentValue], json: JSON) - case outOfBounds(indexPath: [IndexPathComponentValue], json: JSON) - case valueNotDictionary(indexPath: [IndexPathComponentValue], json: JSON) - case valueNotFound(indexPath: [IndexPathComponentValue], json: JSON) -} - -extension JSONError : CustomStringConvertible { - /// :nodoc: - public var description: String { - switch self { - case let .noContent(type): - return "Cannot initialize type \"\(String(describing: type))\" with no content." - case let .cannotInitialize(type, json): - return "Cannot initialize type \"\(String(describing: type))\" with json \(json)." - case let .cannotInitializeWithContent(type, content): - return "Cannot initialize type \"\(String(describing: type))\" with type \(content)." - case let .valueNotArray(indexPath, content): - return "Cannot get json element for index path \"\(indexPath.string)\". Element is not an array \(content)." - case let .outOfBounds(indexPath, content): - return "Cannot get json element for index path \"\(indexPath.string)\". Index is out of bounds for element \(content)." - case let .valueNotDictionary(indexPath, content): - return "Cannot get json element for index path \"\(indexPath.string)\". Element is not a dictionary \(content)." - case let .valueNotFound(indexPath, content): - return "Cannot get json element for index path \"\(indexPath.string)\". Key is not present in element \(content)." - } - } -} - public enum JSON { case null case bool(Bool) @@ -43,58 +11,7 @@ public enum JSON { } extension JSON { - /// :nodoc: - public init(_ value: T?) { - self = value?.json() ?? .null - } - - /// :nodoc: - public init(_ values: [T]?) { - if let values = values { - self = .array(values.map({ $0.json() })) - } else { - self = .null - } - } - - /// :nodoc: - public init(_ values: [T?]?) { - if let values = values { - self = .array(values.map({ $0?.json() ?? .null})) - } else { - self = .null - } - } - - /// :nodoc: - public init(_ values: [String: T]?) { - if let values = values { - var dictionary: [String: JSON] = [:] - - for (key, value) in values.map({($0.key, $0.value.json() )}) { - dictionary[key] = value - } - - self = .object(dictionary) - } else { - self = .null - } - } - - /// :nodoc: - public init(_ values: [String: T?]?) { - if let values = values { - var dictionary: [String: JSON] = [:] - - for (key, value) in values.map({($0.key, $0.value?.json() ?? .null)}) { - dictionary[key] = value - } - - self = .object(dictionary) - } else { - self = .null - } - } + public static var mediaType: MediaType = .json } extension JSON { @@ -159,51 +76,6 @@ extension JSON { } } -extension JSON { - public func get(_ indexPath: IndexPathComponent...) throws -> T { - let content = try _get(indexPath as [IndexPathComponent]) - return try T(json: content) - } - - public func get(_ indexPath: IndexPathComponent...) throws -> JSON { - return try _get(indexPath as [IndexPathComponent]) - } - - private func _get(_ indexPath: [IndexPathComponent]) throws -> JSON { - var value = self - var visited: [IndexPathComponentValue] = [] - - for component in indexPath { - visited.append(component.indexPathComponent) - - switch component.indexPathComponent { - case let .index(index): - guard case let .array(array) = value else { - throw JSONError.valueNotArray(indexPath: visited, json: self) - } - - guard array.indices.contains(index) else { - throw JSONError.outOfBounds(indexPath: visited, json: self) - } - - value = array[index] - case let .key(key): - guard case let .object(dictionary) = value else { - throw JSONError.valueNotDictionary(indexPath: visited, json: self) - } - - guard let newValue = dictionary[key] else { - throw JSONError.valueNotFound(indexPath: visited, json: self) - } - - value = newValue - } - } - - return value - } -} - extension JSON : Equatable { /// :nodoc: public static func == (lhs: JSON, rhs: JSON) -> Bool { @@ -268,7 +140,11 @@ extension JSON : ExpressibleByStringLiteral { extension JSON : ExpressibleByArrayLiteral { /// :nodoc: public init(arrayLiteral elements: JSON...) { - self = .array(elements.map({ $0.json() })) + self = .array(elements) + } + + public init(arrayLiteral elements: [JSON]) { + self = .array(elements) } } @@ -278,7 +154,7 @@ extension JSON : ExpressibleByDictionaryLiteral { var dictionary = [String: JSON](minimumCapacity: elements.count) for (key, value) in elements { - dictionary[key] = value.json() + dictionary[key] = value } self = .object(dictionary) diff --git a/Sources/Media/JSON/JSONDecodingMedia.swift b/Sources/Media/JSON/JSONDecodingMedia.swift new file mode 100644 index 00000000..2993bb9f --- /dev/null +++ b/Sources/Media/JSON/JSONDecodingMedia.swift @@ -0,0 +1,471 @@ +import Core +import Venice + +extension JSON : DecodingMedia { + public init(from readable: Readable, deadline: Deadline) throws { + let parser = JSONParser() + let buffer = UnsafeMutableRawBufferPointer.allocate(count: 4096) + + defer { + buffer.deallocate() + } + + while true { + let read = try readable.read(buffer, deadline: deadline) + + guard !read.isEmpty else { + break + } + + guard let json = try parser.parse(read) else { + continue + } + + self = json + return + } + + self = try parser.finish() + } + + public func keyCount() -> Int? { + if case let .object(object) = self { + return object.keys.count + } + + if case let .array(array) = self { + return array.count + } + + return nil + } + + public func allKeys(keyedBy: Key.Type) -> [Key] where Key : CodingKey { + if case let .object(object) = self { + return object.keys.flatMap({ Key(stringValue: $0) }) + } + + if case let .array(array) = self { + return array.indices.flatMap({ Key(intValue: $0) }) + } + + return [] + } + + public func contains(_ key: Key) -> Bool where Key : CodingKey { + guard let map = try? decodeIfPresent(type(of: self), forKey: key) else { + return false + } + + return map != nil + } + + public func keyedContainer() throws -> DecodingMedia { + guard isObject else { + throw DecodingError.typeMismatch(type(of: self), DecodingError.Context()) + } + + return self + } + + public func unkeyedContainer() throws -> DecodingMedia { + guard isArray else { + throw DecodingError.typeMismatch(type(of: self), DecodingError.Context()) + } + + return self + } + + public func singleValueContainer() throws -> DecodingMedia { + if isObject { + throw DecodingError.typeMismatch(type(of: self), DecodingError.Context()) + } + + if isArray { + throw DecodingError.typeMismatch(type(of: self), DecodingError.Context()) + } + + return self + } + + public func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia { + if let index = key.intValue { + guard case let .array(array) = self else { + throw DecodingError.typeMismatch( + [JSON].self, + DecodingError.Context(codingPath: [key]) + ) + } + + guard array.indices.contains(index) else { + throw DecodingError.valueNotFound( + JSON.self, + DecodingError.Context(codingPath: [key]) + ) + } + + return array[index] + } else { + guard case let .object(object) = self else { + throw DecodingError.typeMismatch( + [String: JSON].self, + DecodingError.Context(codingPath: [key]) + ) + } + + guard let newValue = object[key.stringValue] else { + throw DecodingError.valueNotFound( + JSON.self, + DecodingError.Context(codingPath: [key]) + ) + } + + return newValue + } + } + + public func decodeIfPresent( + _ type: DecodingMedia.Type, + forKey key: CodingKey + ) throws -> DecodingMedia? { + if let index = key.intValue { + guard case let .array(array) = self else { + throw DecodingError.typeMismatch( + [JSON].self, + DecodingError.Context(codingPath: [key]) + ) + } + + guard array.indices.contains(index) else { + throw DecodingError.valueNotFound( + JSON.self, + DecodingError.Context(codingPath: [key]) + ) + } + + return array[index] + + } else { + guard case let .object(object) = self else { + throw DecodingError.typeMismatch( + [String: JSON].self, + DecodingError.Context(codingPath: [key]) + ) + } + + guard let newValue = object[key.stringValue] else { + throw DecodingError.valueNotFound( + JSON.self, + DecodingError.Context(codingPath: [key]) + ) + } + + return newValue + + } + } + + public func decodeNil() -> Bool { + return isNull + } + + public func decode(_ type: Bool.Type) throws -> Bool { + if case .null = self { + throw DecodingError.valueNotFound( + Bool.self, + DecodingError.Context() + ) + } + + guard case let .bool(bool) = self else { + throw DecodingError.typeMismatch( + Bool.self, + DecodingError.Context() + ) + } + + return bool + } + + public func decode(_ type: Int.Type) throws -> Int { + if case .null = self { + throw DecodingError.valueNotFound( + Int.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self { + return int + } + + if case let .double(double) = self, let int = Int(exactly: double) { + return int + } + + throw DecodingError.typeMismatch( + Int.self, + DecodingError.Context() + ) + } + + public func decode(_ type: Int8.Type) throws -> Int8 { + if case .null = self { + throw DecodingError.valueNotFound( + Int8.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let int8 = Int8(exactly: int) { + return int8 + } + + if case let .double(double) = self, let int8 = Int8(exactly: double) { + return int8 + } + + throw DecodingError.typeMismatch( + Int8.self, + DecodingError.Context() + ) + } + + public func decode(_ type: Int16.Type) throws -> Int16 { + if case .null = self { + throw DecodingError.valueNotFound( + Int16.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let int16 = Int16(exactly: int) { + return int16 + } + + if case let .double(double) = self, let int16 = Int16(exactly: double) { + return int16 + } + + throw DecodingError.typeMismatch( + Int16.self, + DecodingError.Context() + ) + } + + public func decode(_ type: Int32.Type) throws -> Int32 { + if case .null = self { + throw DecodingError.valueNotFound( + Int32.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let int32 = Int32(exactly: int) { + return int32 + } + + if case let .double(double) = self, let int32 = Int32(exactly: double) { + return int32 + } + + throw DecodingError.typeMismatch( + Int32.self, + DecodingError.Context() + ) + } + + public func decode(_ type: Int64.Type) throws -> Int64 { + if case .null = self { + throw DecodingError.valueNotFound( + Int64.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let int64 = Int64(exactly: int) { + return int64 + } + + if case let .double(double) = self, let int64 = Int64(exactly: double) { + return int64 + } + + throw DecodingError.typeMismatch( + Int64.self, + DecodingError.Context() + ) + } + + public func decode(_ type: UInt.Type) throws -> UInt { + if case .null = self { + throw DecodingError.valueNotFound( + UInt.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let uint = UInt(exactly: int) { + return uint + } + + if case let .double(double) = self, let uint = UInt(exactly: double) { + return uint + } + + throw DecodingError.typeMismatch( + UInt.self, + DecodingError.Context() + ) + } + + public func decode(_ type: UInt8.Type) throws -> UInt8 { + if case .null = self { + throw DecodingError.valueNotFound( + UInt8.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let uint8 = UInt8(exactly: int) { + return uint8 + } + + if case let .double(double) = self, let uint8 = UInt8(exactly: double) { + return uint8 + } + + throw DecodingError.typeMismatch( + UInt8.self, + DecodingError.Context() + ) + } + + public func decode(_ type: UInt16.Type) throws -> UInt16 { + if case .null = self { + throw DecodingError.valueNotFound( + UInt16.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let uint16 = UInt16(exactly: int) { + return uint16 + } + + if case let .double(double) = self, let uint16 = UInt16(exactly: double) { + return uint16 + } + + throw DecodingError.typeMismatch( + UInt16.self, + DecodingError.Context() + ) + } + + public func decode(_ type: UInt32.Type) throws -> UInt32 { + if case .null = self { + throw DecodingError.valueNotFound( + UInt32.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let uint32 = UInt32(exactly: int) { + return uint32 + } + + if case let .double(double) = self, let uint32 = UInt32(exactly: double) { + return uint32 + } + + throw DecodingError.typeMismatch( + UInt32.self, + DecodingError.Context() + ) + } + + public func decode(_ type: UInt64.Type) throws -> UInt64 { + if case .null = self { + throw DecodingError.valueNotFound( + UInt64.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let uint64 = UInt64(exactly: int) { + return uint64 + } + + if case let .double(double) = self, let uint64 = UInt64(exactly: double) { + return uint64 + } + + throw DecodingError.typeMismatch( + UInt64.self, + DecodingError.Context() + ) + } + + public func decode(_ type: Float.Type) throws -> Float { + if case .null = self { + throw DecodingError.valueNotFound( + Float.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let float = Float(exactly: int) { + return float + } + + if case let .double(double) = self, let float = Float(exactly: double) { + return float + } + + throw DecodingError.typeMismatch( + Float.self, + DecodingError.Context() + ) + } + + public func decode(_ type: Double.Type) throws -> Double { + if case .null = self { + throw DecodingError.valueNotFound( + Double.self, + DecodingError.Context() + ) + } + + if case let .int(int) = self, let double = Double(exactly: int) { + return double + } + + if case let .double(double) = self { + return double + } + + throw DecodingError.typeMismatch( + Double.self, + DecodingError.Context() + ) + } + + public func decode(_ type: String.Type) throws -> String { + if case .null = self { + throw DecodingError.valueNotFound( + String.self, + DecodingError.Context() + ) + } + + guard case let .string(string) = self else { + throw DecodingError.typeMismatch( + String.self, + DecodingError.Context() + ) + } + + return string + } +} diff --git a/Sources/Media/JSON/JSONEncodingMedia.swift b/Sources/Media/JSON/JSONEncodingMedia.swift new file mode 100644 index 00000000..164b11b0 --- /dev/null +++ b/Sources/Media/JSON/JSONEncodingMedia.swift @@ -0,0 +1,158 @@ +import Core +import Venice + +extension JSON : EncodingMedia { + public func encode(to writable: Writable, deadline: Deadline) throws { + let serializer = JSONSerializer() + + try serializer.serialize(self) { buffer in + try writable.write(buffer, deadline: deadline) + } + } + + public func topLevel() throws -> EncodingMedia { + if isObject { + return self + } + + if isArray { + return self + } + + throw EncodingError.invalidValue(self, EncodingError.Context()) + } + + public static func makeKeyedContainer() throws -> EncodingMedia { + return JSON.object([:]) + } + + public static func makeUnkeyedContainer() throws -> EncodingMedia { + return JSON.array([]) + } + + public mutating func encode(_ value: EncodingMedia, forKey key: CodingKey) throws { + guard case var .object(object) = self else { + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [key])) + } + + guard let json = value as? JSON else { + throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [key])) + } + + object[key.stringValue] = json + self = .object(object) + } + + public mutating func encode(_ value: EncodingMedia) throws { + guard case var .array(array) = self else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + guard let json = value as? JSON else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + array.append(json) + self = .array(array) + } + + public static func encodeNil() throws -> EncodingMedia { + return JSON.null + } + + public static func encode(_ value: Bool) throws -> EncodingMedia { + return JSON.bool(value) + } + + public static func encode(_ value: Int) throws -> EncodingMedia { + return JSON.int(value) + } + + public static func encode(_ value: Int8) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: Int16) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: Int32) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: Int64) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: UInt) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: UInt8) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: UInt16) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: UInt32) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: UInt64) throws -> EncodingMedia { + guard let int = Int(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.int(int) + } + + public static func encode(_ value: Float) throws -> EncodingMedia { + guard let double = Double(exactly: value) else { + throw EncodingError.invalidValue(value, EncodingError.Context()) + } + + return JSON.double(double) + } + + public static func encode(_ value: Double) throws -> EncodingMedia { + return JSON.double(value) + } + + public static func encode(_ value: String) throws -> EncodingMedia { + return JSON.string(value) + } +} diff --git a/Sources/Content/JSON/JSONParser.swift b/Sources/Media/JSON/JSONParser.swift similarity index 92% rename from Sources/Content/JSON/JSONParser.swift rename to Sources/Media/JSON/JSONParser.swift index 5b2c1a22..b07a6c00 100755 --- a/Sources/Content/JSON/JSONParser.swift +++ b/Sources/Media/JSON/JSONParser.swift @@ -10,27 +10,27 @@ public struct JSONParserError : Error, CustomStringConvertible { public let description: String } -public final class JSONParser { - public struct Options : OptionSet { - public let rawValue: Int - public static let allowComments = Options(rawValue: 1 << 0) - public static let dontValidateStrings = Options(rawValue: 1 << 1) - public static let allowTrailingGarbage = Options(rawValue: 1 << 2) - public static let allowMultipleValues = Options(rawValue: 1 << 3) - public static let allowPartialValues = Options(rawValue: 1 << 4) +final class JSONParser { + struct Options : OptionSet { + let rawValue: Int + static let allowComments = Options(rawValue: 1 << 0) + static let dontValidateStrings = Options(rawValue: 1 << 1) + static let allowTrailingGarbage = Options(rawValue: 1 << 2) + static let allowMultipleValues = Options(rawValue: 1 << 3) + static let allowPartialValues = Options(rawValue: 1 << 4) - public init(rawValue: Int) { + init(rawValue: Int) { self.rawValue = rawValue } } - public static func parse(_ bytes: UnsafeRawBufferPointer, options: Options = []) throws -> JSON { + static func parse(_ bytes: UnsafeRawBufferPointer, options: Options = []) throws -> JSON { let parser = JSONParser(options: options) try parser.parse(bytes) return try parser.finish() } - public let options: Options + let options: Options fileprivate var state: JSONParserState = JSONParserState(dictionary: true) fileprivate var stack: [JSONParserState] = [] @@ -42,11 +42,11 @@ public final class JSONParser { fileprivate var handle: yajl_handle? - public convenience init() { + convenience init() { self.init(options: []) } - public init(options: Options = []) { + init(options: Options = []) { self.options = options self.state.dictionaryKey = "root" self.stack.reserveCapacity(12) @@ -62,7 +62,6 @@ public final class JSONParser { yajl_config_set(handle, yajl_allow_trailing_garbage, options.contains(.allowTrailingGarbage) ? 1 : 0) yajl_config_set(handle, yajl_allow_multiple_values, options.contains(.allowMultipleValues) ? 1 : 0) yajl_config_set(handle, yajl_allow_partial_values, options.contains(.allowPartialValues) ? 1 : 0) - } deinit { @@ -70,8 +69,7 @@ public final class JSONParser { buffer.deallocate(capacity: bufferCapacity) } - @discardableResult - public func parse(_ bytes: UnsafeRawBufferPointer) throws -> JSON? { + @discardableResult func parse(_ bytes: UnsafeRawBufferPointer) throws -> JSON? { let final = bytes.isEmpty guard result == nil else { @@ -129,7 +127,7 @@ public final class JSONParser { return result } - public func finish() throws -> JSON { + func finish() throws -> JSON { let empty = UnsafeRawBufferPointer(start: nil, count: 0) guard let result = try self.parse(empty) else { diff --git a/Sources/Content/JSON/JSONSchema.swift b/Sources/Media/JSON/JSONSchema.swift similarity index 76% rename from Sources/Content/JSON/JSONSchema.swift rename to Sources/Media/JSON/JSONSchema.swift index 54ebb6dc..fe2b427e 100644 --- a/Sources/Content/JSON/JSONSchema.swift +++ b/Sources/Media/JSON/JSONSchema.swift @@ -67,24 +67,22 @@ extension JSON { public struct Schema { public let title: String? public let description: String? - public let type: [JSONType]? let formats: [String: Validate] - let schema: JSON public init(_ schema: JSON) { - title = try? schema.get("title") - description = try? schema.get("description") + title = try? schema.decode(String.self, forKey: "title") + description = try? schema.decode(String.self, forKey: "description") - if let type = try? schema.get("type") as String { + if let type = try? schema.decode(String.self, forKey: "type") { if let type = JSONType(rawValue: type) { self.type = [type] } else { self.type = [] } - } else if let types = try? schema.get("type") as [String] { + } else if let types = try? schema.decode([String].self, forKey: "type") { self.type = types.map { JSONType(rawValue: $0) }.filter { $0 != nil }.map { $0! } } else { self.type = [] @@ -110,26 +108,26 @@ extension JSON { let reference = tmp.removingPercentEncoding { var components = reference.components(separatedBy: "/") - var schema = self.schema + let schema = self.schema while let component = components.first { components.remove(at: components.startIndex) - if let _ = try? schema.get(component) as [String: JSON] { - schema = try! schema.get(component) as JSON - continue - } else if let _ = try? schema.get(component) as [[String: JSON]] { - let schemas = try! schema.get(component) as [JSON] - - if let component = components.first, let index = Int(component) { - components.remove(at: components.startIndex) - - if schemas.count > index { - schema = schemas[index] - continue - } - } - } +// if let _ = try? schema.get(component) as [String: JSON] { +// schema = try! schema.get(component) as JSON +// continue +// } else if let _ = try? schema.get(component) as [[String: JSON]] { +// let schemas = try! schema.get(component) as [JSON] +// +// if let component = components.first, let index = Int(component) { +// components.remove(at: components.startIndex) +// +// if schemas.count > index { +// schema = schemas[index] +// continue +// } +// } +// } return invalidValidation("Reference not found '\(component)' in '\(reference)'") } @@ -153,44 +151,44 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { return { schema in var validators: [Validate] = [] - if let ref = try? schema.get("$ref") as String { + if let ref = try? schema.decode(String.self, forKey: "$ref") { validators.append(root.validatorForReference(ref)) } - if let type = try? schema.get("type") as String { + if let type = try? schema.decode(String.self, forKey: "type") { validators.append(validateType(type)) } - if let _ = try? schema.get("allOf") as [[String: JSON]] { - let allOf = try! schema.get("allOf") as [JSON] - validators += allOf.map(getValidators(root)).reduce([], +) - } - - if let _ = try? schema.get("anyOf") as [[String: JSON]] { - let anyOfSchemas = try! schema.get("anyOf") as [JSON] - let anyOfValidators = anyOfSchemas.map(getValidators(root)).map(allOf) as [Validate] - validators.append(anyOf(anyOfValidators)) - } - - if let _ = try? schema.get("oneOf") as [[String: JSON]] { - let oneOfSchemas = try! schema.get("oneOf") as [JSON] - let oneOfValidators = oneOfSchemas.map(getValidators(root)).map(allOf) as [Validate] - validators.append(oneOf(oneOfValidators)) - } - - if let _ = try? schema.get("not") as [String: JSON] { - let notSchema = try! schema.get("not") as JSON - let notValidator = allOf(getValidators(root)(notSchema)) - validators.append(not(notValidator)) - } - - if let enumValues = try? schema.get("enum") as [JSON] { - validators.append(validateEnum(enumValues)) - } +// if let _ = try? schema.get("allOf") as [[String: JSON]] { +// let allOf = try! schema.get("allOf") as [JSON] +// validators += allOf.map(getValidators(root)).reduce([], +) +// } +// +// if let _ = try? schema.get("anyOf") as [[String: JSON]] { +// let anyOfSchemas = try! schema.get("anyOf") as [JSON] +// let anyOfValidators = anyOfSchemas.map(getValidators(root)).map(allOf) as [Validate] +// validators.append(anyOf(anyOfValidators)) +// } +// +// if let _ = try? schema.get("oneOf") as [[String: JSON]] { +// let oneOfSchemas = try! schema.get("oneOf") as [JSON] +// let oneOfValidators = oneOfSchemas.map(getValidators(root)).map(allOf) as [Validate] +// validators.append(oneOf(oneOfValidators)) +// } +// +// if let _ = try? schema.get("not") as [String: JSON] { +// let notSchema = try! schema.get("not") as JSON +// let notValidator = allOf(getValidators(root)(notSchema)) +// validators.append(not(notValidator)) +// } +// +// if let enumValues = try? schema.get("enum") as [JSON] { +// validators.append(validateEnum(enumValues)) +// } // String - if let maxLength = try? schema.get("maxLength") as Int { + if let maxLength = try? schema.decode(Int.self, forKey: "maxLength") { validators.append( validateLength( <=, @@ -200,7 +198,7 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { ) } - if let minLength = try? schema.get("minLength") as Int { + if let minLength = try? schema.decode(Int.self, forKey: "minLength") { validators.append( validateLength( >=, @@ -210,35 +208,35 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { ) } - if let pattern = try? schema.get("pattern") as String { + if let pattern = try? schema.decode(String.self, forKey: "pattern") { validators.append(validatePattern(pattern)) } // Numerical - if let multipleOf = try? schema.get("multipleOf") as Double { + if let multipleOf = try? schema.decode(Double.self, forKey: "multipleOf") { validators.append(validateMultipleOf(multipleOf)) } - if let minimum = try? schema.get("minimum") as Double { + if let minimum = try? schema.decode(Double.self, forKey: "minimum") { validators.append( validateNumericLength( minimum, comparator: >=, exclusiveComparitor: >, - exclusive: try? schema.get("exclusiveMinimum") as Bool, + exclusive: try? schema.decode(Bool.self, forKey: "exclusiveMinimum"), error: "Value is lower than minimum value of \(minimum)" ) ) } - if let maximum = try? schema.get("maximum") as Double { + if let maximum = try? schema.decode(Double.self, forKey: "maximum") { validators.append( validateNumericLength( maximum, comparator: <=, exclusiveComparitor: <, - exclusive: try? schema.get("exclusiveMaximum") as Bool, + exclusive: try? schema.decode(Bool.self, forKey: "exclusiveMaximum"), error: "Value exceeds maximum value of \(maximum)" ) ) @@ -246,7 +244,7 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { // Array - if let minItems = try? schema.get("minItems") as Int { + if let minItems = try? schema.decode(Int.self, forKey: "minItems") { validators.append( validateArrayLength( minItems, @@ -256,7 +254,7 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { ) } - if let maxItems = try? schema.get("maxItems") as Int { + if let maxItems = try? schema.decode(Int.self, forKey: "maxItems") { validators.append( validateArrayLength( maxItems, @@ -272,56 +270,56 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { // } // } - if let _ = try? schema.get("items") as [String: JSON] { - let items = try! schema.get("items") as JSON - let itemsValidators = allOf(getValidators(root)(items)) - validators.append(validateItems(itemsValidators)) - } else if let _ = try? schema.get("items") as [[String: JSON]] { - func createAdditionalItemsValidator(_ additionalItems: JSON?) -> Validate { - if let items = additionalItems, let _ = try? items.get() as [String: JSON] { - let additionalItems = try! additionalItems!.get() as JSON - return allOf(getValidators(root)(additionalItems)) - } - - let additionalItems = additionalItems.flatMap({ try? $0.get() as Bool }) ?? true - - if additionalItems { - return validValidation - } - - return invalidValidation("Additional results are not permitted in this array.") - } - - let additionalItemsValidator = createAdditionalItemsValidator( - try? schema.get("additionalItems") - ) - - let items = try! schema.get("items") as [JSON] - let itemValidators = items.map(getValidators(root)) - - func validateItems(_ value: JSON) -> ValidationResult { - if let value = try? value.get() as [JSON] { - var results: [ValidationResult] = [] - - for (index, element) in value.enumerated() { - if index >= itemValidators.count { - results.append(additionalItemsValidator(element)) - } else { - let validators = allOf(itemValidators[index]) - results.append(validators(element)) - } - } - - return flatten(results) - } - - return .valid - } - - validators.append(validateItems) - } +// if let _ = try? schema.get("items") as [String: JSON] { +// let items = try! schema.get("items") as JSON +// let itemsValidators = allOf(getValidators(root)(items)) +// validators.append(validateItems(itemsValidators)) +// } else if let _ = try? schema.get("items") as [[String: JSON]] { +// func createAdditionalItemsValidator(_ additionalItems: JSON?) -> Validate { +// if let items = additionalItems, let _ = try? items.get() as [String: JSON] { +// let additionalItems = try! additionalItems!.get() as JSON +// return allOf(getValidators(root)(additionalItems)) +// } +// +// let additionalItems = additionalItems.flatMap({ try? $0.decode(Bool.self) }) ?? true +// +// if additionalItems { +// return validValidation +// } +// +// return invalidValidation("Additional results are not permitted in this array.") +// } +// +// let additionalItemsValidator = createAdditionalItemsValidator( +// try? schema.get("additionalItems") +// ) +// +// let items = try! schema.get("items") as [JSON] +// let itemValidators = items.map(getValidators(root)) +// +// func validateItems(_ value: JSON) -> ValidationResult { +// if let value = try? value.get() as [JSON] { +// var results: [ValidationResult] = [] +// +// for (index, element) in value.enumerated() { +// if index >= itemValidators.count { +// results.append(additionalItemsValidator(element)) +// } else { +// let validators = allOf(itemValidators[index]) +// results.append(validators(element)) +// } +// } +// +// return flatten(results) +// } +// +// return .valid +// } +// +// validators.append(validateItems) +// } - if let maxProperties = try? schema.get("maxProperties") as Int { + if let maxProperties = try? schema.decode(Int.self, forKey: "maxProperties") { validators.append( validatePropertiesLength( maxProperties, @@ -331,7 +329,7 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { ) } - if let minProperties = try? schema.get("minProperties") as Int { + if let minProperties = try? schema.decode(Int.self, forKey: "minProperties") { validators.append( validatePropertiesLength( minProperties, @@ -341,7 +339,7 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { ) } - if let required = try? schema.get("required") as [String] { + if let required = try? schema.decode([String].self, forKey: "required") { validators.append(validateRequired(required)) } @@ -384,19 +382,19 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { // validators.append(validateProperties(properties, patternProperties: patternProperties, additionalProperties: additionalPropertyValidator)) // } - if let dependencies = try? schema.get("dependencies") as [String: JSON] { - for (key, dependencies) in dependencies { - if let _ = try? dependencies.get() as [String: JSON] { - let dependencies = try! dependencies.get() as JSON - let schema = allOf(getValidators(root)(dependencies)) - validators.append(validateDependency(key, validator: schema)) - } else if let dependencies = try? dependencies.get() as [String] { - validators.append(validateDependencies(key, dependencies: dependencies)) - } - } - } - - if let format = try? schema.get("format") as String { +// if let dependencies = try? schema.get("dependencies") as [String: JSON] { +// for (key, dependencies) in dependencies { +// if let _ = try? dependencies.get() as [String: JSON] { +// let dependencies = try! dependencies.get() as JSON +// let schema = allOf(getValidators(root)(dependencies)) +// validators.append(validateDependency(key, validator: schema)) +// } else if let dependencies = try? dependencies.get() as [String] { +// validators.append(validateDependencies(key, dependencies: dependencies)) +// } +// } +// } + + if let format = try? schema.decode(String.self, forKey: "format") { if let validator = root.formats[format] { validators.append(validator) } else { @@ -411,7 +409,7 @@ func getValidators(_ root: JSON.Schema) -> (_ schema: JSON) -> [Validate] { } public func validate(_ value: JSON, schema: [String: JSON]) -> ValidationResult { - let schema = JSON(schema) + let schema = JSON.object(schema) let root = JSON.Schema(schema) let validator = allOf(getValidators(root)(schema)) let result = validator(value) @@ -581,7 +579,7 @@ func validateLength( error: String ) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as String { + if let value = try? value.decode(String.self) { if !comparator(value.characters.count, length) { return .invalid([error]) } @@ -594,7 +592,7 @@ func validateLength( func validatePattern(_ pattern: String) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as String { + if let value = try? value.decode(String.self) { let expression = try? NSRegularExpression( pattern: pattern, options: [] @@ -620,7 +618,7 @@ func validatePattern(_ pattern: String) -> (_ value: JSON) -> ValidationResult { func validateMultipleOf(_ number: Double) -> (_ value: JSON) -> ValidationResult { return { value in if number > 0.0 { - if let value = try? value.get() as Double { + if let value = try? value.decode(Double.self) { let result = value / number if result != floor(result) { @@ -641,7 +639,7 @@ func validateNumericLength( error: String ) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as Double { + if let value = try? value.decode(Double.self) { if exclusive ?? false { if !exclusiveComparitor(value, length) { return .invalid([error]) @@ -665,7 +663,7 @@ func validateArrayLength( error: String ) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as [JSON] { + if case let .array(value) = value { if !comparator(value.count, rhs) { return .invalid([error]) } @@ -683,7 +681,7 @@ func validatePropertiesLength( error: String ) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as [String: JSON] { + if case let .object(value) = value { if !comparator(length, value.count) { return .invalid([error]) } @@ -695,7 +693,7 @@ func validatePropertiesLength( func validateRequired(_ required: [String]) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as [String: JSON] { + if case let .object(value) = value { if (required.filter { r in !value.keys.contains(r) }.count == 0) { return .valid } @@ -712,7 +710,7 @@ func validateDependency( validator: @escaping Validate ) -> (_ value: JSON) -> ValidationResult { return { value in - if let object = try? value.get() as [String: JSON] { + if case let .object(object) = value { if object[key] != nil { return validator(value) } @@ -727,7 +725,7 @@ func validateDependencies( dependencies: [String] ) -> (_ value: JSON) -> ValidationResult { return { value in - if let value = try? value.get() as [String: JSON] { + if case let .object(value) = value { if value[key] != nil { return flatten(dependencies.map { dependency in if value[dependency] == nil { @@ -747,7 +745,7 @@ func validateItems( _ itemsValidators: @escaping (JSON) -> ValidationResult ) -> (_ value: JSON) -> ValidationResult { return { value in - if let document = try? value.get() as [JSON] { + if case let .array(document) = value { return flatten(document.map(itemsValidators)) } @@ -864,7 +862,7 @@ extension String { func stringByRemovingPrefix(_ prefix: String) -> String? { if hasPrefix(prefix) { let index = characters.index(startIndex, offsetBy: prefix.characters.count) - return substring(from: index) + return String(self[index...]) } return nil diff --git a/Sources/Content/JSON/JSONSerializer.swift b/Sources/Media/JSON/JSONSerializer.swift similarity index 84% rename from Sources/Content/JSON/JSONSerializer.swift rename to Sources/Media/JSON/JSONSerializer.swift index 67bd11bd..b86bab0d 100755 --- a/Sources/Content/JSON/JSONSerializer.swift +++ b/Sources/Media/JSON/JSONSerializer.swift @@ -8,25 +8,21 @@ import CYAJL import Venice public struct JSONSerializerError : Error, CustomStringConvertible { - let reason: String - - public var description: String { - return reason - } + public let description: String } -public final class JSONSerializer { +final class JSONSerializer { private var ordering: Bool private var buffer: String = "" private var bufferSize: Int = 0 private var handle: yajl_gen? - public convenience init() { + convenience init() { self.init(ordering: false) } - public init(ordering: Bool) { + init(ordering: Bool) { self.ordering = ordering self.handle = yajl_gen_alloc(nil) } @@ -35,7 +31,7 @@ public final class JSONSerializer { yajl_gen_free(handle) } - public func serialize(_ json: JSON, bufferSize: Int = 4096, body: (UnsafeRawBufferPointer) throws -> Void) throws { + func serialize(_ json: JSON, bufferSize: Int = 4096, body: (UnsafeRawBufferPointer) throws -> Void) throws { yajl_gen_reset(handle, nil) self.bufferSize = bufferSize try generate(json, body: body) @@ -141,23 +137,23 @@ public final class JSONSerializer { private func check(status: yajl_gen_status) throws { switch status { case yajl_gen_keys_must_be_strings: - throw JSONSerializerError(reason: "Keys must be strings.") + throw JSONSerializerError(description: "Keys must be strings.") case yajl_max_depth_exceeded: - throw JSONSerializerError(reason: "Max depth exceeded.") + throw JSONSerializerError(description: "Max depth exceeded.") case yajl_gen_in_error_state: - throw JSONSerializerError(reason: "In error state.") + throw JSONSerializerError(description: "In error state.") case yajl_gen_invalid_number: - throw JSONSerializerError(reason: "Invalid number.") + throw JSONSerializerError(description: "Invalid number.") case yajl_gen_no_buf: - throw JSONSerializerError(reason: "No buffer.") + throw JSONSerializerError(description: "No buffer.") case yajl_gen_invalid_string: - throw JSONSerializerError(reason: "Invalid string.") + throw JSONSerializerError(description: "Invalid string.") case yajl_gen_status_ok: break case yajl_gen_generation_complete: break default: - throw JSONSerializerError(reason: "Unknown.") + throw JSONSerializerError(description: "Unknown.") } } @@ -166,7 +162,7 @@ public final class JSONSerializer { var bufferLength: Int = 0 guard yajl_gen_get_buf(handle, &buffer, &bufferLength) == yajl_gen_status_ok else { - throw JSONSerializerError(reason: "Could not get buffer.") + throw JSONSerializerError(description: "Could not get buffer.") } guard bufferLength >= highwater else { diff --git a/Sources/Media/Media/Coding.swift b/Sources/Media/Media/Coding.swift new file mode 100644 index 00000000..62476916 --- /dev/null +++ b/Sources/Media/Media/Coding.swift @@ -0,0 +1,71 @@ +enum MapSuperKey : String, CodingKey { + case `super` +} + +extension String : CodingKey { + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self = stringValue + } + + public var intValue: Int? { + return Int(self) + } + + public init?(intValue: Int) { + self = String(intValue) + } +} + +extension Int : CodingKey { + public var stringValue: String { + return description + } + + public init?(stringValue: String) { + guard let int = Int(stringValue) else { + return nil + } + + self = int + } + + public var intValue: Int? { + return self + } + + public init?(intValue: Int) { + self = intValue + } +} + +extension EncodingError.Context { + public init(codingPath: [CodingKey] = []) { + self.codingPath = codingPath + self.debugDescription = "" + self.underlyingError = nil; + } + + public init(debugDescription: String) { + self.codingPath = [] + self.debugDescription = debugDescription + self.underlyingError = nil + } +} + +extension DecodingError.Context { + public init(codingPath: [CodingKey] = []) { + self.codingPath = codingPath + self.debugDescription = "" + self.underlyingError = nil + } + + public init(debugDescription: String) { + self.codingPath = [] + self.debugDescription = debugDescription + self.underlyingError = nil + } +} diff --git a/Sources/Media/Media/DecodingMedia.swift b/Sources/Media/Media/DecodingMedia.swift new file mode 100644 index 00000000..ada92fc8 --- /dev/null +++ b/Sources/Media/Media/DecodingMedia.swift @@ -0,0 +1,514 @@ +import Core +import Venice + +extension Decodable { + public init( + from map: Map, + userInfo: [CodingUserInfoKey: Any] = [:] + ) throws { + let decoder = MediaDecoder(referencing: map, userInfo: userInfo) + try self.init(from: decoder) + } +} + +extension DecodingMedia { + public static func decode( + _ type: T.Type, + from readable: Readable, + deadline: Deadline, + userInfo: [CodingUserInfoKey: Any] = [:] + ) throws -> T { + let media = try self.init(from: readable, deadline: deadline) + return try T(from: media, userInfo: userInfo) + } + + public init(from buffer: UnsafeRawBufferPointer, deadline: Deadline) throws { + let readable = ReadableBuffer(buffer) + try self.init(from: readable, deadline: deadline) + } +} + +public protocol DecodingMedia { + static var mediaType: MediaType { get } + + init(from readable: Readable, deadline: Deadline) throws + + func keyCount() -> Int? + func allKeys(keyedBy: Key.Type) -> [Key] + func contains(_ key: Key) -> Bool + + func keyedContainer() throws -> DecodingMedia + func unkeyedContainer() throws -> DecodingMedia + func singleValueContainer() throws -> DecodingMedia + + func decodeIfPresent(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia? + func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia + func decodeNil() -> Bool + func decode(_ type: Bool.Type) throws -> Bool + func decode(_ type: Int.Type) throws -> Int + func decode(_ type: Int8.Type) throws -> Int8 + func decode(_ type: Int16.Type) throws -> Int16 + func decode(_ type: Int32.Type) throws -> Int32 + func decode(_ type: Int64.Type) throws -> Int64 + func decode(_ type: UInt.Type) throws -> UInt + func decode(_ type: UInt8.Type) throws -> UInt8 + func decode(_ type: UInt16.Type) throws -> UInt16 + func decode(_ type: UInt32.Type) throws -> UInt32 + func decode(_ type: UInt64.Type) throws -> UInt64 + func decode(_ type: Float.Type) throws -> Float + func decode(_ type: Double.Type) throws -> Double + func decode(_ type: String.Type) throws -> String + + // Optional + + func keyedContainer(forKey key: CodingKey) throws -> DecodingMedia + func unkeyedContainer(forKey key: CodingKey) throws -> DecodingMedia + + func decodeIfPresent(_ type: Bool.Type, forKey key: CodingKey) throws -> Bool? + func decodeIfPresent(_ type: Int.Type, forKey key: CodingKey) throws -> Int? + func decodeIfPresent(_ type: Int8.Type, forKey key: CodingKey) throws -> Int8? + func decodeIfPresent(_ type: Int16.Type, forKey key: CodingKey) throws -> Int16? + func decodeIfPresent(_ type: Int32.Type, forKey key: CodingKey) throws -> Int32? + func decodeIfPresent(_ type: Int64.Type, forKey key: CodingKey) throws -> Int64? + func decodeIfPresent(_ type: UInt.Type, forKey key: CodingKey) throws -> UInt? + func decodeIfPresent(_ type: UInt8.Type, forKey key: CodingKey) throws -> UInt8? + func decodeIfPresent(_ type: UInt16.Type, forKey key: CodingKey) throws -> UInt16? + func decodeIfPresent(_ type: UInt32.Type, forKey key: CodingKey) throws -> UInt32? + func decodeIfPresent(_ type: UInt64.Type, forKey key: CodingKey) throws -> UInt64? + func decodeIfPresent(_ type: Float.Type, forKey key: CodingKey) throws -> Float? + func decodeIfPresent(_ type: Double.Type, forKey key: CodingKey) throws -> Double? + func decodeIfPresent(_ type: String.Type, forKey key: CodingKey) throws -> String? + + func decodeIfPresent(_ type: Bool.Type) throws -> Bool? + func decodeIfPresent(_ type: Int.Type) throws -> Int? + func decodeIfPresent(_ type: Int8.Type) throws -> Int8? + func decodeIfPresent(_ type: Int16.Type) throws -> Int16? + func decodeIfPresent(_ type: Int32.Type) throws -> Int32? + func decodeIfPresent(_ type: Int64.Type) throws -> Int64? + func decodeIfPresent(_ type: UInt.Type) throws -> UInt? + func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? + func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? + func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? + func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? + func decodeIfPresent(_ type: Float.Type) throws -> Float? + func decodeIfPresent(_ type: Double.Type) throws -> Double? + func decodeIfPresent(_ type: String.Type) throws -> String? +} + +extension DecodingMedia { + public func keyedContainer(forKey key: CodingKey) throws -> DecodingMedia { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.keyNotFound(key, DecodingError.Context()) + } + + return try map.keyedContainer() + } + + public func unkeyedContainer(forKey key: CodingKey) throws -> DecodingMedia { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.keyNotFound(key, DecodingError.Context()) + } + + return try map.unkeyedContainer() + } + + public func decode(_ type: D.Type, forKey key: CodingKey) throws -> D { + guard let map = try decodeIfPresent(Self.self, forKey: key) as? Self else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try D(from: map) + } + + public func decode(_ type: Bool.Type, forKey key: CodingKey) throws -> Bool { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Int.Type, forKey key: CodingKey) throws -> Int { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Int8.Type, forKey key: CodingKey) throws -> Int8 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Int16.Type, forKey key: CodingKey) throws -> Int16 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Int32.Type, forKey key: CodingKey) throws -> Int32 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Int64.Type, forKey key: CodingKey) throws -> Int64 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: UInt.Type, forKey key: CodingKey) throws -> UInt { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: UInt8.Type, forKey key: CodingKey) throws -> UInt8 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: UInt16.Type, forKey key: CodingKey) throws -> UInt16 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: UInt32.Type, forKey key: CodingKey) throws -> UInt32 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: UInt64.Type, forKey key: CodingKey) throws -> UInt64 { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Float.Type, forKey key: CodingKey) throws -> Float { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: Double.Type, forKey key: CodingKey) throws -> Double { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decode(_ type: String.Type, forKey key: CodingKey) throws -> String { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + throw DecodingError.valueNotFound(type, DecodingError.Context()) + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Bool.Type, forKey key: CodingKey) throws -> Bool? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Int.Type, forKey key: CodingKey) throws -> Int? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Int8.Type, forKey key: CodingKey) throws -> Int8? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Int16.Type, forKey key: CodingKey) throws -> Int16? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Int32.Type, forKey key: CodingKey) throws -> Int32? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Int64.Type, forKey key: CodingKey) throws -> Int64? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: UInt.Type, forKey key: CodingKey) throws -> UInt? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: UInt8.Type, forKey key: CodingKey) throws -> UInt8? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: UInt16.Type, forKey key: CodingKey) throws -> UInt16? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: UInt32.Type, forKey key: CodingKey) throws -> UInt32? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: UInt64.Type, forKey key: CodingKey) throws -> UInt64? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Float.Type, forKey key: CodingKey) throws -> Float? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Double.Type, forKey key: CodingKey) throws -> Double? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: String.Type, forKey key: CodingKey) throws -> String? { + guard let map = try decodeIfPresent(Self.self, forKey: key) else { + return nil + } + + guard !map.decodeNil() else { + return nil + } + + return try map.decode(type) + } + + public func decodeIfPresent(_ type: Bool.Type) throws -> Bool? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Int.Type) throws -> Int? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Int8.Type) throws -> Int8? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Int16.Type) throws -> Int16? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Int32.Type) throws -> Int32? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Int64.Type) throws -> Int64? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: UInt.Type) throws -> UInt? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Float.Type) throws -> Float? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: Double.Type) throws -> Double? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } + + public func decodeIfPresent(_ type: String.Type) throws -> String? { + guard !decodeNil() else { + return nil + } + + return try decode(type) + } +} diff --git a/Sources/Media/Media/EncodingMedia.swift b/Sources/Media/Media/EncodingMedia.swift new file mode 100644 index 00000000..757f7aee --- /dev/null +++ b/Sources/Media/Media/EncodingMedia.swift @@ -0,0 +1,207 @@ +import Core +import Venice + +extension EncodingMedia { + public init(from encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:]) throws { + let encoder = MediaEncoder(userInfo: userInfo) + try encodable.encode(to: encoder) + self = try encoder.topLevelMap() + } + + public static func encode( + _ value: T, + to writable: Writable, + deadline: Deadline, + userInfo: [CodingUserInfoKey: Any] = [:] + ) throws { + let media = try self.init(from: value, userInfo: userInfo) + try media.encode(to: writable, deadline: deadline) + } +} + +public protocol EncodingMedia { + static var mediaType: MediaType { get } + + func encode(to writable: Writable, deadline: Deadline) throws + + func topLevel() throws -> EncodingMedia + + static func makeKeyedContainer() throws -> EncodingMedia + static func makeUnkeyedContainer() throws -> EncodingMedia + + mutating func encode(_ value: EncodingMedia, forKey key: CodingKey) throws + mutating func encode(_ value: EncodingMedia) throws + + static func encodeNil() throws -> EncodingMedia + static func encode(_ value: Bool) throws -> EncodingMedia + static func encode(_ value: Int) throws -> EncodingMedia + static func encode(_ value: Int8) throws -> EncodingMedia + static func encode(_ value: Int16) throws -> EncodingMedia + static func encode(_ value: Int32) throws -> EncodingMedia + static func encode(_ value: Int64) throws -> EncodingMedia + static func encode(_ value: UInt) throws -> EncodingMedia + static func encode(_ value: UInt8) throws -> EncodingMedia + static func encode(_ value: UInt16) throws -> EncodingMedia + static func encode(_ value: UInt32) throws -> EncodingMedia + static func encode(_ value: UInt64) throws -> EncodingMedia + static func encode(_ value: Float) throws -> EncodingMedia + static func encode(_ value: Double) throws -> EncodingMedia + static func encode(_ value: String) throws -> EncodingMedia + + // Optional + + static func makeKeyedContainer(forKey key: CodingKey) throws -> EncodingMedia + static func makeUnkeyedContainer(forKey key: CodingKey) throws -> EncodingMedia + + mutating func encode(_ value: Bool, forKey key: CodingKey) throws + mutating func encode(_ value: Int, forKey key: CodingKey) throws + mutating func encode(_ value: Int8, forKey key: CodingKey) throws + mutating func encode(_ value: Int16, forKey key: CodingKey) throws + mutating func encode(_ value: Int32, forKey key: CodingKey) throws + mutating func encode(_ value: Int64, forKey key: CodingKey) throws + mutating func encode(_ value: UInt, forKey key: CodingKey) throws + mutating func encode(_ value: UInt8, forKey key: CodingKey) throws + mutating func encode(_ value: UInt16, forKey key: CodingKey) throws + mutating func encode(_ value: UInt32, forKey key: CodingKey) throws + mutating func encode(_ value: UInt64, forKey key: CodingKey) throws + mutating func encode(_ value: Float, forKey key: CodingKey) throws + mutating func encode(_ value: Double, forKey key: CodingKey) throws + mutating func encode(_ value: String, forKey key: CodingKey) throws + + mutating func encode(_ value: Bool) throws + mutating func encode(_ value: Int) throws + mutating func encode(_ value: Int8) throws + mutating func encode(_ value: Int16) throws + mutating func encode(_ value: Int32) throws + mutating func encode(_ value: Int64) throws + mutating func encode(_ value: UInt) throws + mutating func encode(_ value: UInt8) throws + mutating func encode(_ value: UInt16) throws + mutating func encode(_ value: UInt32) throws + mutating func encode(_ value: UInt64) throws + mutating func encode(_ value: Float) throws + mutating func encode(_ value: Double) throws + mutating func encode(_ value: String) throws +} + +extension EncodingMedia { + public static func makeKeyedContainer(forKey key: CodingKey) throws -> EncodingMedia { + return try makeKeyedContainer() + } + + public static func makeUnkeyedContainer(forKey key: CodingKey) throws -> EncodingMedia { + return try makeKeyedContainer() + } + + public mutating func encode(_ value: Bool, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Int, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Int8, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Int16, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Int32, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Int64, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: UInt, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: UInt8, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: UInt16, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: UInt32, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: UInt64, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Float, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Double, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: String, forKey key: CodingKey) throws { + try encode(Self.encode(value), forKey: key) + } + + public mutating func encode(_ value: Bool) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Int) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Int8) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Int16) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Int32) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Int64) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: UInt) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: UInt8) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: UInt16) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: UInt32) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: UInt64) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Float) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: Double) throws { + try encode(Self.encode(value)) + } + + public mutating func encode(_ value: String) throws { + try encode(Self.encode(value)) + } +} diff --git a/Sources/Media/Media/MediaCodable.swift b/Sources/Media/Media/MediaCodable.swift new file mode 100644 index 00000000..e5836b33 --- /dev/null +++ b/Sources/Media/Media/MediaCodable.swift @@ -0,0 +1,20 @@ +public typealias MediaCodable = MediaEncodable & MediaDecodable + +public enum MediaCodingError : Error { + case noDefaultEncodingMedia + case noDefaultDecodingMedia + case unsupportedMediaType +} + +extension MediaCodingError : CustomStringConvertible { + public var description: String { + switch self { + case .noDefaultEncodingMedia: + return "No default encoding media." + case .noDefaultDecodingMedia: + return "No default decoding media." + case .unsupportedMediaType: + return "Unsupported media type." + } + } +} diff --git a/Sources/Media/Media/MediaDecodable.swift b/Sources/Media/Media/MediaDecodable.swift new file mode 100644 index 00000000..4f38b691 --- /dev/null +++ b/Sources/Media/Media/MediaDecodable.swift @@ -0,0 +1,27 @@ +public protocol MediaDecodable : Decodable { + static var decodingMedia: [DecodingMedia.Type] { get } +} + +extension MediaDecodable { + public static var decodingMedia: [DecodingMedia.Type] { + return [JSON.self, XML.self] + } +} + +extension MediaDecodable { + public static func defaultDecodingMedia() throws -> DecodingMedia.Type { + guard let media = decodingMedia.first else { + throw MediaCodingError.noDefaultDecodingMedia + } + + return media + } + + public static func decodingMedia(for mediaType: MediaType) throws -> DecodingMedia.Type { + for media in decodingMedia where media.mediaType.matches(other: mediaType) { + return media + } + + throw MediaCodingError.unsupportedMediaType + } +} diff --git a/Sources/Media/Media/MediaDecoder/MediaDecoder.swift b/Sources/Media/Media/MediaDecoder/MediaDecoder.swift new file mode 100644 index 00000000..6a522a0b --- /dev/null +++ b/Sources/Media/Media/MediaDecoder/MediaDecoder.swift @@ -0,0 +1,49 @@ +import Core + +class MediaDecoder : Decoder { + var stack: Stack + var codingPath: [CodingKey] + var userInfo: [CodingUserInfoKey: Any] + + init( + referencing map: DecodingMedia, + at codingPath: [CodingKey] = [], + userInfo: [CodingUserInfoKey: Any] + ) { + self.stack = Stack() + self.stack.push(map) + self.codingPath = codingPath + self.userInfo = userInfo + } + + func with(pushedKey: CodingKey, _ work: () throws -> T) rethrows -> T { + codingPath.append(pushedKey) + + let result: T = try work() + codingPath.removeLast() + return result + } + + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { + let container = MediaKeyedDecodingContainer( + referencing: self, + wrapping: try stack.top.keyedContainer() + ) + + return KeyedDecodingContainer(container) + } + + func unkeyedContainer() throws -> UnkeyedDecodingContainer { + return MediaUnkeyedDecodingContainer( + referencing: self, + wrapping: try stack.top.unkeyedContainer() + ) + } + + func singleValueContainer() throws -> SingleValueDecodingContainer { + return MediaSingleValueDecodingContainer( + referencing: self, + wrapping: try stack.top.singleValueContainer() + ) + } +} diff --git a/Sources/Media/Media/MediaDecoder/MediaKeyedDecodingContainer.swift b/Sources/Media/Media/MediaDecoder/MediaKeyedDecodingContainer.swift new file mode 100644 index 00000000..9bd15c64 --- /dev/null +++ b/Sources/Media/Media/MediaDecoder/MediaKeyedDecodingContainer.swift @@ -0,0 +1,273 @@ +struct MediaKeyedDecodingContainer : KeyedDecodingContainerProtocol { + + typealias Key = K + + let decoder: MediaDecoder + let map: DecodingMedia + var codingPath: [CodingKey] + + init(referencing decoder: MediaDecoder, wrapping map: DecodingMedia) { + self.decoder = decoder + self.map = map + self.codingPath = decoder.codingPath + } + + var allKeys: [Key] { + return map.allKeys(keyedBy: Key.self) + } + + func contains(_ key: Key) -> Bool { + return map.contains(key) + } + + func decodeNil(forKey key: K) throws -> Bool { + return decoder.with(pushedKey: key) { + map.decodeNil() + } + } + + func decode(_ type: Bool.Type, forKey key: K) throws -> Bool { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Int.Type, forKey key: K) throws -> Int { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: UInt.Type, forKey key: K) throws -> UInt { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Float.Type, forKey key: K) throws -> Float { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: Double.Type, forKey key: K) throws -> Double { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: String.Type, forKey key: K) throws -> String { + return try decoder.with(pushedKey: key) { + try map.decode(type, forKey: key) + } + } + + func decode(_ type: T.Type, forKey key: K) throws -> T { + return try decoder.with(pushedKey: key) { + let value = try map.decode(Map.self, forKey: key) + decoder.stack.push(value) + let result: T = try T(from: decoder) + decoder.stack.pop() + return result + } + } + + func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? { + return try decoder.with(pushedKey: key) { + try map.decodeIfPresent(type, forKey: key) + } + } + + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? { + return try decoder.with(pushedKey: key) { + guard let value = try map.decodeIfPresent(Map.self, forKey: key) else { + return nil + } + + decoder.stack.push(value) + let result: T = try T(from: decoder) + decoder.stack.pop() + return result + } + } + + func nestedContainer( + keyedBy type: NestedKey.Type, + forKey key: Key + ) throws -> KeyedDecodingContainer { + return try decoder.with(pushedKey: key) { + let container = MediaKeyedDecodingContainer( + referencing: decoder, + wrapping: try map.keyedContainer(forKey: key) + ) + + return KeyedDecodingContainer(container) + } + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { + return try decoder.with(pushedKey: key) { + return MediaUnkeyedDecodingContainer( + referencing: decoder, + wrapping: try map.unkeyedContainer(forKey: key) + ) + } + } + + func superDecoder() throws -> Decoder { + return try _superDecoder(forKey: MapSuperKey.super) + } + + func superDecoder(forKey key: Key) throws -> Decoder { + return try _superDecoder(forKey: key) + } + + func _superDecoder(forKey key: CodingKey) throws -> Decoder { + return try decoder.with(pushedKey: key) { + guard let value = try map.decodeIfPresent(Map.self, forKey: key) else { + var path = codingPath + path.append(key) + + let context = DecodingError.Context( + codingPath: path, + debugDescription: "Key not found when expecting non-optional type \(Map.self) for coding key \"\(key)\"" + ) + + throw DecodingError.keyNotFound(key, context) + } + + return MediaDecoder( + referencing: value, + at: decoder.codingPath, + userInfo: decoder.userInfo + ) + } + } +} + diff --git a/Sources/Media/Media/MediaDecoder/MediaSingleValueDecodingContainer.swift b/Sources/Media/Media/MediaDecoder/MediaSingleValueDecodingContainer.swift new file mode 100644 index 00000000..da114356 --- /dev/null +++ b/Sources/Media/Media/MediaDecoder/MediaSingleValueDecodingContainer.swift @@ -0,0 +1,79 @@ +struct MediaSingleValueDecodingContainer : SingleValueDecodingContainer { + + var codingPath: [CodingKey] + let decoder: MediaDecoder + let map: DecodingMedia + + init(referencing decoder: MediaDecoder, wrapping map: DecodingMedia) { + self.decoder = decoder + self.map = map + self.codingPath = decoder.codingPath + } + + func decodeNil() -> Bool { + return map.decodeNil() + } + + func decode(_ type: Bool.Type) throws -> Bool { + return try map.decode(type) + } + + func decode(_ type: Int.Type) throws -> Int { + return try map.decode(type) + } + + func decode(_ type: Int8.Type) throws -> Int8 { + return try map.decode(type) + } + + func decode(_ type: Int16.Type) throws -> Int16 { + return try map.decode(type) + } + + func decode(_ type: Int32.Type) throws -> Int32 { + return try map.decode(type) + } + + func decode(_ type: Int64.Type) throws -> Int64 { + return try map.decode(type) + } + + func decode(_ type: UInt.Type) throws -> UInt { + return try map.decode(type) + } + + func decode(_ type: UInt8.Type) throws -> UInt8 { + return try map.decode(type) + } + + func decode(_ type: UInt16.Type) throws -> UInt16 { + return try map.decode(type) + } + + func decode(_ type: UInt32.Type) throws -> UInt32 { + return try map.decode(type) + } + + func decode(_ type: UInt64.Type) throws -> UInt64 { + return try map.decode(type) + } + + func decode(_ type: Float.Type) throws -> Float { + return try map.decode(type) + } + + func decode(_ type: Double.Type) throws -> Double { + return try map.decode(type) + } + + func decode(_ type: String.Type) throws -> String { + return try map.decode(type) + } + + func decode(_ type: T.Type) throws -> T { + decoder.stack.push(map) + let result: T = try T(from: decoder) + decoder.stack.pop() + return result + } +} diff --git a/Sources/Media/Media/MediaDecoder/MediaUnkeyedDecodingContainer.swift b/Sources/Media/Media/MediaDecoder/MediaUnkeyedDecodingContainer.swift new file mode 100644 index 00000000..b4b12305 --- /dev/null +++ b/Sources/Media/Media/MediaDecoder/MediaUnkeyedDecodingContainer.swift @@ -0,0 +1,420 @@ +struct MediaUnkeyedDecodingContainer : UnkeyedDecodingContainer { + + let decoder: MediaDecoder + let map: DecodingMedia + var codingPath: [CodingKey] + var currentIndex: Int + + init(referencing decoder: MediaDecoder, wrapping map: DecodingMedia) { + self.decoder = decoder + self.map = map + self.codingPath = decoder.codingPath + self.currentIndex = 0 + } + + var count: Int? { + return map.keyCount() + } + + var isAtEnd: Bool { + guard let count = map.keyCount() else { + return true + } + + return currentIndex >= count + } + + func throwIfAtEnd() throws { + // TODO: throw a relevant error + } + + mutating func decodeNil() throws -> Bool { + try throwIfAtEnd() + + return decoder.with(pushedKey: currentIndex) { + let decoded = map.decodeNil() + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Bool.Type) throws -> Bool { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Int.Type) throws -> Int { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Int8.Type) throws -> Int8 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Int16.Type) throws -> Int16 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Int32.Type) throws -> Int32 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Int64.Type) throws -> Int64 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: UInt.Type) throws -> UInt { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: UInt8.Type) throws -> UInt8 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: UInt16.Type) throws -> UInt16 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: UInt32.Type) throws -> UInt32 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: UInt64.Type) throws -> UInt64 { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Float.Type) throws -> Float { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: Double.Type) throws -> Double { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: String.Type) throws -> String { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + try throwIfAtEnd() + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decode(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: String.Type) throws -> String? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + let decoded = try map.decodeIfPresent(type, forKey: currentIndex) + currentIndex += 1 + return decoded + } + } + + mutating func decodeIfPresent(_ type: T.Type) throws -> T? { + guard !isAtEnd else { return nil } + + return try decoder.with(pushedKey: currentIndex) { + guard let value = try map.decodeIfPresent(Map.self, forKey: currentIndex) else { + return nil + } + + decoder.stack.push(value) + let decoded: T = try T(from: decoder) + decoder.stack.pop() + + currentIndex += 1 + return decoded + } + } + + mutating func nestedContainer( + keyedBy type: NestedKey.Type + ) throws -> KeyedDecodingContainer { + return try decoder.with(pushedKey: currentIndex) { + try self.assertNotAtEnd( + forType: KeyedDecodingContainer.self, + message: "Cannot get nested keyed container -- unkeyed container is at end." + ) + + let container = MediaKeyedDecodingContainer( + referencing: decoder, + wrapping: try map.keyedContainer(forKey: currentIndex) + ) + + currentIndex += 1 + return KeyedDecodingContainer(container) + } + } + + mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { + return try decoder.with(pushedKey: currentIndex) { + try self.assertNotAtEnd( + forType: UnkeyedDecodingContainer.self, + message: "Cannot get nested unkeyed container -- unkeyed container is at end." + ) + + let container = MediaUnkeyedDecodingContainer( + referencing: decoder, + wrapping: try map.unkeyedContainer(forKey: currentIndex) + ) + + currentIndex += 1 + return container + } + } + + mutating func superDecoder() throws -> Decoder { + return try decoder.with(pushedKey: currentIndex) { + try self.assertNotAtEnd( + forType: Decoder.self, + message: "Cannot get superDecoder() -- unkeyed container is at end." + ) + + guard let value = try map.decodeIfPresent(Map.self, forKey: currentIndex) else { + let context = DecodingError.Context( + codingPath: codingPath, + debugDescription: "Cannot get superDecoder() -- value not found for key \(currentIndex)." + ) + + throw DecodingError.keyNotFound(currentIndex, context) + } + + currentIndex += 1 + + return MediaDecoder( + referencing: value, + at: decoder.codingPath, + userInfo: decoder.userInfo + ) + } + } + + func assertNotAtEnd(forType type: Any.Type, message: String) throws { + guard !isAtEnd else { + let context = DecodingError.Context( + codingPath: codingPath, + debugDescription: message + ) + + throw DecodingError.valueNotFound(type, context) + } + } +} diff --git a/Sources/Media/Media/MediaEncodable.swift b/Sources/Media/Media/MediaEncodable.swift new file mode 100644 index 00000000..cb5947e5 --- /dev/null +++ b/Sources/Media/Media/MediaEncodable.swift @@ -0,0 +1,27 @@ +public protocol MediaEncodable : Encodable { + static var encodingMedia: [EncodingMedia.Type] { get } +} + +extension MediaEncodable { + public static var encodingMedia: [EncodingMedia.Type] { + return [JSON.self] + } +} + +extension MediaEncodable { + public static func defaultEncodingMedia() throws -> EncodingMedia.Type { + guard let media = encodingMedia.first else { + throw MediaCodingError.noDefaultEncodingMedia + } + + return media + } + + public static func encodingMedia(for mediaType: MediaType) throws -> EncodingMedia.Type { + for media in encodingMedia where media.mediaType.matches(other: mediaType) { + return media + } + + throw MediaCodingError.unsupportedMediaType + } +} diff --git a/Sources/Media/Media/MediaEncoder/MediaEncoder.swift b/Sources/Media/Media/MediaEncoder/MediaEncoder.swift new file mode 100644 index 00000000..721d6861 --- /dev/null +++ b/Sources/Media/Media/MediaEncoder/MediaEncoder.swift @@ -0,0 +1,110 @@ +import Core + +class MediaEncoder : Encoder { + + var stack: Stack + var codingPath: [CodingKey] + var userInfo: [CodingUserInfoKey: Any] + + init(codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey: Any]) { + self.stack = Stack() + self.codingPath = codingPath + self.userInfo = userInfo + } + + func with(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { + codingPath.append(key) + + let result: T = try work() + + codingPath.removeLast() + + return result + } + + var canEncodeNewElement: Bool { + // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). + // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. + // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. + // + // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. + // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). + return stack.count == codingPath.count + } + + func assertCanRequestNewContainer() { + guard canEncodeNewElement else { + preconditionFailure("Attempt to encode with new container when already encoded with a container.") + } + } + + func container(keyedBy: Key.Type) -> KeyedEncodingContainer { + assertCanRequestNewContainer() + + do { + try stack.push(Map.makeKeyedContainer()) + } catch { + fatalError("return a failure container") + } + + let container = MediaKeyedEncodingContainer( + referencing: self, + codingPath: codingPath + ) + + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + assertCanRequestNewContainer() + + do { + try stack.push(Map.makeUnkeyedContainer()) + } catch { + fatalError("return a failure container") + } + + return MediaUnkeyedEncodingContainer( + referencing: self, + codingPath: codingPath + ) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + assertCanRequestNewContainer() + return self + } + + func topLevelMap() throws -> Map { + guard stack.count > 0 else { + let context = EncodingError.Context( + debugDescription: "encoder did not encode any values." + ) + + throw EncodingError.invalidValue(self, context) + } + + guard let encoded = try stack.pop().topLevel() as? Map else { + let context = EncodingError.Context( + debugDescription: "Encoder did not encode to the requested type \(Map.self)." + ) + + throw EncodingError.invalidValue(self, context) + } + + return encoded + } +} + +extension MediaEncoder { + func box(_ value: T) throws -> EncodingMedia { + let count = stack.count + try value.encode(to: self) + + guard stack.count != count else { + return try Map.makeKeyedContainer() + } + + return stack.pop() + } +} diff --git a/Sources/Media/Media/MediaEncoder/MediaKeyedEncodingContainer.swift b/Sources/Media/Media/MediaEncoder/MediaKeyedEncodingContainer.swift new file mode 100644 index 00000000..c245b719 --- /dev/null +++ b/Sources/Media/Media/MediaEncoder/MediaKeyedEncodingContainer.swift @@ -0,0 +1,220 @@ +final class MediaKeyedEncodingContainer : KeyedEncodingContainerProtocol { + + typealias Key = K + let encoder: MediaEncoder + var codingPath: [CodingKey] + + init(referencing encoder: MediaEncoder, codingPath: [CodingKey]) { + self.encoder = encoder + self.codingPath = codingPath + } + + func with(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { + codingPath.append(key) + + let result: T = try work() + + codingPath.removeLast() + return result + } + + + func encodeNil(forKey key: K) throws { + try encoder.with(pushedKey: key) { + try encoder.stack.push(Map.encodeNil()) + } + } + + func encode(_ value: Bool, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Int, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Int8, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Int16, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Int32, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Int64, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: UInt, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: UInt8, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: UInt16, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: UInt32, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: UInt64, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Float, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: Double, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: String, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(value, forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func encode(_ value: T, forKey key: Key) throws { + try encoder.with(pushedKey: key) { + var top = encoder.stack.top + try top.encode(encoder.box(value), forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } + } + + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: Key + ) -> KeyedEncodingContainer { + do { + var top = encoder.stack.top + try top.encode(Map.makeKeyedContainer(forKey: key), forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } catch { + fatalError("return a failure container") + } + + return with(pushedKey: key) { + let container = MediaKeyedEncodingContainer( + referencing: encoder, + codingPath: codingPath + ) + + return KeyedEncodingContainer(container) + } + } + + func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + do { + var top = encoder.stack.top + try top.encode(Map.makeUnkeyedContainer(forKey: key), forKey: key) + encoder.stack.pop() + encoder.stack.push(top) + } catch { + fatalError("return a failure container") + } + + return with(pushedKey: key) { + return MediaUnkeyedEncodingContainer( + referencing: encoder, + codingPath: codingPath + ) + } + } + + func superEncoder() -> Encoder { + return MediaReferencingEncoder(referencing: encoder, at: MapSuperKey.super) { value in + var top = self.encoder.stack.top + try top.encode(value, forKey: MapSuperKey.super) + self.encoder.stack.pop() + self.encoder.stack.push(top) + } + } + + func superEncoder(forKey key: Key) -> Encoder { + return MediaReferencingEncoder(referencing: encoder, at: key) { value in + var top = self.encoder.stack.top + try top.encode(value, forKey: key) + self.encoder.stack.pop() + self.encoder.stack.push(top) } + } +} diff --git a/Sources/Media/Media/MediaEncoder/MediaReferencingEncoder.swift b/Sources/Media/Media/MediaEncoder/MediaReferencingEncoder.swift new file mode 100644 index 00000000..cb5a5d59 --- /dev/null +++ b/Sources/Media/Media/MediaEncoder/MediaReferencingEncoder.swift @@ -0,0 +1,38 @@ +class MediaReferencingEncoder : MediaEncoder { + let encoder: MediaEncoder + let write: (EncodingMedia) throws -> Void + + init( + referencing encoder: MediaEncoder, + at key: CodingKey?, + write: @escaping (EncodingMedia) throws -> Void + ) { + self.encoder = encoder + self.write = write + super.init(codingPath: encoder.codingPath, userInfo: encoder.userInfo) + if let key = key {self.codingPath.append(key)} + } + + override var canEncodeNewElement: Bool { + // With a regular encoder, the storage and coding path grow together. + // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. + // We have to take this into account. + return stack.count == codingPath.count - encoder.codingPath.count - 1 + } + + deinit { + let value: EncodingMedia + + switch stack.count { + case 0: value = try! Map.makeKeyedContainer() + case 1: value = stack.pop() + default: fatalError("Referencing encoder deallocated with multiple containers on stack.") + } + + do { + try write(value) + } catch { + fatalError("Could not write to container.") + } + } +} diff --git a/Sources/Media/Media/MediaEncoder/MediaSingleValueEncodingContainer.swift b/Sources/Media/Media/MediaEncoder/MediaSingleValueEncodingContainer.swift new file mode 100644 index 00000000..9a84f059 --- /dev/null +++ b/Sources/Media/Media/MediaEncoder/MediaSingleValueEncodingContainer.swift @@ -0,0 +1,87 @@ +extension MediaEncoder : SingleValueEncodingContainer { + func assertCanEncodeSingleValue() { + guard canEncodeNewElement else { + preconditionFailure("Attempt to encode with new container when already encoded with a container.") + } + } + + func encodeNil() throws { + assertCanEncodeSingleValue() + try stack.push(Map.encodeNil()) + } + + func encode(_ value: Bool) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Int) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Int8) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Int16) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Int32) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Int64) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: UInt) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: UInt8) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: UInt16) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: UInt32) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: UInt64) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Float) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: Double) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: String) throws { + assertCanEncodeSingleValue() + try stack.push(Map.encode(value)) + } + + func encode(_ value: T) throws { + assertCanEncodeSingleValue() + try stack.push(box(value)) + } +} diff --git a/Sources/Media/Media/MediaEncoder/MediaUnkeyedEncodingContainer.swift b/Sources/Media/Media/MediaEncoder/MediaUnkeyedEncodingContainer.swift new file mode 100644 index 00000000..5ca64522 --- /dev/null +++ b/Sources/Media/Media/MediaEncoder/MediaUnkeyedEncodingContainer.swift @@ -0,0 +1,231 @@ +final class MediaUnkeyedEncodingContainer : UnkeyedEncodingContainer { + + var count: Int + + let encoder: MediaEncoder + var codingPath: [CodingKey] + + + init(referencing encoder: MediaEncoder, codingPath: [CodingKey]) { + self.encoder = encoder + self.codingPath = codingPath + self.count = 0 + } + + func with(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T { + codingPath.append(key) + let result: T = try work() + codingPath.removeLast() + + return result + } + + func encodeNil() throws { + try encoder.with(pushedKey: count) { + try encoder.stack.push(Map.encodeNil()) + } + count += 1 + } + + func encode(_ value: Bool) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Int) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Int8) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Int16) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Int32) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Int64) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: UInt) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: UInt8) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: UInt16) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: UInt32) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: UInt64) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Float) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: Double) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func encode(_ value: String) throws { + var top = encoder.stack.top + try top.encode(value) + encoder.stack.pop() + encoder.stack.push(top) + } + + func encode(_ value: T) throws { + try encoder.with(pushedKey: count) { + var top = encoder.stack.top + try top.encode(encoder.box(value)) + encoder.stack.pop() + encoder.stack.push(top) + } + count += 1 + } + + func nestedContainer( + keyedBy keyType: NestedKey.Type + ) -> KeyedEncodingContainer { + do { + var top = encoder.stack.top + try top.encode(Map.makeKeyedContainer()) + encoder.stack.pop() + encoder.stack.push(top) + } catch { + fatalError("return a failure container") + } + + let res: KeyedEncodingContainer = with(pushedKey: count) { + let container = MediaKeyedEncodingContainer( + referencing: encoder, + codingPath: codingPath + ) + + return KeyedEncodingContainer(container) + } + count += 1 + return res + } + + func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + do { + var top = encoder.stack.top + try top.encode(Map.makeUnkeyedContainer()) + encoder.stack.pop() + encoder.stack.push(top) + } catch { + fatalError("return a failure container") + } + + let res: UnkeyedEncodingContainer = with(pushedKey: count) { + return MediaUnkeyedEncodingContainer( + referencing: encoder, + codingPath: codingPath + ) + } + count += 1 + return res + } + + func superEncoder() -> Encoder { + let res: Encoder = MediaReferencingEncoder(referencing: encoder, at: count) { value in + var top = self.encoder.stack.top + try top.encode(value) + self.encoder.stack.pop() + self.encoder.stack.push(top) + } + count += 1 + return res + } +} diff --git a/Sources/Media/Media/Stack.swift b/Sources/Media/Media/Stack.swift new file mode 100644 index 00000000..2026daea --- /dev/null +++ b/Sources/Media/Media/Stack.swift @@ -0,0 +1,23 @@ +struct Stack { + private(set) var stack: [T] = [] + + init() {} + + var count: Int { + return stack.count + } + + var top: T { + precondition(stack.count > 0, "Empty container stack.") + return stack.last! + } + + mutating func push(_ value: T) { + stack.append(value) + } + + @discardableResult mutating func pop() -> T { + precondition(stack.count > 0, "Empty map stack.") + return stack.popLast()! + } +} diff --git a/Sources/Content/MediaType/MediaType.swift b/Sources/Media/MediaType/MediaType.swift similarity index 100% rename from Sources/Content/MediaType/MediaType.swift rename to Sources/Media/MediaType/MediaType.swift diff --git a/Sources/Media/XML/XML.swift b/Sources/Media/XML/XML.swift new file mode 100644 index 00000000..9fbd7b4d --- /dev/null +++ b/Sources/Media/XML/XML.swift @@ -0,0 +1,157 @@ +public protocol XMLNode { + var xmlNode: XML.Node { get } +} + +extension XML.Element : XMLNode { + public var xmlNode: XML.Node { + return .element(self) + } +} + +extension String : XMLNode { + public var xmlNode: XML.Node { + return .content(self) + } +} + +public struct XML { + public enum Node { + case element(XML.Element) + case content(String) + } + + public struct Element { + public let name: String + public let attributes: [String: String] + public internal(set) var children: [Node] + + init(name: String, attributes: [String: String], children: [XML.Node]) { + self.name = name + self.attributes = attributes + self.children = children + } + + public init(name: String, attributes: [String: String] = [:], children: [XMLNode] = []) { + self.name = name + self.attributes = attributes + self.children = children.map({ $0.xmlNode }) + } + + public func attribute(named name: String) throws -> String { + guard let attribute = attributes[name] else { + throw DecodingError.keyNotFound(name, DecodingError.Context()) + } + + return attribute + } + + public var contents: String { + var string = "" + + for child in children { + if case let .content(content) = child { + string += content.description + } + } + + return string + } + + public func elements(named name: String) -> [Element] { + var elements: [Element] = [] + + for element in self.elements where element.name == name { + elements.append(element) + } + + return elements + } + + public var elements: [Element] { + var elements: [Element] = [] + + for child in children { + if case let .element(element) = child { + elements.append(element) + } + } + + return elements + } + + public mutating func add(element: Element) { + children.append(.element(element)) + } + + public mutating func add(content: String) { + children.append(.content(content)) + } + } + + public let root: Element + + public init(root: Element) { + self.root = root + } +} + +extension XML : CustomStringConvertible { + public var description: String { + return root.description + } +} + +extension XML.Element : CustomStringConvertible { + public var description: String { + var attributes = "" + + for (offset: index, element: (key: key, value: value)) in self.attributes.enumerated() { + if index == 0 { + attributes += " " + } + + attributes += key + attributes += "=" + attributes += value + + if index < self.attributes.count - 1 { + attributes += " " + } + } + + if !children.isEmpty { + var string = "" + string += "<" + string += name + string += attributes + string += ">" + + for child in children { + string += child.description + } + + string += "" + return string + } + + guard !contents.isEmpty else { + return "<\(name)\(attributes)/>" + + } + + return "<\(name)\(attributes)>\(contents)" + } +} + +extension XML.Node : CustomStringConvertible { + public var description: String { + switch self { + case let .element(element): + return element.description + case let .content(content): + return content + } + } +} diff --git a/Sources/Media/XML/XMLDecodingMedia.swift b/Sources/Media/XML/XMLDecodingMedia.swift new file mode 100644 index 00000000..5d6488ef --- /dev/null +++ b/Sources/Media/XML/XMLDecodingMedia.swift @@ -0,0 +1,351 @@ +import Core +import Venice + +extension XML : DecodingMedia { + public static var mediaType: MediaType { + return .xml + } + + public init(from readable: Readable, deadline: Deadline) throws { + self = try XMLParser.parse(readable, deadline: deadline) + } + + public func keyCount() -> Int? { + return 1 + } + + public func allKeys(keyedBy: Key.Type) -> [Key] where Key : CodingKey { + return Key(stringValue: root.name).map({ [$0] }) ?? [] + } + + public func contains(_ key: Key) -> Bool where Key : CodingKey { + return root.name == key.stringValue + } + + public func keyedContainer() throws -> DecodingMedia { + return self + } + + public func unkeyedContainer() throws -> DecodingMedia { + throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) + } + + public func singleValueContainer() throws -> DecodingMedia { + throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) + } + + public func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia { + + return XMLMap.single(root) // change this (wrap root) + } + + public func decodeIfPresent( + _ type: DecodingMedia.Type, + forKey key: CodingKey + ) throws -> DecodingMedia? { + guard root.name == key.stringValue else { + return nil + } + + return XMLMap.single(root) // change this (wrap root) + } + + public func decodeNil() -> Bool { + return false + } + + public func decode(_ type: Bool.Type) throws -> Bool { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Int.Type) throws -> Int { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Int8.Type) throws -> Int8 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Int16.Type) throws -> Int16 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Int32.Type) throws -> Int32 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Int64.Type) throws -> Int64 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: UInt.Type) throws -> UInt { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: UInt8.Type) throws -> UInt8 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: UInt16.Type) throws -> UInt16 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: UInt32.Type) throws -> UInt32 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: UInt64.Type) throws -> UInt64 { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Float.Type) throws -> Float { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: Double.Type) throws -> Double { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + public func decode(_ type: String.Type) throws -> String { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } +} + +enum XMLMap { + case single(XML.Element) + case multiple([XML.Element]) +} + +extension XMLMap : DecodingMedia { + static var mediaType: MediaType { + return .xml + } + + init(from readable: Readable, deadline: Deadline) throws { + let xml = try XML(from: readable, deadline: deadline) + self = .single(xml.root) + } + + public func keyCount() -> Int? { + switch self { + case let .single(element): + return Set(element.elements.map({ $0.name })).count + case let .multiple(elements): + return elements.count + } + } + + public func allKeys(keyedBy: Key.Type) -> [Key] where Key : CodingKey { + switch self { + case let .single(element): + return Set(element.elements.map({ $0.name })).flatMap({ Key(stringValue: $0) }) + case let .multiple(elements): + return elements.indices.flatMap({ Key(intValue: $0) }) + } + } + + public func contains(_ key: Key) -> Bool where Key : CodingKey { + switch self { + case let .single(element): + return !element.elements(named: key.stringValue).isEmpty + case let .multiple(elements): + return elements.indices.contains(key.intValue ?? -1) + } + } + + public func keyedContainer() throws -> DecodingMedia { + switch self { + case .single: + return self + default: + throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) + } + } + + public func unkeyedContainer() throws -> DecodingMedia { + switch self { + case .multiple: + return self + default: + throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) + } + } + + public func singleValueContainer() throws -> DecodingMedia { + switch self { + case .single: + return self + default: + throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) + } + } + + func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia { + switch self { + case let .single(element): + let elements = element.elements(named: key.stringValue) + + guard elements.count == 1, let element = elements.first else { + return XMLMap.multiple(elements) + } + + return XMLMap.single(element) + case let .multiple(elements): + guard let index = key.intValue else { + throw DecodingError.keyNotFound(key, DecodingError.Context()) + } + + guard elements.indices.contains(index) else { + throw DecodingError.keyNotFound(key, DecodingError.Context()) + } + + return XMLMap.single(elements[index]) + } + } + + public func decodeIfPresent( + _ type: DecodingMedia.Type, + forKey key: CodingKey + ) throws -> DecodingMedia? { + switch self { + case let .single(element): + let elements = element.elements(named: key.stringValue) + + guard elements.count == 1, let element = elements.first else { + return XMLMap.multiple(elements) + } + + return XMLMap.single(element) + case let .multiple(elements): + guard let index = key.intValue else { + throw DecodingError.keyNotFound(key, DecodingError.Context()) + } + + guard elements.indices.contains(index) else { + throw DecodingError.keyNotFound(key, DecodingError.Context()) + } + + return XMLMap.single(elements[index]) + } + } + + public func decodeNil() -> Bool { + return false + } + + public func decode(_ type: Bool.Type) throws -> Bool { + guard let bool = try Bool(contents(forType: type)) else { + throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) + } + + return bool + } + + public func decode(_ type: Int.Type) throws -> Int { + guard let int = try Int(contents(forType: type)) else { + throw DecodingError.typeMismatch(Int.self, DecodingError.Context()) + } + + return int + } + + public func decode(_ type: Int8.Type) throws -> Int8 { + guard let int8 = try Int8(contents(forType: type)) else { + throw DecodingError.typeMismatch(Int8.self, DecodingError.Context()) + } + + return int8 + } + + public func decode(_ type: Int16.Type) throws -> Int16 { + guard let int16 = try Int16(contents(forType: type)) else { + throw DecodingError.typeMismatch(Int16.self, DecodingError.Context()) + } + + return int16 + } + + public func decode(_ type: Int32.Type) throws -> Int32 { + guard let int32 = try Int32(contents(forType: type)) else { + throw DecodingError.typeMismatch(Int32.self, DecodingError.Context()) + } + + return int32 + } + + public func decode(_ type: Int64.Type) throws -> Int64 { + guard let int64 = try Int64(contents(forType: type)) else { + throw DecodingError.typeMismatch(Int64.self, DecodingError.Context()) + } + + return int64 + } + + public func decode(_ type: UInt.Type) throws -> UInt { + guard let uint = try UInt(contents(forType: type)) else { + throw DecodingError.typeMismatch(UInt.self, DecodingError.Context()) + } + + return uint + } + + public func decode(_ type: UInt8.Type) throws -> UInt8 { + guard let uint8 = try UInt8(contents(forType: type)) else { + throw DecodingError.typeMismatch(UInt8.self, DecodingError.Context()) + } + + return uint8 + } + + public func decode(_ type: UInt16.Type) throws -> UInt16 { + guard let uint16 = try UInt16(contents(forType: type)) else { + throw DecodingError.typeMismatch(UInt16.self, DecodingError.Context()) + } + + return uint16 + } + + public func decode(_ type: UInt32.Type) throws -> UInt32 { + guard let uint32 = try UInt32(contents(forType: type)) else { + throw DecodingError.typeMismatch(UInt32.self, DecodingError.Context()) + } + + return uint32 + } + + public func decode(_ type: UInt64.Type) throws -> UInt64 { + guard let uint64 = try UInt64(contents(forType: type)) else { + throw DecodingError.typeMismatch(UInt64.self, DecodingError.Context()) + } + + return uint64 + } + + public func decode(_ type: Float.Type) throws -> Float { + guard let float = try Float(contents(forType: type)) else { + throw DecodingError.typeMismatch(Float.self, DecodingError.Context()) + } + + return float + } + + public func decode(_ type: Double.Type) throws -> Double { + guard let double = try Double(contents(forType: type)) else { + throw DecodingError.typeMismatch(Double.self, DecodingError.Context()) + } + + return double + } + + public func decode(_ type: String.Type) throws -> String { + return try contents(forType: type) + } + + private func contents(forType: Any.Type) throws -> String { + guard case let .single(element) = self else { + throw DecodingError.typeMismatch(forType, DecodingError.Context()) + } + + return element.contents + } +} diff --git a/Sources/Content/XML/XMLParser.swift b/Sources/Media/XML/XMLParser.swift similarity index 70% rename from Sources/Content/XML/XMLParser.swift rename to Sources/Media/XML/XMLParser.swift index 5af41ad1..41096818 100644 --- a/Sources/Content/XML/XMLParser.swift +++ b/Sources/Media/XML/XMLParser.swift @@ -30,14 +30,14 @@ public enum XMLParserError : Error { } fileprivate class ParserStream : InputStream { - private let stream: Readable + private let readable: Readable private let deadline: Deadline private let buffer: UnsafeMutableRawBufferPointer private var lastError: Error? private var finished = false - fileprivate init(stream: Readable, deadline: Deadline, bufferSize: Int = 4096) { - self.stream = stream + fileprivate init(readable: Readable, deadline: Deadline, bufferSize: Int = 4096) { + self.readable = readable self.deadline = deadline self.buffer = UnsafeMutableRawBufferPointer.allocate(count: bufferSize) super.init(data: Data()) @@ -47,25 +47,9 @@ fileprivate class ParserStream : InputStream { buffer.deallocate() } - #if os(macOS) fileprivate override var streamError: Error? { return lastError } - #else - fileprivate override var streamError: NSError? { - let userInfo: [String: Any] = [ - NSLocalizedDescriptionKey: lastError.map({ String(describing: $0) }) ?? "" - ] - - let error = NSError( - domain: "XMLParserError", - code: 0, - userInfo: userInfo - ) - - return error - } - #endif fileprivate override func open() {} fileprivate override func close() {} @@ -74,7 +58,7 @@ fileprivate class ParserStream : InputStream { let buffer = UnsafeMutableRawBufferPointer(start: buffer, count: count) do { - let read = try stream.read(buffer, deadline: deadline) + let read = try readable.read(buffer, deadline: deadline) if read.isEmpty { finished = true @@ -101,17 +85,16 @@ fileprivate class ParserStream : InputStream { } } -public class XMLParser : NSObject, XMLParserDelegate { +class XMLParser : NSObject, XMLParserDelegate { var stack = Stack() - public static func parse( - _ stream: Readable, + static func parse( + _ readable: Readable, bufferSize: Int = 4096, deadline: Deadline ) throws -> XML { let xmlParser = XMLParser() - - let parseStream = ParserStream(stream: stream, deadline: deadline) + let parseStream = ParserStream(readable: readable, deadline: deadline) let parser = Foundation.XMLParser(stream: parseStream) parser.delegate = xmlParser @@ -123,65 +106,107 @@ public class XMLParser : NSObject, XMLParserDelegate { throw XMLParserError.invalidXML } - return root + return XML(root: root.xmlElement) } - public func parser( + func parser( _ parser: Foundation.XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String] ) { - let element = XML(name: name, attributes: attributes) - - if !stack.isEmpty { - stack.top().addElement(element) - } - - stack.push(element) + let element = Element(name: name, attributes: attributes) + stack.addElement(element) } - public func parser(_ parser: Foundation.XMLParser, foundCharacters content: String) { - stack.top().addContent(content) + func parser(_ parser: Foundation.XMLParser, foundCharacters content: String) { + stack.addContent(content) } - public func parser( + func parser( _ parser: Foundation.XMLParser, - didEndElement elementName: String, + didEndElement name: String, namespaceURI: String?, - qualifiedName qName: String? + qualifiedName: String? ) { stack.drop() } -} - -struct Stack { - var root: XML? - private var items: [XML] = [] - mutating func push(_ item: XML) { - if root == nil { - root = item - } + enum Node { + case element(Element) + case content(String) - items.append(item) - } - - mutating func drop() { - items.removeLast() - } - - mutating func removeAll() { - items.removeAll(keepingCapacity: false) + var xmlNode: XML.Node { + switch self { + case let .element(element): + return .element( + XML.Element( + name: element.name, + attributes: element.attributes, + children: element.children.map({ $0.xmlNode }) + ) + ) + case let .content(content): + return .content(content) + } + } } - func top() -> XML { - return items[items.count - 1] + class Element { + let name: String + let attributes: [String: String] + var children: [Node] = [] + + init(name: String, attributes: [String: String]) { + self.name = name + self.attributes = attributes + } + + var xmlElement: XML.Element { + return XML.Element( + name: name, + attributes: attributes, + children: children.map({ $0.xmlNode }) + ) + } } - var isEmpty: Bool { - return items.isEmpty + struct Stack { + var root: Element? = nil + private var items: [Element] = [] + + mutating func addElement(_ element: Element) { + if !isEmpty { + let item = items[items.count - 1] + item.children.append(.element(element)) + items[items.count - 1] = item + } + + items.append(element) + } + + mutating func addContent(_ content: String) { + let item = items[items.count - 1] + item.children.append(.content(content)) + items[items.count - 1] = item + } + + mutating func drop() { + let item = items.removeLast() + + if isEmpty { + root = item + } + } + + mutating func removeAll() { + items.removeAll(keepingCapacity: false) + } + + var isEmpty: Bool { + return items.isEmpty + } } } @@ -209,7 +234,7 @@ extension XMLParserDelegate { _ parser: Foundation.XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, - type: String?, + media: String?, defaultValue: String? ) {} diff --git a/Sources/Zewo/Zewo.swift b/Sources/Zewo/Zewo.swift new file mode 100644 index 00000000..5d8f03bb --- /dev/null +++ b/Sources/Zewo/Zewo.swift @@ -0,0 +1,5 @@ +@_exported import Venice +@_exported import Core +@_exported import IO +@_exported import Media +@_exported import HTTP diff --git a/Tests/ContentTests/JSONTests.swift b/Tests/ContentTests/JSONTests.swift deleted file mode 100644 index 14be99dc..00000000 --- a/Tests/ContentTests/JSONTests.swift +++ /dev/null @@ -1,30 +0,0 @@ -import XCTest -@testable import Content -import Foundation - -public class JSONTests: XCTestCase { - func testJSONSchema() throws { - let schema = JSON.Schema([ - "type": "object", - "properties": [ - "name": ["type": "string"], - "price": ["type": "number"], - ], - "required": ["name"], - ]) - - var result = schema.validate(["name": "Eggs", "price": 34.99]) - XCTAssert(result.isValid) - - result = schema.validate(["price": 34.99]) - XCTAssertEqual(result.errors, ["Required properties are missing '[\"name\"]\'"]) - } -} - -extension JSONTests { - public static var allTests: [(String, (JSONTests) -> () throws -> Void)] { - return [ - ("testJSONSchema", testJSONSchema), - ] - } -} diff --git a/Tests/ContentTests/XMLTests.swift b/Tests/ContentTests/XMLTests.swift deleted file mode 100644 index 0965047f..00000000 --- a/Tests/ContentTests/XMLTests.swift +++ /dev/null @@ -1,40 +0,0 @@ -import XCTest -@testable import Content -import Foundation - -public class XMLTests: XCTestCase { - func testXML() throws { - let xml = XML(name: "Root", children: [ - XML(name: "Catalog", children: [ - XML(name: "Book", attributes: ["id": "a"], children: [ - XML(name: "Author", children: ["Bob"]), - ]), - XML(name: "Book", attributes: ["id": "b"], children: [ - XML(name: "Author", children: ["John"]), - ]), - XML(name: "Book", attributes: ["id": "c"], children: [ - XML(name: "Author", children: ["Mark"]), - ]), - ]), - ]) - - try print(xml.get("Catalog", "Book", 1, "Author").content) - try print(xml.get("Catalog", 0, "Book", 1, "Author", 0).content) - try print(xml.get("Catalog", "Book", 1).getAttribute("id") ?? "nope") - try print(xml.get("Catalog", "Book").withAttribute("id", equalTo: "b")?.get("Author").content ?? "nope") - - for element in try xml.get("Catalog", "Book") { - try print(element.get("Author").content) - } - } -} - - - -extension XMLTests { - public static var allTests: [(String, (XMLTests) -> () throws -> Void)] { - return [ - ("testXML", testXML), - ] - } -} diff --git a/Tests/CoreTests/StringTests.swift b/Tests/CoreTests/StringTests.swift new file mode 100644 index 00000000..4fc7b938 --- /dev/null +++ b/Tests/CoreTests/StringTests.swift @@ -0,0 +1,45 @@ +import XCTest +@testable import Core + +public class StringTests : XCTestCase { + func testCamelCaseSplit() { + XCTAssertEqual("".camelCaseSplit(), []) + XCTAssertEqual("lowercase".camelCaseSplit(), ["lowercase"]) + XCTAssertEqual("Class".camelCaseSplit(), ["Class"]) + XCTAssertEqual("MyClass".camelCaseSplit(), ["My", "Class"]) + XCTAssertEqual("MyC".camelCaseSplit(), ["My", "C"]) + XCTAssertEqual("HTML".camelCaseSplit(), ["HTML"]) + XCTAssertEqual("PDFLoader".camelCaseSplit(), ["PDF", "Loader"]) + XCTAssertEqual("AString".camelCaseSplit(), ["A", "String"]) + XCTAssertEqual("SimpleXMLParser".camelCaseSplit(), ["Simple", "XML", "Parser"]) + XCTAssertEqual("vimRPCPlugin".camelCaseSplit(), ["vim", "RPC", "Plugin"]) + XCTAssertEqual("GL11Version".camelCaseSplit(), ["GL", "11", "Version"]) + XCTAssertEqual("99Bottles".camelCaseSplit(), ["99", "Bottles"]) + XCTAssertEqual("May5".camelCaseSplit(), ["May", "5"]) + XCTAssertEqual("BFG9000".camelCaseSplit(), ["BFG", "9000"]) + XCTAssertEqual("BöseÜberraschung".camelCaseSplit(), ["Böse", "Überraschung"]) + XCTAssertEqual("Two spaces".camelCaseSplit(), ["Two", " ", "spaces"]) + } + + func testUppercasedFirstCharacter() { + XCTAssertEqual("hello".uppercasedFirstCharacter(), "Hello") + XCTAssertEqual("1hello".uppercasedFirstCharacter(), "1hello") + XCTAssertEqual("@hello".uppercasedFirstCharacter(), "@hello") + XCTAssertEqual("Hello".uppercasedFirstCharacter(), "Hello") + } + + func testTrimmed() { + XCTAssertEqual(" hello".trimmed(), "hello") + XCTAssertEqual("hello".trimmed(), "hello") + XCTAssertEqual("hel lo".trimmed(), "hel lo") + XCTAssertEqual("hel lo".trimmed(), "hel lo") + XCTAssertEqual("hel lo".trimmed(), "hel lo") + XCTAssertEqual("hello ".trimmed(), "hello") + } + + public static var allTests = [ + ("testCamelCaseSplit", testCamelCaseSplit), + ("testUppercasedFirstCharacter", testUppercasedFirstCharacter), + ("testTrimmed", testTrimmed), + ] +} diff --git a/Tests/HTTPTests/ClientTests.swift b/Tests/HTTPTests/ClientTests.swift index 15c927d3..946405b1 100755 --- a/Tests/HTTPTests/ClientTests.swift +++ b/Tests/HTTPTests/ClientTests.swift @@ -1,15 +1,145 @@ import XCTest -import Content +import Media import HTTP +struct Resources : MediaCodable { + let currentUserURL: String + let currentUserAuthorizationsHTMLURL: String + let authorizationsURL: String + let codeSearchURL: String + let commitSearchURL: String + let emailsURL: String + let emojisURL: String + let eventsURL: String + let feedsURL: String + let followersURL: String + let followingURL: String + let gistsURL: String + let hubURL: String + let issueSearchURL: String + let issuesURL: String + let keysURL: String + let notificationsURL: String + let organizationRepositoriesURL: String + let organizationURL: String + let publicGistsURL: String + let rateLimitURL: String + let repositoryURL: String + let currentUserRepositoriesURL: String + let starredURL: String + let starredGistsURL: String + let teamURL: String + let userURL: String + let userOrganizationsURL: String + let userRepositoriesURL: String + let userSearchURL: String + + enum Key : String, CodingKey { + case currentUserURL = "current_user_url" + case currentUserAuthorizationsHTMLURL = "current_user_authorizations_html_url" + case authorizationsURL = "authorizations_url" + case codeSearchURL = "code_search_url" + case commitSearchURL = "commit_search_url" + case emailsURL = "emails_url" + case emojisURL = "emojis_url" + case eventsURL = "events_url" + case feedsURL = "feeds_url" + case followersURL = "followers_url" + case followingURL = "following_url" + case gistsURL = "gists_url" + case hubURL = "hub_url" + case issueSearchURL = "issue_search_url" + case issuesURL = "issues_url" + case keysURL = "keys_url" + case notificationsURL = "notifications_url" + case organizationRepositoriesURL = "organization_repositories_url" + case organizationURL = "organization_url" + case publicGistsURL = "public_gists_url" + case rateLimitURL = "rate_limit_url" + case repositoryURL = "repository_url" + case currentUserRepositoriesURL = "current_user_repositories_url" + case starredURL = "starred_url" + case starredGistsURL = "starred_gists_url" + case teamURL = "team_url" + case userURL = "user_url" + case userOrganizationsURL = "user_organizations_url" + case userRepositoriesURL = "user_repositories_url" + case userSearchURL = "user_search_url" + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Key.self) + currentUserURL = try container.decode(String.self, forKey: .currentUserURL) + currentUserAuthorizationsHTMLURL = try container.decode(String.self, forKey: .currentUserAuthorizationsHTMLURL) + authorizationsURL = try container.decode(String.self, forKey: .authorizationsURL) + codeSearchURL = try container.decode(String.self, forKey: .codeSearchURL) + commitSearchURL = try container.decode(String.self, forKey: .commitSearchURL) + emailsURL = try container.decode(String.self, forKey: .emailsURL) + emojisURL = try container.decode(String.self, forKey: .emojisURL) + eventsURL = try container.decode(String.self, forKey: .eventsURL) + feedsURL = try container.decode(String.self, forKey: .feedsURL) + followersURL = try container.decode(String.self, forKey: .followersURL) + followingURL = try container.decode(String.self, forKey: .followingURL) + gistsURL = try container.decode(String.self, forKey: .gistsURL) + hubURL = try container.decode(String.self, forKey: .hubURL) + issueSearchURL = try container.decode(String.self, forKey: .issueSearchURL) + issuesURL = try container.decode(String.self, forKey: .issuesURL) + keysURL = try container.decode(String.self, forKey: .keysURL) + notificationsURL = try container.decode(String.self, forKey: .notificationsURL) + organizationRepositoriesURL = try container.decode(String.self, forKey: .organizationRepositoriesURL) + organizationURL = try container.decode(String.self, forKey: .organizationURL) + publicGistsURL = try container.decode(String.self, forKey: .publicGistsURL) + rateLimitURL = try container.decode(String.self, forKey: .rateLimitURL) + repositoryURL = try container.decode(String.self, forKey: .repositoryURL) + currentUserRepositoriesURL = try container.decode(String.self, forKey: .currentUserRepositoriesURL) + starredURL = try container.decode(String.self, forKey: .starredURL) + starredGistsURL = try container.decode(String.self, forKey: .starredGistsURL) + teamURL = try container.decode(String.self, forKey: .teamURL) + userURL = try container.decode(String.self, forKey: .userURL) + userOrganizationsURL = try container.decode(String.self, forKey: .userOrganizationsURL) + userRepositoriesURL = try container.decode(String.self, forKey: .userRepositoriesURL) + userSearchURL = try container.decode(String.self, forKey: .userSearchURL) + } +} + public class ClientTests: XCTestCase { func testClient() throws { do { let client = try Client(uri: "https://api.github.com") - let request = try Request(method: .get, uri: "/zen") + let request = try Request(method: .get, uri: "/") let response = try client.send(request) - let zen: PlainText = try response.content() - print(zen) + let resources: Resources = try response.content() + + XCTAssertEqual(resources.currentUserURL, "https://api.github.com/user") + XCTAssertEqual(resources.currentUserAuthorizationsHTMLURL, "https://github.com/settings/connections/applications{/client_id}") + XCTAssertEqual(resources.authorizationsURL, "https://api.github.com/authorizations") + XCTAssertEqual(resources.codeSearchURL, "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}") + XCTAssertEqual(resources.commitSearchURL, "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}") + XCTAssertEqual(resources.emailsURL, "https://api.github.com/user/emails") + XCTAssertEqual(resources.emojisURL, "https://api.github.com/emojis") + XCTAssertEqual(resources.eventsURL, "https://api.github.com/events") + XCTAssertEqual(resources.feedsURL, "https://api.github.com/feeds") + XCTAssertEqual(resources.followersURL, "https://api.github.com/user/followers") + XCTAssertEqual(resources.followingURL, "https://api.github.com/user/following{/target}") + XCTAssertEqual(resources.gistsURL, "https://api.github.com/gists{/gist_id}") + XCTAssertEqual(resources.hubURL, "https://api.github.com/hub") + XCTAssertEqual(resources.issueSearchURL, "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}") + XCTAssertEqual(resources.issuesURL, "https://api.github.com/issues") + XCTAssertEqual(resources.keysURL, "https://api.github.com/user/keys") + XCTAssertEqual(resources.notificationsURL, "https://api.github.com/notifications") + XCTAssertEqual(resources.organizationRepositoriesURL, "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}") + XCTAssertEqual(resources.organizationURL, "https://api.github.com/orgs/{org}") + XCTAssertEqual(resources.publicGistsURL, "https://api.github.com/gists/public") + XCTAssertEqual(resources.rateLimitURL, "https://api.github.com/rate_limit") + XCTAssertEqual(resources.repositoryURL, "https://api.github.com/repos/{owner}/{repo}") + XCTAssertEqual(resources.currentUserRepositoriesURL, "https://api.github.com/user/repos{?type,page,per_page,sort}") + XCTAssertEqual(resources.starredURL, "https://api.github.com/user/starred{/owner}{/repo}") + XCTAssertEqual(resources.starredGistsURL, "https://api.github.com/gists/starred") + XCTAssertEqual(resources.teamURL, "https://api.github.com/teams") + XCTAssertEqual(resources.userURL, "https://api.github.com/users/{user}") + XCTAssertEqual(resources.userOrganizationsURL, "https://api.github.com/user/orgs") + XCTAssertEqual(resources.userRepositoriesURL, "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}") + XCTAssertEqual(resources.userSearchURL, "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}") } catch { print(error) } diff --git a/Tests/HTTPTests/ServerTest.swift b/Tests/HTTPTests/ServerTest.swift new file mode 100644 index 00000000..18d0c241 --- /dev/null +++ b/Tests/HTTPTests/ServerTest.swift @@ -0,0 +1,41 @@ +import XCTest +import Media +import HTTP +import Venice +import Zewo + +class ServerTest: XCTestCase { + func testServer() throws { + let message = "Hello" + let method: Request.Method = .get + let uri = "/link" + let deadline = 1.second.fromNow() + let server = Server { (request) -> Response in + XCTAssertEqual(request.method, method) + XCTAssertEqual(request.uri.path, uri) + return Response(status: .ok, body: "Hello") + } + let coroutine = try Coroutine { + do { + try server.start() + } catch { + XCTAssertEqual("\(error)", "Operation canceled") + } + } + + try Coroutine.wakeUp(deadline) + + let client = try Client(uri: "http://localhost:8080") + let request = try Request(method: method, uri: uri, body: message) + let response = try client.send(request) + let bufferSize = response.contentLength ?? 0 + let buffer = UnsafeMutableRawBufferPointer.allocate(count: bufferSize) + _ = try response.body.convertedToReadable().read(buffer, deadline: .immediately) + XCTAssertEqual(String(buffer), message) + + coroutine.cancel() + + try Coroutine.wakeUp(10.seconds.fromNow()) + + } +} diff --git a/Tests/MediaTests/JSONTests.swift b/Tests/MediaTests/JSONTests.swift new file mode 100644 index 00000000..553a1f56 --- /dev/null +++ b/Tests/MediaTests/JSONTests.swift @@ -0,0 +1,68 @@ +import XCTest +@testable import Media + +public class JSONTests : XCTestCase { + func testJSONSchema() throws { + let schema = JSON.Schema([ + "type": "object", + "properties": [ + "name": ["type": "string"], + "price": ["type": "number"], + ], + "required": ["name"], + ]) + + var result = schema.validate(["name": "Eggs", "price": 34.99]) + XCTAssert(result.isValid) + + result = schema.validate(["price": 34.99]) + XCTAssertEqual(result.errors, ["Required properties are missing '[\"name\"]\'"]) + } + + func testSerialize() throws { + let json: JSON = ["string": "string", "int": 1, "bool": true, "nil": nil, "array":["a": 1, "b": 2], "object": ["c": "d", "e": "f"], "intarray": [1, 2, 3, 5]] + + var s: String? + try JSONSerializer().serialize(json) { (buf) in + s = String(buf) + } + + XCTAssertEqual("{\"nil\":null,\"intarray\":[1,2,3,5],\"object\":{\"e\":\"f\",\"c\":\"d\"},\"array\":{\"b\":2,\"a\":1},\"int\":1,\"bool\":true,\"string\":\"string\"}", s) + } + + func testJSONFromVariables() throws { + let var0 = "hello" + let var1: JSON = JSON(stringLiteral:var0) + + let array: JSON = ["string": var1, "int": 1, "bool": true, "nil": nil, "array":["a": 1, "b": 2], "object": ["c": "d", "e": "f"], "intarray": [1, 2, 3, 5]] + + var s: String? + try JSONSerializer().serialize(array) { (buf) in + s = String(buf) + } + + XCTAssertEqual("{\"nil\":null,\"intarray\":[1,2,3,5],\"object\":{\"e\":\"f\",\"c\":\"d\"},\"array\":{\"b\":2,\"a\":1},\"int\":1,\"bool\":true,\"string\":\"hello\"}", s) + } + + func testParseFromString() throws { + let str = "{\"nil\":null,\"intarray\":[1,2,3,5],\"object\":{\"e\":\"f\",\"c\":\"d\"},\"array\":{\"b\":2,\"a\":1},\"int\":1,\"bool\":true,\"string\":\"string\"}" + + let json = try str.withBuffer { (b) -> JSON in + return try JSON(from: b, deadline: .never) + } + let json2: JSON = ["string": "string", "int": 1, "bool": true, "nil": nil, "array":["a": 1, "b": 2], "object": ["c": "d", "e": "f"], "intarray": [1, 2, 3, 5]] + + XCTAssertEqual(json, json2) + + } +} + +extension JSONTests { + public static var allTests: [(String, (JSONTests) -> () throws -> Void)] { + return [ + ("testJSONSchema", testJSONSchema), + ("testSerialize", testSerialize), + ("testParseFromString", testParseFromString), + ] + } +} diff --git a/Tests/MediaTests/MapTests.swift b/Tests/MediaTests/MapTests.swift new file mode 100644 index 00000000..bae79cc1 --- /dev/null +++ b/Tests/MediaTests/MapTests.swift @@ -0,0 +1,107 @@ +import XCTest +import Foundation +@testable import Media + +struct User : Codable { + let string: String + let int: Int + let bool: Bool + let double: Double? + let null: String? +} + +struct Organization: Codable { + let name: String + let departments: [Department] +} + +struct Department: Codable { + let name: String + let workers: [User] + let manager: User +} + +class MapperTests : XCTestCase { + + func testDecodeObject() throws { + let json: JSON = ["string": "Paulo", "int": 100, "bool": true, "double": 0.1, "null": nil] + + let user = try User(from: json) + + XCTAssertEqual(user.string, "Paulo") + XCTAssertEqual(user.int, 100) + XCTAssertEqual(user.bool, true) + XCTAssertEqual(user.double, 0.1) + XCTAssertNil(user.null) + } + + func testDecodeArrayOfObjects() throws { + let json: JSON = [["string": "Paulo0", "double": 0.1, "int": 100, "bool": true, "null": nil], ["string": "Paulo1", "double": 1.1, "int": 101, "bool": true, "null": nil]] + + let users = try [User](from: json) + + var i = 0 + for user in users { + XCTAssertEqual(user.string, "Paulo\(i)") + XCTAssertEqual(user.int, 100 + i) + XCTAssertEqual(user.bool, true) + XCTAssertEqual(user.double, 0.1 + Double(i)) + XCTAssertNil(user.null) + i += 1 + } + } + + func testDecodeArrayWithNil() throws { + let input = [1, nil, 3, nil] + let json: JSON = [1, nil, 3, nil] + let output = try [Int?](from: json) + + for i in 0 ..< input.count { + XCTAssertEqual(input[i], output[i]) + } + } + + func testDecodeSingleValue() throws { + let json: JSON = 1 + let result = try Int(from: json) + + XCTAssertEqual(result, 1) + } + + func testDecodeSingleNil() throws { + let json: JSON = JSON.null + let result = try Int?(from: json) + + XCTAssertNil(result) + } + + func testDecodeHierarchy() throws { + let json: JSON = ["name": "organization", + "departments": [ + ["name": "department", + "manager": ["string": "Paulo", "double": 0.1, "int": 100, "bool": true, "null": nil], + "workers": [ + ["string": "Paulo", "double": 0.1, "int": 100, "bool": true, "null": nil] + ] + ] + ] + ] + + let result = try Organization(from: json) + print(result) + } +} + + +extension MapperTests { + public static var allTests: [(String, (MapperTests) -> () throws -> Void)] { + return [ + ("testDecodeObject", testDecodeObject), + ("testDecodeArrayOfObjects", testDecodeArrayOfObjects), + ("testDecodeArrayWithNil", testDecodeArrayWithNil), + ("testDecodeSingleValue", testDecodeSingleValue), + ("testDecodeSingleNil", testDecodeSingleNil), + ("testDecodeHierarchy", testDecodeHierarchy), + ] + } +} diff --git a/Tests/MediaTests/XMLTests.swift b/Tests/MediaTests/XMLTests.swift new file mode 100644 index 00000000..f1d75d09 --- /dev/null +++ b/Tests/MediaTests/XMLTests.swift @@ -0,0 +1,107 @@ +import XCTest +@testable import Media +import Foundation + +struct Book : Codable { + let author: String + + enum Key : String, CodingKey { + case author = "Author" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Key.self) + author = try container.decode(String.self, forKey: .author) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: Key.self) + try container.encode(author, forKey: .author) + } +} + +struct Catalog : Codable { + let books: [Book] + + enum Key : String, CodingKey { + case book = "Book" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Key.self) + books = try container.decode([Book].self, forKey: .book) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: Key.self) + try container.encode(books, forKey: .book) + } +} + +struct Root : Codable { + let catalog: Catalog + + enum Key : String, CodingKey { + case catalog = "Catalog" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Key.self) + catalog = try container.decode(Catalog.self, forKey: .catalog) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: Key.self) + try container.encode(catalog, forKey: .catalog) + } +} + +public class XMLTests: XCTestCase { + func testXML() throws { + do { + let xml = XML(root: + XML.Element(name: "Catalog", children: [ + XML.Element(name: "Book", attributes: ["id": "a"], children: [ + XML.Element(name: "Author", children: ["Bob"]), + ]), + XML.Element(name: "Book", attributes: ["id": "b"], children: [ + XML.Element(name: "Author", children: ["John"]), + ]), + XML.Element(name: "Book", attributes: ["id": "c"], children: [ + XML.Element(name: "Author", children: ["Mark"]), + ]), + ]) + ) + + let json: JSON = [ + "Catalog": [ + "Book": [ + ["Author": "Bob"], + ["Author": "John"], + ["Author": "Mark"], + ] + ] + ] + + var root: Root + + root = try Root(from: json) + + root = try Root(from: xml) + + + let json2 = try JSON(from: root) + XCTAssertEqual(json, json2) + } catch { + print(error) + } + } +} + +extension XMLTests { + public static var allTests: [(String, (XMLTests) -> () throws -> Void)] { + return [ + ("testXML", testXML), + ] + } +} diff --git a/circle.yml b/circle.yml index fe016d20..14d52dd4 100644 --- a/circle.yml +++ b/circle.yml @@ -1,3 +1,6 @@ +machine: + xcode: + version: 9.0 dependencies: override: - eval "$(curl -sL http://sh.zewo.io/install-zewo.sh)" diff --git a/docs/Core/js/jquery.min.js b/docs/Core/js/jquery.min.js index ab28a247..c023c6e4 100755 --- a/docs/Core/js/jquery.min.js +++ b/docs/Core/js/jquery.min.js @@ -1,4 +1,4 @@ /*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="

",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/\s*$/g,rb={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("