1package fzf23import "sync"45// Chunk is a list of Items whose size has the upper limit of chunkSize6type Chunk struct {7 items [chunkSize]Item8 count int9}1011// ItemBuilder is a closure type that builds Item object from byte array12type ItemBuilder func(*Item, []byte) bool1314// ChunkList is a list of Chunks15type ChunkList struct {16 chunks []*Chunk17 mutex sync.Mutex18 trans ItemBuilder19}2021// NewChunkList returns a new ChunkList22func NewChunkList(trans ItemBuilder) *ChunkList {23 return &ChunkList{24 chunks: []*Chunk{},25 mutex: sync.Mutex{},26 trans: trans}27}2829func (c *Chunk) push(trans ItemBuilder, data []byte) bool {30 if trans(&c.items[c.count], data) {31 c.count++32 return true33 }34 return false35}3637// IsFull returns true if the Chunk is full38func (c *Chunk) IsFull() bool {39 return c.count == chunkSize40}4142func (cl *ChunkList) lastChunk() *Chunk {43 return cl.chunks[len(cl.chunks)-1]44}4546// CountItems returns the total number of Items47func CountItems(cs []*Chunk) int {48 if len(cs) == 0 {49 return 050 }51 return chunkSize*(len(cs)-1) + cs[len(cs)-1].count52}5354// Push adds the item to the list55func (cl *ChunkList) Push(data []byte) bool {56 cl.mutex.Lock()5758 if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {59 cl.chunks = append(cl.chunks, &Chunk{})60 }6162 ret := cl.lastChunk().push(cl.trans, data)63 cl.mutex.Unlock()64 return ret65}6667// Clear clears the data68func (cl *ChunkList) Clear() {69 cl.mutex.Lock()70 cl.chunks = nil71 cl.mutex.Unlock()72}7374// Snapshot returns immutable snapshot of the ChunkList75func (cl *ChunkList) Snapshot() ([]*Chunk, int) {76 cl.mutex.Lock()7778 ret := make([]*Chunk, len(cl.chunks))79 copy(ret, cl.chunks)8081 // Duplicate the last chunk82 if cnt := len(ret); cnt > 0 {83 newChunk := *ret[cnt-1]84 ret[cnt-1] = &newChunk85 }8687 cl.mutex.Unlock()88 return ret, CountItems(ret)89}