A simple thread-safe, fixed size LRU written in Go. Based on dominictarr's Hashlru Algorithm. πŸ”ƒ

Overview

go-hashlru

A simple thread-safe, fixed size LRU written in Go. Based on dominictarr's Hashlru Algorithm. πŸ”ƒ

Uses map[interface{}]interface{} to allow kv pairs of any type. The hlru package contains all the necessary functions.

cache, _ := hlru.NewHLRU(100)

cache.Set("key", "value")

val, _ := cache.Get("key")

fmt.Println(val)
// value

Visit example/example.go in the root directory for a simple example.


Table of Contents :

Installation

$ go get github.com/saurabh0719/go-hashlru

Latest - v0.1.0


API Reference

HashLRU Struct

type HashLRU struct {
	maxSize            int
	size               int
	oldCache, newCache map[interface{}]interface{}
	onEvictedCB        func(key, value interface{})
	lock               sync.RWMutex
}

The HashLRU algorithm maintains two separate maps and bulk eviction happens only after both the maps fill up. Hence onEvictedCB is triggered in bulk and is not an accurate measure of timely LRU-ness.

As explained by dominictarr :

  • This algorithm does not give you an ordered list of the N most recently used items, but has the important properties of the LRU (bounded memory use and O(1) time complexity)

This implementation uses sync.RWMutex to ensure thread-safety.

Go back to the table of contents

func NewHLRU

func NewHLRU(maxSize int) (*HashLRU, error)

Returns a new instance of HashLRU of the given size: maxSize.

func NewWithEvict

func NewWithEvict(maxSize int, onEvict func(key, value interface{})) (*HashLRU, error)

Takes maxSzie and a callback function onEvict as arguments and returns a new instance of HashLRU of the given size.

func (lru *HashLRU) Set

func (lru *HashLRU) Set(key, value interface{})

Adds a new key-value pair to the cache and updates it.

func (lru *HashLRU) Get

func (lru *HashLRU) Get(key interface{}) (interface{}, bool)

Get the value of any key and updates the cache. Returns value, true if the kv pair is found, else returns nil, false.

func (lru *HashLRU) Has

func (lru *HashLRU) Has(key interface{}) bool

Returns true if the key exists, else returns false.

func (lru *HashLRU) Remove

func (lru *HashLRU) Remove(key interface{}) bool

Deletes the key-value pair and returns true if its successful, else returns false.

Go back to the table of contents

func (lru *HashLRU) Peek

func (lru *LRU) Peek(key interface{}) (interface{}, bool)

Get the value of a key without updating the cache. Returns value, true if the kv pair is found, else returns nil, false.

func (lru *HashLRU) Clear

func (lru *HashLRU) Clear()

Empties the Cache.

func (lru *HashLRU) Resize

func (lru *HashLRU) Resize(newSize int) (int, error)

Update the maxSize of the cache. Items will be evicted automatically to adjust. Returns the number of evicted key-value pairs due to the re-size.

func (lru *HashLRU) Len

func (lru *HashLRU) Len() int

Returns the total number of key-value pairs present in the cache.

func (lru *HashLRU) Keys

func (lru* HashLRU) Keys() []interface{}

Returns a slice of all the Keys in the cache.

func (lru *HashLRU) Vals

func (lru *HashLRU) Vals() []interface{}

Returns a slice of all the Values in the cache.

Go back to the table of contents


Tests

$ go test 

Use -v for an detailed output.


Benchmark

$ go test -run=XXX -bench=.

HashLRU has a better hit/miss ratio for BenchmarkHLRU_Rand and BenchmarkHLRU_Freq (negligible) as compared to same benchmark tests from golang-lru. However, golang-lru does have a slightly lower ns/op.

Go back to the table of contents


You might also like...
Go-generics-simple-doubly-linked-list - A simple doubly linked list implemented using generics (Golang)

Welcome to Go-Generics-Simple-Doubly-Linked-List! Hi, This repository contains a

go generate based graphql server library
go generate based graphql server library

