Faster HTML String disk cache

This commit is contained in:
Thomas Ricouard 2023-02-05 21:23:47 +01:00
parent d7bad26f04
commit 0af60c4b1e

View file

@ -2,22 +2,38 @@ import Foundation
import SwiftSoup
import SwiftUI
fileprivate enum CodingKeys: CodingKey {
case htmlValue, asMarkdown, asRawText, statusesURLs
}
public struct HTMLString: Codable, Equatable, Hashable {
public var htmlValue: String = ""
public var asMarkdown: String = ""
public var asRawText: String = ""
public var statusesURLs = [URL]()
public var asSafeMarkdownAttributedString: AttributedString = .init()
private var regex: NSRegularExpression?
public init(from decoder: Decoder) {
var alreadyDecoded: Bool = false
do {
let container = try decoder.singleValueContainer()
htmlValue = try container.decode(String.self)
} catch {
do {
alreadyDecoded = true
let container = try decoder.container(keyedBy: CodingKeys.self)
htmlValue = try container.decode(String.self, forKey: .htmlValue)
asMarkdown = try container.decode(String.self, forKey: .asMarkdown)
asRawText = try container.decode(String.self, forKey: .asRawText)
statusesURLs = try container.decode([URL].self, forKey: .statusesURLs)
} catch {
htmlValue = ""
}
}
if !alreadyDecoded {
// https://daringfireball.net/projects/markdown/syntax
// Pre-escape \ ` _ * and [ as these are the only
// characters the markdown parser used picks up
@ -48,6 +64,7 @@ public struct HTMLString: Codable, Equatable, Hashable {
} catch {
asRawText = htmlValue
}
}
do {
let options = AttributedString.MarkdownParsingOptions(allowsExtendedAttributes: true,
@ -67,8 +84,11 @@ public struct HTMLString: Codable, Equatable, Hashable {
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(htmlValue)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(htmlValue, forKey: .htmlValue)
try container.encode(asMarkdown, forKey: .asMarkdown)
try container.encode(asRawText, forKey: .asRawText)
try container.encode(statusesURLs, forKey: .statusesURLs)
}
private mutating func handleNode(node: SwiftSoup.Node) {