Update to gobook@c6d7a22edd03e7738c38d5baa2174ff325d8d863

This commit is contained in:
Alan Donovan
2015-10-28 14:20:59 -04:00
parent fce1727c4c
commit 30090035de
150 changed files with 8559 additions and 6 deletions
+44
View File
@@ -0,0 +1,44 @@
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 275.
// Package memo provides a concurrency-safe memoization a function of
// type Func. Concurrent requests are serialized by a Mutex.
package memo
import "sync"
// Func is the type of the function to memoize.
type Func func(string) (interface{}, error)
type result struct {
value interface{}
err error
}
func New(f Func) *Memo {
return &Memo{f: f, cache: make(map[string]result)}
}
//!+
type Memo struct {
f Func
mu sync.Mutex // guards cache
cache map[string]result
}
// Get is concurrency-safe.
func (memo *Memo) Get(key string) (value interface{}, err error) {
memo.mu.Lock()
res, ok := memo.cache[key]
if !ok {
res.value, res.err = memo.f(key)
memo.cache[key] = res
}
memo.mu.Unlock()
return res.value, res.err
}
//!-
+23
View File
@@ -0,0 +1,23 @@
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
package memo_test
import (
"testing"
"gopl.io/ch9/memo2"
"gopl.io/ch9/memotest"
)
var httpGetBody = memotest.HTTPGetBody
func Test(t *testing.T) {
m := memo.New(httpGetBody)
memotest.Sequential(t, m)
}
func TestConcurrent(t *testing.T) {
m := memo.New(httpGetBody)
memotest.Concurrent(t, m)
}