orderedmap

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2022 License: Apache-2.0 Imports: 4 Imported by: 0

README

orderedmap

License Go Report Card Coverage

🧑‍💻 Implementation of ordered map in golang. Fast, thread-safe and generic support

Install

  • go version >= 1.18
go get -u github.com/LPX3F8/orderedmap

Features

  • Support conversion to slices
  • Support JSON marshaler
  • Support ordered traversal
  • Support filter
  • Thread safety
  • Generics support

Example

import "github.com/LPX3F8/orderedmap"

func main() {
	om := New[string, int]()
	om.Store("k1", 1).Store("k2", 2).Store("k3", 3).
		Store("k4", 4).Store("k5", 5)
	om.Load("k5")                // return 5, true
	om.LoadOrStore("k5", 55)     // return 5, true
	om.LoadOrStore("k6", 6)      // return 6, false
	om.Delete("k6").Delete("k7") // 'k6' be removed, Deleting a non-existent key will not report an error.
	om.Has("k6")                 // return false

	// use filter func to filter items
	filter1 := func(idx int, k string, v int) (want bool) { return v > 1 }
	filter2 := func(idx int, k string, v int) (want bool) { return v < 5 }
	filter3 := func(idx int, k string, v int) (want bool) { return v%2 == 0 }
	s0 := om.Slice()
	fmt.Println(s0) // out: [1 2 3 4 5]
	s1 := om.Slice(filter1, filter2, filter3)
	fmt.Println(s1) // out: [2 4]

	// travel items
	for i := om.Front(); i != nil; i = i.Next() {
		fmt.Println("[TEST FRONT]", i.Key(), i.Value())
	}
	for i := om.Back(); i != nil; i = i.Prev() {
		fmt.Println("[TEST BACK]", i.Key(), i.Value())
	}
	// use a filter to filter the key value when travel items
	om.TravelForward(func(idx int, k string, v int) (skip bool) {
		fmt.Printf("[NOFILTER] idx: %v, key: %v, val: %v\n", idx, k, v)
		return false
	})
	om.TravelForward(func(idx int, k string, v int) (skip bool) {
		fmt.Printf("[FILTER] idx: %v, key: %v, val: %v\n", idx, k, v)
		return false
	}, filter3)

	// JSON Marshal
	// output: {"k1":1,"k2":2,"k3":3,"k4":4,"k5":5}
	jBytes, _ := json.Marshal(om)
	fmt.Println(string(jBytes))
}

Benchmark

goos: darwin
goarch: arm64
pkg: github.com/LPX3F8/orderedmap

# Basic test
BenchmarkOrderedMap-10                   	 3498038	       338.5 ns/op	      64 B/op	       2 allocs/op
BenchmarkOrderedMapSlack-10              	 3410408	       352.6 ns/op	      64 B/op	       2 allocs/op
BenchmarkOrderedMapWork-10               	 3167127	       378.6 ns/op	      64 B/op	       2 allocs/op
BenchmarkOrderedMapWorkSlack-10          	 3039068	       394.3 ns/op	      64 B/op	       2 allocs/op

# Native Sync.Map test
BenchmarkNativeSyncMap_Store-10          	 1510597	       668.7 ns/op	     140 B/op	       5 allocs/op
BenchmarkNativeSyncMap_LoadOrStore-10    	 1749106	       689.8 ns/op	     181 B/op	       4 allocs/op
BenchmarkNativeSyncMap_Delete-10         	 1000000	      2203 ns/op	       0 B/op	       0 allocs/op

# OrderedMap test
BenchmarkOrderedMap_Store-10             	 3161652	       379.7 ns/op	     120 B/op	       2 allocs/op
BenchmarkOrderedMap_LoadOrStore-10       	 2854708	       421.1 ns/op	     125 B/op	       2 allocs/op
BenchmarkOrderedMap_Delete-10            	 8021584	       144.9 ns/op	       0 B/op	       0 allocs/op

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Filter

type Filter[K comparable, V any] func(idx int, key K, val V) (want bool)

