File: history_buffer.go

package info (click to toggle)
lazygit 0.57.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,748 kB
  • sloc: sh: 153; makefile: 76
file content (38 lines) | stat: -rw-r--r-- 749 bytes parent folder | download | duplicates (2)
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
package utils

import (
	"errors"
)

type HistoryBuffer[T any] struct {
	maxSize int
	items   []T
}

func NewHistoryBuffer[T any](maxSize int) *HistoryBuffer[T] {
	return &HistoryBuffer[T]{
		maxSize: maxSize,
		items:   make([]T, 0, maxSize),
	}
}

func (self *HistoryBuffer[T]) Push(item T) {
	if len(self.items) == self.maxSize {
		self.items = self.items[:len(self.items)-1]
	}
	self.items = append([]T{item}, self.items...)
}

func (self *HistoryBuffer[T]) PeekAt(index int) (T, error) {
	var item T
	if len(self.items) == 0 {
		return item, errors.New("Buffer is empty")
	}
	if len(self.items) <= index || index < -1 {
		return item, errors.New("Index out of range")
	}
	if index == -1 {
		return item, nil
	}
	return self.items[index], nil
}