github.com/puzpuzpuz/xsync/v2@v2.5.2-0.20231021165734-92b8269e19a9/example_test.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  package xsync_test
     5  
     6  import (
     7  	"encoding/binary"
     8  	"fmt"
     9  	"hash/maphash"
    10  	"time"
    11  
    12  	"github.com/puzpuzpuz/xsync/v2"
    13  )
    14  
    15  func ExampleNewTypedMapOf() {
    16  	type Person struct {
    17  		GivenName   string
    18  		FamilyName  string
    19  		YearOfBirth int16
    20  	}
    21  	age := xsync.NewTypedMapOf[Person, int](func(seed maphash.Seed, p Person) uint64 {
    22  		var h maphash.Hash
    23  		h.SetSeed(seed)
    24  		h.WriteString(p.GivenName)
    25  		hash := h.Sum64()
    26  		h.Reset()
    27  		h.WriteString(p.FamilyName)
    28  		hash = 31*hash + h.Sum64()
    29  		h.Reset()
    30  		binary.Write(&h, binary.LittleEndian, p.YearOfBirth)
    31  		return 31*hash + h.Sum64()
    32  	})
    33  	Y := time.Now().Year()
    34  	age.Store(Person{"Ada", "Lovelace", 1815}, Y-1815)
    35  	age.Store(Person{"Charles", "Babbage", 1791}, Y-1791)
    36  }
    37  
    38  func ExampleMapOf_Compute() {
    39  	counts := xsync.NewIntegerMapOf[int, int]()
    40  
    41  	// Store a new value.
    42  	v, ok := counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    43  		// loaded is false here.
    44  		newValue = 42
    45  		delete = false
    46  		return
    47  	})
    48  	// v: 42, ok: true
    49  	fmt.Printf("v: %v, ok: %v\n", v, ok)
    50  
    51  	// Update an existing value.
    52  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    53  		// loaded is true here.
    54  		newValue = oldValue + 42
    55  		delete = false
    56  		return
    57  	})
    58  	// v: 84, ok: true
    59  	fmt.Printf("v: %v, ok: %v\n", v, ok)
    60  
    61  	// Set a new value or keep the old value conditionally.
    62  	var oldVal int
    63  	minVal := 63
    64  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    65  		oldVal = oldValue
    66  		if !loaded || oldValue < minVal {
    67  			newValue = minVal
    68  			delete = false
    69  			return
    70  		}
    71  		newValue = oldValue
    72  		delete = false
    73  		return
    74  	})
    75  	// v: 84, ok: true, oldVal: 84
    76  	fmt.Printf("v: %v, ok: %v, oldVal: %v\n", v, ok, oldVal)
    77  
    78  	// Delete an existing value.
    79  	v, ok = counts.Compute(42, func(oldValue int, loaded bool) (newValue int, delete bool) {
    80  		// loaded is true here.
    81  		delete = true
    82  		return
    83  	})
    84  	// v: 84, ok: false
    85  	fmt.Printf("v: %v, ok: %v\n", v, ok)
    86  }