This repository has been archived by the owner on Jun 17, 2022. It is now read-only.
/
concprintermap.go
89 lines (73 loc) · 2.17 KB
/
concprintermap.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Copyright 2015 Google Inc. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
*/
package lib
import "sync"
// ConcurrentPrinterMap is a map-like data structure that is also
// thread-safe. Printers are keyed by Printer.Name and Printer.GCPID.
type ConcurrentPrinterMap struct {
byNativeName map[string]Printer
byGCPID map[string]Printer
mutex sync.RWMutex
}
// NewConcurrentPrinterMap initializes an empty ConcurrentPrinterMap.
func NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap {
cpm := ConcurrentPrinterMap{}
// TODO will this fail on nil?
cpm.Refresh(printers)
return &cpm
}
// Refresh replaces the internal (non-concurrent) map with newPrinters.
func (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer) {
c := make(map[string]Printer, len(newPrinters))
for _, printer := range newPrinters {
c[printer.Name] = printer
}
g := make(map[string]Printer, len(newPrinters))
for _, printer := range newPrinters {
if len(printer.GCPID) > 0 {
g[printer.GCPID] = printer
}
}
cpm.mutex.Lock()
defer cpm.mutex.Unlock()
cpm.byNativeName = c
cpm.byGCPID = g
}
// Get gets a printer, using the native name as key.
//
// The second return value is true if the entry exists.
func (cpm *ConcurrentPrinterMap) GetByNativeName(name string) (Printer, bool) {
cpm.mutex.RLock()
defer cpm.mutex.RUnlock()
if p, exists := cpm.byNativeName[name]; exists {
return p, true
}
return Printer{}, false
}
// Get gets a printer, using the GCP ID as key.
//
// The second return value is true if the entry exists.
func (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool) {
cpm.mutex.RLock()
defer cpm.mutex.RUnlock()
if p, exists := cpm.byGCPID[gcpID]; exists {
return p, true
}
return Printer{}, false
}
// GetAll returns a slice of all printers.
func (cpm *ConcurrentPrinterMap) GetAll() []Printer {
cpm.mutex.RLock()
defer cpm.mutex.RUnlock()
printers := make([]Printer, len(cpm.byNativeName))
i := 0
for _, printer := range cpm.byNativeName {
printers[i] = printer
i++
}
return printers
}