You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
945 B

package messagelog
import (
"errors"
"sync"
)
type Log struct {
log map[string][]Message
logLock sync.RWMutex
}
func (ml *Log) AddTopic(topic string, capacity int) {
ml.logLock.Lock()
ml.log[topic] = make([]Message, 0, capacity)
ml.logLock.Unlock()
}
func (ml *Log) Push(topic string, message Message) error {
if err := message.validate(); err != nil {
return err
}
ml.logLock.Lock()
defer ml.logLock.Unlock()
log, ok := ml.log[topic]
if !ok {
return errors.New("topic doesn't exist")
}
message.Index = len(log)
ml.log[topic] = append(log, message)
return nil
}
func (ml *Log) List(topic string, offset int) ([]Message, error) {
ml.logLock.RLock()
defer ml.logLock.RUnlock()
log, ok := ml.log[topic]
if !ok {
return nil, errors.New("topic doesn't exist")
}
if offset >= len(log) {
return []Message{}, nil
}
return log[offset:], nil
}
func New() *Log {
return &Log{
log: map[string][]Message{},
}
}