aboutsummaryrefslogtreecommitdiff
path: root/internal/mru/touch.go
blob: 67ac6706fb6aaec20b1dcc8b7b5a126b4585ff72 (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package mru

// Touch moves key to the front, best-effort.
//
// When key is already the most-recently-used,
// Touch is lock-free and allocation-free;
// this is the common case.
// Otherwise Touch reorders under a non-blocking lock attempt,
// so a read never blocks merely to reorder.
// A contended attempt,
// or a key that is not a member,
// leaves the order unchanged.
func (order *Order[K]) Touch(key K) {
	keys := order.Keys()
	if len(keys) == 0 || keys[0] == key {
		return
	}

	if !order.mu.TryLock() {
		return
	}
	defer order.mu.Unlock()

	// The snapshot may have changed before we took the lock.
	keys = order.Keys()

	index := -1

	for i, candidate := range keys {
		if candidate == key {
			index = i

			break
		}
	}

	if index <= 0 {
		return
	}

	next := make([]K, 0, len(keys))
	next = append(next, key)
	next = append(next, keys[:index]...)
	next = append(next, keys[index+1:]...)

	order.snapshot.Store(&next)
}