Filter Used to filter elements during traversal this method receives the position index of the element in OrderedMap, and the key-value. Only when the method returns true will the element be passed to the subsequent Filter and Visitor. The relationship between multiple Filter is 'and'.

type Item

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

func (*Item[K, V]) Key

func (i *Item[K, V]) Key() K

func (*Item[K, V]) Next

func (i *Item[K, V]) Next() *Item[K, V]

func (*Item[K, V]) Prev

func (i *Item[K, V]) Prev() *Item[K, V]

func (*Item[K, V]) Value

func (i *Item[K, V]) Value() V

type OrderedMap

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

OrderedMap use List[T] to ensure order The actual key-value pair exists in the basic map All operations lock objects and use read-write mutex to reduce lock competition.

func New

func New[K comparable, V any]() *OrderedMap[K, V]

New returns a pointer of *OrderedMap[K, V]

func (*OrderedMap[K, V]) Back

func (m *OrderedMap[K, V]) Back() *Item[K, V]

Back returns the last Item of list l or nil if the list is empty.

func (*OrderedMap[K, V]) Clear

func (m *OrderedMap[K, V]) Clear() *OrderedMap[K, V]

Clear empty saved elements

func (*OrderedMap[K, V]) Delete

func (m *OrderedMap[K, V]) Delete(k K) *OrderedMap[K, V]

Delete removes key-value pair

func (*OrderedMap[K, V]) Front

func (m *OrderedMap[K, V]) Front() *Item[K, V]

Front returns the first Item of list l or nil if the list is empty.

func (*OrderedMap[K, V]) Has

func (m *OrderedMap[K, V]) Has(k K) bool

Has return key exists

func (*OrderedMap[K, V]) Len

func (m *OrderedMap[K, V]) Len() int

Len return the map key size

func (*OrderedMap[K, V]) Load

func (m *OrderedMap[K, V]) Load(k K) (V, bool)

Load returns the value stored in the map for a key, or zero-value if no value is present, It depends on the data type. The ok result indicates whether value was found in the map.

func (*OrderedMap[K, V]) LoadOrStore

func (m *OrderedMap[K, V]) LoadOrStore(k K, v V) (actual V, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*OrderedMap[K, V]) MarshalJSON

func (m *OrderedMap[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON implement the json.Marshaler interface. the interface implemented by types that can marshal themselves into valid JSON.

func (*OrderedMap[K, V]) Range

func (m *OrderedMap[K, V]) Range(f func(key K, val V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration. Deprecated: Please replace it with the TravelForward.

func (*OrderedMap[K, V]) Reverse

func (m *OrderedMap[K, V]) Reverse(filters ...Filter[K, V]) []V

Reverse the elements in the array.

func (*OrderedMap[K, V]) Slice

func (m *OrderedMap[K, V]) Slice(filters ...Filter[K, V]) []V

Slice returns the elements slice

func (*OrderedMap[K, V]) Store

func (m *OrderedMap[K, V]) Store(k K, v V) *OrderedMap[K, V]

Store key-value pair

func (*OrderedMap[K, V]) Travel

func (m *OrderedMap[K, V]) Travel(mode TravelMode, f Visitor[K, V], filters ...Filter[K, V])

Travel items with custom travel mode

func (*OrderedMap[K, V]) TravelForward

func (m *OrderedMap[K, V]) TravelForward(f Visitor[K, V], filters ...Filter[K, V])

TravelForward all items with visitor and filters

func (*OrderedMap[K, V]) TravelReverse

func (m *OrderedMap[K, V]) TravelReverse(f Visitor[K, V], filters ...Filter[K, V])

TravelReverse all items with visitor and filters

type TravelMode

type TravelMode uint

TravelMode used to specify the direction of traversal

const (
	Forward TravelMode = iota
	Reverse
)

type Visitor

type Visitor[K comparable, V any] func(idx int, key K, val V) (skip bool)

Visitor is the method to allow user access to the elements when visit all items. Returning true will interrupt the traversal.

Jump to

Keyboard shortcuts

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