1
0
mirror of https://github.com/divan/expvarmon.git synced 2025-04-27 13:48:55 +08:00
expvarmon/stack.go

67 lines
1.3 KiB
Go
Raw Normal View History

2015-04-21 16:33:04 +03:00
package main
2015-05-01 16:49:19 +03: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 09:06:45 +03:00
// Stack is a limited FIFO for holding sparkline values.
2015-04-21 16:33:04 +03:00
type Stack struct {
2015-05-02 01:21:52 +03:00
Values []interface{}
2015-04-21 16:33:04 +03:00
Len int
}
2015-05-01 16:49:19 +03: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 16:33:04 +03:00
return &Stack{
2015-05-02 01:21:52 +03:00
Values: make([]interface{}, size),
2015-04-21 16:33:04 +03:00
Len: size,
}
}
2015-04-25 09:06:45 +03:00
// Push inserts data to stack, preserving constant length.
2015-05-02 01:21:52 +03:00
func (s *Stack) Push(val interface{}) {
2015-04-21 16:33:04 +03:00
s.Values = append(s.Values, val)
if len(s.Values) > s.Len {
s.Values = s.Values[1:]
}
}
2015-04-30 23:54:54 +03:00
// Front returns front value.
2015-05-02 01:21:52 +03:00
func (s *Stack) Front() interface{} {
2015-04-30 23:54:54 +03:00
if len(s.Values) == 0 {
2015-05-02 01:21:52 +03:00
return nil
2015-04-30 23:54:54 +03:00
}
return s.Values[len(s.Values)-1]
}
2015-05-02 01:21:52 +03: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
}
b, ok := v.(bool)
if ok {
if b {
ret[i] = 1
} else {
ret[i] = 0
}
}
}
return ret
}