clock

package
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2022 License: MIT Imports: 1 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is used The clock cache replacement policy.

The clock algorithm keeps a circular list of pages in memory, with the "hand" (iterator) pointing to the last examined page frame in the list. When a page fault occurs and no empty frames exist, then the R (referenced) bit is inspected at the hand's location. If R is 0, the new page is put in place of the page the "hand" points to, and the hand is advanced one position. Otherwise, the R bit is cleared, then the clock hand is incremented and the process is repeated until a page is replaced.

func NewCache

func NewCache[K comparable, V any](opts ...Option) *Cache[K, V]

NewCache creates a new non-thread safe clock cache whose capacity is the default size (128).

Example
package main

import (
	"fmt"

	"github.com/xuxife/go-generics-cache/policy/clock"
)

func main() {
	c := clock.NewCache[string, int]()
	c.Set("a", 1)
	c.Set("b", 2)
	av, aok := c.Get("a")
	bv, bok := c.Get("b")
	cv, cok := c.Get("c")
	fmt.Println(av, aok)
	fmt.Println(bv, bok)
	fmt.Println(cv, cok)
	c.Delete("a")
	_, aok2 := c.Get("a")
	if !aok2 {
		fmt.Println("key 'a' has been deleted")
	}
	// update
	c.Set("b", 3)
	newbv, _ := c.Get("b")
	fmt.Println(newbv)
}
Output:

1 true
2 true
0 false
key 'a' has been deleted
3

func (*Cache[K, V]) Delete

func (c *Cache[K, V]) Delete(key K)

Delete deletes the item with provided key from the cache.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (zero V, _ bool)

Get looks up a key's value from the cache.

func (*Cache[K, V]) Keys

func (c *Cache[K, V]) Keys() []K

Keys returns the keys of the cache. the order as same as current ring order.

Example
package main

import (
	"fmt"

	"github.com/xuxife/go-generics-cache/policy/clock"
)

func main() {
	c := clock.NewCache[string, int]()
	c.Set("foo", 1)
	c.Set("bar", 2)
	c.Set("baz", 3)
	keys := c.Keys()
	for _, key := range keys {
		fmt.Println(key)
	}
}
Output:

foo
bar
baz

func (*Cache[K, V]) Len

func (c *Cache[K, V]) Len() int

Len returns the number of items in the cache.

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, val V)

Set sets any item to the cache. replacing any existing item.

type Option

type Option func(*options)

Option is an option for clock cache.

func WithCapacity

func WithCapacity(cap int) Option

WithCapacity is an option to set cache capacity.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL