repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
lightninglabs/neutrino
blockmanager.go
SynchronizeFilterHeaders
func (b *blockManager) SynchronizeFilterHeaders(f func(uint32) error) error { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() return f(b.filterHeaderTip) }
go
func (b *blockManager) SynchronizeFilterHeaders(f func(uint32) error) error { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() return f(b.filterHeaderTip) }
[ "func", "(", "b", "*", "blockManager", ")", "SynchronizeFilterHeaders", "(", "f", "func", "(", "uint32", ")", "error", ")", "error", "{", "b", ".", "newFilterHeadersMtx", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "newFilterHeadersMtx", ".", "RUnlock...
// SynchronizeFilterHeaders allows the caller to execute a function closure // that depends on synchronization with the current set of filter headers. This // allows the caller to execute an action that depends on the current filter // header state, thereby ensuring that the state would shift from underneath // them. Each execution of the closure will have the current filter header tip // passed in to ensue that the caller gets a consistent view.
[ "SynchronizeFilterHeaders", "allows", "the", "caller", "to", "execute", "a", "function", "closure", "that", "depends", "on", "synchronization", "with", "the", "current", "set", "of", "filter", "headers", ".", "This", "allows", "the", "caller", "to", "execute", "...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L1951-L1956
train
lightninglabs/neutrino
blockmanager.go
checkHeaderSanity
func (b *blockManager) checkHeaderSanity(blockHeader *wire.BlockHeader, maxTimestamp time.Time, reorgAttempt bool) error { diff, err := b.calcNextRequiredDifficulty( blockHeader.Timestamp, reorgAttempt) if err != nil { return err } stubBlock := btcutil.NewBlock(&wire.MsgBlock{ Header: *blockHeader, }) err = blockchain.CheckProofOfWork(stubBlock, blockchain.CompactToBig(diff)) if err != nil { return err } // Ensure the block time is not too far in the future. if blockHeader.Timestamp.After(maxTimestamp) { return fmt.Errorf("block timestamp of %v is too far in the "+ "future", blockHeader.Timestamp) } return nil }
go
func (b *blockManager) checkHeaderSanity(blockHeader *wire.BlockHeader, maxTimestamp time.Time, reorgAttempt bool) error { diff, err := b.calcNextRequiredDifficulty( blockHeader.Timestamp, reorgAttempt) if err != nil { return err } stubBlock := btcutil.NewBlock(&wire.MsgBlock{ Header: *blockHeader, }) err = blockchain.CheckProofOfWork(stubBlock, blockchain.CompactToBig(diff)) if err != nil { return err } // Ensure the block time is not too far in the future. if blockHeader.Timestamp.After(maxTimestamp) { return fmt.Errorf("block timestamp of %v is too far in the "+ "future", blockHeader.Timestamp) } return nil }
[ "func", "(", "b", "*", "blockManager", ")", "checkHeaderSanity", "(", "blockHeader", "*", "wire", ".", "BlockHeader", ",", "maxTimestamp", "time", ".", "Time", ",", "reorgAttempt", "bool", ")", "error", "{", "diff", ",", "err", ":=", "b", ".", "calcNextReq...
// checkHeaderSanity checks the PoW, and timestamp of a block header.
[ "checkHeaderSanity", "checks", "the", "PoW", "and", "timestamp", "of", "a", "block", "header", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2416-L2437
train
lightninglabs/neutrino
blockmanager.go
calcNextRequiredDifficulty
func (b *blockManager) calcNextRequiredDifficulty(newBlockTime time.Time, reorgAttempt bool) (uint32, error) { hList := b.headerList if reorgAttempt { hList = b.reorgList } lastNode := hList.Back() // Genesis block. if lastNode == nil { return b.server.chainParams.PowLimitBits, nil } // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. if (lastNode.Height+1)%b.blocksPerRetarget != 0 { // For networks that support it, allow special reduction of the // required difficulty once too much time has elapsed without // mining a block. if b.server.chainParams.ReduceMinDifficulty { // Return minimum difficulty when more than the desired // amount of time has elapsed without mining a block. reductionTime := int64( b.server.chainParams.MinDiffReductionTime / time.Second) allowMinTime := lastNode.Header.Timestamp.Unix() + reductionTime if newBlockTime.Unix() > allowMinTime { return b.server.chainParams.PowLimitBits, nil } // The block was mined within the desired timeframe, so // return the difficulty for the last block which did // not have the special minimum difficulty rule applied. prevBits, err := b.findPrevTestNetDifficulty(hList) if err != nil { return 0, err } return prevBits, nil } // For the main network (or any unrecognized networks), simply // return the previous block's difficulty requirements. return lastNode.Header.Bits, nil } // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode, err := b.server.BlockHeaders.FetchHeaderByHeight( uint32(lastNode.Height + 1 - b.blocksPerRetarget), ) if err != nil { return 0, err } // Limit the amount of adjustment that can occur to the previous // difficulty. actualTimespan := lastNode.Header.Timestamp.Unix() - firstNode.Timestamp.Unix() adjustedTimespan := actualTimespan if actualTimespan < b.minRetargetTimespan { adjustedTimespan = b.minRetargetTimespan } else if actualTimespan > b.maxRetargetTimespan { adjustedTimespan = b.maxRetargetTimespan } // Calculate new target difficulty as: // currentDifficulty * (adjustedTimespan / targetTimespan) // The result uses integer division which means it will be slightly // rounded down. Bitcoind also uses integer division to calculate this // result. oldTarget := blockchain.CompactToBig(lastNode.Header.Bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) targetTimeSpan := int64(b.server.chainParams.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. if newTarget.Cmp(b.server.chainParams.PowLimit) > 0 { newTarget.Set(b.server.chainParams.PowLimit) } // Log new target difficulty and return it. The new target logging is // intentionally converting the bits back to a number instead of using // newTarget since conversion to the compact representation loses // precision. newTargetBits := blockchain.BigToCompact(newTarget) log.Debugf("Difficulty retarget at block height %d", lastNode.Height+1) log.Debugf("Old target %08x (%064x)", lastNode.Header.Bits, oldTarget) log.Debugf("New target %08x (%064x)", newTargetBits, blockchain.CompactToBig(newTargetBits)) log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, b.server.chainParams.TargetTimespan) return newTargetBits, nil }
go
func (b *blockManager) calcNextRequiredDifficulty(newBlockTime time.Time, reorgAttempt bool) (uint32, error) { hList := b.headerList if reorgAttempt { hList = b.reorgList } lastNode := hList.Back() // Genesis block. if lastNode == nil { return b.server.chainParams.PowLimitBits, nil } // Return the previous block's difficulty requirements if this block // is not at a difficulty retarget interval. if (lastNode.Height+1)%b.blocksPerRetarget != 0 { // For networks that support it, allow special reduction of the // required difficulty once too much time has elapsed without // mining a block. if b.server.chainParams.ReduceMinDifficulty { // Return minimum difficulty when more than the desired // amount of time has elapsed without mining a block. reductionTime := int64( b.server.chainParams.MinDiffReductionTime / time.Second) allowMinTime := lastNode.Header.Timestamp.Unix() + reductionTime if newBlockTime.Unix() > allowMinTime { return b.server.chainParams.PowLimitBits, nil } // The block was mined within the desired timeframe, so // return the difficulty for the last block which did // not have the special minimum difficulty rule applied. prevBits, err := b.findPrevTestNetDifficulty(hList) if err != nil { return 0, err } return prevBits, nil } // For the main network (or any unrecognized networks), simply // return the previous block's difficulty requirements. return lastNode.Header.Bits, nil } // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode, err := b.server.BlockHeaders.FetchHeaderByHeight( uint32(lastNode.Height + 1 - b.blocksPerRetarget), ) if err != nil { return 0, err } // Limit the amount of adjustment that can occur to the previous // difficulty. actualTimespan := lastNode.Header.Timestamp.Unix() - firstNode.Timestamp.Unix() adjustedTimespan := actualTimespan if actualTimespan < b.minRetargetTimespan { adjustedTimespan = b.minRetargetTimespan } else if actualTimespan > b.maxRetargetTimespan { adjustedTimespan = b.maxRetargetTimespan } // Calculate new target difficulty as: // currentDifficulty * (adjustedTimespan / targetTimespan) // The result uses integer division which means it will be slightly // rounded down. Bitcoind also uses integer division to calculate this // result. oldTarget := blockchain.CompactToBig(lastNode.Header.Bits) newTarget := new(big.Int).Mul(oldTarget, big.NewInt(adjustedTimespan)) targetTimeSpan := int64(b.server.chainParams.TargetTimespan / time.Second) newTarget.Div(newTarget, big.NewInt(targetTimeSpan)) // Limit new value to the proof of work limit. if newTarget.Cmp(b.server.chainParams.PowLimit) > 0 { newTarget.Set(b.server.chainParams.PowLimit) } // Log new target difficulty and return it. The new target logging is // intentionally converting the bits back to a number instead of using // newTarget since conversion to the compact representation loses // precision. newTargetBits := blockchain.BigToCompact(newTarget) log.Debugf("Difficulty retarget at block height %d", lastNode.Height+1) log.Debugf("Old target %08x (%064x)", lastNode.Header.Bits, oldTarget) log.Debugf("New target %08x (%064x)", newTargetBits, blockchain.CompactToBig(newTargetBits)) log.Debugf("Actual timespan %v, adjusted timespan %v, target timespan %v", time.Duration(actualTimespan)*time.Second, time.Duration(adjustedTimespan)*time.Second, b.server.chainParams.TargetTimespan) return newTargetBits, nil }
[ "func", "(", "b", "*", "blockManager", ")", "calcNextRequiredDifficulty", "(", "newBlockTime", "time", ".", "Time", ",", "reorgAttempt", "bool", ")", "(", "uint32", ",", "error", ")", "{", "hList", ":=", "b", ".", "headerList", "\n", "if", "reorgAttempt", ...
// calcNextRequiredDifficulty calculates the required difficulty for the block // after the passed previous block node based on the difficulty retarget rules.
[ "calcNextRequiredDifficulty", "calculates", "the", "required", "difficulty", "for", "the", "block", "after", "the", "passed", "previous", "block", "node", "based", "on", "the", "difficulty", "retarget", "rules", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2441-L2540
train
lightninglabs/neutrino
blockmanager.go
onBlockConnected
func (b *blockManager) onBlockConnected(header wire.BlockHeader, height uint32) { select { case b.blockNtfnChan <- blockntfns.NewBlockConnected(header, height): case <-b.quit: } }
go
func (b *blockManager) onBlockConnected(header wire.BlockHeader, height uint32) { select { case b.blockNtfnChan <- blockntfns.NewBlockConnected(header, height): case <-b.quit: } }
[ "func", "(", "b", "*", "blockManager", ")", "onBlockConnected", "(", "header", "wire", ".", "BlockHeader", ",", "height", "uint32", ")", "{", "select", "{", "case", "b", ".", "blockNtfnChan", "<-", "blockntfns", ".", "NewBlockConnected", "(", "header", ",", ...
// onBlockConnected queues a block notification that extends the current chain.
[ "onBlockConnected", "queues", "a", "block", "notification", "that", "extends", "the", "current", "chain", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2591-L2596
train
lightninglabs/neutrino
blockmanager.go
onBlockDisconnected
func (b *blockManager) onBlockDisconnected(headerDisconnected wire.BlockHeader, heightDisconnected uint32, newChainTip wire.BlockHeader) { select { case b.blockNtfnChan <- blockntfns.NewBlockDisconnected( headerDisconnected, heightDisconnected, newChainTip, ): case <-b.quit: } }
go
func (b *blockManager) onBlockDisconnected(headerDisconnected wire.BlockHeader, heightDisconnected uint32, newChainTip wire.BlockHeader) { select { case b.blockNtfnChan <- blockntfns.NewBlockDisconnected( headerDisconnected, heightDisconnected, newChainTip, ): case <-b.quit: } }
[ "func", "(", "b", "*", "blockManager", ")", "onBlockDisconnected", "(", "headerDisconnected", "wire", ".", "BlockHeader", ",", "heightDisconnected", "uint32", ",", "newChainTip", "wire", ".", "BlockHeader", ")", "{", "select", "{", "case", "b", ".", "blockNtfnCh...
// onBlockDisconnected queues a block notification that reorgs the current // chain.
[ "onBlockDisconnected", "queues", "a", "block", "notification", "that", "reorgs", "the", "current", "chain", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2600-L2609
train
lightninglabs/neutrino
blockmanager.go
NotificationsSinceHeight
func (b *blockManager) NotificationsSinceHeight( height uint32) ([]blockntfns.BlockNtfn, uint32, error) { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() bestHeight := b.filterHeaderTip // If a height of 0 is provided by the caller, then a backlog of // notifications is not needed. if height == 0 { return nil, bestHeight, nil } // If the best height matches the filter header tip, then we're done and // don't need to proceed any further. if bestHeight == height { return nil, bestHeight, nil } // If the request has a height later than a height we've yet to come // across in the chain, we'll return an error to indicate so to the // caller. if height > bestHeight { return nil, 0, fmt.Errorf("request with height %d is greater "+ "than best height known %d", height, bestHeight) } // Otherwise, we need to read block headers from disk to deliver a // backlog to the caller before we proceed. blocks := make([]blockntfns.BlockNtfn, 0, bestHeight-height) for i := height + 1; i <= bestHeight; i++ { header, err := b.server.BlockHeaders.FetchHeaderByHeight(i) if err != nil { return nil, 0, err } blocks = append(blocks, blockntfns.NewBlockConnected(*header, i)) } return blocks, bestHeight, nil }
go
func (b *blockManager) NotificationsSinceHeight( height uint32) ([]blockntfns.BlockNtfn, uint32, error) { b.newFilterHeadersMtx.RLock() defer b.newFilterHeadersMtx.RUnlock() bestHeight := b.filterHeaderTip // If a height of 0 is provided by the caller, then a backlog of // notifications is not needed. if height == 0 { return nil, bestHeight, nil } // If the best height matches the filter header tip, then we're done and // don't need to proceed any further. if bestHeight == height { return nil, bestHeight, nil } // If the request has a height later than a height we've yet to come // across in the chain, we'll return an error to indicate so to the // caller. if height > bestHeight { return nil, 0, fmt.Errorf("request with height %d is greater "+ "than best height known %d", height, bestHeight) } // Otherwise, we need to read block headers from disk to deliver a // backlog to the caller before we proceed. blocks := make([]blockntfns.BlockNtfn, 0, bestHeight-height) for i := height + 1; i <= bestHeight; i++ { header, err := b.server.BlockHeaders.FetchHeaderByHeight(i) if err != nil { return nil, 0, err } blocks = append(blocks, blockntfns.NewBlockConnected(*header, i)) } return blocks, bestHeight, nil }
[ "func", "(", "b", "*", "blockManager", ")", "NotificationsSinceHeight", "(", "height", "uint32", ")", "(", "[", "]", "blockntfns", ".", "BlockNtfn", ",", "uint32", ",", "error", ")", "{", "b", ".", "newFilterHeadersMtx", ".", "RLock", "(", ")", "\n", "de...
// NotificationsSinceHeight returns a backlog of block notifications starting // from the given height to the tip of the chain. When providing a height of 0, // a backlog will not be delivered.
[ "NotificationsSinceHeight", "returns", "a", "backlog", "of", "block", "notifications", "starting", "from", "the", "given", "height", "to", "the", "tip", "of", "the", "chain", ".", "When", "providing", "a", "height", "of", "0", "a", "backlog", "will", "not", ...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/blockmanager.go#L2620-L2661
train
lightninglabs/neutrino
cache/cacheable_filter.go
Size
func (c *CacheableFilter) Size() (uint64, error) { f, err := c.Filter.NBytes() if err != nil { return 0, err } return uint64(len(f)), nil }
go
func (c *CacheableFilter) Size() (uint64, error) { f, err := c.Filter.NBytes() if err != nil { return 0, err } return uint64(len(f)), nil }
[ "func", "(", "c", "*", "CacheableFilter", ")", "Size", "(", ")", "(", "uint64", ",", "error", ")", "{", "f", ",", "err", ":=", "c", ".", "Filter", ".", "NBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", ...
// Size returns size of this filter in bytes.
[ "Size", "returns", "size", "of", "this", "filter", "in", "bytes", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/cacheable_filter.go#L22-L28
train
lightninglabs/neutrino
cache/lru/lru.go
NewCache
func NewCache(capacity uint64) *Cache { return &Cache{ capacity: capacity, ll: list.New(), cache: make(elementMap), } }
go
func NewCache(capacity uint64) *Cache { return &Cache{ capacity: capacity, ll: list.New(), cache: make(elementMap), } }
[ "func", "NewCache", "(", "capacity", "uint64", ")", "*", "Cache", "{", "return", "&", "Cache", "{", "capacity", ":", "capacity", ",", "ll", ":", "list", ".", "New", "(", ")", ",", "cache", ":", "make", "(", "elementMap", ")", ",", "}", "\n", "}" ]
// NewCache return a cache with specified capacity, the cache's size can't // exceed that given capacity.
[ "NewCache", "return", "a", "cache", "with", "specified", "capacity", "the", "cache", "s", "size", "can", "t", "exceed", "that", "given", "capacity", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L45-L51
train
lightninglabs/neutrino
cache/lru/lru.go
evict
func (c *Cache) evict(needed uint64) (bool, error) { if needed > c.capacity { return false, fmt.Errorf("can't evict %v elements in size, "+ "since capacity is %v", needed, c.capacity) } evicted := false for c.capacity-c.size < needed { // We still need to evict some more elements. if c.ll.Len() == 0 { // We should never reach here. return false, fmt.Errorf("all elements got evicted, "+ "yet still need to evict %v, likelihood of "+ "error during size calculation", needed-(c.capacity-c.size)) } // Find the least recently used item. if elr := c.ll.Back(); elr != nil { // Determine lru item's size. ce := elr.Value.(*entry) es, err := ce.value.Size() if err != nil { return false, fmt.Errorf("couldn't determine "+ "size of existing cache value %v", err) } // Account for that element's removal in evicted and // cache size. c.size -= es // Remove the element from the cache. c.ll.Remove(elr) delete(c.cache, ce.key) evicted = true } } return evicted, nil }
go
func (c *Cache) evict(needed uint64) (bool, error) { if needed > c.capacity { return false, fmt.Errorf("can't evict %v elements in size, "+ "since capacity is %v", needed, c.capacity) } evicted := false for c.capacity-c.size < needed { // We still need to evict some more elements. if c.ll.Len() == 0 { // We should never reach here. return false, fmt.Errorf("all elements got evicted, "+ "yet still need to evict %v, likelihood of "+ "error during size calculation", needed-(c.capacity-c.size)) } // Find the least recently used item. if elr := c.ll.Back(); elr != nil { // Determine lru item's size. ce := elr.Value.(*entry) es, err := ce.value.Size() if err != nil { return false, fmt.Errorf("couldn't determine "+ "size of existing cache value %v", err) } // Account for that element's removal in evicted and // cache size. c.size -= es // Remove the element from the cache. c.ll.Remove(elr) delete(c.cache, ce.key) evicted = true } } return evicted, nil }
[ "func", "(", "c", "*", "Cache", ")", "evict", "(", "needed", "uint64", ")", "(", "bool", ",", "error", ")", "{", "if", "needed", ">", "c", ".", "capacity", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"can't evict %v elements in size, \"", ...
// evict will evict as many elements as necessary to make enough space for a new // element with size needed to be inserted.
[ "evict", "will", "evict", "as", "many", "elements", "as", "necessary", "to", "make", "enough", "space", "for", "a", "new", "element", "with", "size", "needed", "to", "be", "inserted", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L55-L94
train
lightninglabs/neutrino
cache/lru/lru.go
Get
func (c *Cache) Get(key interface{}) (cache.Value, error) { c.mtx.Lock() defer c.mtx.Unlock() el, ok := c.cache[key] if !ok { // Element not found in the cache. return nil, cache.ErrElementNotFound } // When the cache needs to evict a element to make space for another // one, it starts eviction from the back, so by moving this element to // the front, it's eviction is delayed because it's recently accessed. c.ll.MoveToFront(el) return el.Value.(*entry).value, nil }
go
func (c *Cache) Get(key interface{}) (cache.Value, error) { c.mtx.Lock() defer c.mtx.Unlock() el, ok := c.cache[key] if !ok { // Element not found in the cache. return nil, cache.ErrElementNotFound } // When the cache needs to evict a element to make space for another // one, it starts eviction from the back, so by moving this element to // the front, it's eviction is delayed because it's recently accessed. c.ll.MoveToFront(el) return el.Value.(*entry).value, nil }
[ "func", "(", "c", "*", "Cache", ")", "Get", "(", "key", "interface", "{", "}", ")", "(", "cache", ".", "Value", ",", "error", ")", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "...
// Get will return value for a given key, making the element the most recently // accessed item in the process. Will return nil if the key isn't found.
[ "Get", "will", "return", "value", "for", "a", "given", "key", "making", "the", "element", "the", "most", "recently", "accessed", "item", "in", "the", "process", ".", "Will", "return", "nil", "if", "the", "key", "isn", "t", "found", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L144-L159
train
lightninglabs/neutrino
cache/lru/lru.go
Len
func (c *Cache) Len() int { c.mtx.RLock() defer c.mtx.RUnlock() return c.ll.Len() }
go
func (c *Cache) Len() int { c.mtx.RLock() defer c.mtx.RUnlock() return c.ll.Len() }
[ "func", "(", "c", "*", "Cache", ")", "Len", "(", ")", "int", "{", "c", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "ll", ".", "Len", "(", ")", "\n", "}" ]
// Len returns number of elements in the cache.
[ "Len", "returns", "number", "of", "elements", "in", "the", "cache", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/cache/lru/lru.go#L162-L167
train
lightninglabs/neutrino
headerlist/bounded_header_list.go
NewBoundedMemoryChain
func NewBoundedMemoryChain(maxNodes uint32) *BoundedMemoryChain { return &BoundedMemoryChain{ headPtr: -1, tailPtr: -1, maxSize: int32(maxNodes), chain: make([]Node, maxNodes), } }
go
func NewBoundedMemoryChain(maxNodes uint32) *BoundedMemoryChain { return &BoundedMemoryChain{ headPtr: -1, tailPtr: -1, maxSize: int32(maxNodes), chain: make([]Node, maxNodes), } }
[ "func", "NewBoundedMemoryChain", "(", "maxNodes", "uint32", ")", "*", "BoundedMemoryChain", "{", "return", "&", "BoundedMemoryChain", "{", "headPtr", ":", "-", "1", ",", "tailPtr", ":", "-", "1", ",", "maxSize", ":", "int32", "(", "maxNodes", ")", ",", "ch...
// NewBoundedMemoryChain returns a new instance of the BoundedMemoryChain with // a target max number of nodes.
[ "NewBoundedMemoryChain", "returns", "a", "new", "instance", "of", "the", "BoundedMemoryChain", "with", "a", "target", "max", "number", "of", "nodes", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerlist/bounded_header_list.go#L35-L42
train
lightninglabs/neutrino
pushtx/error.go
IsBroadcastError
func IsBroadcastError(err error, codes ...BroadcastErrorCode) bool { broadcastErr, ok := err.(*BroadcastError) if !ok { return false } for _, code := range codes { if broadcastErr.Code == code { return true } } return false }
go
func IsBroadcastError(err error, codes ...BroadcastErrorCode) bool { broadcastErr, ok := err.(*BroadcastError) if !ok { return false } for _, code := range codes { if broadcastErr.Code == code { return true } } return false }
[ "func", "IsBroadcastError", "(", "err", "error", ",", "codes", "...", "BroadcastErrorCode", ")", "bool", "{", "broadcastErr", ",", "ok", ":=", "err", ".", "(", "*", "BroadcastError", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", ...
// IsBroadcastError is a helper function that can be used to determine whether // an error is a BroadcastError that matches any of the specified codes.
[ "IsBroadcastError", "is", "a", "helper", "function", "that", "can", "be", "used", "to", "determine", "whether", "an", "error", "is", "a", "BroadcastError", "that", "matches", "any", "of", "the", "specified", "codes", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/error.go#L72-L85
train
lightninglabs/neutrino
pushtx/error.go
ParseBroadcastError
func ParseBroadcastError(msg *wire.MsgReject, peerAddr string) *BroadcastError { // We'll determine the appropriate broadcast error code by looking at // the reject's message code and reason. The only reject codes returned // from peers (bitcoind and btcd) when attempting to accept a // transaction into their mempool are: // RejectInvalid, RejectNonstandard, RejectInsufficientFee, // RejectDuplicate var code BroadcastErrorCode switch { // The cases below apply for reject messages sent from any kind of peer. case msg.Code == wire.RejectInvalid || msg.Code == wire.RejectNonstandard: code = Invalid case msg.Code == wire.RejectInsufficientFee: code = InsufficientFee // The cases below apply for reject messages sent from bitcoind peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-mempool-conflict"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-in-mempool"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-known"): code = Confirmed // The cases below apply for reject messages sent from btcd peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already spent"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already have transaction"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "transaction already exists"): code = Confirmed // Any other reject messages will use the unknown code. default: code = Unknown } reason := fmt.Sprintf("rejected by %v: %v", peerAddr, msg.Reason) return &BroadcastError{Code: code, Reason: reason} }
go
func ParseBroadcastError(msg *wire.MsgReject, peerAddr string) *BroadcastError { // We'll determine the appropriate broadcast error code by looking at // the reject's message code and reason. The only reject codes returned // from peers (bitcoind and btcd) when attempting to accept a // transaction into their mempool are: // RejectInvalid, RejectNonstandard, RejectInsufficientFee, // RejectDuplicate var code BroadcastErrorCode switch { // The cases below apply for reject messages sent from any kind of peer. case msg.Code == wire.RejectInvalid || msg.Code == wire.RejectNonstandard: code = Invalid case msg.Code == wire.RejectInsufficientFee: code = InsufficientFee // The cases below apply for reject messages sent from bitcoind peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-mempool-conflict"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-in-mempool"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "txn-already-known"): code = Confirmed // The cases below apply for reject messages sent from btcd peers. // // If the transaction double spends an unconfirmed transaction in the // peer's mempool, then we'll deem it as invalid. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already spent"): code = Invalid // If the transaction was rejected due to it already existing in the // peer's mempool, then return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "already have transaction"): code = Mempool // If the transaction was rejected due to it already existing in the // chain according to our peer, then we'll return an error signaling so. case msg.Code == wire.RejectDuplicate && strings.Contains(msg.Reason, "transaction already exists"): code = Confirmed // Any other reject messages will use the unknown code. default: code = Unknown } reason := fmt.Sprintf("rejected by %v: %v", peerAddr, msg.Reason) return &BroadcastError{Code: code, Reason: reason} }
[ "func", "ParseBroadcastError", "(", "msg", "*", "wire", ".", "MsgReject", ",", "peerAddr", "string", ")", "*", "BroadcastError", "{", "var", "code", "BroadcastErrorCode", "\n", "switch", "{", "case", "msg", ".", "Code", "==", "wire", ".", "RejectInvalid", "|...
// ParseBroadcastError maps a peer's reject message for a transaction to a // BroadcastError.
[ "ParseBroadcastError", "maps", "a", "peer", "s", "reject", "message", "for", "a", "transaction", "to", "a", "BroadcastError", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/pushtx/error.go#L89-L152
train
lightninglabs/neutrino
filterdb/db.go
New
func New(db walletdb.DB, params chaincfg.Params) (*FilterStore, error) { err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { // As part of our initial setup, we'll try to create the top // level filter bucket. If this already exists, then we can // exit early. filters, err := tx.CreateTopLevelBucket(filterBucket) if err != nil { return err } // If the main bucket doesn't already exist, then we'll need to // create the sub-buckets, and also initialize them with the // genesis filters. genesisBlock := params.GenesisBlock genesisHash := params.GenesisHash // First we'll create the bucket for the regular filters. regFilters, err := filters.CreateBucketIfNotExists(regBucket) if err != nil { return err } // With the bucket created, we'll now construct the initial // basic genesis filter and store it within the database. basicFilter, err := builder.BuildBasicFilter(genesisBlock, nil) if err != nil { return err } return putFilter(regFilters, genesisHash, basicFilter) }) if err != nil && err != walletdb.ErrBucketExists { return nil, err } return &FilterStore{ db: db, }, nil }
go
func New(db walletdb.DB, params chaincfg.Params) (*FilterStore, error) { err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error { // As part of our initial setup, we'll try to create the top // level filter bucket. If this already exists, then we can // exit early. filters, err := tx.CreateTopLevelBucket(filterBucket) if err != nil { return err } // If the main bucket doesn't already exist, then we'll need to // create the sub-buckets, and also initialize them with the // genesis filters. genesisBlock := params.GenesisBlock genesisHash := params.GenesisHash // First we'll create the bucket for the regular filters. regFilters, err := filters.CreateBucketIfNotExists(regBucket) if err != nil { return err } // With the bucket created, we'll now construct the initial // basic genesis filter and store it within the database. basicFilter, err := builder.BuildBasicFilter(genesisBlock, nil) if err != nil { return err } return putFilter(regFilters, genesisHash, basicFilter) }) if err != nil && err != walletdb.ErrBucketExists { return nil, err } return &FilterStore{ db: db, }, nil }
[ "func", "New", "(", "db", "walletdb", ".", "DB", ",", "params", "chaincfg", ".", "Params", ")", "(", "*", "FilterStore", ",", "error", ")", "{", "err", ":=", "walletdb", ".", "Update", "(", "db", ",", "func", "(", "tx", "walletdb", ".", "ReadWriteTx"...
// New creates a new instance of the FilterStore given an already open // database, and the target chain parameters.
[ "New", "creates", "a", "new", "instance", "of", "the", "FilterStore", "given", "an", "already", "open", "database", "and", "the", "target", "chain", "parameters", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/filterdb/db.go#L70-L108
train
lightninglabs/neutrino
filterdb/db.go
putFilter
func putFilter(bucket walletdb.ReadWriteBucket, hash *chainhash.Hash, filter *gcs.Filter) error { if filter == nil { return bucket.Put(hash[:], nil) } bytes, err := filter.NBytes() if err != nil { return err } return bucket.Put(hash[:], bytes) }
go
func putFilter(bucket walletdb.ReadWriteBucket, hash *chainhash.Hash, filter *gcs.Filter) error { if filter == nil { return bucket.Put(hash[:], nil) } bytes, err := filter.NBytes() if err != nil { return err } return bucket.Put(hash[:], bytes) }
[ "func", "putFilter", "(", "bucket", "walletdb", ".", "ReadWriteBucket", ",", "hash", "*", "chainhash", ".", "Hash", ",", "filter", "*", "gcs", ".", "Filter", ")", "error", "{", "if", "filter", "==", "nil", "{", "return", "bucket", ".", "Put", "(", "has...
// putFilter stores a filter in the database according to the corresponding // block hash. The passed bucket is expected to be the proper bucket for the // passed filter type.
[ "putFilter", "stores", "a", "filter", "in", "the", "database", "according", "to", "the", "corresponding", "block", "hash", ".", "The", "passed", "bucket", "is", "expected", "to", "be", "the", "proper", "bucket", "for", "the", "passed", "filter", "type", "." ...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/filterdb/db.go#L113-L126
train
lightninglabs/neutrino
headerfs/store.go
newHeaderStore
func newHeaderStore(db walletdb.DB, filePath string, hType HeaderType) (*headerStore, error) { var flatFileName string switch hType { case Block: flatFileName = "block_headers.bin" case RegularFilter: flatFileName = "reg_filter_headers.bin" default: return nil, fmt.Errorf("unrecognized filter type: %v", hType) } flatFileName = filepath.Join(filePath, flatFileName) // We'll open the file, creating it if necessary and ensuring that all // writes are actually appends to the end of the file. fileFlags := os.O_RDWR | os.O_APPEND | os.O_CREATE headerFile, err := os.OpenFile(flatFileName, fileFlags, 0644) if err != nil { return nil, err } // With the file open, we'll then create the header index so we can // have random access into the flat files. index, err := newHeaderIndex(db, hType) if err != nil { return nil, err } return &headerStore{ filePath: filePath, file: headerFile, headerIndex: index, }, nil }
go
func newHeaderStore(db walletdb.DB, filePath string, hType HeaderType) (*headerStore, error) { var flatFileName string switch hType { case Block: flatFileName = "block_headers.bin" case RegularFilter: flatFileName = "reg_filter_headers.bin" default: return nil, fmt.Errorf("unrecognized filter type: %v", hType) } flatFileName = filepath.Join(filePath, flatFileName) // We'll open the file, creating it if necessary and ensuring that all // writes are actually appends to the end of the file. fileFlags := os.O_RDWR | os.O_APPEND | os.O_CREATE headerFile, err := os.OpenFile(flatFileName, fileFlags, 0644) if err != nil { return nil, err } // With the file open, we'll then create the header index so we can // have random access into the flat files. index, err := newHeaderIndex(db, hType) if err != nil { return nil, err } return &headerStore{ filePath: filePath, file: headerFile, headerIndex: index, }, nil }
[ "func", "newHeaderStore", "(", "db", "walletdb", ".", "DB", ",", "filePath", "string", ",", "hType", "HeaderType", ")", "(", "*", "headerStore", ",", "error", ")", "{", "var", "flatFileName", "string", "\n", "switch", "hType", "{", "case", "Block", ":", ...
// newHeaderStore creates a new headerStore given an already open database, a // target file path for the flat-file and a particular header type. The target // file will be created as necessary.
[ "newHeaderStore", "creates", "a", "new", "headerStore", "given", "an", "already", "open", "database", "a", "target", "file", "path", "for", "the", "flat", "-", "file", "and", "a", "particular", "header", "type", ".", "The", "target", "file", "will", "be", ...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L94-L129
train
lightninglabs/neutrino
headerfs/store.go
NewBlockHeaderStore
func NewBlockHeaderStore(filePath string, db walletdb.DB, netParams *chaincfg.Params) (BlockHeaderStore, error) { hStore, err := newHeaderStore(db, filePath, Block) if err != nil { return nil, err } // With the header store created, we'll fetch the file size to see if // we need to initialize it with the first header or not. fileInfo, err := hStore.file.Stat() if err != nil { return nil, err } bhs := &blockHeaderStore{ headerStore: hStore, } // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { genesisHeader := BlockHeader{ BlockHeader: &netParams.GenesisBlock.Header, Height: 0, } if err := bhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return bhs, nil } // As a final initialization step (if this isn't the first time), we'll // ensure that the header tip within the flat files, is in sync with // out database index. tipHash, tipHeight, err := bhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/80) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := bhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // done here. latestBlockHash := latestFileHeader.BlockHash() if tipHash.IsEqual(&latestBlockHash) { return bhs, nil } // TODO(roasbeef): below assumes index can never get ahead? // * we always update files _then_ indexes // * need to dual pointer walk back for max safety // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := bhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } return bhs, nil }
go
func NewBlockHeaderStore(filePath string, db walletdb.DB, netParams *chaincfg.Params) (BlockHeaderStore, error) { hStore, err := newHeaderStore(db, filePath, Block) if err != nil { return nil, err } // With the header store created, we'll fetch the file size to see if // we need to initialize it with the first header or not. fileInfo, err := hStore.file.Stat() if err != nil { return nil, err } bhs := &blockHeaderStore{ headerStore: hStore, } // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { genesisHeader := BlockHeader{ BlockHeader: &netParams.GenesisBlock.Header, Height: 0, } if err := bhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return bhs, nil } // As a final initialization step (if this isn't the first time), we'll // ensure that the header tip within the flat files, is in sync with // out database index. tipHash, tipHeight, err := bhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/80) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := bhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // done here. latestBlockHash := latestFileHeader.BlockHash() if tipHash.IsEqual(&latestBlockHash) { return bhs, nil } // TODO(roasbeef): below assumes index can never get ahead? // * we always update files _then_ indexes // * need to dual pointer walk back for max safety // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := bhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } return bhs, nil }
[ "func", "NewBlockHeaderStore", "(", "filePath", "string", ",", "db", "walletdb", ".", "DB", ",", "netParams", "*", "chaincfg", ".", "Params", ")", "(", "BlockHeaderStore", ",", "error", ")", "{", "hStore", ",", "err", ":=", "newHeaderStore", "(", "db", ","...
// NewBlockHeaderStore creates a new instance of the blockHeaderStore based on // a target file path, an open database instance, and finally a set of // parameters for the target chain. These parameters are required as if this is // the initial start up of the blockHeaderStore, then the initial genesis // header will need to be inserted.
[ "NewBlockHeaderStore", "creates", "a", "new", "instance", "of", "the", "blockHeaderStore", "based", "on", "a", "target", "file", "path", "an", "open", "database", "instance", "and", "finally", "a", "set", "of", "parameters", "for", "the", "target", "chain", "....
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L148-L221
train
lightninglabs/neutrino
headerfs/store.go
toIndexEntry
func (b *BlockHeader) toIndexEntry() headerEntry { return headerEntry{ hash: b.BlockHash(), height: b.Height, } }
go
func (b *BlockHeader) toIndexEntry() headerEntry { return headerEntry{ hash: b.BlockHash(), height: b.Height, } }
[ "func", "(", "b", "*", "BlockHeader", ")", "toIndexEntry", "(", ")", "headerEntry", "{", "return", "headerEntry", "{", "hash", ":", "b", ".", "BlockHash", "(", ")", ",", "height", ":", "b", ".", "Height", ",", "}", "\n", "}" ]
// toIndexEntry converts the BlockHeader into a matching headerEntry. This // method is used when a header is to be written to disk.
[ "toIndexEntry", "converts", "the", "BlockHeader", "into", "a", "matching", "headerEntry", ".", "This", "method", "is", "used", "when", "a", "header", "is", "to", "be", "written", "to", "disk", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L356-L361
train
lightninglabs/neutrino
headerfs/store.go
BlockLocatorFromHash
func (h *blockHeaderStore) BlockLocatorFromHash(hash *chainhash.Hash) ( blockchain.BlockLocator, error) { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return h.blockLocatorFromHash(hash) }
go
func (h *blockHeaderStore) BlockLocatorFromHash(hash *chainhash.Hash) ( blockchain.BlockLocator, error) { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return h.blockLocatorFromHash(hash) }
[ "func", "(", "h", "*", "blockHeaderStore", ")", "BlockLocatorFromHash", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "blockchain", ".", "BlockLocator", ",", "error", ")", "{", "h", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "h", ".", ...
// BlockLocatorFromHash computes a block locator given a particular hash. The // standard Bitcoin algorithm to compute block locators are employed.
[ "BlockLocatorFromHash", "computes", "a", "block", "locator", "given", "a", "particular", "hash", ".", "The", "standard", "Bitcoin", "algorithm", "to", "compute", "block", "locators", "are", "employed", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L472-L480
train
lightninglabs/neutrino
headerfs/store.go
CheckConnectivity
func (h *blockHeaderStore) CheckConnectivity() error { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return walletdb.View(h.db, func(tx walletdb.ReadTx) error { // First, we'll fetch the root bucket, in order to use that to // fetch the bucket that houses the header index. rootBucket := tx.ReadBucket(indexBucket) // With the header bucket retrieved, we'll now fetch the chain // tip so we can start our backwards scan. tipHash := rootBucket.Get(bitcoinTip) tipHeightBytes := rootBucket.Get(tipHash) // With the height extracted, we'll now read the _last_ block // header within the file before we kick off our connectivity // loop. tipHeight := binary.BigEndian.Uint32(tipHeightBytes) header, err := h.readHeader(tipHeight) if err != nil { return err } // We'll now cycle backwards, seeking backwards along the // header file to ensure each header connects properly and the // index entries are also accurate. To do this, we start from a // height of one before our current tip. var newHeader wire.BlockHeader for height := tipHeight - 1; height > 0; height-- { // First, read the block header for this block height, // and also compute the block hash for it. newHeader, err = h.readHeader(height) if err != nil { return fmt.Errorf("Couldn't retrieve header %s:"+ " %s", header.PrevBlock, err) } newHeaderHash := newHeader.BlockHash() // With the header retrieved, we'll now fetch the // height for this current header hash to ensure the // on-disk state and the index matches up properly. indexHeightBytes := rootBucket.Get(newHeaderHash[:]) if indexHeightBytes == nil { return fmt.Errorf("index and on-disk file out of sync "+ "at height: %v", height) } indexHeight := binary.BigEndian.Uint32(indexHeightBytes) // With the index entry retrieved, we'll now assert // that the height matches up with our current height // in this backwards walk. if indexHeight != height { return fmt.Errorf("index height isn't monotonically " + "increasing") } // Finally, we'll assert that this new header is // actually the prev header of the target header from // the last loop. This ensures connectivity. if newHeader.BlockHash() != header.PrevBlock { return fmt.Errorf("Block %s doesn't match "+ "block %s's PrevBlock (%s)", newHeader.BlockHash(), header.BlockHash(), header.PrevBlock) } // As all the checks have passed, we'll now reset our // header pointer to this current location, and // continue our backwards walk. header = newHeader } return nil }) }
go
func (h *blockHeaderStore) CheckConnectivity() error { // Lock store for read. h.mtx.RLock() defer h.mtx.RUnlock() return walletdb.View(h.db, func(tx walletdb.ReadTx) error { // First, we'll fetch the root bucket, in order to use that to // fetch the bucket that houses the header index. rootBucket := tx.ReadBucket(indexBucket) // With the header bucket retrieved, we'll now fetch the chain // tip so we can start our backwards scan. tipHash := rootBucket.Get(bitcoinTip) tipHeightBytes := rootBucket.Get(tipHash) // With the height extracted, we'll now read the _last_ block // header within the file before we kick off our connectivity // loop. tipHeight := binary.BigEndian.Uint32(tipHeightBytes) header, err := h.readHeader(tipHeight) if err != nil { return err } // We'll now cycle backwards, seeking backwards along the // header file to ensure each header connects properly and the // index entries are also accurate. To do this, we start from a // height of one before our current tip. var newHeader wire.BlockHeader for height := tipHeight - 1; height > 0; height-- { // First, read the block header for this block height, // and also compute the block hash for it. newHeader, err = h.readHeader(height) if err != nil { return fmt.Errorf("Couldn't retrieve header %s:"+ " %s", header.PrevBlock, err) } newHeaderHash := newHeader.BlockHash() // With the header retrieved, we'll now fetch the // height for this current header hash to ensure the // on-disk state and the index matches up properly. indexHeightBytes := rootBucket.Get(newHeaderHash[:]) if indexHeightBytes == nil { return fmt.Errorf("index and on-disk file out of sync "+ "at height: %v", height) } indexHeight := binary.BigEndian.Uint32(indexHeightBytes) // With the index entry retrieved, we'll now assert // that the height matches up with our current height // in this backwards walk. if indexHeight != height { return fmt.Errorf("index height isn't monotonically " + "increasing") } // Finally, we'll assert that this new header is // actually the prev header of the target header from // the last loop. This ensures connectivity. if newHeader.BlockHash() != header.PrevBlock { return fmt.Errorf("Block %s doesn't match "+ "block %s's PrevBlock (%s)", newHeader.BlockHash(), header.BlockHash(), header.PrevBlock) } // As all the checks have passed, we'll now reset our // header pointer to this current location, and // continue our backwards walk. header = newHeader } return nil }) }
[ "func", "(", "h", "*", "blockHeaderStore", ")", "CheckConnectivity", "(", ")", "error", "{", "h", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "h", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "return", "walletdb", ".", "View", "(", "h", ".", ...
// CheckConnectivity cycles through all of the block headers on disk, from last // to first, and makes sure they all connect to each other. Additionally, at // each block header, we also ensure that the index entry for that height and // hash also match up properly.
[ "CheckConnectivity", "cycles", "through", "all", "of", "the", "block", "headers", "on", "disk", "from", "last", "to", "first", "and", "makes", "sure", "they", "all", "connect", "to", "each", "other", ".", "Additionally", "at", "each", "block", "header", "we"...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L486-L561
train
lightninglabs/neutrino
headerfs/store.go
NewFilterHeaderStore
func NewFilterHeaderStore(filePath string, db walletdb.DB, filterType HeaderType, netParams *chaincfg.Params) (*FilterHeaderStore, error) { fStore, err := newHeaderStore(db, filePath, filterType) if err != nil { return nil, err } // With the header store created, we'll fetch the fiie size to see if // we need to initialize it with the first header or not. fileInfo, err := fStore.file.Stat() if err != nil { return nil, err } fhs := &FilterHeaderStore{ fStore, } // TODO(roasbeef): also reconsile with block header state due to way // roll back works atm // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { var genesisFilterHash chainhash.Hash switch filterType { case RegularFilter: basicFilter, err := builder.BuildBasicFilter( netParams.GenesisBlock, nil, ) if err != nil { return nil, err } genesisFilterHash, err = builder.MakeHeaderForFilter( basicFilter, netParams.GenesisBlock.Header.PrevBlock, ) if err != nil { return nil, err } default: return nil, fmt.Errorf("unknown filter type: %v", filterType) } genesisHeader := FilterHeader{ HeaderHash: *netParams.GenesisHash, FilterHash: genesisFilterHash, Height: 0, } if err := fhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return fhs, nil } // As a final initialization step, we'll ensure that the header tip // within the flat files, is in sync with out database index. tipHash, tipHeight, err := fhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/32) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := fhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // doing here. if tipHash.IsEqual(latestFileHeader) { return fhs, nil } // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := fhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } // TODO(roasbeef): make above into func return fhs, nil }
go
func NewFilterHeaderStore(filePath string, db walletdb.DB, filterType HeaderType, netParams *chaincfg.Params) (*FilterHeaderStore, error) { fStore, err := newHeaderStore(db, filePath, filterType) if err != nil { return nil, err } // With the header store created, we'll fetch the fiie size to see if // we need to initialize it with the first header or not. fileInfo, err := fStore.file.Stat() if err != nil { return nil, err } fhs := &FilterHeaderStore{ fStore, } // TODO(roasbeef): also reconsile with block header state due to way // roll back works atm // If the size of the file is zero, then this means that we haven't yet // written the initial genesis header to disk, so we'll do so now. if fileInfo.Size() == 0 { var genesisFilterHash chainhash.Hash switch filterType { case RegularFilter: basicFilter, err := builder.BuildBasicFilter( netParams.GenesisBlock, nil, ) if err != nil { return nil, err } genesisFilterHash, err = builder.MakeHeaderForFilter( basicFilter, netParams.GenesisBlock.Header.PrevBlock, ) if err != nil { return nil, err } default: return nil, fmt.Errorf("unknown filter type: %v", filterType) } genesisHeader := FilterHeader{ HeaderHash: *netParams.GenesisHash, FilterHash: genesisFilterHash, Height: 0, } if err := fhs.WriteHeaders(genesisHeader); err != nil { return nil, err } return fhs, nil } // As a final initialization step, we'll ensure that the header tip // within the flat files, is in sync with out database index. tipHash, tipHeight, err := fhs.chainTip() if err != nil { return nil, err } // First, we'll compute the size of the current file so we can // calculate the latest header written to disk. fileHeight := uint32(fileInfo.Size()/32) - 1 // Using the file's current height, fetch the latest on-disk header. latestFileHeader, err := fhs.readHeader(fileHeight) if err != nil { return nil, err } // If the index's tip hash, and the file on-disk match, then we're // doing here. if tipHash.IsEqual(latestFileHeader) { return fhs, nil } // Otherwise, we'll need to truncate the file until it matches the // current index tip. for fileHeight > tipHeight { if err := fhs.singleTruncate(); err != nil { return nil, err } fileHeight-- } // TODO(roasbeef): make above into func return fhs, nil }
[ "func", "NewFilterHeaderStore", "(", "filePath", "string", ",", "db", "walletdb", ".", "DB", ",", "filterType", "HeaderType", ",", "netParams", "*", "chaincfg", ".", "Params", ")", "(", "*", "FilterHeaderStore", ",", "error", ")", "{", "fStore", ",", "err", ...
// NewFilterHeaderStore returns a new instance of the FilterHeaderStore based // on a target file path, filter type, and target net parameters. These // parameters are required as if this is the initial start up of the // FilterHeaderStore, then the initial genesis filter header will need to be // inserted.
[ "NewFilterHeaderStore", "returns", "a", "new", "instance", "of", "the", "FilterHeaderStore", "based", "on", "a", "target", "file", "path", "filter", "type", "and", "target", "net", "parameters", ".", "These", "parameters", "are", "required", "as", "if", "this", ...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L598-L694
train
lightninglabs/neutrino
headerfs/store.go
FetchHeader
func (f *FilterHeaderStore) FetchHeader(hash *chainhash.Hash) (*chainhash.Hash, error) { // Lock store for read. f.mtx.RLock() defer f.mtx.RUnlock() height, err := f.heightFromHash(hash) if err != nil { return nil, err } return f.readHeader(height) }
go
func (f *FilterHeaderStore) FetchHeader(hash *chainhash.Hash) (*chainhash.Hash, error) { // Lock store for read. f.mtx.RLock() defer f.mtx.RUnlock() height, err := f.heightFromHash(hash) if err != nil { return nil, err } return f.readHeader(height) }
[ "func", "(", "f", "*", "FilterHeaderStore", ")", "FetchHeader", "(", "hash", "*", "chainhash", ".", "Hash", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "f", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "mtx", ...
// FetchHeader returns the filter header that corresponds to the passed block // height.
[ "FetchHeader", "returns", "the", "filter", "header", "that", "corresponds", "to", "the", "passed", "block", "height", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L698-L709
train
lightninglabs/neutrino
headerfs/store.go
FetchHeaderByHeight
func (f *FilterHeaderStore) FetchHeaderByHeight(height uint32) (*chainhash.Hash, error) { // Lock store for read. f.mtx.RLock() defer f.mtx.RUnlock() return f.readHeader(height) }
go
func (f *FilterHeaderStore) FetchHeaderByHeight(height uint32) (*chainhash.Hash, error) { // Lock store for read. f.mtx.RLock() defer f.mtx.RUnlock() return f.readHeader(height) }
[ "func", "(", "f", "*", "FilterHeaderStore", ")", "FetchHeaderByHeight", "(", "height", "uint32", ")", "(", "*", "chainhash", ".", "Hash", ",", "error", ")", "{", "f", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "mtx", ".", "RUnlock",...
// FetchHeaderByHeight returns the filter header for a particular block height.
[ "FetchHeaderByHeight", "returns", "the", "filter", "header", "for", "a", "particular", "block", "height", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L712-L718
train
lightninglabs/neutrino
headerfs/store.go
FetchHeaderAncestors
func (f *FilterHeaderStore) FetchHeaderAncestors(numHeaders uint32, stopHash *chainhash.Hash) ([]chainhash.Hash, uint32, error) { // First, we'll find the final header in the range, this will be the // ending height of our scan. endHeight, err := f.heightFromHash(stopHash) if err != nil { return nil, 0, err } startHeight := endHeight - numHeaders headers, err := f.readHeaderRange(startHeight, endHeight) if err != nil { return nil, 0, err } return headers, startHeight, nil }
go
func (f *FilterHeaderStore) FetchHeaderAncestors(numHeaders uint32, stopHash *chainhash.Hash) ([]chainhash.Hash, uint32, error) { // First, we'll find the final header in the range, this will be the // ending height of our scan. endHeight, err := f.heightFromHash(stopHash) if err != nil { return nil, 0, err } startHeight := endHeight - numHeaders headers, err := f.readHeaderRange(startHeight, endHeight) if err != nil { return nil, 0, err } return headers, startHeight, nil }
[ "func", "(", "f", "*", "FilterHeaderStore", ")", "FetchHeaderAncestors", "(", "numHeaders", "uint32", ",", "stopHash", "*", "chainhash", ".", "Hash", ")", "(", "[", "]", "chainhash", ".", "Hash", ",", "uint32", ",", "error", ")", "{", "endHeight", ",", "...
// FetchHeaderAncestors fetches the numHeaders filter headers that are the // ancestors of the target stop block hash. A total of numHeaders+1 headers will be // returned, as we'll walk back numHeaders distance to collect each header, // then return the final header specified by the stop hash. We'll also return // the starting height of the header range as well so callers can compute the // height of each header without knowing the height of the stop hash.
[ "FetchHeaderAncestors", "fetches", "the", "numHeaders", "filter", "headers", "that", "are", "the", "ancestors", "of", "the", "target", "stop", "block", "hash", ".", "A", "total", "of", "numHeaders", "+", "1", "headers", "will", "be", "returned", "as", "we", ...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L726-L743
train
lightninglabs/neutrino
headerfs/store.go
toIndexEntry
func (f *FilterHeader) toIndexEntry() headerEntry { return headerEntry{ hash: f.HeaderHash, height: f.Height, } }
go
func (f *FilterHeader) toIndexEntry() headerEntry { return headerEntry{ hash: f.HeaderHash, height: f.Height, } }
[ "func", "(", "f", "*", "FilterHeader", ")", "toIndexEntry", "(", ")", "headerEntry", "{", "return", "headerEntry", "{", "hash", ":", "f", ".", "HeaderHash", ",", "height", ":", "f", ".", "Height", ",", "}", "\n", "}" ]
// toIndexEntry converts the filter header into a index entry to be stored // within the database.
[ "toIndexEntry", "converts", "the", "filter", "header", "into", "a", "index", "entry", "to", "be", "stored", "within", "the", "database", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L762-L767
train
lightninglabs/neutrino
headerfs/store.go
WriteHeaders
func (f *FilterHeaderStore) WriteHeaders(hdrs ...FilterHeader) error { // Lock store for write. f.mtx.Lock() defer f.mtx.Unlock() // If there are 0 headers to be written, return immediately. This // prevents the newTip assignment from panicking because of an index // of -1. if len(hdrs) == 0 { return nil } // First, we'll grab a buffer from the write buffer pool so we an // reduce our total number of allocations, and also write the headers // in a single swoop. headerBuf := headerBufPool.Get().(*bytes.Buffer) headerBuf.Reset() defer headerBufPool.Put(headerBuf) // Next, we'll write out all the passed headers in series into the // buffer we just extracted from the pool. for _, header := range hdrs { if _, err := headerBuf.Write(header.FilterHash[:]); err != nil { return err } } // With all the headers written to the buffer, we'll now write out the // entire batch in a single write call. if err := f.appendRaw(headerBuf.Bytes()); err != nil { return err } // As the block headers should already be written, we only need to // update the tip pointer for this particular header type. newTip := hdrs[len(hdrs)-1].toIndexEntry().hash return f.truncateIndex(&newTip, false) }
go
func (f *FilterHeaderStore) WriteHeaders(hdrs ...FilterHeader) error { // Lock store for write. f.mtx.Lock() defer f.mtx.Unlock() // If there are 0 headers to be written, return immediately. This // prevents the newTip assignment from panicking because of an index // of -1. if len(hdrs) == 0 { return nil } // First, we'll grab a buffer from the write buffer pool so we an // reduce our total number of allocations, and also write the headers // in a single swoop. headerBuf := headerBufPool.Get().(*bytes.Buffer) headerBuf.Reset() defer headerBufPool.Put(headerBuf) // Next, we'll write out all the passed headers in series into the // buffer we just extracted from the pool. for _, header := range hdrs { if _, err := headerBuf.Write(header.FilterHash[:]); err != nil { return err } } // With all the headers written to the buffer, we'll now write out the // entire batch in a single write call. if err := f.appendRaw(headerBuf.Bytes()); err != nil { return err } // As the block headers should already be written, we only need to // update the tip pointer for this particular header type. newTip := hdrs[len(hdrs)-1].toIndexEntry().hash return f.truncateIndex(&newTip, false) }
[ "func", "(", "f", "*", "FilterHeaderStore", ")", "WriteHeaders", "(", "hdrs", "...", "FilterHeader", ")", "error", "{", "f", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "hdrs",...
// WriteHeaders writes a batch of filter headers to persistent storage. The // headers themselves are appended to the flat file, and then the index updated // to reflect the new entires.
[ "WriteHeaders", "writes", "a", "batch", "of", "filter", "headers", "to", "persistent", "storage", ".", "The", "headers", "themselves", "are", "appended", "to", "the", "flat", "file", "and", "then", "the", "index", "updated", "to", "reflect", "the", "new", "e...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L772-L809
train
lightninglabs/neutrino
headerfs/store.go
ChainTip
func (f *FilterHeaderStore) ChainTip() (*chainhash.Hash, uint32, error) { // Lock store for read. f.mtx.RLock() defer f.mtx.RUnlock() _, tipHeight, err := f.chainTip() if err != nil { return nil, 0, fmt.Errorf("unable to fetch chain tip: %v", err) } latestHeader, err := f.readHeader(tipHeight) if err != nil { return nil, 0, fmt.Errorf("unable to read header: %v", err) } return latestHeader, tipHeight, nil }
go
func (f *FilterHeaderStore) ChainTip() (*chainhash.Hash, uint32, error) { // Lock store for read. f.mtx.RLock() defer f.mtx.RUnlock() _, tipHeight, err := f.chainTip() if err != nil { return nil, 0, fmt.Errorf("unable to fetch chain tip: %v", err) } latestHeader, err := f.readHeader(tipHeight) if err != nil { return nil, 0, fmt.Errorf("unable to read header: %v", err) } return latestHeader, tipHeight, nil }
[ "func", "(", "f", "*", "FilterHeaderStore", ")", "ChainTip", "(", ")", "(", "*", "chainhash", ".", "Hash", ",", "uint32", ",", "error", ")", "{", "f", ".", "mtx", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "mtx", ".", "RUnlock", "(", ")", ...
// ChainTip returns the latest filter header and height known to the // FilterHeaderStore.
[ "ChainTip", "returns", "the", "latest", "filter", "header", "and", "height", "known", "to", "the", "FilterHeaderStore", "." ]
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L813-L829
train
lightninglabs/neutrino
headerfs/store.go
RollbackLastBlock
func (f *FilterHeaderStore) RollbackLastBlock(newTip *chainhash.Hash) (*waddrmgr.BlockStamp, error) { // Lock store for write. f.mtx.Lock() defer f.mtx.Unlock() // First, we'll obtain the latest height that the index knows of. _, chainTipHeight, err := f.chainTip() if err != nil { return nil, err } // With this height obtained, we'll use it to read what will be the new // chain tip from disk. newHeightTip := chainTipHeight - 1 newHeaderTip, err := f.readHeader(newHeightTip) if err != nil { return nil, err } // Now that we have the information we need to return from this // function, we can now truncate both the header file and the index. if err := f.singleTruncate(); err != nil { return nil, err } if err := f.truncateIndex(newTip, false); err != nil { return nil, err } // TODO(roasbeef): return chain hash also? return &waddrmgr.BlockStamp{ Height: int32(newHeightTip), Hash: *newHeaderTip, }, nil }
go
func (f *FilterHeaderStore) RollbackLastBlock(newTip *chainhash.Hash) (*waddrmgr.BlockStamp, error) { // Lock store for write. f.mtx.Lock() defer f.mtx.Unlock() // First, we'll obtain the latest height that the index knows of. _, chainTipHeight, err := f.chainTip() if err != nil { return nil, err } // With this height obtained, we'll use it to read what will be the new // chain tip from disk. newHeightTip := chainTipHeight - 1 newHeaderTip, err := f.readHeader(newHeightTip) if err != nil { return nil, err } // Now that we have the information we need to return from this // function, we can now truncate both the header file and the index. if err := f.singleTruncate(); err != nil { return nil, err } if err := f.truncateIndex(newTip, false); err != nil { return nil, err } // TODO(roasbeef): return chain hash also? return &waddrmgr.BlockStamp{ Height: int32(newHeightTip), Hash: *newHeaderTip, }, nil }
[ "func", "(", "f", "*", "FilterHeaderStore", ")", "RollbackLastBlock", "(", "newTip", "*", "chainhash", ".", "Hash", ")", "(", "*", "waddrmgr", ".", "BlockStamp", ",", "error", ")", "{", "f", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "f", ".",...
// RollbackLastBlock rollsback both the index, and on-disk header file by a // _single_ filter header. This method is meant to be used in the case of // re-org which disconnects the latest filter header from the end of the main // chain. The information about the latest header tip after truncation is // returned.
[ "RollbackLastBlock", "rollsback", "both", "the", "index", "and", "on", "-", "disk", "header", "file", "by", "a", "_single_", "filter", "header", ".", "This", "method", "is", "meant", "to", "be", "used", "in", "the", "case", "of", "re", "-", "org", "which...
a655679fe131a5d1b4417872cc834fc3862ac70e
https://github.com/lightninglabs/neutrino/blob/a655679fe131a5d1b4417872cc834fc3862ac70e/headerfs/store.go#L836-L869
train
Workiva/go-datastructures
numerics/optimization/global.go
search
func (results *results) search(result *nmVertex) int { return sort.Search(len(results.vertices), func(i int) bool { return !results.vertices[i].less(results.config, result) }) }
go
func (results *results) search(result *nmVertex) int { return sort.Search(len(results.vertices), func(i int) bool { return !results.vertices[i].less(results.config, result) }) }
[ "func", "(", "results", "*", "results", ")", "search", "(", "result", "*", "nmVertex", ")", "int", "{", "return", "sort", ".", "Search", "(", "len", "(", "results", ".", "vertices", ")", ",", "func", "(", "i", "int", ")", "bool", "{", "return", "!"...
// search will search this list of results based on order, order // being defined in the NelderMeadConfiguration, that is a defined // target will be treated
[ "search", "will", "search", "this", "list", "of", "results", "based", "on", "order", "order", "being", "defined", "in", "the", "NelderMeadConfiguration", "that", "is", "a", "defined", "target", "will", "be", "treated" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/global.go#L79-L83
train
Workiva/go-datastructures
numerics/optimization/global.go
reSort
func (results *results) reSort(vertex *nmVertex) { results.insert(vertex) bestGuess := results.vertices[0] sigma := calculateSigma(len(results.config.Vars), len(results.vertices)) results.pbs.calculateProbabilities(bestGuess, sigma) results.pbs.sort() }
go
func (results *results) reSort(vertex *nmVertex) { results.insert(vertex) bestGuess := results.vertices[0] sigma := calculateSigma(len(results.config.Vars), len(results.vertices)) results.pbs.calculateProbabilities(bestGuess, sigma) results.pbs.sort() }
[ "func", "(", "results", "*", "results", ")", "reSort", "(", "vertex", "*", "nmVertex", ")", "{", "results", ".", "insert", "(", "vertex", ")", "\n", "bestGuess", ":=", "results", ".", "vertices", "[", "0", "]", "\n", "sigma", ":=", "calculateSigma", "(...
// reSort will re-sort the list of possible guess vertices // based upon the latest calculated result. It was also // add this result to the list of results.
[ "reSort", "will", "re", "-", "sort", "the", "list", "of", "possible", "guess", "vertices", "based", "upon", "the", "latest", "calculated", "result", ".", "It", "was", "also", "add", "this", "result", "to", "the", "list", "of", "results", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/global.go#L145-L152
train
Workiva/go-datastructures
rangetree/immutable.go
Add
func (irt *immutableRangeTree) Add(entries ...Entry) *immutableRangeTree { if len(entries) == 0 { return irt } cache := newCache(irt.dimensions) top := make(orderedNodes, len(irt.top)) copy(top, irt.top) added := uint64(0) for _, entry := range entries { irt.add(&top, cache, entry, &added) } tree := newImmutableRangeTree(irt.dimensions) tree.top = top tree.number = irt.number + added return tree }
go
func (irt *immutableRangeTree) Add(entries ...Entry) *immutableRangeTree { if len(entries) == 0 { return irt } cache := newCache(irt.dimensions) top := make(orderedNodes, len(irt.top)) copy(top, irt.top) added := uint64(0) for _, entry := range entries { irt.add(&top, cache, entry, &added) } tree := newImmutableRangeTree(irt.dimensions) tree.top = top tree.number = irt.number + added return tree }
[ "func", "(", "irt", "*", "immutableRangeTree", ")", "Add", "(", "entries", "...", "Entry", ")", "*", "immutableRangeTree", "{", "if", "len", "(", "entries", ")", "==", "0", "{", "return", "irt", "\n", "}", "\n", "cache", ":=", "newCache", "(", "irt", ...
// Add will add the provided entries into the tree and return // a new tree with those entries added.
[ "Add", "will", "add", "the", "provided", "entries", "into", "the", "tree", "and", "return", "a", "new", "tree", "with", "those", "entries", "added", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/immutable.go#L78-L95
train
Workiva/go-datastructures
rangetree/immutable.go
InsertAtDimension
func (irt *immutableRangeTree) InsertAtDimension(dimension uint64, index, number int64) (*immutableRangeTree, Entries, Entries) { if dimension > irt.dimensions || number == 0 { return irt, nil, nil } modified, deleted := make(Entries, 0, 100), make(Entries, 0, 100) tree := newImmutableRangeTree(irt.dimensions) tree.top = irt.top.immutableInsert( dimension, 1, irt.dimensions, index, number, &modified, &deleted, ) tree.number = irt.number - uint64(len(deleted)) return tree, modified, deleted }
go
func (irt *immutableRangeTree) InsertAtDimension(dimension uint64, index, number int64) (*immutableRangeTree, Entries, Entries) { if dimension > irt.dimensions || number == 0 { return irt, nil, nil } modified, deleted := make(Entries, 0, 100), make(Entries, 0, 100) tree := newImmutableRangeTree(irt.dimensions) tree.top = irt.top.immutableInsert( dimension, 1, irt.dimensions, index, number, &modified, &deleted, ) tree.number = irt.number - uint64(len(deleted)) return tree, modified, deleted }
[ "func", "(", "irt", "*", "immutableRangeTree", ")", "InsertAtDimension", "(", "dimension", "uint64", ",", "index", ",", "number", "int64", ")", "(", "*", "immutableRangeTree", ",", "Entries", ",", "Entries", ")", "{", "if", "dimension", ">", "irt", ".", "d...
// InsertAtDimension will increment items at and above the given index // by the number provided. Provide a negative number to to decrement. // Returned are two lists and the modified tree. The first list is a // list of entries that were moved. The second is a list entries that // were deleted. These lists are exclusive.
[ "InsertAtDimension", "will", "increment", "items", "at", "and", "above", "the", "given", "index", "by", "the", "number", "provided", ".", "Provide", "a", "negative", "number", "to", "to", "decrement", ".", "Returned", "are", "two", "lists", "and", "the", "mo...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/immutable.go#L102-L120
train
Workiva/go-datastructures
threadsafe/err/error.go
Set
func (e *Error) Set(err error) { e.lock.Lock() defer e.lock.Unlock() e.err = err }
go
func (e *Error) Set(err error) { e.lock.Lock() defer e.lock.Unlock() e.err = err }
[ "func", "(", "e", "*", "Error", ")", "Set", "(", "err", "error", ")", "{", "e", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "lock", ".", "Unlock", "(", ")", "\n", "e", ".", "err", "=", "err", "\n", "}" ]
// Set will set the error of this structure to the provided // value.
[ "Set", "will", "set", "the", "error", "of", "this", "structure", "to", "the", "provided", "value", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/threadsafe/err/error.go#L36-L41
train
Workiva/go-datastructures
threadsafe/err/error.go
Get
func (e *Error) Get() error { e.lock.RLock() defer e.lock.RUnlock() return e.err }
go
func (e *Error) Get() error { e.lock.RLock() defer e.lock.RUnlock() return e.err }
[ "func", "(", "e", "*", "Error", ")", "Get", "(", ")", "error", "{", "e", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "e", ".", "err", "\n", "}" ]
// Get will return any error associated with this structure.
[ "Get", "will", "return", "any", "error", "associated", "with", "this", "structure", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/threadsafe/err/error.go#L44-L49
train
Workiva/go-datastructures
rangetree/orderedtree.go
add
func (ot *orderedTree) add(entry Entry) *node { var node *node list := &ot.top for i := uint64(1); i <= ot.dimensions; i++ { if isLastDimension(ot.dimensions, i) { overwritten := list.add( newNode(entry.ValueAtDimension(i), entry, false), ) if overwritten == nil { ot.number++ } return overwritten } node, _ = list.getOrAdd(entry, i, ot.dimensions) list = &node.orderedNodes } return nil }
go
func (ot *orderedTree) add(entry Entry) *node { var node *node list := &ot.top for i := uint64(1); i <= ot.dimensions; i++ { if isLastDimension(ot.dimensions, i) { overwritten := list.add( newNode(entry.ValueAtDimension(i), entry, false), ) if overwritten == nil { ot.number++ } return overwritten } node, _ = list.getOrAdd(entry, i, ot.dimensions) list = &node.orderedNodes } return nil }
[ "func", "(", "ot", "*", "orderedTree", ")", "add", "(", "entry", "Entry", ")", "*", "node", "{", "var", "node", "*", "node", "\n", "list", ":=", "&", "ot", ".", "top", "\n", "for", "i", ":=", "uint64", "(", "1", ")", ";", "i", "<=", "ot", "."...
// add will add the provided entry to the rangetree and return an // entry if one was overwritten.
[ "add", "will", "add", "the", "provided", "entry", "to", "the", "rangetree", "and", "return", "an", "entry", "if", "one", "was", "overwritten", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/orderedtree.go#L44-L63
train
Workiva/go-datastructures
slice/int64.go
Search
func (s Int64Slice) Search(x int64) int { return sort.Search(len(s), func(i int) bool { return s[i] >= x }) }
go
func (s Int64Slice) Search(x int64) int { return sort.Search(len(s), func(i int) bool { return s[i] >= x }) }
[ "func", "(", "s", "Int64Slice", ")", "Search", "(", "x", "int64", ")", "int", "{", "return", "sort", ".", "Search", "(", "len", "(", "s", ")", ",", "func", "(", "i", "int", ")", "bool", "{", "return", "s", "[", "i", "]", ">=", "x", "\n", "}",...
// Search will search this slice and return an index that corresponds // to the lowest position of that value. You'll need to check // separately if the value at that position is equal to x. The // behavior of this method is undefinited if the slice is not sorted.
[ "Search", "will", "search", "this", "slice", "and", "return", "an", "index", "that", "corresponds", "to", "the", "lowest", "position", "of", "that", "value", ".", "You", "ll", "need", "to", "check", "separately", "if", "the", "value", "at", "that", "positi...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/slice/int64.go#L45-L49
train
Workiva/go-datastructures
slice/int64.go
Exists
func (s Int64Slice) Exists(x int64) bool { i := s.Search(x) if i == len(s) { return false } return s[i] == x }
go
func (s Int64Slice) Exists(x int64) bool { i := s.Search(x) if i == len(s) { return false } return s[i] == x }
[ "func", "(", "s", "Int64Slice", ")", "Exists", "(", "x", "int64", ")", "bool", "{", "i", ":=", "s", ".", "Search", "(", "x", ")", "\n", "if", "i", "==", "len", "(", "s", ")", "{", "return", "false", "\n", "}", "\n", "return", "s", "[", "i", ...
// Exists returns a bool indicating if the provided value exists // in this list. This has undefined behavior if the list is not // sorted.
[ "Exists", "returns", "a", "bool", "indicating", "if", "the", "provided", "value", "exists", "in", "this", "list", ".", "This", "has", "undefined", "behavior", "if", "the", "list", "is", "not", "sorted", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/slice/int64.go#L65-L72
train
Workiva/go-datastructures
slice/int64.go
Insert
func (s Int64Slice) Insert(x int64) Int64Slice { i := s.Search(x) if i == len(s) { return append(s, x) } if s[i] == x { return s } s = append(s, 0) copy(s[i+1:], s[i:]) s[i] = x return s }
go
func (s Int64Slice) Insert(x int64) Int64Slice { i := s.Search(x) if i == len(s) { return append(s, x) } if s[i] == x { return s } s = append(s, 0) copy(s[i+1:], s[i:]) s[i] = x return s }
[ "func", "(", "s", "Int64Slice", ")", "Insert", "(", "x", "int64", ")", "Int64Slice", "{", "i", ":=", "s", ".", "Search", "(", "x", ")", "\n", "if", "i", "==", "len", "(", "s", ")", "{", "return", "append", "(", "s", ",", "x", ")", "\n", "}", ...
// Insert will insert x into the sorted position in this list // and return a list with the value added. If this slice has not // been sorted Insert's behavior is undefined.
[ "Insert", "will", "insert", "x", "into", "the", "sorted", "position", "in", "this", "list", "and", "return", "a", "list", "with", "the", "value", "added", ".", "If", "this", "slice", "has", "not", "been", "sorted", "Insert", "s", "behavior", "is", "undef...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/slice/int64.go#L77-L91
train
Workiva/go-datastructures
btree/immutable/config.go
DefaultConfig
func DefaultConfig(persister Persister, comparator Comparator) Config { return Config{ NodeWidth: 10000, Persister: persister, Comparator: comparator, } }
go
func DefaultConfig(persister Persister, comparator Comparator) Config { return Config{ NodeWidth: 10000, Persister: persister, Comparator: comparator, } }
[ "func", "DefaultConfig", "(", "persister", "Persister", ",", "comparator", "Comparator", ")", "Config", "{", "return", "Config", "{", "NodeWidth", ":", "10000", ",", "Persister", ":", "persister", ",", "Comparator", ":", "comparator", ",", "}", "\n", "}" ]
// DefaultConfig returns a configuration with the persister set. All other // fields are set to smart defaults for persistence.
[ "DefaultConfig", "returns", "a", "configuration", "with", "the", "persister", "set", ".", "All", "other", "fields", "are", "set", "to", "smart", "defaults", "for", "persistence", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/btree/immutable/config.go#L37-L43
train
Workiva/go-datastructures
trie/xfast/iterator.go
exhaust
func (iter *Iterator) exhaust() Entries { entries := make(Entries, 0, 100) for it := iter; it.Next(); { entries = append(entries, it.Value()) } return entries }
go
func (iter *Iterator) exhaust() Entries { entries := make(Entries, 0, 100) for it := iter; it.Next(); { entries = append(entries, it.Value()) } return entries }
[ "func", "(", "iter", "*", "Iterator", ")", "exhaust", "(", ")", "Entries", "{", "entries", ":=", "make", "(", "Entries", ",", "0", ",", "100", ")", "\n", "for", "it", ":=", "iter", ";", "it", ".", "Next", "(", ")", ";", "{", "entries", "=", "ap...
// exhaust is a helper function that will exhaust this iterator // and return a list of entries. This is for internal use only.
[ "exhaust", "is", "a", "helper", "function", "that", "will", "exhaust", "this", "iterator", "and", "return", "a", "list", "of", "entries", ".", "This", "is", "for", "internal", "use", "only", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/trie/xfast/iterator.go#L53-L60
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
roundUp
func roundUp(v uint64) uint64 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v |= v >> 32 v++ return v }
go
func roundUp(v uint64) uint64 { v-- v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 v |= v >> 32 v++ return v }
[ "func", "roundUp", "(", "v", "uint64", ")", "uint64", "{", "v", "--", "\n", "v", "|=", "v", ">>", "1", "\n", "v", "|=", "v", ">>", "2", "\n", "v", "|=", "v", ">>", "4", "\n", "v", "|=", "v", ">>", "8", "\n", "v", "|=", "v", ">>", "16", ...
// roundUp takes a uint64 greater than 0 and rounds it up to the next // power of 2.
[ "roundUp", "takes", "a", "uint64", "greater", "than", "0", "and", "rounds", "it", "up", "to", "the", "next", "power", "of", "2", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L27-L37
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
rebuild
func (fi *FastIntegerHashMap) rebuild() { packets := make(packets, roundUp(uint64(len(fi.packets))+1)) for _, packet := range fi.packets { if packet == nil { continue } packets.set(packet) } fi.packets = packets }
go
func (fi *FastIntegerHashMap) rebuild() { packets := make(packets, roundUp(uint64(len(fi.packets))+1)) for _, packet := range fi.packets { if packet == nil { continue } packets.set(packet) } fi.packets = packets }
[ "func", "(", "fi", "*", "FastIntegerHashMap", ")", "rebuild", "(", ")", "{", "packets", ":=", "make", "(", "packets", ",", "roundUp", "(", "uint64", "(", "len", "(", "fi", ".", "packets", ")", ")", "+", "1", ")", ")", "\n", "for", "_", ",", "pack...
// rebuild is an expensive operation which requires us to iterate // over the current bucket and rehash the keys for insertion into // the new bucket. The new bucket is twice as large as the old // bucket by default.
[ "rebuild", "is", "an", "expensive", "operation", "which", "requires", "us", "to", "iterate", "over", "the", "current", "bucket", "and", "rehash", "the", "keys", "for", "insertion", "into", "the", "new", "bucket", ".", "The", "new", "bucket", "is", "twice", ...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L109-L119
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
Get
func (fi *FastIntegerHashMap) Get(key uint64) (uint64, bool) { return fi.packets.get(key) }
go
func (fi *FastIntegerHashMap) Get(key uint64) (uint64, bool) { return fi.packets.get(key) }
[ "func", "(", "fi", "*", "FastIntegerHashMap", ")", "Get", "(", "key", "uint64", ")", "(", "uint64", ",", "bool", ")", "{", "return", "fi", ".", "packets", ".", "get", "(", "key", ")", "\n", "}" ]
// Get returns an item from the map if it exists. Otherwise, // returns false for the second argument.
[ "Get", "returns", "an", "item", "from", "the", "map", "if", "it", "exists", ".", "Otherwise", "returns", "false", "for", "the", "second", "argument", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L123-L125
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
Set
func (fi *FastIntegerHashMap) Set(key, value uint64) { if float64(fi.count+1)/float64(len(fi.packets)) > ratio { fi.rebuild() } fi.packets.set(&packet{key: key, value: value}) fi.count++ }
go
func (fi *FastIntegerHashMap) Set(key, value uint64) { if float64(fi.count+1)/float64(len(fi.packets)) > ratio { fi.rebuild() } fi.packets.set(&packet{key: key, value: value}) fi.count++ }
[ "func", "(", "fi", "*", "FastIntegerHashMap", ")", "Set", "(", "key", ",", "value", "uint64", ")", "{", "if", "float64", "(", "fi", ".", "count", "+", "1", ")", "/", "float64", "(", "len", "(", "fi", ".", "packets", ")", ")", ">", "ratio", "{", ...
// Set will set the provided key with the provided value.
[ "Set", "will", "set", "the", "provided", "key", "with", "the", "provided", "value", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L128-L135
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
Exists
func (fi *FastIntegerHashMap) Exists(key uint64) bool { return fi.packets.exists(key) }
go
func (fi *FastIntegerHashMap) Exists(key uint64) bool { return fi.packets.exists(key) }
[ "func", "(", "fi", "*", "FastIntegerHashMap", ")", "Exists", "(", "key", "uint64", ")", "bool", "{", "return", "fi", ".", "packets", ".", "exists", "(", "key", ")", "\n", "}" ]
// Exists will return a bool indicating if the provided key // exists in the map.
[ "Exists", "will", "return", "a", "bool", "indicating", "if", "the", "provided", "key", "exists", "in", "the", "map", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L139-L141
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
Delete
func (fi *FastIntegerHashMap) Delete(key uint64) { if fi.packets.delete(key) { fi.count-- } }
go
func (fi *FastIntegerHashMap) Delete(key uint64) { if fi.packets.delete(key) { fi.count-- } }
[ "func", "(", "fi", "*", "FastIntegerHashMap", ")", "Delete", "(", "key", "uint64", ")", "{", "if", "fi", ".", "packets", ".", "delete", "(", "key", ")", "{", "fi", ".", "count", "--", "\n", "}", "\n", "}" ]
// Delete will remove the provided key from the hashmap. If // the key cannot be found, this is a no-op.
[ "Delete", "will", "remove", "the", "provided", "key", "from", "the", "hashmap", ".", "If", "the", "key", "cannot", "be", "found", "this", "is", "a", "no", "-", "op", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L145-L149
train
Workiva/go-datastructures
hashmap/fastinteger/hashmap.go
New
func New(hint uint64) *FastIntegerHashMap { if hint == 0 { hint = 16 } hint = roundUp(hint) return &FastIntegerHashMap{ count: 0, packets: make(packets, hint), } }
go
func New(hint uint64) *FastIntegerHashMap { if hint == 0 { hint = 16 } hint = roundUp(hint) return &FastIntegerHashMap{ count: 0, packets: make(packets, hint), } }
[ "func", "New", "(", "hint", "uint64", ")", "*", "FastIntegerHashMap", "{", "if", "hint", "==", "0", "{", "hint", "=", "16", "\n", "}", "\n", "hint", "=", "roundUp", "(", "hint", ")", "\n", "return", "&", "FastIntegerHashMap", "{", "count", ":", "0", ...
// New returns a new FastIntegerHashMap with a bucket size specified // by hint.
[ "New", "returns", "a", "new", "FastIntegerHashMap", "with", "a", "bucket", "size", "specified", "by", "hint", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/hashmap/fastinteger/hashmap.go#L163-L173
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
Compare
func (se skipEntry) Compare(other common.Comparator) int { otherSe := other.(skipEntry) if se == otherSe { return 0 } if se > otherSe { return 1 } return -1 }
go
func (se skipEntry) Compare(other common.Comparator) int { otherSe := other.(skipEntry) if se == otherSe { return 0 } if se > otherSe { return 1 } return -1 }
[ "func", "(", "se", "skipEntry", ")", "Compare", "(", "other", "common", ".", "Comparator", ")", "int", "{", "otherSe", ":=", "other", ".", "(", "skipEntry", ")", "\n", "if", "se", "==", "otherSe", "{", "return", "0", "\n", "}", "\n", "if", "se", ">...
// Compare is required by the Comparator interface.
[ "Compare", "is", "required", "by", "the", "Comparator", "interface", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L51-L62
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
isLastDimension
func isLastDimension(dimension, lastDimension uint64) bool { if dimension >= lastDimension { // useful in testing and denotes a serious problem panic(`Dimension is greater than possible dimensions.`) } return dimension == lastDimension-1 }
go
func isLastDimension(dimension, lastDimension uint64) bool { if dimension >= lastDimension { // useful in testing and denotes a serious problem panic(`Dimension is greater than possible dimensions.`) } return dimension == lastDimension-1 }
[ "func", "isLastDimension", "(", "dimension", ",", "lastDimension", "uint64", ")", "bool", "{", "if", "dimension", ">=", "lastDimension", "{", "panic", "(", "`Dimension is greater than possible dimensions.`", ")", "\n", "}", "\n", "return", "dimension", "==", "lastDi...
// isLastDimension simply returns dimension == lastDimension-1. // This panics if dimension >= lastDimension.
[ "isLastDimension", "simply", "returns", "dimension", "==", "lastDimension", "-", "1", ".", "This", "panics", "if", "dimension", ">", "=", "lastDimension", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L70-L76
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
needsDeletion
func needsDeletion(value, index, number int64) bool { if number > 0 { return false } number = -number // get the magnitude offset := value - index return offset >= 0 && offset < number }
go
func needsDeletion(value, index, number int64) bool { if number > 0 { return false } number = -number // get the magnitude offset := value - index return offset >= 0 && offset < number }
[ "func", "needsDeletion", "(", "value", ",", "index", ",", "number", "int64", ")", "bool", "{", "if", "number", ">", "0", "{", "return", "false", "\n", "}", "\n", "number", "=", "-", "number", "\n", "offset", ":=", "value", "-", "index", "\n", "return...
// needsDeletion returns a bool indicating if the provided value // needs to be deleted based on the provided index and number.
[ "needsDeletion", "returns", "a", "bool", "indicating", "if", "the", "provided", "value", "needs", "to", "be", "deleted", "based", "on", "the", "provided", "index", "and", "number", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L80-L89
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
Get
func (rt *skipListRT) Get(entries ...rangetree.Entry) rangetree.Entries { results := make(rangetree.Entries, 0, len(entries)) for _, e := range entries { results = append(results, rt.get(e)) } return results }
go
func (rt *skipListRT) Get(entries ...rangetree.Entry) rangetree.Entries { results := make(rangetree.Entries, 0, len(entries)) for _, e := range entries { results = append(results, rt.get(e)) } return results }
[ "func", "(", "rt", "*", "skipListRT", ")", "Get", "(", "entries", "...", "rangetree", ".", "Entry", ")", "rangetree", ".", "Entries", "{", "results", ":=", "make", "(", "rangetree", ".", "Entries", ",", "0", ",", "len", "(", "entries", ")", ")", "\n"...
// Get will return any rangetree.Entries matching the provided entries. // Similar in functionality to a key lookup, this returns nil for any // entry that could not be found.
[ "Get", "will", "return", "any", "rangetree", ".", "Entries", "matching", "the", "provided", "entries", ".", "Similar", "in", "functionality", "to", "a", "key", "lookup", "this", "returns", "nil", "for", "any", "entry", "that", "could", "not", "be", "found", ...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L235-L242
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
deleteRecursive
func (rt *skipListRT) deleteRecursive(sl *skip.SkipList, dimension uint64, entry rangetree.Entry) rangetree.Entry { value := entry.ValueAtDimension(dimension) if isLastDimension(dimension, rt.dimensions) { entries := sl.Delete(skipEntry(value)) if entries[0] == nil { return nil } rt.number-- return entries[0].(*lastBundle).entry } db, ok := sl.Get(skipEntry(value))[0].(*dimensionalBundle) if !ok { // value was not found return nil } result := rt.deleteRecursive(db.sl, dimension+1, entry) if result == nil { return nil } if db.sl.Len() == 0 { sl.Delete(db) } return result }
go
func (rt *skipListRT) deleteRecursive(sl *skip.SkipList, dimension uint64, entry rangetree.Entry) rangetree.Entry { value := entry.ValueAtDimension(dimension) if isLastDimension(dimension, rt.dimensions) { entries := sl.Delete(skipEntry(value)) if entries[0] == nil { return nil } rt.number-- return entries[0].(*lastBundle).entry } db, ok := sl.Get(skipEntry(value))[0].(*dimensionalBundle) if !ok { // value was not found return nil } result := rt.deleteRecursive(db.sl, dimension+1, entry) if result == nil { return nil } if db.sl.Len() == 0 { sl.Delete(db) } return result }
[ "func", "(", "rt", "*", "skipListRT", ")", "deleteRecursive", "(", "sl", "*", "skip", ".", "SkipList", ",", "dimension", "uint64", ",", "entry", "rangetree", ".", "Entry", ")", "rangetree", ".", "Entry", "{", "value", ":=", "entry", ".", "ValueAtDimension"...
// deleteRecursive is used by the delete logic. The recursion depth // only goes as far as the number of dimensions, so this shouldn't be an // issue.
[ "deleteRecursive", "is", "used", "by", "the", "delete", "logic", ".", "The", "recursion", "depth", "only", "goes", "as", "far", "as", "the", "number", "of", "dimensions", "so", "this", "shouldn", "t", "be", "an", "issue", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L252-L281
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
Apply
func (rt *skipListRT) Apply(interval rangetree.Interval, fn func(rangetree.Entry) bool) { rt.apply(rt.top, 0, interval, fn) }
go
func (rt *skipListRT) Apply(interval rangetree.Interval, fn func(rangetree.Entry) bool) { rt.apply(rt.top, 0, interval, fn) }
[ "func", "(", "rt", "*", "skipListRT", ")", "Apply", "(", "interval", "rangetree", ".", "Interval", ",", "fn", "func", "(", "rangetree", ".", "Entry", ")", "bool", ")", "{", "rt", ".", "apply", "(", "rt", ".", "top", ",", "0", ",", "interval", ",", ...
// Apply will call the provided function with each entry that exists // within the provided range, in order. Return false at any time to // cancel iteration. Altering the entry in such a way that its location // changes will result in undefined behavior.
[ "Apply", "will", "call", "the", "provided", "function", "with", "each", "entry", "that", "exists", "within", "the", "provided", "range", "in", "order", ".", "Return", "false", "at", "any", "time", "to", "cancel", "iteration", ".", "Altering", "the", "entry",...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L332-L334
train
Workiva/go-datastructures
rangetree/skiplist/skiplist.go
Query
func (rt *skipListRT) Query(interval rangetree.Interval) rangetree.Entries { entries := make(rangetree.Entries, 0, 100) rt.apply(rt.top, 0, interval, func(e rangetree.Entry) bool { entries = append(entries, e) return true }) return entries }
go
func (rt *skipListRT) Query(interval rangetree.Interval) rangetree.Entries { entries := make(rangetree.Entries, 0, 100) rt.apply(rt.top, 0, interval, func(e rangetree.Entry) bool { entries = append(entries, e) return true }) return entries }
[ "func", "(", "rt", "*", "skipListRT", ")", "Query", "(", "interval", "rangetree", ".", "Interval", ")", "rangetree", ".", "Entries", "{", "entries", ":=", "make", "(", "rangetree", ".", "Entries", ",", "0", ",", "100", ")", "\n", "rt", ".", "apply", ...
// Query will return a list of entries that fall within // the provided interval.
[ "Query", "will", "return", "a", "list", "of", "entries", "that", "fall", "within", "the", "provided", "interval", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/skiplist/skiplist.go#L338-L346
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
Swap
func (u uintSlice) Swap(i, j int64) { u[i], u[j] = u[j], u[i] }
go
func (u uintSlice) Swap(i, j int64) { u[i], u[j] = u[j], u[i] }
[ "func", "(", "u", "uintSlice", ")", "Swap", "(", "i", ",", "j", "int64", ")", "{", "u", "[", "i", "]", ",", "u", "[", "j", "]", "=", "u", "[", "j", "]", ",", "u", "[", "i", "]", "\n", "}" ]
// Swap swaps values in this slice at the positions given.
[ "Swap", "swaps", "values", "in", "this", "slice", "at", "the", "positions", "given", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L32-L34
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
Less
func (u uintSlice) Less(i, j int64) bool { return u[i] < u[j] }
go
func (u uintSlice) Less(i, j int64) bool { return u[i] < u[j] }
[ "func", "(", "u", "uintSlice", ")", "Less", "(", "i", ",", "j", "int64", ")", "bool", "{", "return", "u", "[", "i", "]", "<", "u", "[", "j", "]", "\n", "}" ]
// Less returns a bool indicating if the value at position i is // less than position j.
[ "Less", "returns", "a", "bool", "indicating", "if", "the", "value", "at", "position", "i", "is", "less", "than", "position", "j", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L38-L40
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
SetBit
func (sba *sparseBitArray) SetBit(k uint64) error { index, position := getIndexAndRemainder(k) i, inserted := sba.indices.insert(index) if inserted { sba.blocks.insert(i) } sba.blocks[i] = sba.blocks[i].insert(position) return nil }
go
func (sba *sparseBitArray) SetBit(k uint64) error { index, position := getIndexAndRemainder(k) i, inserted := sba.indices.insert(index) if inserted { sba.blocks.insert(i) } sba.blocks[i] = sba.blocks[i].insert(position) return nil }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "SetBit", "(", "k", "uint64", ")", "error", "{", "index", ",", "position", ":=", "getIndexAndRemainder", "(", "k", ")", "\n", "i", ",", "inserted", ":=", "sba", ".", "indices", ".", "insert", "(", "index"...
// SetBit sets the bit at the given position.
[ "SetBit", "sets", "the", "bit", "at", "the", "given", "position", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L108-L117
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
GetBit
func (sba *sparseBitArray) GetBit(k uint64) (bool, error) { index, position := getIndexAndRemainder(k) i := sba.indices.get(index) if i == -1 { return false, nil } return sba.blocks[i].get(position), nil }
go
func (sba *sparseBitArray) GetBit(k uint64) (bool, error) { index, position := getIndexAndRemainder(k) i := sba.indices.get(index) if i == -1 { return false, nil } return sba.blocks[i].get(position), nil }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "GetBit", "(", "k", "uint64", ")", "(", "bool", ",", "error", ")", "{", "index", ",", "position", ":=", "getIndexAndRemainder", "(", "k", ")", "\n", "i", ":=", "sba", ".", "indices", ".", "get", "(", ...
// GetBit gets the bit at the given position.
[ "GetBit", "gets", "the", "bit", "at", "the", "given", "position", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L120-L128
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
ToNums
func (sba *sparseBitArray) ToNums() []uint64 { if len(sba.indices) == 0 { return nil } diff := uint64(len(sba.indices)) * s nums := make([]uint64, 0, diff/4) for i, offset := range sba.indices { sba.blocks[i].toNums(offset*s, &nums) } return nums }
go
func (sba *sparseBitArray) ToNums() []uint64 { if len(sba.indices) == 0 { return nil } diff := uint64(len(sba.indices)) * s nums := make([]uint64, 0, diff/4) for i, offset := range sba.indices { sba.blocks[i].toNums(offset*s, &nums) } return nums }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "ToNums", "(", ")", "[", "]", "uint64", "{", "if", "len", "(", "sba", ".", "indices", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "diff", ":=", "uint64", "(", "len", "(", "sba", ".", "i...
// ToNums converts this sparse bitarray to a list of numbers contained // within it.
[ "ToNums", "converts", "this", "sparse", "bitarray", "to", "a", "list", "of", "numbers", "contained", "within", "it", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L132-L145
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
ClearBit
func (sba *sparseBitArray) ClearBit(k uint64) error { index, position := getIndexAndRemainder(k) i := sba.indices.get(index) if i == -1 { return nil } sba.blocks[i] = sba.blocks[i].remove(position) if sba.blocks[i] == 0 { sba.blocks.deleteAtIndex(i) sba.indices.deleteAtIndex(i) } return nil }
go
func (sba *sparseBitArray) ClearBit(k uint64) error { index, position := getIndexAndRemainder(k) i := sba.indices.get(index) if i == -1 { return nil } sba.blocks[i] = sba.blocks[i].remove(position) if sba.blocks[i] == 0 { sba.blocks.deleteAtIndex(i) sba.indices.deleteAtIndex(i) } return nil }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "ClearBit", "(", "k", "uint64", ")", "error", "{", "index", ",", "position", ":=", "getIndexAndRemainder", "(", "k", ")", "\n", "i", ":=", "sba", ".", "indices", ".", "get", "(", "index", ")", "\n", "if...
// ClearBit clears the bit at the given position.
[ "ClearBit", "clears", "the", "bit", "at", "the", "given", "position", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L148-L162
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
Reset
func (sba *sparseBitArray) Reset() { sba.blocks = sba.blocks[:0] sba.indices = sba.indices[:0] }
go
func (sba *sparseBitArray) Reset() { sba.blocks = sba.blocks[:0] sba.indices = sba.indices[:0] }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "Reset", "(", ")", "{", "sba", ".", "blocks", "=", "sba", ".", "blocks", "[", ":", "0", "]", "\n", "sba", ".", "indices", "=", "sba", ".", "indices", "[", ":", "0", "]", "\n", "}" ]
// Reset erases all values from this bitarray.
[ "Reset", "erases", "all", "values", "from", "this", "bitarray", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L165-L168
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
Equals
func (sba *sparseBitArray) Equals(other BitArray) bool { if other.Capacity() == 0 && sba.Capacity() > 0 { return false } var selfIndex uint64 for iter := other.Blocks(); iter.Next(); { otherIndex, otherBlock := iter.Value() if len(sba.indices) == 0 { if otherBlock > 0 { return false } continue } if selfIndex >= uint64(len(sba.indices)) { return false } if otherIndex < sba.indices[selfIndex] { if otherBlock > 0 { return false } continue } if otherIndex > sba.indices[selfIndex] { return false } if !sba.blocks[selfIndex].equals(otherBlock) { return false } selfIndex++ } return true }
go
func (sba *sparseBitArray) Equals(other BitArray) bool { if other.Capacity() == 0 && sba.Capacity() > 0 { return false } var selfIndex uint64 for iter := other.Blocks(); iter.Next(); { otherIndex, otherBlock := iter.Value() if len(sba.indices) == 0 { if otherBlock > 0 { return false } continue } if selfIndex >= uint64(len(sba.indices)) { return false } if otherIndex < sba.indices[selfIndex] { if otherBlock > 0 { return false } continue } if otherIndex > sba.indices[selfIndex] { return false } if !sba.blocks[selfIndex].equals(otherBlock) { return false } selfIndex++ } return true }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "Equals", "(", "other", "BitArray", ")", "bool", "{", "if", "other", ".", "Capacity", "(", ")", "==", "0", "&&", "sba", ".", "Capacity", "(", ")", ">", "0", "{", "return", "false", "\n", "}", "\n", ...
// Equals returns a bool indicating if the provided bit array // equals this bitarray.
[ "Equals", "returns", "a", "bool", "indicating", "if", "the", "provided", "bit", "array", "equals", "this", "bitarray", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L187-L226
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
Or
func (sba *sparseBitArray) Or(other BitArray) BitArray { if ba, ok := other.(*sparseBitArray); ok { return orSparseWithSparseBitArray(sba, ba) } return orSparseWithDenseBitArray(sba, other.(*bitArray)) }
go
func (sba *sparseBitArray) Or(other BitArray) BitArray { if ba, ok := other.(*sparseBitArray); ok { return orSparseWithSparseBitArray(sba, ba) } return orSparseWithDenseBitArray(sba, other.(*bitArray)) }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "Or", "(", "other", "BitArray", ")", "BitArray", "{", "if", "ba", ",", "ok", ":=", "other", ".", "(", "*", "sparseBitArray", ")", ";", "ok", "{", "return", "orSparseWithSparseBitArray", "(", "sba", ",", "...
// Or will perform a bitwise or operation with the provided bitarray and // return a new result bitarray.
[ "Or", "will", "perform", "a", "bitwise", "or", "operation", "with", "the", "provided", "bitarray", "and", "return", "a", "new", "result", "bitarray", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L230-L236
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
And
func (sba *sparseBitArray) And(other BitArray) BitArray { if ba, ok := other.(*sparseBitArray); ok { return andSparseWithSparseBitArray(sba, ba) } return andSparseWithDenseBitArray(sba, other.(*bitArray)) }
go
func (sba *sparseBitArray) And(other BitArray) BitArray { if ba, ok := other.(*sparseBitArray); ok { return andSparseWithSparseBitArray(sba, ba) } return andSparseWithDenseBitArray(sba, other.(*bitArray)) }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "And", "(", "other", "BitArray", ")", "BitArray", "{", "if", "ba", ",", "ok", ":=", "other", ".", "(", "*", "sparseBitArray", ")", ";", "ok", "{", "return", "andSparseWithSparseBitArray", "(", "sba", ",", ...
// And will perform a bitwise and operation with the provided bitarray and // return a new result bitarray.
[ "And", "will", "perform", "a", "bitwise", "and", "operation", "with", "the", "provided", "bitarray", "and", "return", "a", "new", "result", "bitarray", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L240-L246
train
Workiva/go-datastructures
bitarray/sparse_bitarray.go
Intersects
func (sba *sparseBitArray) Intersects(other BitArray) bool { if other.Capacity() == 0 { return true } var selfIndex int64 for iter := other.Blocks(); iter.Next(); { otherI, otherBlock := iter.Value() if len(sba.indices) == 0 { if otherBlock > 0 { return false } continue } // here we grab where the block should live in ourselves i := uintSlice(sba.indices[selfIndex:]).search(otherI) // this is a block we don't have, doesn't intersect if i == int64(len(sba.indices)) { return false } if sba.indices[i] != otherI { return false } if !sba.blocks[i].intersects(otherBlock) { return false } selfIndex = i } return true }
go
func (sba *sparseBitArray) Intersects(other BitArray) bool { if other.Capacity() == 0 { return true } var selfIndex int64 for iter := other.Blocks(); iter.Next(); { otherI, otherBlock := iter.Value() if len(sba.indices) == 0 { if otherBlock > 0 { return false } continue } // here we grab where the block should live in ourselves i := uintSlice(sba.indices[selfIndex:]).search(otherI) // this is a block we don't have, doesn't intersect if i == int64(len(sba.indices)) { return false } if sba.indices[i] != otherI { return false } if !sba.blocks[i].intersects(otherBlock) { return false } selfIndex = i } return true }
[ "func", "(", "sba", "*", "sparseBitArray", ")", "Intersects", "(", "other", "BitArray", ")", "bool", "{", "if", "other", ".", "Capacity", "(", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "var", "selfIndex", "int64", "\n", "for", "iter", "...
// Intersects returns a bool indicating if the provided bit array // intersects with this bitarray.
[ "Intersects", "returns", "a", "bool", "indicating", "if", "the", "provided", "bit", "array", "intersects", "with", "this", "bitarray", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/sparse_bitarray.go#L277-L310
train
Workiva/go-datastructures
augmentedtree/atree.go
compare
func compare(nodeLow, ivLow int64, nodeID, ivID uint64) int { if ivLow > nodeLow { return 1 } if ivLow < nodeLow { return 0 } return intFromBool(ivID > nodeID) }
go
func compare(nodeLow, ivLow int64, nodeID, ivID uint64) int { if ivLow > nodeLow { return 1 } if ivLow < nodeLow { return 0 } return intFromBool(ivID > nodeID) }
[ "func", "compare", "(", "nodeLow", ",", "ivLow", "int64", ",", "nodeID", ",", "ivID", "uint64", ")", "int", "{", "if", "ivLow", ">", "nodeLow", "{", "return", "1", "\n", "}", "\n", "if", "ivLow", "<", "nodeLow", "{", "return", "0", "\n", "}", "\n",...
// compare returns an int indicating which direction the node // should go.
[ "compare", "returns", "an", "int", "indicating", "which", "direction", "the", "node", "should", "go", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/augmentedtree/atree.go#L43-L53
train
Workiva/go-datastructures
augmentedtree/atree.go
add
func (tree *tree) add(iv Interval) { if tree.root == nil { tree.root = newNode( iv, iv.LowAtDimension(1), iv.HighAtDimension(1), 1, ) tree.root.red = false tree.number++ return } tree.resetDummy() var ( dummy = tree.dummy parent, grandParent *node node = tree.root dir, last int otherLast = 1 id = iv.ID() max = iv.HighAtDimension(1) ivLow = iv.LowAtDimension(1) helper = &dummy ) // set this AFTER clearing dummy helper.children[1] = tree.root for { if node == nil { node = newNode(iv, ivLow, max, 1) parent.children[dir] = node tree.number++ } else if isRed(node.children[0]) && isRed(node.children[1]) { node.red = true node.children[0].red = false node.children[1].red = false } if max > node.max { node.max = max } if ivLow < node.min { node.min = ivLow } if isRed(parent) && isRed(node) { localDir := intFromBool(helper.children[1] == grandParent) if node == parent.children[last] { helper.children[localDir] = rotate(grandParent, otherLast) } else { helper.children[localDir] = doubleRotate(grandParent, otherLast) } } if node.id == id { break } last = dir otherLast = takeOpposite(last) dir = compare(node.interval.LowAtDimension(1), ivLow, node.id, id) if grandParent != nil { helper = grandParent } grandParent, parent, node = parent, node, node.children[dir] } tree.root = dummy.children[1] tree.root.red = false }
go
func (tree *tree) add(iv Interval) { if tree.root == nil { tree.root = newNode( iv, iv.LowAtDimension(1), iv.HighAtDimension(1), 1, ) tree.root.red = false tree.number++ return } tree.resetDummy() var ( dummy = tree.dummy parent, grandParent *node node = tree.root dir, last int otherLast = 1 id = iv.ID() max = iv.HighAtDimension(1) ivLow = iv.LowAtDimension(1) helper = &dummy ) // set this AFTER clearing dummy helper.children[1] = tree.root for { if node == nil { node = newNode(iv, ivLow, max, 1) parent.children[dir] = node tree.number++ } else if isRed(node.children[0]) && isRed(node.children[1]) { node.red = true node.children[0].red = false node.children[1].red = false } if max > node.max { node.max = max } if ivLow < node.min { node.min = ivLow } if isRed(parent) && isRed(node) { localDir := intFromBool(helper.children[1] == grandParent) if node == parent.children[last] { helper.children[localDir] = rotate(grandParent, otherLast) } else { helper.children[localDir] = doubleRotate(grandParent, otherLast) } } if node.id == id { break } last = dir otherLast = takeOpposite(last) dir = compare(node.interval.LowAtDimension(1), ivLow, node.id, id) if grandParent != nil { helper = grandParent } grandParent, parent, node = parent, node, node.children[dir] } tree.root = dummy.children[1] tree.root.red = false }
[ "func", "(", "tree", "*", "tree", ")", "add", "(", "iv", "Interval", ")", "{", "if", "tree", ".", "root", "==", "nil", "{", "tree", ".", "root", "=", "newNode", "(", "iv", ",", "iv", ".", "LowAtDimension", "(", "1", ")", ",", "iv", ".", "HighAt...
// add will add the provided interval to the tree.
[ "add", "will", "add", "the", "provided", "interval", "to", "the", "tree", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/augmentedtree/atree.go#L148-L219
train
Workiva/go-datastructures
augmentedtree/atree.go
Add
func (tree *tree) Add(intervals ...Interval) { for _, iv := range intervals { tree.add(iv) } }
go
func (tree *tree) Add(intervals ...Interval) { for _, iv := range intervals { tree.add(iv) } }
[ "func", "(", "tree", "*", "tree", ")", "Add", "(", "intervals", "...", "Interval", ")", "{", "for", "_", ",", "iv", ":=", "range", "intervals", "{", "tree", ".", "add", "(", "iv", ")", "\n", "}", "\n", "}" ]
// Add will add the provided intervals to this tree.
[ "Add", "will", "add", "the", "provided", "intervals", "to", "this", "tree", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/augmentedtree/atree.go#L222-L226
train
Workiva/go-datastructures
augmentedtree/atree.go
Delete
func (tree *tree) Delete(intervals ...Interval) { for _, iv := range intervals { tree.delete(iv) } if tree.root != nil { tree.root.adjustRanges() } }
go
func (tree *tree) Delete(intervals ...Interval) { for _, iv := range intervals { tree.delete(iv) } if tree.root != nil { tree.root.adjustRanges() } }
[ "func", "(", "tree", "*", "tree", ")", "Delete", "(", "intervals", "...", "Interval", ")", "{", "for", "_", ",", "iv", ":=", "range", "intervals", "{", "tree", ".", "delete", "(", "iv", ")", "\n", "}", "\n", "if", "tree", ".", "root", "!=", "nil"...
// Delete will remove the provided intervals from this tree.
[ "Delete", "will", "remove", "the", "provided", "intervals", "from", "this", "tree", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/augmentedtree/atree.go#L310-L317
train
Workiva/go-datastructures
augmentedtree/atree.go
Query
func (tree *tree) Query(interval Interval) Intervals { if tree.root == nil { return nil } var ( Intervals = intervalsPool.Get().(Intervals) ivLow = interval.LowAtDimension(1) ivHigh = interval.HighAtDimension(1) ) tree.root.query(ivLow, ivHigh, interval, tree.maxDimension, func(node *node) { Intervals = append(Intervals, node.interval) }) return Intervals }
go
func (tree *tree) Query(interval Interval) Intervals { if tree.root == nil { return nil } var ( Intervals = intervalsPool.Get().(Intervals) ivLow = interval.LowAtDimension(1) ivHigh = interval.HighAtDimension(1) ) tree.root.query(ivLow, ivHigh, interval, tree.maxDimension, func(node *node) { Intervals = append(Intervals, node.interval) }) return Intervals }
[ "func", "(", "tree", "*", "tree", ")", "Query", "(", "interval", "Interval", ")", "Intervals", "{", "if", "tree", ".", "root", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "var", "(", "Intervals", "=", "intervalsPool", ".", "Get", "(", ")", ...
// Query will return a list of intervals that intersect the provided // interval. The provided interval's ID method is ignored so the // provided ID is irrelevant.
[ "Query", "will", "return", "a", "list", "of", "intervals", "that", "intersect", "the", "provided", "interval", ".", "The", "provided", "interval", "s", "ID", "method", "is", "ignored", "so", "the", "provided", "ID", "is", "irrelevant", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/augmentedtree/atree.go#L322-L338
train
Workiva/go-datastructures
fibheap/fibheap.go
Enqueue
func (heap *FloatingFibonacciHeap) Enqueue(priority float64) *Entry { singleton := newEntry(priority) // Merge singleton list with heap heap.min = mergeLists(heap.min, singleton) heap.size++ return singleton }
go
func (heap *FloatingFibonacciHeap) Enqueue(priority float64) *Entry { singleton := newEntry(priority) // Merge singleton list with heap heap.min = mergeLists(heap.min, singleton) heap.size++ return singleton }
[ "func", "(", "heap", "*", "FloatingFibonacciHeap", ")", "Enqueue", "(", "priority", "float64", ")", "*", "Entry", "{", "singleton", ":=", "newEntry", "(", "priority", ")", "\n", "heap", ".", "min", "=", "mergeLists", "(", "heap", ".", "min", ",", "single...
// Enqueue adds and element to the heap
[ "Enqueue", "adds", "and", "element", "to", "the", "heap" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/fibheap/fibheap.go#L118-L125
train
Workiva/go-datastructures
fibheap/fibheap.go
Min
func (heap *FloatingFibonacciHeap) Min() (*Entry, error) { if heap.IsEmpty() { return nil, EmptyHeapError("Trying to get minimum element of empty heap") } return heap.min, nil }
go
func (heap *FloatingFibonacciHeap) Min() (*Entry, error) { if heap.IsEmpty() { return nil, EmptyHeapError("Trying to get minimum element of empty heap") } return heap.min, nil }
[ "func", "(", "heap", "*", "FloatingFibonacciHeap", ")", "Min", "(", ")", "(", "*", "Entry", ",", "error", ")", "{", "if", "heap", ".", "IsEmpty", "(", ")", "{", "return", "nil", ",", "EmptyHeapError", "(", "\"Trying to get minimum element of empty heap\"", "...
// Min returns the minimum element in the heap
[ "Min", "returns", "the", "minimum", "element", "in", "the", "heap" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/fibheap/fibheap.go#L128-L133
train
Workiva/go-datastructures
fibheap/fibheap.go
DequeueMin
func (heap *FloatingFibonacciHeap) DequeueMin() (*Entry, error) { if heap.IsEmpty() { return nil, EmptyHeapError("Cannot dequeue minimum of empty heap") } heap.size-- // Copy pointer. Will need it later. min := heap.min if min.next == min { // This is the only root node heap.min = nil } else { // There are more root nodes heap.min.prev.next = heap.min.next heap.min.next.prev = heap.min.prev heap.min = heap.min.next // Arbitrary element of the root list } if min.child != nil { // Keep track of the first visited node curr := min.child for ok := true; ok; ok = (curr != min.child) { curr.parent = nil curr = curr.next } } heap.min = mergeLists(heap.min, min.child) if heap.min == nil { // If there are no entries left, we're done. return min, nil } treeSlice := make([]*Entry, 0, heap.size) toVisit := make([]*Entry, 0, heap.size) for curr := heap.min; len(toVisit) == 0 || toVisit[0] != curr; curr = curr.next { toVisit = append(toVisit, curr) } for _, curr := range toVisit { for { for curr.degree >= len(treeSlice) { treeSlice = append(treeSlice, nil) } if treeSlice[curr.degree] == nil { treeSlice[curr.degree] = curr break } other := treeSlice[curr.degree] treeSlice[curr.degree] = nil // Determine which of two trees has the smaller root var minT, maxT *Entry if other.Priority < curr.Priority { minT = other maxT = curr } else { minT = curr maxT = other } // Break max out of the root list, // then merge it into min's child list maxT.next.prev = maxT.prev maxT.prev.next = maxT.next // Make it a singleton so that we can merge it maxT.prev = maxT maxT.next = maxT minT.child = mergeLists(minT.child, maxT) // Reparent max appropriately maxT.parent = minT // Clear max's mark, since it can now lose another child maxT.marked = false // Increase min's degree. It has another child. minT.degree++ // Continue merging this tree curr = minT } /* Update the global min based on this node. Note that we compare * for <= instead of < here. That's because if we just did a * reparent operation that merged two different trees of equal * priority, we need to make sure that the min pointer points to * the root-level one. */ if curr.Priority <= heap.min.Priority { heap.min = curr } } return min, nil }
go
func (heap *FloatingFibonacciHeap) DequeueMin() (*Entry, error) { if heap.IsEmpty() { return nil, EmptyHeapError("Cannot dequeue minimum of empty heap") } heap.size-- // Copy pointer. Will need it later. min := heap.min if min.next == min { // This is the only root node heap.min = nil } else { // There are more root nodes heap.min.prev.next = heap.min.next heap.min.next.prev = heap.min.prev heap.min = heap.min.next // Arbitrary element of the root list } if min.child != nil { // Keep track of the first visited node curr := min.child for ok := true; ok; ok = (curr != min.child) { curr.parent = nil curr = curr.next } } heap.min = mergeLists(heap.min, min.child) if heap.min == nil { // If there are no entries left, we're done. return min, nil } treeSlice := make([]*Entry, 0, heap.size) toVisit := make([]*Entry, 0, heap.size) for curr := heap.min; len(toVisit) == 0 || toVisit[0] != curr; curr = curr.next { toVisit = append(toVisit, curr) } for _, curr := range toVisit { for { for curr.degree >= len(treeSlice) { treeSlice = append(treeSlice, nil) } if treeSlice[curr.degree] == nil { treeSlice[curr.degree] = curr break } other := treeSlice[curr.degree] treeSlice[curr.degree] = nil // Determine which of two trees has the smaller root var minT, maxT *Entry if other.Priority < curr.Priority { minT = other maxT = curr } else { minT = curr maxT = other } // Break max out of the root list, // then merge it into min's child list maxT.next.prev = maxT.prev maxT.prev.next = maxT.next // Make it a singleton so that we can merge it maxT.prev = maxT maxT.next = maxT minT.child = mergeLists(minT.child, maxT) // Reparent max appropriately maxT.parent = minT // Clear max's mark, since it can now lose another child maxT.marked = false // Increase min's degree. It has another child. minT.degree++ // Continue merging this tree curr = minT } /* Update the global min based on this node. Note that we compare * for <= instead of < here. That's because if we just did a * reparent operation that merged two different trees of equal * priority, we need to make sure that the min pointer points to * the root-level one. */ if curr.Priority <= heap.min.Priority { heap.min = curr } } return min, nil }
[ "func", "(", "heap", "*", "FloatingFibonacciHeap", ")", "DequeueMin", "(", ")", "(", "*", "Entry", ",", "error", ")", "{", "if", "heap", ".", "IsEmpty", "(", ")", "{", "return", "nil", ",", "EmptyHeapError", "(", "\"Cannot dequeue minimum of empty heap\"", "...
// DequeueMin removes and returns the // minimal element in the heap
[ "DequeueMin", "removes", "and", "returns", "the", "minimal", "element", "in", "the", "heap" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/fibheap/fibheap.go#L147-L247
train
Workiva/go-datastructures
fibheap/fibheap.go
DecreaseKey
func (heap *FloatingFibonacciHeap) DecreaseKey(node *Entry, newPriority float64) (*Entry, error) { if heap.IsEmpty() { return nil, EmptyHeapError("Cannot decrease key in an empty heap") } if node == nil { return nil, NilError("Cannot decrease key: given node is nil") } if newPriority >= node.Priority { return nil, fmt.Errorf("The given new priority: %v, is larger than or equal to the old: %v", newPriority, node.Priority) } decreaseKeyUnchecked(heap, node, newPriority) return node, nil }
go
func (heap *FloatingFibonacciHeap) DecreaseKey(node *Entry, newPriority float64) (*Entry, error) { if heap.IsEmpty() { return nil, EmptyHeapError("Cannot decrease key in an empty heap") } if node == nil { return nil, NilError("Cannot decrease key: given node is nil") } if newPriority >= node.Priority { return nil, fmt.Errorf("The given new priority: %v, is larger than or equal to the old: %v", newPriority, node.Priority) } decreaseKeyUnchecked(heap, node, newPriority) return node, nil }
[ "func", "(", "heap", "*", "FloatingFibonacciHeap", ")", "DecreaseKey", "(", "node", "*", "Entry", ",", "newPriority", "float64", ")", "(", "*", "Entry", ",", "error", ")", "{", "if", "heap", ".", "IsEmpty", "(", ")", "{", "return", "nil", ",", "EmptyHe...
// DecreaseKey decreases the key of the given element, sets it to the new // given priority and returns the node if successfully set
[ "DecreaseKey", "decreases", "the", "key", "of", "the", "given", "element", "sets", "it", "to", "the", "new", "given", "priority", "and", "returns", "the", "node", "if", "successfully", "set" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/fibheap/fibheap.go#L251-L268
train
Workiva/go-datastructures
fibheap/fibheap.go
Delete
func (heap *FloatingFibonacciHeap) Delete(node *Entry) error { if heap.IsEmpty() { return EmptyHeapError("Cannot delete element from an empty heap") } if node == nil { return NilError("Cannot delete node: given node is nil") } decreaseKeyUnchecked(heap, node, -math.MaxFloat64) heap.DequeueMin() return nil }
go
func (heap *FloatingFibonacciHeap) Delete(node *Entry) error { if heap.IsEmpty() { return EmptyHeapError("Cannot delete element from an empty heap") } if node == nil { return NilError("Cannot delete node: given node is nil") } decreaseKeyUnchecked(heap, node, -math.MaxFloat64) heap.DequeueMin() return nil }
[ "func", "(", "heap", "*", "FloatingFibonacciHeap", ")", "Delete", "(", "node", "*", "Entry", ")", "error", "{", "if", "heap", ".", "IsEmpty", "(", ")", "{", "return", "EmptyHeapError", "(", "\"Cannot delete element from an empty heap\"", ")", "\n", "}", "\n", ...
// Delete deletes the given element in the heap
[ "Delete", "deletes", "the", "given", "element", "in", "the", "heap" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/fibheap/fibheap.go#L271-L284
train
Workiva/go-datastructures
fibheap/fibheap.go
Merge
func (heap *FloatingFibonacciHeap) Merge(other *FloatingFibonacciHeap) (FloatingFibonacciHeap, error) { if heap == nil || other == nil { return FloatingFibonacciHeap{}, NilError("One of the heaps to merge is nil. Cannot merge") } resultSize := heap.size + other.size resultMin := mergeLists(heap.min, other.min) heap.min = nil other.min = nil heap.size = 0 other.size = 0 return FloatingFibonacciHeap{resultMin, resultSize}, nil }
go
func (heap *FloatingFibonacciHeap) Merge(other *FloatingFibonacciHeap) (FloatingFibonacciHeap, error) { if heap == nil || other == nil { return FloatingFibonacciHeap{}, NilError("One of the heaps to merge is nil. Cannot merge") } resultSize := heap.size + other.size resultMin := mergeLists(heap.min, other.min) heap.min = nil other.min = nil heap.size = 0 other.size = 0 return FloatingFibonacciHeap{resultMin, resultSize}, nil }
[ "func", "(", "heap", "*", "FloatingFibonacciHeap", ")", "Merge", "(", "other", "*", "FloatingFibonacciHeap", ")", "(", "FloatingFibonacciHeap", ",", "error", ")", "{", "if", "heap", "==", "nil", "||", "other", "==", "nil", "{", "return", "FloatingFibonacciHeap...
// Merge returns a new Fibonacci heap that contains // all of the elements of the two heaps. Each of the input heaps is // destructively modified by having all its elements removed. You can // continue to use those heaps, but be aware that they will be empty // after this call completes.
[ "Merge", "returns", "a", "new", "Fibonacci", "heap", "that", "contains", "all", "of", "the", "elements", "of", "the", "two", "heaps", ".", "Each", "of", "the", "input", "heaps", "is", "destructively", "modified", "by", "having", "all", "its", "elements", "...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/fibheap/fibheap.go#L291-L307
train
Workiva/go-datastructures
batcher/batcher.go
Put
func (b *basicBatcher) Put(item interface{}) error { b.lock.Lock() if b.disposed { b.lock.Unlock() return ErrDisposed } b.items = append(b.items, item) if b.calculateBytes != nil { b.availableBytes += b.calculateBytes(item) } if b.ready() { // To guarantee ordering this MUST be in the lock, otherwise multiple // flush calls could be blocked at the same time, in which case // there's no guarantee each batch is placed into the channel in // the proper order b.flush() } b.lock.Unlock() return nil }
go
func (b *basicBatcher) Put(item interface{}) error { b.lock.Lock() if b.disposed { b.lock.Unlock() return ErrDisposed } b.items = append(b.items, item) if b.calculateBytes != nil { b.availableBytes += b.calculateBytes(item) } if b.ready() { // To guarantee ordering this MUST be in the lock, otherwise multiple // flush calls could be blocked at the same time, in which case // there's no guarantee each batch is placed into the channel in // the proper order b.flush() } b.lock.Unlock() return nil }
[ "func", "(", "b", "*", "basicBatcher", ")", "Put", "(", "item", "interface", "{", "}", ")", "error", "{", "b", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "b", ".", "disposed", "{", "b", ".", "lock", ".", "Unlock", "(", ")", "\n", "return",...
// Put adds items to the batcher.
[ "Put", "adds", "items", "to", "the", "batcher", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/batcher/batcher.go#L121-L142
train
Workiva/go-datastructures
batcher/batcher.go
Get
func (b *basicBatcher) Get() ([]interface{}, error) { // Don't check disposed yet so any items remaining in the queue // will be returned properly. var timeout <-chan time.Time if b.maxTime > 0 { timeout = time.After(b.maxTime) } select { case items, ok := <-b.batchChan: // If there's something on the batch channel, we definitely want that. if !ok { return nil, ErrDisposed } return items, nil case <-timeout: // It's possible something was added to the channel after something // was received on the timeout channel, in which case that must // be returned first to satisfy our ordering guarantees. // We can't just grab the lock here in case the batch channel is full, // in which case a Put or Flush will be blocked and holding // onto the lock. In that case, there should be something on the // batch channel for { if b.lock.TryLock() { // We have a lock, try to read from channel first in case // something snuck in select { case items, ok := <-b.batchChan: b.lock.Unlock() if !ok { return nil, ErrDisposed } return items, nil default: } // If that is unsuccessful, nothing was added to the channel, // and the temp buffer can't have changed because of the lock, // so grab that items := b.items b.items = make([]interface{}, 0, b.maxItems) b.availableBytes = 0 b.lock.Unlock() return items, nil } else { // If we didn't get a lock, there are two cases: // 1) The batch chan is full. // 2) A Put or Flush temporarily has the lock. // In either case, trying to read something off the batch chan, // and going back to trying to get a lock if unsuccessful // works. select { case items, ok := <-b.batchChan: if !ok { return nil, ErrDisposed } return items, nil default: } } } } }
go
func (b *basicBatcher) Get() ([]interface{}, error) { // Don't check disposed yet so any items remaining in the queue // will be returned properly. var timeout <-chan time.Time if b.maxTime > 0 { timeout = time.After(b.maxTime) } select { case items, ok := <-b.batchChan: // If there's something on the batch channel, we definitely want that. if !ok { return nil, ErrDisposed } return items, nil case <-timeout: // It's possible something was added to the channel after something // was received on the timeout channel, in which case that must // be returned first to satisfy our ordering guarantees. // We can't just grab the lock here in case the batch channel is full, // in which case a Put or Flush will be blocked and holding // onto the lock. In that case, there should be something on the // batch channel for { if b.lock.TryLock() { // We have a lock, try to read from channel first in case // something snuck in select { case items, ok := <-b.batchChan: b.lock.Unlock() if !ok { return nil, ErrDisposed } return items, nil default: } // If that is unsuccessful, nothing was added to the channel, // and the temp buffer can't have changed because of the lock, // so grab that items := b.items b.items = make([]interface{}, 0, b.maxItems) b.availableBytes = 0 b.lock.Unlock() return items, nil } else { // If we didn't get a lock, there are two cases: // 1) The batch chan is full. // 2) A Put or Flush temporarily has the lock. // In either case, trying to read something off the batch chan, // and going back to trying to get a lock if unsuccessful // works. select { case items, ok := <-b.batchChan: if !ok { return nil, ErrDisposed } return items, nil default: } } } } }
[ "func", "(", "b", "*", "basicBatcher", ")", "Get", "(", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "var", "timeout", "<-", "chan", "time", ".", "Time", "\n", "if", "b", ".", "maxTime", ">", "0", "{", "timeout", "=", "tim...
// Get retrieves a batch from the batcher. This call will block until // one of the conditions for a "complete" batch is reached.
[ "Get", "retrieves", "a", "batch", "from", "the", "batcher", ".", "This", "call", "will", "block", "until", "one", "of", "the", "conditions", "for", "a", "complete", "batch", "is", "reached", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/batcher/batcher.go#L146-L210
train
Workiva/go-datastructures
batcher/batcher.go
Flush
func (b *basicBatcher) Flush() error { // This is the same pattern as a Put b.lock.Lock() if b.disposed { b.lock.Unlock() return ErrDisposed } b.flush() b.lock.Unlock() return nil }
go
func (b *basicBatcher) Flush() error { // This is the same pattern as a Put b.lock.Lock() if b.disposed { b.lock.Unlock() return ErrDisposed } b.flush() b.lock.Unlock() return nil }
[ "func", "(", "b", "*", "basicBatcher", ")", "Flush", "(", ")", "error", "{", "b", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "b", ".", "disposed", "{", "b", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "ErrDisposed", "\n", "}", "\...
// Flush forcibly completes the batch currently being built
[ "Flush", "forcibly", "completes", "the", "batch", "currently", "being", "built" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/batcher/batcher.go#L213-L223
train
Workiva/go-datastructures
batcher/batcher.go
Dispose
func (b *basicBatcher) Dispose() { for { if b.lock.TryLock() { // We've got a lock if b.disposed { b.lock.Unlock() return } b.disposed = true b.items = nil b.drainBatchChan() close(b.batchChan) b.lock.Unlock() } else { // Two cases here: // 1) Something is blocked and holding onto the lock // 2) Something temporarily has a lock // For case 1, we have to clear at least some space so the blocked // Put/Flush can release the lock. For case 2, nothing bad // will happen here b.drainBatchChan() } } }
go
func (b *basicBatcher) Dispose() { for { if b.lock.TryLock() { // We've got a lock if b.disposed { b.lock.Unlock() return } b.disposed = true b.items = nil b.drainBatchChan() close(b.batchChan) b.lock.Unlock() } else { // Two cases here: // 1) Something is blocked and holding onto the lock // 2) Something temporarily has a lock // For case 1, we have to clear at least some space so the blocked // Put/Flush can release the lock. For case 2, nothing bad // will happen here b.drainBatchChan() } } }
[ "func", "(", "b", "*", "basicBatcher", ")", "Dispose", "(", ")", "{", "for", "{", "if", "b", ".", "lock", ".", "TryLock", "(", ")", "{", "if", "b", ".", "disposed", "{", "b", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\...
// Dispose will dispose of the batcher. Any calls to Put or Flush // will return ErrDisposed, calls to Get will return an error iff // there are no more ready batches. Any items not flushed and retrieved // by a Get may or may not be retrievable after calling this.
[ "Dispose", "will", "dispose", "of", "the", "batcher", ".", "Any", "calls", "to", "Put", "or", "Flush", "will", "return", "ErrDisposed", "calls", "to", "Get", "will", "return", "an", "error", "iff", "there", "are", "no", "more", "ready", "batches", ".", "...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/batcher/batcher.go#L229-L254
train
Workiva/go-datastructures
batcher/batcher.go
IsDisposed
func (b *basicBatcher) IsDisposed() bool { b.lock.Lock() disposed := b.disposed b.lock.Unlock() return disposed }
go
func (b *basicBatcher) IsDisposed() bool { b.lock.Lock() disposed := b.disposed b.lock.Unlock() return disposed }
[ "func", "(", "b", "*", "basicBatcher", ")", "IsDisposed", "(", ")", "bool", "{", "b", ".", "lock", ".", "Lock", "(", ")", "\n", "disposed", ":=", "b", ".", "disposed", "\n", "b", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "disposed", "...
// IsDisposed will determine if the batcher is disposed
[ "IsDisposed", "will", "determine", "if", "the", "batcher", "is", "disposed" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/batcher/batcher.go#L257-L262
train
Workiva/go-datastructures
batcher/batcher.go
flush
func (b *basicBatcher) flush() { b.batchChan <- b.items b.items = make([]interface{}, 0, b.maxItems) b.availableBytes = 0 }
go
func (b *basicBatcher) flush() { b.batchChan <- b.items b.items = make([]interface{}, 0, b.maxItems) b.availableBytes = 0 }
[ "func", "(", "b", "*", "basicBatcher", ")", "flush", "(", ")", "{", "b", ".", "batchChan", "<-", "b", ".", "items", "\n", "b", ".", "items", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "b", ".", "maxItems", ")", "\n", "b...
// flush adds the batch currently being built to the queue of completed batches. // flush is not threadsafe, so should be synchronized externally.
[ "flush", "adds", "the", "batch", "currently", "being", "built", "to", "the", "queue", "of", "completed", "batches", ".", "flush", "is", "not", "threadsafe", "so", "should", "be", "synchronized", "externally", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/batcher/batcher.go#L266-L270
train
Workiva/go-datastructures
bitarray/iterator.go
Value
func (iter *sparseBitArrayIterator) Value() (uint64, block) { return iter.sba.indices[iter.index], iter.sba.blocks[iter.index] }
go
func (iter *sparseBitArrayIterator) Value() (uint64, block) { return iter.sba.indices[iter.index], iter.sba.blocks[iter.index] }
[ "func", "(", "iter", "*", "sparseBitArrayIterator", ")", "Value", "(", ")", "(", "uint64", ",", "block", ")", "{", "return", "iter", ".", "sba", ".", "indices", "[", "iter", ".", "index", "]", ",", "iter", ".", "sba", ".", "blocks", "[", "iter", "....
// Value returns the index and block at the given index.
[ "Value", "returns", "the", "index", "and", "block", "at", "the", "given", "index", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/iterator.go#L32-L34
train
Workiva/go-datastructures
bitarray/iterator.go
Value
func (iter *bitArrayIterator) Value() (uint64, block) { return uint64(iter.index), iter.ba.blocks[iter.index] }
go
func (iter *bitArrayIterator) Value() (uint64, block) { return uint64(iter.index), iter.ba.blocks[iter.index] }
[ "func", "(", "iter", "*", "bitArrayIterator", ")", "Value", "(", ")", "(", "uint64", ",", "block", ")", "{", "return", "uint64", "(", "iter", ".", "index", ")", ",", "iter", ".", "ba", ".", "blocks", "[", "iter", ".", "index", "]", "\n", "}" ]
// Value returns an index and the block at this index.
[ "Value", "returns", "an", "index", "and", "the", "block", "at", "this", "index", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/bitarray/iterator.go#L57-L59
train
Workiva/go-datastructures
rangetree/entries.go
Dispose
func (entries *Entries) Dispose() { for i := 0; i < len(*entries); i++ { (*entries)[i] = nil } *entries = (*entries)[:0] entriesPool.Put(*entries) }
go
func (entries *Entries) Dispose() { for i := 0; i < len(*entries); i++ { (*entries)[i] = nil } *entries = (*entries)[:0] entriesPool.Put(*entries) }
[ "func", "(", "entries", "*", "Entries", ")", "Dispose", "(", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "*", "entries", ")", ";", "i", "++", "{", "(", "*", "entries", ")", "[", "i", "]", "=", "nil", "\n", "}", "\n", "*", ...
// Dispose will free the resources consumed by this list and // allow the list to be reused.
[ "Dispose", "will", "free", "the", "resources", "consumed", "by", "this", "list", "and", "allow", "the", "list", "to", "be", "reused", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/rangetree/entries.go#L33-L40
train
Workiva/go-datastructures
tree/avl/node.go
copy
func (n *node) copy() *node { return &node{ balance: n.balance, children: [2]*node{n.children[0], n.children[1]}, entry: n.entry, } }
go
func (n *node) copy() *node { return &node{ balance: n.balance, children: [2]*node{n.children[0], n.children[1]}, entry: n.entry, } }
[ "func", "(", "n", "*", "node", ")", "copy", "(", ")", "*", "node", "{", "return", "&", "node", "{", "balance", ":", "n", ".", "balance", ",", "children", ":", "[", "2", "]", "*", "node", "{", "n", ".", "children", "[", "0", "]", ",", "n", "...
// copy returns a copy of this node with pointers to the original // children.
[ "copy", "returns", "a", "copy", "of", "this", "node", "with", "pointers", "to", "the", "original", "children", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/tree/avl/node.go#L35-L41
train
Workiva/go-datastructures
tree/avl/avl.go
copy
func (immutable *Immutable) copy() *Immutable { var root *node if immutable.root != nil { root = immutable.root.copy() } cp := &Immutable{ root: root, number: immutable.number, dummy: *newNode(nil), } return cp }
go
func (immutable *Immutable) copy() *Immutable { var root *node if immutable.root != nil { root = immutable.root.copy() } cp := &Immutable{ root: root, number: immutable.number, dummy: *newNode(nil), } return cp }
[ "func", "(", "immutable", "*", "Immutable", ")", "copy", "(", ")", "*", "Immutable", "{", "var", "root", "*", "node", "\n", "if", "immutable", ".", "root", "!=", "nil", "{", "root", "=", "immutable", ".", "root", ".", "copy", "(", ")", "\n", "}", ...
// copy returns a copy of this immutable tree with a copy // of the root and a new dummy helper for the insertion operation.
[ "copy", "returns", "a", "copy", "of", "this", "immutable", "tree", "with", "a", "copy", "of", "the", "root", "and", "a", "new", "dummy", "helper", "for", "the", "insertion", "operation", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/tree/avl/avl.go#L47-L58
train
Workiva/go-datastructures
tree/avl/avl.go
Get
func (immutable *Immutable) Get(entries ...Entry) Entries { result := make(Entries, 0, len(entries)) for _, e := range entries { result = append(result, immutable.get(e)) } return result }
go
func (immutable *Immutable) Get(entries ...Entry) Entries { result := make(Entries, 0, len(entries)) for _, e := range entries { result = append(result, immutable.get(e)) } return result }
[ "func", "(", "immutable", "*", "Immutable", ")", "Get", "(", "entries", "...", "Entry", ")", "Entries", "{", "result", ":=", "make", "(", "Entries", ",", "0", ",", "len", "(", "entries", ")", ")", "\n", "for", "_", ",", "e", ":=", "range", "entries...
// Get will get the provided Entries from the tree. If no matching // Entry is found, a nil is returned in its place.
[ "Get", "will", "get", "the", "provided", "Entries", "from", "the", "tree", ".", "If", "no", "matching", "Entry", "is", "found", "a", "nil", "is", "returned", "in", "its", "place", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/tree/avl/avl.go#L90-L97
train
Workiva/go-datastructures
tree/avl/avl.go
Insert
func (immutable *Immutable) Insert(entries ...Entry) (*Immutable, Entries) { if len(entries) == 0 { return immutable, Entries{} } overwritten := make(Entries, 0, len(entries)) cp := immutable.copy() for _, e := range entries { overwritten = append(overwritten, cp.insert(e)) } return cp, overwritten }
go
func (immutable *Immutable) Insert(entries ...Entry) (*Immutable, Entries) { if len(entries) == 0 { return immutable, Entries{} } overwritten := make(Entries, 0, len(entries)) cp := immutable.copy() for _, e := range entries { overwritten = append(overwritten, cp.insert(e)) } return cp, overwritten }
[ "func", "(", "immutable", "*", "Immutable", ")", "Insert", "(", "entries", "...", "Entry", ")", "(", "*", "Immutable", ",", "Entries", ")", "{", "if", "len", "(", "entries", ")", "==", "0", "{", "return", "immutable", ",", "Entries", "{", "}", "\n", ...
// Insert will add the provided entries into the tree and return the new // state. Also returned is a list of Entries that were overwritten. If // nothing was overwritten for an Entry, a nil is returned in its place.
[ "Insert", "will", "add", "the", "provided", "entries", "into", "the", "tree", "and", "return", "the", "new", "state", ".", "Also", "returned", "is", "a", "list", "of", "Entries", "that", "were", "overwritten", ".", "If", "nothing", "was", "overwritten", "f...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/tree/avl/avl.go#L190-L202
train
Workiva/go-datastructures
tree/avl/avl.go
Delete
func (immutable *Immutable) Delete(entries ...Entry) (*Immutable, Entries) { if len(entries) == 0 { return immutable, Entries{} } deleted := make(Entries, 0, len(entries)) cp := immutable.copy() for _, e := range entries { deleted = append(deleted, cp.delete(e)) } return cp, deleted }
go
func (immutable *Immutable) Delete(entries ...Entry) (*Immutable, Entries) { if len(entries) == 0 { return immutable, Entries{} } deleted := make(Entries, 0, len(entries)) cp := immutable.copy() for _, e := range entries { deleted = append(deleted, cp.delete(e)) } return cp, deleted }
[ "func", "(", "immutable", "*", "Immutable", ")", "Delete", "(", "entries", "...", "Entry", ")", "(", "*", "Immutable", ",", "Entries", ")", "{", "if", "len", "(", "entries", ")", "==", "0", "{", "return", "immutable", ",", "Entries", "{", "}", "\n", ...
// Delete will remove the provided entries from this AVL tree and // return a new tree and any entries removed. If an entry could not // be found, nil is returned in its place.
[ "Delete", "will", "remove", "the", "provided", "entries", "from", "this", "AVL", "tree", "and", "return", "a", "new", "tree", "and", "any", "entries", "removed", ".", "If", "an", "entry", "could", "not", "be", "found", "nil", "is", "returned", "in", "its...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/tree/avl/avl.go#L314-L326
train
Workiva/go-datastructures
queue/ring.go
Put
func (rb *RingBuffer) Put(item interface{}) error { _, err := rb.put(item, false) return err }
go
func (rb *RingBuffer) Put(item interface{}) error { _, err := rb.put(item, false) return err }
[ "func", "(", "rb", "*", "RingBuffer", ")", "Put", "(", "item", "interface", "{", "}", ")", "error", "{", "_", ",", "err", ":=", "rb", ".", "put", "(", "item", ",", "false", ")", "\n", "return", "err", "\n", "}" ]
// Put adds the provided item to the queue. If the queue is full, this // call will block until an item is added to the queue or Dispose is called // on the queue. An error will be returned if the queue is disposed.
[ "Put", "adds", "the", "provided", "item", "to", "the", "queue", ".", "If", "the", "queue", "is", "full", "this", "call", "will", "block", "until", "an", "item", "is", "added", "to", "the", "queue", "or", "Dispose", "is", "called", "on", "the", "queue",...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/queue/ring.go#L75-L78
train
Workiva/go-datastructures
queue/ring.go
Offer
func (rb *RingBuffer) Offer(item interface{}) (bool, error) { return rb.put(item, true) }
go
func (rb *RingBuffer) Offer(item interface{}) (bool, error) { return rb.put(item, true) }
[ "func", "(", "rb", "*", "RingBuffer", ")", "Offer", "(", "item", "interface", "{", "}", ")", "(", "bool", ",", "error", ")", "{", "return", "rb", ".", "put", "(", "item", ",", "true", ")", "\n", "}" ]
// Offer adds the provided item to the queue if there is space. If the queue // is full, this call will return false. An error will be returned if the // queue is disposed.
[ "Offer", "adds", "the", "provided", "item", "to", "the", "queue", "if", "there", "is", "space", ".", "If", "the", "queue", "is", "full", "this", "call", "will", "return", "false", ".", "An", "error", "will", "be", "returned", "if", "the", "queue", "is"...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/queue/ring.go#L83-L85
train
Workiva/go-datastructures
queue/ring.go
Poll
func (rb *RingBuffer) Poll(timeout time.Duration) (interface{}, error) { var ( n *node pos = atomic.LoadUint64(&rb.dequeue) start time.Time ) if timeout > 0 { start = time.Now() } L: for { if atomic.LoadUint64(&rb.disposed) == 1 { return nil, ErrDisposed } n = rb.nodes[pos&rb.mask] seq := atomic.LoadUint64(&n.position) switch dif := seq - (pos + 1); { case dif == 0: if atomic.CompareAndSwapUint64(&rb.dequeue, pos, pos+1) { break L } case dif < 0: panic(`Ring buffer in compromised state during a get operation.`) default: pos = atomic.LoadUint64(&rb.dequeue) } if timeout > 0 && time.Since(start) >= timeout { return nil, ErrTimeout } runtime.Gosched() // free up the cpu before the next iteration } data := n.data n.data = nil atomic.StoreUint64(&n.position, pos+rb.mask+1) return data, nil }
go
func (rb *RingBuffer) Poll(timeout time.Duration) (interface{}, error) { var ( n *node pos = atomic.LoadUint64(&rb.dequeue) start time.Time ) if timeout > 0 { start = time.Now() } L: for { if atomic.LoadUint64(&rb.disposed) == 1 { return nil, ErrDisposed } n = rb.nodes[pos&rb.mask] seq := atomic.LoadUint64(&n.position) switch dif := seq - (pos + 1); { case dif == 0: if atomic.CompareAndSwapUint64(&rb.dequeue, pos, pos+1) { break L } case dif < 0: panic(`Ring buffer in compromised state during a get operation.`) default: pos = atomic.LoadUint64(&rb.dequeue) } if timeout > 0 && time.Since(start) >= timeout { return nil, ErrTimeout } runtime.Gosched() // free up the cpu before the next iteration } data := n.data n.data = nil atomic.StoreUint64(&n.position, pos+rb.mask+1) return data, nil }
[ "func", "(", "rb", "*", "RingBuffer", ")", "Poll", "(", "timeout", "time", ".", "Duration", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "(", "n", "*", "node", "\n", "pos", "=", "atomic", ".", "LoadUint64", "(", "&", "rb", ".",...
// Poll will return the next item in the queue. This call will block // if the queue is empty. This call will unblock when an item is added // to the queue, Dispose is called on the queue, or the timeout is reached. An // error will be returned if the queue is disposed or a timeout occurs. A // non-positive timeout will block indefinitely.
[ "Poll", "will", "return", "the", "next", "item", "in", "the", "queue", ".", "This", "call", "will", "block", "if", "the", "queue", "is", "empty", ".", "This", "call", "will", "unblock", "when", "an", "item", "is", "added", "to", "the", "queue", "Dispos...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/queue/ring.go#L134-L172
train
Workiva/go-datastructures
queue/ring.go
Len
func (rb *RingBuffer) Len() uint64 { return atomic.LoadUint64(&rb.queue) - atomic.LoadUint64(&rb.dequeue) }
go
func (rb *RingBuffer) Len() uint64 { return atomic.LoadUint64(&rb.queue) - atomic.LoadUint64(&rb.dequeue) }
[ "func", "(", "rb", "*", "RingBuffer", ")", "Len", "(", ")", "uint64", "{", "return", "atomic", ".", "LoadUint64", "(", "&", "rb", ".", "queue", ")", "-", "atomic", ".", "LoadUint64", "(", "&", "rb", ".", "dequeue", ")", "\n", "}" ]
// Len returns the number of items in the queue.
[ "Len", "returns", "the", "number", "of", "items", "in", "the", "queue", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/queue/ring.go#L175-L177
train
Workiva/go-datastructures
queue/ring.go
NewRingBuffer
func NewRingBuffer(size uint64) *RingBuffer { rb := &RingBuffer{} rb.init(size) return rb }
go
func NewRingBuffer(size uint64) *RingBuffer { rb := &RingBuffer{} rb.init(size) return rb }
[ "func", "NewRingBuffer", "(", "size", "uint64", ")", "*", "RingBuffer", "{", "rb", ":=", "&", "RingBuffer", "{", "}", "\n", "rb", ".", "init", "(", "size", ")", "\n", "return", "rb", "\n", "}" ]
// NewRingBuffer will allocate, initialize, and return a ring buffer // with the specified size.
[ "NewRingBuffer", "will", "allocate", "initialize", "and", "return", "a", "ring", "buffer", "with", "the", "specified", "size", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/queue/ring.go#L199-L203
train
Workiva/go-datastructures
numerics/optimization/nelder_mead.go
generateRandomVerticesFromGuess
func generateRandomVerticesFromGuess(guess *nmVertex, num int) vertices { // summed allows us to prevent duplicate guesses, checking // all previous guesses for every guess created would be too // time consuming so we take an indexed shortcut here. summed // is a map of a sum of the vars to the vertices that have an // identical sum. In this way, we can sum the vars of a new guess // and check only a small subset of previous guesses to determine // if this is an identical guess. summed := make(map[float64]vertices, num) dimensions := len(guess.vars) vs := make(vertices, 0, num) i := 0 r := rand.New(rand.NewSource(time.Now().UnixNano())) Guess: for i < num { sum := float64(0) vars := make([]float64, 0, dimensions) for j := 0; j < dimensions; j++ { v := r.Float64() * 1000 // we do a separate random check here to determine // sign so we don't end up with all high v's one sign // and low v's another if r.Float64() > .5 { v = -v } sum += v vars = append(vars, v) } guess := &nmVertex{ vars: vars, } if vs, ok := summed[sum]; !ok { vs = make(vertices, 0, dimensions) // dimensions is really just a guess, no real way of knowing what this is vs = append(vs, guess) summed[sum] = vs } else { for _, vertex := range vs { // if we've already guessed this, try the loop again if guess.equalToVertex(vertex) { continue Guess } } vs = append(vs, guess) } vs = append(vs, guess) i++ } return vs }
go
func generateRandomVerticesFromGuess(guess *nmVertex, num int) vertices { // summed allows us to prevent duplicate guesses, checking // all previous guesses for every guess created would be too // time consuming so we take an indexed shortcut here. summed // is a map of a sum of the vars to the vertices that have an // identical sum. In this way, we can sum the vars of a new guess // and check only a small subset of previous guesses to determine // if this is an identical guess. summed := make(map[float64]vertices, num) dimensions := len(guess.vars) vs := make(vertices, 0, num) i := 0 r := rand.New(rand.NewSource(time.Now().UnixNano())) Guess: for i < num { sum := float64(0) vars := make([]float64, 0, dimensions) for j := 0; j < dimensions; j++ { v := r.Float64() * 1000 // we do a separate random check here to determine // sign so we don't end up with all high v's one sign // and low v's another if r.Float64() > .5 { v = -v } sum += v vars = append(vars, v) } guess := &nmVertex{ vars: vars, } if vs, ok := summed[sum]; !ok { vs = make(vertices, 0, dimensions) // dimensions is really just a guess, no real way of knowing what this is vs = append(vs, guess) summed[sum] = vs } else { for _, vertex := range vs { // if we've already guessed this, try the loop again if guess.equalToVertex(vertex) { continue Guess } } vs = append(vs, guess) } vs = append(vs, guess) i++ } return vs }
[ "func", "generateRandomVerticesFromGuess", "(", "guess", "*", "nmVertex", ",", "num", "int", ")", "vertices", "{", "summed", ":=", "make", "(", "map", "[", "float64", "]", "vertices", ",", "num", ")", "\n", "dimensions", ":=", "len", "(", "guess", ".", "...
// generateRandomVerticesFromGuess will generate num number of vertices // with random
[ "generateRandomVerticesFromGuess", "will", "generate", "num", "number", "of", "vertices", "with", "random" ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/nelder_mead.go#L29-L82
train
Workiva/go-datastructures
numerics/optimization/nelder_mead.go
findMidpoint
func findMidpoint(vertices ...*nmVertex) *nmVertex { num := len(vertices) // this is what we divide by vars := make([]float64, 0, num) for i := 0; i < num; i++ { sum := float64(0) for _, v := range vertices { sum += v.vars[i] } vars = append(vars, sum/float64(num)) } return &nmVertex{ vars: vars, } }
go
func findMidpoint(vertices ...*nmVertex) *nmVertex { num := len(vertices) // this is what we divide by vars := make([]float64, 0, num) for i := 0; i < num; i++ { sum := float64(0) for _, v := range vertices { sum += v.vars[i] } vars = append(vars, sum/float64(num)) } return &nmVertex{ vars: vars, } }
[ "func", "findMidpoint", "(", "vertices", "...", "*", "nmVertex", ")", "*", "nmVertex", "{", "num", ":=", "len", "(", "vertices", ")", "\n", "vars", ":=", "make", "(", "[", "]", "float64", ",", "0", ",", "num", ")", "\n", "for", "i", ":=", "0", ";...
// findMidpoint will find the midpoint of the provided vertices // and return a new vertex.
[ "findMidpoint", "will", "find", "the", "midpoint", "of", "the", "provided", "vertices", "and", "return", "a", "new", "vertex", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/nelder_mead.go#L101-L116
train
Workiva/go-datastructures
numerics/optimization/nelder_mead.go
evaluate
func (vertices vertices) evaluate(config NelderMeadConfiguration) { for _, v := range vertices { v.evaluate(config) } vertices.sort(config) }
go
func (vertices vertices) evaluate(config NelderMeadConfiguration) { for _, v := range vertices { v.evaluate(config) } vertices.sort(config) }
[ "func", "(", "vertices", "vertices", ")", "evaluate", "(", "config", "NelderMeadConfiguration", ")", "{", "for", "_", ",", "v", ":=", "range", "vertices", "{", "v", ".", "evaluate", "(", "config", ")", "\n", "}", "\n", "vertices", ".", "sort", "(", "co...
// evaluate will call evaluate on all the verticies in this list // and order them by distance to target.
[ "evaluate", "will", "call", "evaluate", "on", "all", "the", "verticies", "in", "this", "list", "and", "order", "them", "by", "distance", "to", "target", "." ]
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/nelder_mead.go#L135-L141
train
Workiva/go-datastructures
numerics/optimization/nelder_mead.go
Less
func (sorter sorter) Less(i, j int) bool { return sorter.vertices[i].less(sorter.config, sorter.vertices[j]) }
go
func (sorter sorter) Less(i, j int) bool { return sorter.vertices[i].less(sorter.config, sorter.vertices[j]) }
[ "func", "(", "sorter", "sorter", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "sorter", ".", "vertices", "[", "i", "]", ".", "less", "(", "sorter", ".", "config", ",", "sorter", ".", "vertices", "[", "j", "]", ")", "\n", ...
// the following methods are required for sort.Interface. We // use the standard libraries sort here as it uses an adaptive // sort and we really don't expect there to be a ton of dimensions // here so mulithreaded sort in this repo really isn't // necessary.
[ "the", "following", "methods", "are", "required", "for", "sort", ".", "Interface", ".", "We", "use", "the", "standard", "libraries", "sort", "here", "as", "it", "uses", "an", "adaptive", "sort", "and", "we", "really", "don", "t", "expect", "there", "to", ...
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/nelder_mead.go#L166-L168
train