gqlgen What is gqlgen? gqlgen is a Go library for building GraphQL servers without any fuss. gqlgen is based on a Schema first approach β€” You get to D

A Golang tool to whitelist ASN's based on organization name

A Golang tool to whitelist ASN's based on organization name. This works by providing a list of ASN org names. This tool uses goPacket to monitor incoming traffic, capturing the IP's and checking the IP to see if it is a part of a whitelisted ASN. If it is not, it blocks that connection and future connections using iptables.

ptypes is a pointer-based box typing system for golang.

ptypes bypass go's type system through unsafe pointers the paradigm is to created a "boxed" type with .From and then use whatever types we want by ass

Fast, scalable pseudo random number generator based on xxh3
Fast, scalable pseudo random number generator based on xxh3

XXH3-Based Pseudorandom Number Generator This package contains an experimental implementation of a noise based pseudorandom number generator that scal

Script Based Alerting Manager
Script Based Alerting Manager

A Project in active development. Features may have breaking changes at any time before v1.0.0 version Telegram Group Balerter is a scripts based alert

Daypaper sets your GNOME wallpaper based on the time of day from a random and relevant Unsplash image.

Daypaper Daypaper sets your GNOME wallpaper based on the time of day from a random and relevant Unsplash image. Installation You will need an Access T

CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON.

Cuetils CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON. Using As a command line binary The cu

Configuration based URL shortner useful for on page 301 redirects

GO_URL_SHORT Configuration based URL shortner useful for on page 301 redirects Configuration for shortened url can be loaded from a JSON file in forma

Releases(v0.1.0)
Owner
Saurabh Pujari
Software developer
Saurabh Pujari
a thread-safe concurrent map for go

concurrent map As explained here and here, the map type in Go doesn't support concurrent reads and writes. concurrent-map provides a high-performance

Or Hiltch 3.3k Sep 20, 2022
A thread-safe concurrent map for go

concurrent map Original repo didn't support go mod and no any tags,so I forkd this repo add go mod support and patch a tag on this repo. No any code c

Yusan Kurban 0 Dec 7, 2021
A tool to filter URLs by parameter count or size

GoFilter A tool to filter URLs by parameter count or size. This tool requires unique sorted URL list. For example: cat hosts.txt | sort -u > sorted &&

Ayberk ESER 7 Sep 10, 2021
A concurrent rate limiter library for Golang based on Sliding-Window rate limiter algorithm.

ratelimiter A generic concurrent rate limiter library for Golang based on Sliding-window rate limitng algorithm. The implementation of rate-limiter al

Narasimha Prasanna HN 218 Sep 7, 2022
A faster RWLock primitive in Go, 2-3 times faster than RWMutex. A Go implementation of concurrency control algorithm in paper

Go Left Right Concurrency A Go implementation of the left-right concurrency control algorithm in paper <Left-Right - A Concurrency Control Technique w

wangyi 42 Aug 28, 2022
golang implement gossip algorithm

golang implement gossip algorithm

Gabriella Munger 3 Jan 14, 2022
Scalable golang ratelimiter using the sliding window algorithm. Currently supports only Redis.

go-ratelimiter Scalable golang ratelimiter using the sliding window algorithm. Currently supports only Redis. Example usage client := redis.NewClient

null 0 Oct 19, 2021
EVM-compatible chain secured by the Lachesis consensus algorithm.

ICICB-Galaxy EVM-compatible chain secured by the Lachesis consensus algorithm. Building the source Building galaxy requires both a Go (version 1.14 or

null 2 Oct 7, 2021
safe and easy casting from one type to another in Go

cast Easy and safe casting from one type to another in Go Don’t Panic! ... Cast What is Cast? Cast is a library to convert between different go types

Steve Francia 2.5k Sep 25, 2022
Simple base64 coder/decoder written in Golang

base64-coder simple base64 coder/decoder written in Golang ??️ Releases usage example Encode: ./b64 encode from.txt to.dat Decode: ./b64 encode to.dat

Sagleft 0 Jan 4, 2022