Support giving color values as percentage
This commit is contained in:
parent
911db304ae
commit
e65f684654
2 changed files with 42 additions and 1 deletions
|
@ -119,13 +119,25 @@ extension Scanner {
|
||||||
func commaSeparated() -> [UInt8]? {
|
func commaSeparated() -> [UInt8]? {
|
||||||
var result: [UInt8] = []
|
var result: [UInt8] = []
|
||||||
repeat {
|
repeat {
|
||||||
guard let int = scanInt(), let component = UInt8(exactly: int) else {
|
guard let component = self.component() else {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
result.append(component)
|
result.append(component)
|
||||||
} while string(",")
|
} while string(",")
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func component() -> UInt8? {
|
||||||
|
guard var int = scanInt() else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if string("%") {
|
||||||
|
int = int * 0xFF / 100
|
||||||
|
}
|
||||||
|
|
||||||
|
return UInt8(exactly: int)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private extension Scanner {
|
private extension Scanner {
|
||||||
|
|
|
@ -57,6 +57,35 @@ final class ColorParserTest: XCTestCase {
|
||||||
XCTAssertNil(color)
|
XCTAssertNil(color)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func testScanningColorWithPercentage() throws {
|
||||||
|
let color = scanColor("rgba(100%, 0, 50%, 100%)")
|
||||||
|
XCTAssertEqual(color, Color(red: 255, green: 0, blue: 127, alpha: 255))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testReadingComponentAsByte() throws {
|
||||||
|
let scanner = Scanner(string: "128")
|
||||||
|
XCTAssertEqual(scanner.component(), 128)
|
||||||
|
XCTAssertTrue(scanner.isAtEnd)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testReadingComponentAs100Percent() throws {
|
||||||
|
let scanner = Scanner(string: "100%")
|
||||||
|
XCTAssertEqual(scanner.component(), 0xFF)
|
||||||
|
XCTAssertTrue(scanner.isAtEnd)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testReadingComponentAs0Percent() throws {
|
||||||
|
let scanner = Scanner(string: "0%")
|
||||||
|
XCTAssertEqual(scanner.component(), 0)
|
||||||
|
XCTAssertTrue(scanner.isAtEnd)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testReadingComponentAs50PercentRoundsDown() throws {
|
||||||
|
let scanner = Scanner(string: "50%")
|
||||||
|
XCTAssertEqual(scanner.component(), 127)
|
||||||
|
XCTAssertTrue(scanner.isAtEnd)
|
||||||
|
}
|
||||||
|
|
||||||
private func scanColor(_ input: String) -> Color? {
|
private func scanColor(_ input: String) -> Color? {
|
||||||
let scanner = Scanner(string: input)
|
let scanner = Scanner(string: input)
|
||||||
return scanner.color()
|
return scanner.color()
|
||||||
|
|
Loading…
Add table
Reference in a new issue