github.com/grzegorz-zur/bm@v0.0.0-20240312214136-6fc133e3e2c0/history.go (about)

     1  package main
     2  
     3  const (
     4  	// HistorySize is length of the history buffer.
     5  	HistorySize = 1024
     6  )
     7  
     8  // History holds latest records in a ring buffer.
     9  type History struct {
    10  	records Records
    11  	bottom  int
    12  	current int
    13  	top     int
    14  }
    15  
    16  // Records is a list of history records.
    17  type Records []Record
    18  
    19  // Record holds content and position.
    20  type Record struct {
    21  	content  string
    22  	location int
    23  }
    24  
    25  // Archive saves content and position in history and sets position to the recent entry.
    26  func (history *History) Archive(content string, location int) {
    27  	if history.records == nil {
    28  		history.records = make(Records, HistorySize)
    29  	} else {
    30  		history.top = wrap(history.top, HistorySize, 1, Forward)
    31  		if history.top == history.bottom {
    32  			history.bottom = wrap(history.bottom, HistorySize, 1, Forward)
    33  		}
    34  	}
    35  	history.current = history.top
    36  	record := Record{
    37  		content:  content,
    38  		location: location,
    39  	}
    40  	history.records[history.current] = record
    41  }
    42  
    43  // Switch retrieves content and position from history and moves current position.
    44  func (history *History) Switch(direction Direction) (content string, location int) {
    45  	if direction == Backward && history.current != history.bottom ||
    46  		direction == Forward && history.current != history.top {
    47  		history.current = wrap(history.current, HistorySize, 1, direction)
    48  	}
    49  	record := history.records[history.current]
    50  	return record.content, record.location
    51  }