shithub: mycel

Download patch

ref: 905263542c6f19b3d66f94e323995af7880c9355
parent: ccb87a870380861973edfe358e9df1b163a50eb6
author: Philip Silva <philip.silva@protonmail.com>
date: Fri Apr 2 11:59:22 EDT 2021

cache more than 1 website

diff: cannot open b/browser/cache//null: file does not exist: 'b/browser/cache//null'
--- a/browser/browser.go
+++ b/browser/browser.go
@@ -13,6 +13,7 @@
 	"net/http/cookiejar"
 	"net/url"
 	"github.com/psilva261/opossum"
+	"github.com/psilva261/opossum/browser/cache"
 	"github.com/psilva261/opossum/browser/history"
 	"github.com/psilva261/opossum/img"
 	"github.com/psilva261/opossum/logger"
@@ -59,10 +60,6 @@
 var dui *duit.DUI
 var colorCache = make(map[draw.Color]*draw.Image)
 var imageCache = make(map[string]*draw.Image)
-var cache = make(map[string]struct {
-	opossum.ContentType
-	buf []byte
-})
 var log *logger.Logger
 var scroller *Scroll
 var display *draw.Display
@@ -1448,11 +1445,8 @@
 }
 
 func (b *Browser) render(buf []byte) {
-	log.Printf("Empty cache...")
-	cache = make(map[string]struct {
-		opossum.ContentType
-		buf []byte
-	})
+	log.Printf("Empty some cache...")
+	cache.Tidy()
 	imageCache = make(map[string]*draw.Image)
 
 	b.Website.html = string(buf) // TODO: correctly interpret UTF8
@@ -1479,17 +1473,18 @@
 }
 
 func (b *Browser) Get(uri *url.URL) (buf []byte, contentType opossum.ContentType, err error) {
-	c, ok := cache[uri.String()]
+	c, ok := cache.Get(uri.String())
 	if ok {
 		log.Printf("use %v from cache", uri)
 	} else {
-		c.buf, c.ContentType, err = b.get(uri, false)
+		c.Addr = uri.String()
+		c.Buf, c.ContentType, err = b.get(uri, false)
 		if err == nil {
-			cache[uri.String()] = c
+			cache.Set(c)
 		}
 	}
 
-	return c.buf, c.ContentType, err
+	return c.Buf, c.ContentType, err
 }
 
 func (b *Browser) statusBarMsg(msg string, emptyBody bool) {
--- /dev/null
+++ b/browser/cache/cache.go
@@ -1,0 +1,53 @@
+package cache
+
+import (
+	"github.com/psilva261/opossum"
+	"sort"
+	"time"
+)
+
+var c = make(Items, 0, 100)
+
+type Items []*Item
+
+func (is Items) Len() int {
+	return len(is)
+}
+
+func (is Items) Swap(i, j int) {
+	is[i], is[j] = is[j], is[i]
+}
+
+func (is Items) Less(i, j int) bool {
+	return is[i].Used.After(is[j].Used)
+}
+
+type Item struct {
+	Addr string
+	opossum.ContentType
+	Buf []byte
+	Used time.Time
+}
+
+func Get(addr string) (i Item, ok bool) {
+	for _, it := range c {
+		if it.Addr == addr {
+			it.Used = time.Now()
+			return *it, true
+		}
+	}
+	return
+}
+
+func Set(i Item) {
+	i.Used = time.Now()
+	c = append(c, &i)
+}
+
+func Tidy() {
+	if len(c) < 100 {
+		return
+	}
+	sort.Stable(c)
+	c = c[0:50]
+}