refcount

package
v1.44.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2024 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package refcount provides utilities for working with reference-counted objects.

Why would you need refcounting in a language that already has GC? The GC can't always tell that all references to some object are gone. For example, suppose that we have a map[string]*T for looking up values based on some string key, but we want to evict elements of that map if no structure holds the key to it anymore. Doing this correctly requires a separately managed refcount. For this, you would use refcount.Map.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Map

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

Map is a map from keys of type K to values of type *V.

Unlike a built-in map, refcount.Map allows for a key to be inserted multiple times concurrently, and deleted multiple times. A key that is inserted n times will only be evicted from the map once it is deleted n times.

A zero map is empty and ready to use. Like other Go concurrency primitives, it must not be copied after first use.

recount.Map is thread-safe: insertions synchronize-before deletions.

func (*Map[K, V]) Delete

func (m *Map[K, V]) Delete(key K) *V

Delete deletes a key from the map.

The key will only be evicted once Map.Delete has been called an equal number of times to prior calls to Map.Insert for this key.

If the key is present and was actually evicted, the element it maps to is returned. Otherwise, this function returns nil.

func (*Map[K, V]) Get

func (m *Map[K, V]) Get(key K) *V

Get looks up a key in the map.

This is identical to ordinary map lookup: if they key is not present, it does not insert and returns nil.

func (*Map[K, V]) Insert

func (m *Map[K, V]) Insert(key K) (value *V, found bool)

Insert inserts a key into the map.

If the value is already present in the map, its count is incremented by one; otherwise, the zero value is inserted and returned. This function returns whether an existing entry was found.

The returned pointer is never nil.

Jump to

Keyboard shortcuts

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