expvarmon/stack.go

87 lines
1.6 KiB
Go
Raw Normal View History

2015-04-21 21:33:04 +08:00
package main
2015-05-01 21:49:19 +08:00
// DefaultSize specifies maximum number of items in stack.
//
// Values should be enough for sparklines on high-res terminals
// with minimal font size.
const DefaultSize = 1200
2015-04-25 14:06:45 +08:00
// Stack is a limited FIFO for holding sparkline values.
2015-04-21 21:33:04 +08:00
type Stack struct {
2015-05-03 03:29:02 +08:00
Values []VarValue
2015-04-21 21:33:04 +08:00
Len int
2015-05-03 03:29:02 +08:00
Max VarValue
2015-04-21 21:33:04 +08:00
}
2015-05-01 21:49:19 +08:00
// NewStack inits new Stack with default size limit.
func NewStack() *Stack {
return NewStackWithSize(DefaultSize)
}
// NewStackWithSize inits new Stack with size limit.
func NewStackWithSize(size int) *Stack {
2015-04-21 21:33:04 +08:00
return &Stack{
2015-05-03 03:29:02 +08:00
Values: make([]VarValue, size),
2015-04-21 21:33:04 +08:00
Len: size,
}
}
2015-04-25 14:06:45 +08:00
// Push inserts data to stack, preserving constant length.
2015-05-03 03:29:02 +08:00
func (s *Stack) Push(val VarValue) {
2015-04-21 21:33:04 +08:00
s.Values = append(s.Values, val)
if len(s.Values) > s.Len {
s.Values = s.Values[1:]
}
2015-05-03 03:29:02 +08:00
switch val.(type) {
case int64:
if s.Max == nil || val.(int64) > s.Max.(int64) {
s.Max = val
}
case float64:
if s.Max == nil || val.(float64) > s.Max.(float64) {
s.Max = val
}
}
2015-04-21 21:33:04 +08:00
}
2015-05-01 04:54:54 +08:00
// Front returns front value.
2015-05-03 03:29:02 +08:00
func (s *Stack) Front() VarValue {
2015-05-01 04:54:54 +08:00
if len(s.Values) == 0 {
2015-05-02 06:21:52 +08:00
return nil
2015-05-01 04:54:54 +08:00
}
return s.Values[len(s.Values)-1]
}
2015-05-02 06:21:52 +08:00
// IntValues returns stack values explicitly casted to int.
//
// Main case is to use with termui.Sparklines.
func (s *Stack) IntValues() []int {
ret := make([]int, s.Len)
for i, v := range s.Values {
n, ok := v.(int64)
if ok {
ret[i] = int(n)
continue
}
2015-05-02 14:35:39 +08:00
f, ok := v.(float64)
if ok {
// 12.34 (float) -> 1234 (int)
ret[i] = int(f * 100)
continue
}
2015-05-02 06:21:52 +08:00
b, ok := v.(bool)
if ok {
2015-05-02 14:35:39 +08:00
// false => 0, true = 1
2015-05-02 06:21:52 +08:00
if b {
ret[i] = 1
} else {
ret[i] = 0
}
}
}
return ret
}