From e65f68465412c11aa89f1f7da15298bb29c97212 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Fri, 1 Jan 2021 12:52:20 +0100 Subject: [PATCH] Support giving color values as percentage --- .../Model/Scanner+ColorParser.swift | 14 ++++++++- Tests/MakeColorsTests/ColorParserTest.swift | 29 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/Sources/LibMakeColors/Model/Scanner+ColorParser.swift b/Sources/LibMakeColors/Model/Scanner+ColorParser.swift index fb0bd1c..84957cd 100644 --- a/Sources/LibMakeColors/Model/Scanner+ColorParser.swift +++ b/Sources/LibMakeColors/Model/Scanner+ColorParser.swift @@ -119,13 +119,25 @@ extension Scanner { func commaSeparated() -> [UInt8]? { var result: [UInt8] = [] repeat { - guard let int = scanInt(), let component = UInt8(exactly: int) else { + guard let component = self.component() else { return nil } result.append(component) } while string(",") 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 { diff --git a/Tests/MakeColorsTests/ColorParserTest.swift b/Tests/MakeColorsTests/ColorParserTest.swift index 708c77d..edcb587 100644 --- a/Tests/MakeColorsTests/ColorParserTest.swift +++ b/Tests/MakeColorsTests/ColorParserTest.swift @@ -57,6 +57,35 @@ final class ColorParserTest: XCTestCase { 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? { let scanner = Scanner(string: input) return scanner.color()