Fix for crashing range indexes when variable length is 1

This commit is contained in:
Łukasz Kuczborski
2021-04-09 22:51:55 +02:00
parent fd107355c2
commit 7c635975d1
2 changed files with 14 additions and 1 deletions

View File

@@ -50,6 +50,7 @@ public struct Variable: Equatable, Resolvable {
public func resolve(_ context: Context) throws -> Any? { public func resolve(_ context: Context) throws -> Any? {
if (variable.hasPrefix("'") && variable.hasSuffix("'")) || (variable.hasPrefix("\"") && variable.hasSuffix("\"")) { if (variable.hasPrefix("'") && variable.hasSuffix("'")) || (variable.hasPrefix("\"") && variable.hasSuffix("\"")) {
// String literal // String literal
guard variable.count > 1 else { return "" }
return String(variable[variable.index(after: variable.startIndex) ..< variable.index(before: variable.endIndex)]) return String(variable[variable.index(after: variable.startIndex) ..< variable.index(before: variable.endIndex)])
} }

View File

@@ -63,13 +63,25 @@ final class VariableTests: XCTestCase {
let result = try variable.resolve(self.context) as? String let result = try variable.resolve(self.context) as? String
try expect(result) == "name" try expect(result) == "name"
} }
it("can resolve a string literal with one double quote") {
let variable = Variable("\"")
let result = try variable.resolve(self.context) as? String
try expect(result) == ""
}
it("can resolve a string literal with single quotes") { it("can resolve a string literal with single quotes") {
let variable = Variable("'name'") let variable = Variable("'name'")
let result = try variable.resolve(self.context) as? String let result = try variable.resolve(self.context) as? String
try expect(result) == "name" try expect(result) == "name"
} }
it("can resolve a string literal with one single quote") {
let variable = Variable("'")
let result = try variable.resolve(self.context) as? String
try expect(result) == ""
}
it("can resolve an integer literal") { it("can resolve an integer literal") {
let variable = Variable("5") let variable = Variable("5")
let result = try variable.resolve(self.context) as? Int let result = try variable.resolve(self.context) as? Int