// swiftlint:disable all import UIKit public extension UIImage { convenience init?(blurHash: String, size: CGSize, punch: Float = 1) { guard blurHash.count >= 6 else { return nil } let sizeFlag = String(blurHash[0]).decode83() let numY = (sizeFlag / 9) + 1 let numX = (sizeFlag % 9) + 1 let quantisedMaximumValue = String(blurHash[1]).decode83() let maximumValue = Float(quantisedMaximumValue + 1) / 166 guard blurHash.count == 4 + 2 * numX * numY else { return nil } let colours: [(Float, Float, Float)] = (0.. (Float, Float, Float) { let intR = value >> 16 let intG = (value >> 8) & 255 let intB = value & 255 return (sRGBToLinear(intR), sRGBToLinear(intG), sRGBToLinear(intB)) } private func decodeAC(_ value: Int, maximumValue: Float) -> (Float, Float, Float) { let quantR = value / (19 * 19) let quantG = (value / 19) % 19 let quantB = value % 19 let rgb = (signPow((Float(quantR) - 9) / 9, 2) * maximumValue, signPow((Float(quantG) - 9) / 9, 2) * maximumValue, signPow((Float(quantB) - 9) / 9, 2) * maximumValue) return rgb } private func signPow(_ value: Float, _ exp: Float) -> Float { copysign(pow(abs(value), exp), value) } private func linearTosRGB(_ value: Float) -> Int { let v = max(0, min(1, value)) if v <= 0.0031308 { return Int(v * 12.92 * 255 + 0.5) } else { return Int((1.055 * pow(v, 1 / 2.4) - 0.055) * 255 + 0.5) } } private func sRGBToLinear(_ value: Type) -> Float { let v = Float(Int64(value)) / 255 if v <= 0.04045 { return v / 12.92 } else { return pow((v + 0.055) / 1.055, 2.4) } } private let encodeCharacters: [String] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~".map { String($0) } private let decodeCharacters: [String: Int] = { var dict: [String: Int] = [:] for (index, character) in encodeCharacters.enumerated() { dict[character] = index } return dict }() extension String { func decode83() -> Int { var value = 0 for character in self { if let digit = decodeCharacters[String(character)] { value = value * 83 + digit } } return value } } private extension String { subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] } subscript(bounds: CountableRange) -> Substring { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return self[start..