Skip to content

Instantly share code, notes, and snippets.

@dallasmarlow
Last active August 29, 2015 14:10
Show Gist options
  • Save dallasmarlow/cec9183b9fb5affcda60 to your computer and use it in GitHub Desktop.
Save dallasmarlow/cec9183b9fb5affcda60 to your computer and use it in GitHub Desktop.
time index
package main
import (
"fmt"
"math"
"sort"
"sync"
"time"
)
type int64Slice []int64
func (s int64Slice) Len() int { return len(s) }
func (s int64Slice) Less(a, b int) bool { return s[a] < s[b] }
func (s int64Slice) Swap(a, b int) { s[a], s[b] = s[b], s[a] }
type TimeIndex struct {
sync.RWMutex
bInterval time.Duration
m map[int64][]string
}
func (i *TimeIndex) Key(ts int64) int64 {
return int64(math.Mod(float64(ts), i.bInterval.Seconds()))
}
func (i *TimeIndex) Add(ts int64, val string) error {
i.Lock()
defer i.Unlock()
i.m[i.Key(ts)] = append(i.m[i.Key(ts)], val)
return nil
}
func (i *TimeIndex) scanKeys(start, end int64) (int64Slice, error) {
var keys int64Slice
for k := range i.m {
if k > i.Key(start) && k < i.Key(end) {
keys = append(keys, k)
}
}
sort.Sort(keys)
return keys, nil
}
func (i *TimeIndex) Scan(start, end int64) ([]string, error) {
keys, err := i.scanKeys(start, end)
if err != nil {
return []string{}, err
}
var resp []string
for _, k := range keys {
for _, v := range i.m[k] {
resp = append(resp, v)
}
}
return resp, nil
}
func (i *TimeIndex) Stuff() {
fmt.Println("stuff")
}
func main() {
index := &TimeIndex{bInterval: 24 * time.Hour, m: make(map[int64][]string)}
index.Stuff()
now := time.Now().Unix()
fmt.Println(now, index.Key(now))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment