From 2cefb87f200a4974f0642049d30c95cb15feff36 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 23 Aug 2017 21:30:28 -0700 Subject: [PATCH] =?UTF-8?q?Create=20ArticleCache,=20which=20wraps=20a=20we?= =?UTF-8?q?ak-to-weak=20NSMapTable.=20An=20article=20is=20cached=20for=20a?= =?UTF-8?q?s=20long=20as=20there=E2=80=99s=20an=20external=20(outside-the-?= =?UTF-8?q?cache)=20reference=20to=20the=20article.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Frameworks/Database/ArticlesTable.swift | 42 +++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/Frameworks/Database/ArticlesTable.swift b/Frameworks/Database/ArticlesTable.swift index 00ea7ab42..dfe3542ed 100644 --- a/Frameworks/Database/ArticlesTable.swift +++ b/Frameworks/Database/ArticlesTable.swift @@ -20,9 +20,8 @@ final class ArticlesTable: DatabaseTable { private let authorsLookupTable: DatabaseLookupTable private let attachmentsLookupTable: DatabaseLookupTable private let tagsLookupTable: DatabaseLookupTable - -// private let cachedArticles: NSMapTable = NSMapTable.weakToWeakObjects() - + private let articleCache = ArticleCache() + init(name: String) { self.name = name @@ -157,3 +156,40 @@ final class ArticlesTable: DatabaseTable { // } //} +private struct ArticleCache { + + // Main thread only. + // The cache contains a given article only until all outside references are gone. + // Cache key is articleID. + + private let articlesMapTable: NSMapTable = NSMapTable.weakToWeakObjects() + + func uniquedArticles(_ articles: Set
) -> Set
{ + + var articlesToReturn = Set
() + + for article in articles { + let articleID = article.articleID + if let cachedArticle = cachedArticle(for: articleID) { + articlesToReturn.insert(cachedArticle) + } + else { + articlesToReturn.insert(article) + addToCache(article) + } + } + + return articlesToReturn + } + + private func cachedArticle(for articleID: String) -> Article? { + + return articlesMapTable.object(forKey: articleID as NSString) + } + + private func addToCache(_ article: Article) { + + articlesMapTable.setObject(article, forKey: article.articleID as NSString) + } +} +