diff --git a/Sources/JSON/JSON.swift b/Sources/JSON/JSON.swift index 82e4e68..e28a202 100644 --- a/Sources/JSON/JSON.swift +++ b/Sources/JSON/JSON.swift @@ -258,15 +258,27 @@ public enum JSON: Equatable { public static func / (lhs: JSON, rhs: JSON) -> JSON { switch (lhs, rhs) { case let (.Double(x), .Double(y)): + guard y != 0 else { + return JSON.Null + } return .Double(x / y) case let (.Int(x), .Int(y)): + guard y != 0 else { + return JSON.Null + } if x % y == 0 { return .Int(x / y) } return .Double(Swift.Double(x) / Swift.Double(y)) case let (.Double(x), .Int(y)): + guard y != 0 else { + return JSON.Null + } return .Double(x / Swift.Double(y)) case let (.Int(x), .Double(y)): + guard y != 0 else { + return JSON.Null + } return .Double(Swift.Double(x) / y) default: return JSON.Null @@ -276,12 +288,24 @@ public enum JSON: Equatable { public static func % (lhs: JSON, rhs: JSON) -> JSON { switch (lhs, rhs) { case let (.Double(x), .Double(y)): + guard y != 0 else { + return JSON.Null + } return .Double(x.truncatingRemainder(dividingBy: y)) case let (.Int(x), .Int(y)): + guard y != 0 else { + return JSON.Null + } return .Int(x % y) case let (.Double(x), .Int(y)): + guard y != 0 else { + return JSON.Null + } return .Double(x.truncatingRemainder(dividingBy: Swift.Double(y))) case let (.Int(x), .Double(y)): + guard y != 0 else { + return JSON.Null + } return .Double(Swift.Double(x).truncatingRemainder(dividingBy: y)) default: return JSON.Null diff --git a/Tests/jsonlogicTests/ArithmeticTests.swift b/Tests/jsonlogicTests/ArithmeticTests.swift index e537994..c03882a 100644 --- a/Tests/jsonlogicTests/ArithmeticTests.swift +++ b/Tests/jsonlogicTests/ArithmeticTests.swift @@ -134,6 +134,20 @@ class Arithmetic: XCTestCase { XCTAssertEqual(1, try applyRule(rule, to: nil)) } + func testDivisionByZero() { + let rule = + """ + { "/" : [4, 0]} + """ + XCTAssertThrowsError(try applyRule(rule, to: nil) as Double) { error in + XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Double.self)) + } + + XCTAssertThrowsError(try applyRule(rule, to: nil) as Int) { error in + XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Int.self)) + } + } + func testModulo() { var rule = """ @@ -154,6 +168,20 @@ class Arithmetic: XCTestCase { XCTAssertEqual(1, try applyRule(rule, to: nil)) } + func testModuloByZero() { + let rule = + """ + { "%" : [4, 0]} + """ + XCTAssertThrowsError(try applyRule(rule, to: nil) as Double) { error in + XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Double.self)) + } + + XCTAssertThrowsError(try applyRule(rule, to: nil) as Int) { error in + XCTAssertEqual(error as! JSONLogicError, JSONLogicError.canNotConvertResultToType(Int.self)) + } + } + func testUnaryMinus() { var rule = """