File: safemap.go

package info (click to toggle)
golang-github-wellington-go-libsass 0.9.2%2Bgit20181130.4ef5b9d-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,128 kB
  • sloc: cpp: 28,607; ansic: 839; makefile: 44
file content (50 lines) | stat: -rw-r--r-- 744 bytes parent folder | download | duplicates (2)
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
48
49
50
package libs

import "sync"

// globalImports stores []ImportEntry in a place where GC won't
// delete it
type SafeMap struct {
	sync.RWMutex
	idx int
	m   map[int]gcmap
}

type gcmap struct {
	idx *int
	v   interface{}
}

func (s *SafeMap) nextidx() int {
	s.Lock()
	defer s.Unlock()
	s.idx++
	return s.idx
}

func (s *SafeMap) init() {
	s.m = make(map[int]gcmap)
}

func (s *SafeMap) Get(idx int) interface{} {
	s.RLock()
	defer s.RUnlock()
	return s.m[idx].v
}

func (s *SafeMap) Del(idx int) {
	s.Lock()
	delete(s.m, idx)
	s.Unlock()
}

// set accepts an entry and returns an index for it
func (s *SafeMap) Set(ie interface{}) *int {
	idx := s.nextidx()
	pidx := &idx
	s.Lock()
	s.m[idx] = gcmap{pidx, ie}
	defer s.Unlock()

	return pidx
}