Skip to content
This repository has been archived by the owner on Mar 23, 2021. It is now read-only.

Commit

Permalink
Updating to Swift 07-29 (#38)
Browse files Browse the repository at this point in the history
* Updated Swift to 07-29

* Now all
  • Loading branch information
czechboy0 authored Aug 1, 2016
1 parent eef2961 commit e031f3b
Show file tree
Hide file tree
Showing 20 changed files with 185 additions and 80 deletions.
2 changes: 1 addition & 1 deletion .swift-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
DEVELOPMENT-SNAPSHOT-2016-07-25-a
DEVELOPMENT-SNAPSHOT-2016-07-29-a
37 changes: 0 additions & 37 deletions CHANGELOG.md

This file was deleted.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ do {
## Swift Package Manager

```swift
.Package(url: "https://github.com/czechboy0/Jay.git", majorVersion: 0, minor: 16)
.Package(url: "https://github.com/czechboy0/Jay.git", majorVersion: 0, minor: 17)
```

:blue_heart: Code of Conduct
Expand Down
1 change: 1 addition & 0 deletions Sources/Jay/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ enum JayError: Swift.Error {
case unsupportedIntegerType(Any)
case keyIsNotString(Any)
case extraTokensFound(Reader)
case invalidUnicodeScalar(UInt16)
}

4 changes: 2 additions & 2 deletions Sources/Jay/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ extension Collection where Iterator.Element == UInt8 {
public func string() throws -> String {
var utf = UTF8()
var gen = self.makeIterator()
var str = String()
var str = String.UnicodeScalarView()
while true {
switch utf.decode(&gen) {
case .emptyInput: //we're done
return str
return String(str)
case .error: //error, can't describe what however
throw JayError.parseStringFromCharsFailed(Array(self))
case .scalarValue(let unicodeScalar):
Expand Down
2 changes: 1 addition & 1 deletion Sources/Jay/NativeTypeConversions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ struct NativeTypeConverter {
return .boolean(bool)
//number
case let dbl as FloatingPoint:
guard let double = Double(String(dbl)) else {
guard let double = Double(String(describing: dbl)) else {
throw JayError.unsupportedFloatingPointType(dbl)
}
return .number(.double(double))
Expand Down
5 changes: 4 additions & 1 deletion Sources/Jay/OutputStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ public protocol JsonOutputStream {
func print(_ bytes: [UInt8])
}

infix operator <<< { associativity left }
precedencegroup LeftAssociativity {
associativity: left
}
infix operator <<< : LeftAssociativity

@discardableResult
func <<<(stream: JsonOutputStream, value: UInt8) -> JsonOutputStream {
Expand Down
12 changes: 7 additions & 5 deletions Sources/Jay/StringParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ struct StringParser: JsonParser {

func parseString(_ r: Reader) throws -> (String, Reader) {

var str = ""
var chars = String.UnicodeScalarView()
var reader = r
while true {

Expand All @@ -51,19 +51,19 @@ struct StringParser: JsonParser {
case Const.QuotationMark:
//end of string, return what we have
try reader.nextAndCheckNotDone()
return (str, reader)
return (String(chars), reader)

case Const.Escape:
//something that needs escaping, delegate
var char: UnicodeScalar
(char, reader) = try self.unescapedCharacter(reader)
str.append(char)
chars.append(char)

default:
//nothing special, just append a regular unicode character
var char: UnicodeScalar
(char, reader) = try self.readUnicodeCharacter(reader)
str.append(char)
chars.append(char)
}
}
}
Expand Down Expand Up @@ -164,7 +164,9 @@ struct StringParser: JsonParser {
}

//nope, normal unicode char
let char = UnicodeScalar(value)
guard let char = UnicodeScalar(value) else {
throw JayError.invalidUnicodeScalar(value)
}
return (char, reader)
}

Expand Down
140 changes: 140 additions & 0 deletions Sources/JayExample/Utils.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//
// Conversions.swift
// Jay
//
// Created by Honza Dvorsky on 5/16/16.
//
//

import Jay
import Foundation

//Useful methods for easier manipulation of type-safe JSON

extension JSON {

/// Returns the `JSON` as `[String: JSON]` if valid, else `nil`.
public var dictionary: [Swift.String: JSON]? {
guard case .object(let dict) = self else { return nil }
return dict
}

/// Returns the `JSON` as `[JSON]` if valid, else `nil`.
public var array: [JSON]? {
guard case .array(let arr) = self else { return nil }
return arr
}

/// Returns the `JSON` as an `Int` if valid, else `nil`.
public var int: Int? {
guard case .number(let number) = self else { return nil }
guard case .integer(let jsonInt) = number else { return nil }
return jsonInt
}

/// Returns the `JSON` as a `UInt` if valid, else `nil`.
public var uint: UInt? {
guard case .number(let number) = self else { return nil }
switch number {
case .integer(let int): return UInt(int)
case .unsignedInteger(let uint): return uint
default: return nil
}
}

/// Returns the `JSON` as a `Double` if valid, else `nil`.
public var double: Double? {
guard case .number(let number) = self else { return nil }
switch number {
case .double(let dbl): return dbl
case .integer(let int): return Double(int)
case .unsignedInteger(let uint): return Double(uint)
}
}

/// Returns the `JSON` as a `String` if valid, else `nil`.
public var string: Swift.String? {
guard case .string(let str) = self else { return nil }
return str
}

/// Returns the `JSON` as a `Bool` if valid, else `nil`.
public var boolean: Bool? {
guard case .boolean(let bool) = self else { return nil }
return bool
}

/// Returns the `JSON` as `NSNull` if valid, else `nil`.
public var null: NSNull? {
guard case .null = self else { return nil }
return NSNull()
}
}

//Thanks for the inspiration for the following initializers, https://github.com/Zewo/JSON/blob/master/Source/JSON.swift

extension JSON: ExpressibleByNilLiteral {

public init(nilLiteral: ()) {
self = .null
}
}

extension JSON: ExpressibleByBooleanLiteral {

/// Create a `JSON` instance initialized to the provided `booleanLiteral`.
public init(booleanLiteral value: BooleanLiteralType) {
self = .boolean(value)
}
}

extension JSON: ExpressibleByIntegerLiteral {

/// Create a `JSON` instance initialized to the provided `integerLiteral`.
public init(integerLiteral value: IntegerLiteralType) {
self = .number(.integer(value))
}
}

extension JSON: ExpressibleByFloatLiteral {

/// Create a `JSON` instance initialized to the provided `floatLiteral`.
public init(floatLiteral value: FloatLiteralType) {
self = .number(.double(value))
}
}

extension JSON: ExpressibleByStringLiteral {

/// Create a `JSON` instance initialized to the provided `unicodeScalarLiteral`.
public init(unicodeScalarLiteral value: Swift.String) {
self = .string(value)
}

/// Create a `JSON` instance initialized to the provided `extendedGraphemeClusterLiteral`.
public init(extendedGraphemeClusterLiteral value: Swift.String) {
self = .string(value)
}


/// Create a `JSON` instance initialized to the provided `stringLiteral`.
public init(stringLiteral value: StringLiteralType) {
self = .string(value)
}
}

extension JSON: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: JSON...) {
self = .array(elements)
}
}

extension JSON: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, JSON)...) {
var items: [String: JSON] = [:]
for pair in elements {
items[pair.0] = pair.1
}
self = .object(items)
}
}
46 changes: 21 additions & 25 deletions Sources/JayExample/main.swift
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import Jay
import Foundation

func tryParsing() {

let data = Array("{\t\"hello\" : \"wor🇨🇿ld\", \n\t \"val\": 1234, \"many\": [\n-12.32, \"yo\"\r], \"emptyDict\": {}, \"dict\": {\"arr\":[]}, \"name\": true}".utf8)
let exp: [String: Any] = [
let exp: JSON = [
"hello": "wor🇨🇿ld",
"val": 1234,
"val": .number(.unsignedInteger(1234)),
"many": [
-12.32,
// null, add NSNull back once we can reliably compare object hierarchies
"yo"
] as [Any],
"emptyDict": [String:Any](),
],
"emptyDict": [:],
"dict": [
"arr": [Any]()
"arr": []
],
"name": true
]
Expand All @@ -30,24 +28,23 @@ func tryParsing() {
func tryFormatting() {

let origStr = "{\"dict\":{\"arr\":[]},\"emptyDict\":{},\"hello\":\"wor🇨🇿ld\",\"many\":[-12.32,null,\"yo\",{\"hola\":9.23,\"nums\":[1,2,3]}],\"name\":true,\"val\":1234}"
let inObj: [String: Any] = ["hola": 9.23, "nums": [1,2,3]]
let obj: [String: Any] = [
let obj: JSON = [
"hello": "wor🇨🇿ld",
"val": 1234,
"many": [
-12.32,
NSNull(),
nil,
"yo",
inObj
] as [Any],
"emptyDict": [String: Any](),
["hola": 9.23, "nums": [1,2,3]]
],
"emptyDict": [:],
"dict": [
"arr": [Int]()
] as [String: Any],
"arr": []
],
"name": true
]

let dataOut = try! Jay(formatting: .minified).dataFromJson(anyDictionary: obj)
let dataOut = try! Jay(formatting: .minified).dataFromJson(json: obj)
let retStr = try! dataOut.string()

assert(origStr == retStr, "Mismatch: Expected:\n\(origStr)\nReturned:\n\(retStr)")
Expand All @@ -56,26 +53,25 @@ func tryFormatting() {

func tryFormattingToConsole() {

let inObj: [String: Any] = ["hola": 9.23, "nums": [1,2,3]]
let obj: [String: Any] = [
let obj: JSON = [
"hello": "wor🇨🇿ld",
"val": 1234,
"many": [
-12.32,
NSNull(),
nil,
"yo",
inObj
] as [Any],
"emptyDict": [String: Any](),
["hola": 9.23, "nums": [1,2,3]]
],
"emptyDict": [:],
"dict": [
"arr": [Int]()
] as [String: Any],
"arr": []
],
"name": true
]

let output = ConsoleOutputStream()
print("Dumping to console:")
try! Jay(formatting: .prettified).dataFromJson(anyDictionary: obj, output: output)
try! Jay(formatting: .prettified).dataFromJson(json: obj, output: output)
}

tryFormatting()
Expand Down
2 changes: 1 addition & 1 deletion Sources/JayPerformance/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Foundation

func urlForFixture(_ name: String) -> URL {
let parent = (#file).components(separatedBy: "/").dropLast(3).joined(separator: "/")
let url = URL(string: "file://\(parent)/Tests/Jay/Fixtures/\(name).json")!
let url = URL(string: "file://\(parent)/Tests/JayTests/Fixtures/\(name).json")!
print("Loading fixture from url \(url)")
return url
}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit e031f3b

Please sign in to comment.