Skip to content
Snippets Groups Projects
Commit b657615c authored by Fernando Ike's avatar Fernando Ike
Browse files

Imported Upstream version 0.0~git20150804.0.b51b08c

parents
No related branches found
No related tags found
No related merge requests found
LICENSE 0 → 100644
The MIT License (MIT)
Copyright (c) 2015 Emmanuel Odeke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# cache
Simple cache with expirable values
cache.go 0 → 100644
package expirable
import (
"sync"
"time"
)
type Operation int
const (
Noop Operation = 1 << iota
Create
Read
Update
Delete
)
type Keyable interface{}
type Expirable interface {
Expired(baseTime time.Time) bool
Value() interface{}
}
type KeyValue struct {
Key Keyable
Value Expirable
}
type OperationCache struct {
mu *sync.Mutex
body map[Keyable]Expirable
}
func New() *OperationCache {
return &OperationCache{
mu: &sync.Mutex{},
body: make(map[Keyable]Expirable),
}
}
func (oc *OperationCache) Put(k Keyable, v Expirable) bool {
oc.mu.Lock()
defer oc.mu.Unlock()
oc.body[k] = v
return true
}
func (oc *OperationCache) Get(k Keyable) (Expirable, bool) {
oc.mu.Lock()
v, ok := oc.body[k]
oc.mu.Unlock()
if ok && v != nil && v.Expired(time.Now()) {
prev, _ := oc.Remove(k)
return prev, false
}
return v, ok
}
func (oc *OperationCache) Remove(k Keyable) (prev Expirable, exist bool) {
oc.mu.Lock()
defer oc.mu.Unlock()
prev, exist = oc.body[k]
if exist {
delete(oc.body, k)
}
return prev, exist
}
func (oc *OperationCache) Items() chan *KeyValue {
items := make(chan *KeyValue)
go func() {
defer close(items)
for k, v := range oc.body {
items <- &KeyValue{Key: k, Value: v}
}
}()
return items
}
package expirable
import (
"fmt"
"path/filepath"
"strings"
"testing"
"time"
)
type expirableValue struct {
value interface{}
entryTime time.Time
}
func (e *expirableValue) Value() interface{} {
if e == nil {
return nil
}
return e.value
}
func (e *expirableValue) Expired(q time.Time) bool {
if e == nil {
return true
}
return e.entryTime.Before(q)
}
var newExpirableValue = func(v interface{}) *expirableValue {
return newExpirableValueWithOffset(v, 0)
}
func newExpirableValueWithOffset(v interface{}, expiry int) *expirableValue {
return &expirableValue{
value: v,
entryTime: time.Now().Add(time.Duration(expiry)),
}
}
func parDir(p string) string {
return filepath.Dir(p)
}
func TestInit(t *testing.T) {
fmt.Print("testInit")
store := New()
manifestStr := `
/openSrc/node-tika
/openSrc/Radicale
/openSrc/rodats
/openSrc/ical.js
/openSrc/aws-sdk-js
/openSrc/dpxdt
/openSrc/emmodeke-vim-clone
/openSrc/ytrans.js
/openSrc/oxy
/openSrc/drive-js
/openSrc/git
/openSrc/ldappy/
`
manifest := strings.Split(manifestStr, "\n")
expiryMs := 25
tick := time.Tick(time.Duration(expiryMs))
manifestCount := len(manifest)
done := make(chan bool, manifestCount)
for _, item := range manifest {
go func(p string) {
par := parDir(p)
exp := newExpirableValueWithOffset(p, expiryMs)
store.Put(par, exp)
retr, ok := store.Get(par)
if retr != exp {
fmt.Printf("%s encountered a clashing concurrent access %v %v\n", p, retr, exp)
}
fmt.Printf("%s still Fresh? %v\n", par, ok)
done <- true
}(item)
}
for i := 0; i < manifestCount; i++ {
<-done
}
// fmt.Println(store)
<-tick
// Now expecting stale changes
for _, item := range manifest {
go func(p string) {
par := parDir(p)
retr, ok := store.Get(par)
if ok {
t.Errorf("%s should have expired", par)
}
fmt.Printf("%s Retr: %v still Fresh? %v\n", par, retr)
}(item)
}
}
//
// OperationCache.swift
//
// Created by Indragie Karunaratne on 8/3/15.
//
import Foundation
public struct Expirable<ValueType> {
public let expiryDate: NSDate
public let value: ValueType
public var expired: Bool {
return NSDate().compare(expiryDate) == .OrderedDescending
}
}
public func ==<ValueType: Equatable>(lhs: Expirable<ValueType>, rhs: Expirable<ValueType>) -> Bool {
return lhs.expiryDate == rhs.expiryDate && lhs.value == rhs.value
}
/// Swift port of https://github.com/odeke-em/cache/blob/master/cache.go
///
/// Lockless & thread safe with support for multiple concurrent readers
/// and a single writer.
public class OperationCache<KeyType: Hashable, ValueType> {
public typealias ExpirableType = Expirable<ValueType>
private let queue = dispatch_queue_create("com.indragie.OperationCache", DISPATCH_QUEUE_CONCURRENT)
private var storage = [KeyType: ExpirableType]()
public var snapshot: Zip2Sequence<[KeyType], [ExpirableType]> {
var sequence: Zip2Sequence<[KeyType], [ExpirableType]>? = nil
dispatch_sync(queue) {
sequence = zip(self.storage.keys.array, self.storage.values.array)
}
return sequence!
}
public subscript(key: KeyType) -> Expirable<ValueType>? {
get {
var value: ExpirableType?
dispatch_sync(queue) { value = self.storage[key] }
if let value = value where value.expired {
self[key] = nil
return nil
}
return value
}
set {
dispatch_barrier_async(queue) { self.storage[key] = newValue }
}
}
}
//
// OperationCacheTests.swift
//
// Created by Indragie Karunaratne on 8/3/15.
//
import XCTest
@testable import OperationCache
class OperationCacheTests: XCTestCase {
func testInit() {
let cache = OperationCache<String, String>()
for (_, _) in cache.snapshot {
XCTFail("There should be no values")
}
}
func testGetAndSet() {
let cache = OperationCache<String, String>()
XCTAssertTrue(cache["foo"] == nil)
let expirable = Expirable(expiryDate: NSDate.distantFuture(), value: "bar")
cache["foo"] = expirable
XCTAssertTrue(cache["foo"]! == expirable)
let expirable2 = Expirable(expiryDate: NSDate.distantFuture(), value: "baz")
cache["foo"] = expirable2
XCTAssertTrue(cache["foo"]! == expirable2)
}
func testRemove() {
let cache = OperationCache<String, String>()
cache["foo"] = Expirable(expiryDate: NSDate.distantFuture(), value: "bar")
XCTAssertTrue(cache["foo"] != nil)
cache["foo"] = nil
XCTAssertTrue(cache["foo"] == nil)
}
func testExpiration() {
let cache = OperationCache<String, String>()
cache["foo"] = Expirable(expiryDate: NSDate.distantPast(), value: "bar")
XCTAssertTrue(cache["foo"] == nil)
}
func testSnapshot() {
let cache = OperationCache<String, String>()
let expirable = Expirable(expiryDate: NSDate.distantFuture(), value: "bar")
cache["foo"] = expirable
var generator = cache.snapshot.generate()
var next = generator.next()
XCTAssertEqual(next!.0, "foo")
XCTAssertTrue(next!.1 == expirable)
next = generator.next()
XCTAssertTrue(next == nil)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment