-
Notifications
You must be signed in to change notification settings - Fork 26
/
log.go
119 lines (98 loc) · 1.94 KB
/
log.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// Copyright 2009 The Ninep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ninep
type Log struct {
Data interface{}
Owner interface{}
Type int
}
type Logger struct {
items []*Log
idx int
logchan chan *Log
fltchan chan *flt
rszchan chan int
}
type flt struct {
owner interface{}
itype int
fltchan chan []*Log
}
func NewLogger(sz int) *Logger {
if sz == 0 {
return nil
}
l := new(Logger)
l.items = make([]*Log, sz)
l.logchan = make(chan *Log, 16)
l.fltchan = make(chan *flt)
l.rszchan = make(chan int)
go l.doLog()
return l
}
func (l *Logger) Resize(sz int) {
if sz == 0 {
return
}
l.rszchan <- sz
}
func (l *Logger) Log(data, owner interface{}, itype int) {
l.logchan <- &Log{data, owner, itype}
}
func (l *Logger) Filter(owner interface{}, itype int) []*Log {
c := make(chan []*Log)
l.fltchan <- &flt{owner, itype, c}
return <-c
}
func (l *Logger) doLog() {
for {
select {
case it := <-l.logchan:
if l.idx >= len(l.items) {
l.idx = 0
}
l.items[l.idx] = it
l.idx++
case sz := <-l.rszchan:
it := make([]*Log, sz)
for i, j := l.idx, 0; j < len(it); j++ {
if i >= len(l.items) {
i = 0
}
it[j] = l.items[i]
i++
if i == l.idx {
break
}
}
l.items = it
l.idx = 0
case flt := <-l.fltchan:
n := 0
// we don't care about the order while counting
for _, it := range l.items {
if it == nil {
continue
}
if (flt.owner == nil || it.Owner == flt.owner) &&
(flt.itype == 0 || it.Type == flt.itype) {
n++
}
}
its := make([]*Log, n)
for i, m := l.idx, 0; m < len(its); i++ {
if i >= len(l.items) {
i = 0
}
it := l.items[i]
if it != nil && (flt.owner == nil || it.Owner == flt.owner) &&
(flt.itype == 0 || it.Type == flt.itype) {
its[m] = it
m++
}
}
flt.fltchan <- its
}
}
}