id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
9,900
koding/cache
lfu_nots.go
NewLFUNoTS
func NewLFUNoTS(size int) Cache { if size < 1 { panic("invalid cache size") } return &LFUNoTS{ frequencyList: list.New(), cache: NewMemoryNoTS(), size: size, currentSize: 0, } }
go
func NewLFUNoTS(size int) Cache { if size < 1 { panic("invalid cache size") } return &LFUNoTS{ frequencyList: list.New(), cache: NewMemoryNoTS(), size: size, currentSize: 0, } }
[ "func", "NewLFUNoTS", "(", "size", "int", ")", "Cache", "{", "if", "size", "<", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "LFUNoTS", "{", "frequencyList", ":", "list", ".", "New", "(", ")", ",", "cache", ":", "New...
// NewLFUNoTS creates a new LFU cache struct for further cache operations. Size // is used for limiting the upper bound of the cache
[ "NewLFUNoTS", "creates", "a", "new", "LFU", "cache", "struct", "for", "further", "cache", "operations", ".", "Size", "is", "used", "for", "limiting", "the", "upper", "bound", "of", "the", "cache" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L38-L49
9,901
koding/cache
lfu_nots.go
Get
func (l *LFUNoTS) Get(key string) (interface{}, error) { res, err := l.cache.Get(key) if err != nil { return nil, err } ci := res.(*cacheItem) // increase usage of cache item l.incr(ci) return ci.v, nil }
go
func (l *LFUNoTS) Get(key string) (interface{}, error) { res, err := l.cache.Get(key) if err != nil { return nil, err } ci := res.(*cacheItem) // increase usage of cache item l.incr(ci) return ci.v, nil }
[ "func", "(", "l", "*", "LFUNoTS", ")", "Get", "(", "key", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "res", ",", "err", ":=", "l", ".", "cache", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// Get gets value of cache item // then increments the usage of the item
[ "Get", "gets", "value", "of", "cache", "item", "then", "increments", "the", "usage", "of", "the", "item" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L53-L64
9,902
koding/cache
lfu_nots.go
Delete
func (l *LFUNoTS) Delete(key string) error { res, err := l.cache.Get(key) if err != nil && err != ErrNotFound { return err } // we dont need to delete if already doesn't exist if err == ErrNotFound { return nil } ci := res.(*cacheItem) l.remove(ci, ci.freqElement) l.currentSize-- return l.cache.Delete(key) }
go
func (l *LFUNoTS) Delete(key string) error { res, err := l.cache.Get(key) if err != nil && err != ErrNotFound { return err } // we dont need to delete if already doesn't exist if err == ErrNotFound { return nil } ci := res.(*cacheItem) l.remove(ci, ci.freqElement) l.currentSize-- return l.cache.Delete(key) }
[ "func", "(", "l", "*", "LFUNoTS", ")", "Delete", "(", "key", "string", ")", "error", "{", "res", ",", "err", ":=", "l", ".", "cache", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ErrNotFound", "{", "return", ...
// Delete deletes the key and its dependencies
[ "Delete", "deletes", "the", "key", "and", "its", "dependencies" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L80-L96
9,903
koding/cache
lfu_nots.go
set
func (l *LFUNoTS) set(key string, value interface{}) error { res, err := l.cache.Get(key) if err != nil && err != ErrNotFound { return err } if err == ErrNotFound { //create new cache item ci := newCacheItem(key, value) // if cache size si reached to max size // then first remove lfu item from the list if l.currentSize >= l.size { // then evict some data from head of linked list. l.evict(l.frequencyList.Front()) } l.cache.Set(key, ci) l.incr(ci) } else { //update existing one val := res.(*cacheItem) val.v = value l.cache.Set(key, val) l.incr(res.(*cacheItem)) } return nil }
go
func (l *LFUNoTS) set(key string, value interface{}) error { res, err := l.cache.Get(key) if err != nil && err != ErrNotFound { return err } if err == ErrNotFound { //create new cache item ci := newCacheItem(key, value) // if cache size si reached to max size // then first remove lfu item from the list if l.currentSize >= l.size { // then evict some data from head of linked list. l.evict(l.frequencyList.Front()) } l.cache.Set(key, ci) l.incr(ci) } else { //update existing one val := res.(*cacheItem) val.v = value l.cache.Set(key, val) l.incr(res.(*cacheItem)) } return nil }
[ "func", "(", "l", "*", "LFUNoTS", ")", "set", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "res", ",", "err", ":=", "l", ".", "cache", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "&&", "err", ...
// set sets a new key-value pair
[ "set", "sets", "a", "new", "key", "-", "value", "pair" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L99-L128
9,904
koding/cache
lfu_nots.go
incr
func (l *LFUNoTS) incr(ci *cacheItem) { var nextValue int var nextPosition *list.Element // update existing one if ci.freqElement != nil { nextValue = ci.freqElement.Value.(*entry).freqCount + 1 // replace the position of frequency element nextPosition = ci.freqElement.Next() } else { // create new frequency element for cache item // ci.freqElement is nil so next value of freq will be 1 nextValue = 1 // we created new element and its position will be head of linked list nextPosition = l.frequencyList.Front() l.currentSize++ } // we need to check position first, otherwise it will panic if we try to fetch value of entry if nextPosition == nil || nextPosition.Value.(*entry).freqCount != nextValue { // create new entry node for linked list entry := newEntry(nextValue) if ci.freqElement == nil { nextPosition = l.frequencyList.PushFront(entry) } else { nextPosition = l.frequencyList.InsertAfter(entry, ci.freqElement) } } nextPosition.Value.(*entry).listEntry[ci] = struct{}{} ci.freqElement = nextPosition // we have moved the cache item to the next position, // then we need to remove old position of the cacheItem from the list // then we deleted previous position of cacheItem if ci.freqElement.Prev() != nil { l.remove(ci, ci.freqElement.Prev()) } }
go
func (l *LFUNoTS) incr(ci *cacheItem) { var nextValue int var nextPosition *list.Element // update existing one if ci.freqElement != nil { nextValue = ci.freqElement.Value.(*entry).freqCount + 1 // replace the position of frequency element nextPosition = ci.freqElement.Next() } else { // create new frequency element for cache item // ci.freqElement is nil so next value of freq will be 1 nextValue = 1 // we created new element and its position will be head of linked list nextPosition = l.frequencyList.Front() l.currentSize++ } // we need to check position first, otherwise it will panic if we try to fetch value of entry if nextPosition == nil || nextPosition.Value.(*entry).freqCount != nextValue { // create new entry node for linked list entry := newEntry(nextValue) if ci.freqElement == nil { nextPosition = l.frequencyList.PushFront(entry) } else { nextPosition = l.frequencyList.InsertAfter(entry, ci.freqElement) } } nextPosition.Value.(*entry).listEntry[ci] = struct{}{} ci.freqElement = nextPosition // we have moved the cache item to the next position, // then we need to remove old position of the cacheItem from the list // then we deleted previous position of cacheItem if ci.freqElement.Prev() != nil { l.remove(ci, ci.freqElement.Prev()) } }
[ "func", "(", "l", "*", "LFUNoTS", ")", "incr", "(", "ci", "*", "cacheItem", ")", "{", "var", "nextValue", "int", "\n", "var", "nextPosition", "*", "list", ".", "Element", "\n", "// update existing one", "if", "ci", ".", "freqElement", "!=", "nil", "{", ...
// incr increments the usage of cache items // incrementing will be used in 'Get' & 'Set' functions // whenever these functions are used, usage count of any key // will be increased
[ "incr", "increments", "the", "usage", "of", "cache", "items", "incrementing", "will", "be", "used", "in", "Get", "&", "Set", "functions", "whenever", "these", "functions", "are", "used", "usage", "count", "of", "any", "key", "will", "be", "increased" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L143-L180
9,905
koding/cache
lfu_nots.go
remove
func (l *LFUNoTS) remove(ci *cacheItem, position *list.Element) { entry := position.Value.(*entry).listEntry delete(entry, ci) if len(entry) == 0 { l.frequencyList.Remove(position) } }
go
func (l *LFUNoTS) remove(ci *cacheItem, position *list.Element) { entry := position.Value.(*entry).listEntry delete(entry, ci) if len(entry) == 0 { l.frequencyList.Remove(position) } }
[ "func", "(", "l", "*", "LFUNoTS", ")", "remove", "(", "ci", "*", "cacheItem", ",", "position", "*", "list", ".", "Element", ")", "{", "entry", ":=", "position", ".", "Value", ".", "(", "*", "entry", ")", ".", "listEntry", "\n", "delete", "(", "entr...
// remove removes the cache item from the cache list // after deleting key from the list, if its linked list has no any item no longer // then that linked list elemnet will be removed from the list too
[ "remove", "removes", "the", "cache", "item", "from", "the", "cache", "list", "after", "deleting", "key", "from", "the", "list", "if", "its", "linked", "list", "has", "no", "any", "item", "no", "longer", "then", "that", "linked", "list", "elemnet", "will", ...
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L185-L191
9,906
koding/cache
lfu_nots.go
evict
func (l *LFUNoTS) evict(e *list.Element) error { // ne need to return err if list element is already nil if e == nil { return nil } // remove the first item of the linked list for entry := range e.Value.(*entry).listEntry { l.cache.Delete(entry.k) l.remove(entry, e) l.currentSize-- break } return nil }
go
func (l *LFUNoTS) evict(e *list.Element) error { // ne need to return err if list element is already nil if e == nil { return nil } // remove the first item of the linked list for entry := range e.Value.(*entry).listEntry { l.cache.Delete(entry.k) l.remove(entry, e) l.currentSize-- break } return nil }
[ "func", "(", "l", "*", "LFUNoTS", ")", "evict", "(", "e", "*", "list", ".", "Element", ")", "error", "{", "// ne need to return err if list element is already nil", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// remove the first item of the...
// evict deletes the element from list with given linked list element
[ "evict", "deletes", "the", "element", "from", "list", "with", "given", "linked", "list", "element" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L194-L209
9,907
koding/cache
lfu_nots.go
newEntry
func newEntry(freqCount int) *entry { return &entry{ freqCount: freqCount, listEntry: make(map[*cacheItem]struct{}), } }
go
func newEntry(freqCount int) *entry { return &entry{ freqCount: freqCount, listEntry: make(map[*cacheItem]struct{}), } }
[ "func", "newEntry", "(", "freqCount", "int", ")", "*", "entry", "{", "return", "&", "entry", "{", "freqCount", ":", "freqCount", ",", "listEntry", ":", "make", "(", "map", "[", "*", "cacheItem", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// newEntry creates a new entry with frequency count
[ "newEntry", "creates", "a", "new", "entry", "with", "frequency", "count" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L212-L217
9,908
koding/cache
lfu_nots.go
newCacheItem
func newCacheItem(key string, value interface{}) *cacheItem { return &cacheItem{ k: key, v: value, } }
go
func newCacheItem(key string, value interface{}) *cacheItem { return &cacheItem{ k: key, v: value, } }
[ "func", "newCacheItem", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "*", "cacheItem", "{", "return", "&", "cacheItem", "{", "k", ":", "key", ",", "v", ":", "value", ",", "}", "\n\n", "}" ]
// newCacheItem creates a new cache item with key and value
[ "newCacheItem", "creates", "a", "new", "cache", "item", "with", "key", "and", "value" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/lfu_nots.go#L220-L226
9,909
koding/cache
memory_ttl.go
NewMemoryWithTTL
func NewMemoryWithTTL(ttl time.Duration) *MemoryTTL { return &MemoryTTL{ cache: NewMemoryNoTS(), setAts: map[string]time.Time{}, ttl: ttl, } }
go
func NewMemoryWithTTL(ttl time.Duration) *MemoryTTL { return &MemoryTTL{ cache: NewMemoryNoTS(), setAts: map[string]time.Time{}, ttl: ttl, } }
[ "func", "NewMemoryWithTTL", "(", "ttl", "time", ".", "Duration", ")", "*", "MemoryTTL", "{", "return", "&", "MemoryTTL", "{", "cache", ":", "NewMemoryNoTS", "(", ")", ",", "setAts", ":", "map", "[", "string", "]", "time", ".", "Time", "{", "}", ",", ...
// NewMemoryWithTTL creates an inmemory cache system // Which everytime will return the true values about a cache hit // and never will leak memory // ttl is used for expiration of a key from cache
[ "NewMemoryWithTTL", "creates", "an", "inmemory", "cache", "system", "Which", "everytime", "will", "return", "the", "true", "values", "about", "a", "cache", "hit", "and", "never", "will", "leak", "memory", "ttl", "is", "used", "for", "expiration", "of", "a", ...
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/memory_ttl.go#L37-L43
9,910
koding/cache
sharded_ttl.go
NewShardedCacheWithTTL
func NewShardedCacheWithTTL(ttl time.Duration, f func() Cache) *ShardedTTL { return &ShardedTTL{ cache: NewShardedNoTS(f), setAts: map[string]map[string]time.Time{}, ttl: ttl, } }
go
func NewShardedCacheWithTTL(ttl time.Duration, f func() Cache) *ShardedTTL { return &ShardedTTL{ cache: NewShardedNoTS(f), setAts: map[string]map[string]time.Time{}, ttl: ttl, } }
[ "func", "NewShardedCacheWithTTL", "(", "ttl", "time", ".", "Duration", ",", "f", "func", "(", ")", "Cache", ")", "*", "ShardedTTL", "{", "return", "&", "ShardedTTL", "{", "cache", ":", "NewShardedNoTS", "(", "f", ")", ",", "setAts", ":", "map", "[", "s...
// NewShardedCacheWithTTL creates a sharded cache system with TTL based on specified Cache constructor // Which everytime will return the true values about a cache hit // and never will leak memory // ttl is used for expiration of a key from cache
[ "NewShardedCacheWithTTL", "creates", "a", "sharded", "cache", "system", "with", "TTL", "based", "on", "specified", "Cache", "constructor", "Which", "everytime", "will", "return", "the", "true", "values", "about", "a", "cache", "hit", "and", "never", "will", "lea...
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/sharded_ttl.go#L32-L38
9,911
koding/cache
sharded_ttl.go
DeleteShard
func (r *ShardedTTL) DeleteShard(tenantID string) error { r.Lock() defer r.Unlock() _, ok := r.setAts[tenantID] if ok { for key := range r.setAts[tenantID] { r.delete(tenantID, key) } } return nil }
go
func (r *ShardedTTL) DeleteShard(tenantID string) error { r.Lock() defer r.Unlock() _, ok := r.setAts[tenantID] if ok { for key := range r.setAts[tenantID] { r.delete(tenantID, key) } } return nil }
[ "func", "(", "r", "*", "ShardedTTL", ")", "DeleteShard", "(", "tenantID", "string", ")", "error", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n\n", "_", ",", "ok", ":=", "r", ".", "setAts", "[", "tenantID", "]"...
// DeleteShard deletes with given tenantID without key
[ "DeleteShard", "deletes", "with", "given", "tenantID", "without", "key" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/sharded_ttl.go#L137-L148
9,912
koding/cache
mongo_model.go
get
func (m *MongoCache) get(key string) (*Document, error) { keyValue := new(Document) query := func(c *mgo.Collection) error { return c.Find(bson.M{ "_id": key, "expireAt": bson.M{ "$gt": time.Now().UTC(), }}).One(&keyValue) } err := m.run(m.CollectionName, query) if err != nil { return nil, err } return keyValue, nil }
go
func (m *MongoCache) get(key string) (*Document, error) { keyValue := new(Document) query := func(c *mgo.Collection) error { return c.Find(bson.M{ "_id": key, "expireAt": bson.M{ "$gt": time.Now().UTC(), }}).One(&keyValue) } err := m.run(m.CollectionName, query) if err != nil { return nil, err } return keyValue, nil }
[ "func", "(", "m", "*", "MongoCache", ")", "get", "(", "key", "string", ")", "(", "*", "Document", ",", "error", ")", "{", "keyValue", ":=", "new", "(", "Document", ")", "\n\n", "query", ":=", "func", "(", "c", "*", "mgo", ".", "Collection", ")", ...
// getKey fetches the key with its key
[ "getKey", "fetches", "the", "key", "with", "its", "key" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/mongo_model.go#L18-L35
9,913
koding/cache
mongo_model.go
delete
func (m *MongoCache) delete(key string) error { query := func(c *mgo.Collection) error { err := c.RemoveId(key) return err } return m.run(m.CollectionName, query) }
go
func (m *MongoCache) delete(key string) error { query := func(c *mgo.Collection) error { err := c.RemoveId(key) return err } return m.run(m.CollectionName, query) }
[ "func", "(", "m", "*", "MongoCache", ")", "delete", "(", "key", "string", ")", "error", "{", "query", ":=", "func", "(", "c", "*", "mgo", ".", "Collection", ")", "error", "{", "err", ":=", "c", ".", "RemoveId", "(", "key", ")", "\n", "return", "e...
// deleteKey removes the key-value from mongoDB
[ "deleteKey", "removes", "the", "key", "-", "value", "from", "mongoDB" ]
e8a81b0b3f20f895153311abde1062894b5912d6
https://github.com/koding/cache/blob/e8a81b0b3f20f895153311abde1062894b5912d6/mongo_model.go#L53-L60
9,914
docker/leadership
candidate.go
NewCandidate
func NewCandidate(client store.Store, key, node string, ttl time.Duration) *Candidate { return &Candidate{ client: client, key: key, node: node, leader: false, lockTTL: ttl, resignCh: make(chan bool), stopCh: make(chan struct{}), } }
go
func NewCandidate(client store.Store, key, node string, ttl time.Duration) *Candidate { return &Candidate{ client: client, key: key, node: node, leader: false, lockTTL: ttl, resignCh: make(chan bool), stopCh: make(chan struct{}), } }
[ "func", "NewCandidate", "(", "client", "store", ".", "Store", ",", "key", ",", "node", "string", ",", "ttl", "time", ".", "Duration", ")", "*", "Candidate", "{", "return", "&", "Candidate", "{", "client", ":", "client", ",", "key", ":", "key", ",", "...
// NewCandidate creates a new Candidate
[ "NewCandidate", "creates", "a", "new", "Candidate" ]
0a913e2d71a12fd14a028452435cb71ac8d82cb6
https://github.com/docker/leadership/blob/0a913e2d71a12fd14a028452435cb71ac8d82cb6/candidate.go#L31-L42
9,915
docker/leadership
candidate.go
RunForElection
func (c *Candidate) RunForElection() (<-chan bool, <-chan error) { c.electedCh = make(chan bool) c.errCh = make(chan error) go c.campaign() return c.electedCh, c.errCh }
go
func (c *Candidate) RunForElection() (<-chan bool, <-chan error) { c.electedCh = make(chan bool) c.errCh = make(chan error) go c.campaign() return c.electedCh, c.errCh }
[ "func", "(", "c", "*", "Candidate", ")", "RunForElection", "(", ")", "(", "<-", "chan", "bool", ",", "<-", "chan", "error", ")", "{", "c", ".", "electedCh", "=", "make", "(", "chan", "bool", ")", "\n", "c", ".", "errCh", "=", "make", "(", "chan",...
// RunForElection starts the leader election algorithm. Updates in status are // pushed through the ElectedCh channel. // // ElectedCh is used to get a channel which delivers signals on // acquiring or losing leadership. It sends true if we become // the leader, and false if we lose it.
[ "RunForElection", "starts", "the", "leader", "election", "algorithm", ".", "Updates", "in", "status", "are", "pushed", "through", "the", "ElectedCh", "channel", ".", "ElectedCh", "is", "used", "to", "get", "a", "channel", "which", "delivers", "signals", "on", ...
0a913e2d71a12fd14a028452435cb71ac8d82cb6
https://github.com/docker/leadership/blob/0a913e2d71a12fd14a028452435cb71ac8d82cb6/candidate.go#L55-L62
9,916
docker/leadership
candidate.go
Resign
func (c *Candidate) Resign() { c.lock.Lock() defer c.lock.Unlock() if c.leader { c.resignCh <- true } }
go
func (c *Candidate) Resign() { c.lock.Lock() defer c.lock.Unlock() if c.leader { c.resignCh <- true } }
[ "func", "(", "c", "*", "Candidate", ")", "Resign", "(", ")", "{", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "leader", "{", "c", ".", "resignCh", "<-", "true", "\...
// Resign forces the candidate to step-down and try again. // If the candidate is not a leader, it doesn't have any effect. // Candidate will retry immediately to acquire the leadership. If no-one else // took it, then the Candidate will end up being a leader again.
[ "Resign", "forces", "the", "candidate", "to", "step", "-", "down", "and", "try", "again", ".", "If", "the", "candidate", "is", "not", "a", "leader", "it", "doesn", "t", "have", "any", "effect", ".", "Candidate", "will", "retry", "immediately", "to", "acq...
0a913e2d71a12fd14a028452435cb71ac8d82cb6
https://github.com/docker/leadership/blob/0a913e2d71a12fd14a028452435cb71ac8d82cb6/candidate.go#L73-L80
9,917
docker/leadership
follower.go
NewFollower
func NewFollower(client store.Store, key string) *Follower { return &Follower{ client: client, key: key, stopCh: make(chan struct{}), } }
go
func NewFollower(client store.Store, key string) *Follower { return &Follower{ client: client, key: key, stopCh: make(chan struct{}), } }
[ "func", "NewFollower", "(", "client", "store", ".", "Store", ",", "key", "string", ")", "*", "Follower", "{", "return", "&", "Follower", "{", "client", ":", "client", ",", "key", ":", "key", ",", "stopCh", ":", "make", "(", "chan", "struct", "{", "}"...
// NewFollower creates a new follower.
[ "NewFollower", "creates", "a", "new", "follower", "." ]
0a913e2d71a12fd14a028452435cb71ac8d82cb6
https://github.com/docker/leadership/blob/0a913e2d71a12fd14a028452435cb71ac8d82cb6/follower.go#L22-L28
9,918
docker/leadership
follower.go
FollowElection
func (f *Follower) FollowElection() (<-chan string, <-chan error) { f.leaderCh = make(chan string) f.errCh = make(chan error) go f.follow() return f.leaderCh, f.errCh }
go
func (f *Follower) FollowElection() (<-chan string, <-chan error) { f.leaderCh = make(chan string) f.errCh = make(chan error) go f.follow() return f.leaderCh, f.errCh }
[ "func", "(", "f", "*", "Follower", ")", "FollowElection", "(", ")", "(", "<-", "chan", "string", ",", "<-", "chan", "error", ")", "{", "f", ".", "leaderCh", "=", "make", "(", "chan", "string", ")", "\n", "f", ".", "errCh", "=", "make", "(", "chan...
// FollowElection starts monitoring the election.
[ "FollowElection", "starts", "monitoring", "the", "election", "." ]
0a913e2d71a12fd14a028452435cb71ac8d82cb6
https://github.com/docker/leadership/blob/0a913e2d71a12fd14a028452435cb71ac8d82cb6/follower.go#L36-L43
9,919
vrecan/death
death.go
NewDeath
func NewDeath(signals ...os.Signal) (death *Death) { death = &Death{timeout: 10 * time.Second, sigChannel: make(chan os.Signal, 1), callChannel: make(chan struct{}, 1), wg: &sync.WaitGroup{}, log: DefaultLogger()} signal.Notify(death.sigChannel, signals...) death.wg.Add(1) go death.listenForSignal() return death }
go
func NewDeath(signals ...os.Signal) (death *Death) { death = &Death{timeout: 10 * time.Second, sigChannel: make(chan os.Signal, 1), callChannel: make(chan struct{}, 1), wg: &sync.WaitGroup{}, log: DefaultLogger()} signal.Notify(death.sigChannel, signals...) death.wg.Add(1) go death.listenForSignal() return death }
[ "func", "NewDeath", "(", "signals", "...", "os", ".", "Signal", ")", "(", "death", "*", "Death", ")", "{", "death", "=", "&", "Death", "{", "timeout", ":", "10", "*", "time", ".", "Second", ",", "sigChannel", ":", "make", "(", "chan", "os", ".", ...
// NewDeath Create Death with the signals you want to die from.
[ "NewDeath", "Create", "Death", "with", "the", "signals", "you", "want", "to", "die", "from", "." ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L36-L46
9,920
vrecan/death
death.go
SetTimeout
func (d *Death) SetTimeout(t time.Duration) *Death { d.timeout = t return d }
go
func (d *Death) SetTimeout(t time.Duration) *Death { d.timeout = t return d }
[ "func", "(", "d", "*", "Death", ")", "SetTimeout", "(", "t", "time", ".", "Duration", ")", "*", "Death", "{", "d", ".", "timeout", "=", "t", "\n", "return", "d", "\n", "}" ]
// SetTimeout Overrides the time death is willing to wait for a objects to be closed.
[ "SetTimeout", "Overrides", "the", "time", "death", "is", "willing", "to", "wait", "for", "a", "objects", "to", "be", "closed", "." ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L49-L52
9,921
vrecan/death
death.go
WaitForDeath
func (d *Death) WaitForDeath(closable ...io.Closer) (err error) { d.wg.Wait() d.log.Info("Shutdown started...") count := len(closable) d.log.Debug("Closing ", count, " objects") if count > 0 { return d.closeInMass(closable...) } return nil }
go
func (d *Death) WaitForDeath(closable ...io.Closer) (err error) { d.wg.Wait() d.log.Info("Shutdown started...") count := len(closable) d.log.Debug("Closing ", count, " objects") if count > 0 { return d.closeInMass(closable...) } return nil }
[ "func", "(", "d", "*", "Death", ")", "WaitForDeath", "(", "closable", "...", "io", ".", "Closer", ")", "(", "err", "error", ")", "{", "d", ".", "wg", ".", "Wait", "(", ")", "\n", "d", ".", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "coun...
// WaitForDeath wait for signal and then kill all items that need to die. If they fail to // die when instructed we return an error
[ "WaitForDeath", "wait", "for", "signal", "and", "then", "kill", "all", "items", "that", "need", "to", "die", ".", "If", "they", "fail", "to", "die", "when", "instructed", "we", "return", "an", "error" ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L62-L71
9,922
vrecan/death
death.go
WaitForDeathWithFunc
func (d *Death) WaitForDeathWithFunc(f func()) { d.wg.Wait() d.log.Info("Shutdown started...") f() }
go
func (d *Death) WaitForDeathWithFunc(f func()) { d.wg.Wait() d.log.Info("Shutdown started...") f() }
[ "func", "(", "d", "*", "Death", ")", "WaitForDeathWithFunc", "(", "f", "func", "(", ")", ")", "{", "d", ".", "wg", ".", "Wait", "(", ")", "\n", "d", ".", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "f", "(", ")", "\n", "}" ]
// WaitForDeathWithFunc allows you to have a single function get called when it's time to // kill your application.
[ "WaitForDeathWithFunc", "allows", "you", "to", "have", "a", "single", "function", "get", "called", "when", "it", "s", "time", "to", "kill", "your", "application", "." ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L75-L79
9,923
vrecan/death
death.go
getPkgPath
func getPkgPath(c io.Closer) (name string, pkgPath string) { t := reflect.TypeOf(c) if t.Kind() == reflect.Ptr { t = t.Elem() } return t.Name(), t.PkgPath() }
go
func getPkgPath(c io.Closer) (name string, pkgPath string) { t := reflect.TypeOf(c) if t.Kind() == reflect.Ptr { t = t.Elem() } return t.Name(), t.PkgPath() }
[ "func", "getPkgPath", "(", "c", "io", ".", "Closer", ")", "(", "name", "string", ",", "pkgPath", "string", ")", "{", "t", ":=", "reflect", ".", "TypeOf", "(", "c", ")", "\n", "if", "t", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "...
// getPkgPath for an io closer.
[ "getPkgPath", "for", "an", "io", "closer", "." ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L82-L88
9,924
vrecan/death
death.go
closeInMass
func (d *Death) closeInMass(closable ...io.Closer) (err error) { count := len(closable) sentToClose := make(map[int]closer) //call close async doneClosers := make(chan closer, count) for i, c := range closable { name, pkgPath := getPkgPath(c) closer := closer{Index: i, C: c, Name: name, PKGPath: pkgPath} go d.closeObjects(closer, doneClosers) sentToClose[i] = closer } // wait on channel for notifications. timer := time.NewTimer(d.timeout) failedClosers := []closer{} for { select { case <-timer.C: s := "failed to close: " pkgs := []string{} for _, c := range sentToClose { pkgs = append(pkgs, fmt.Sprintf("%s/%s", c.PKGPath, c.Name)) d.log.Error("Failed to close: ", c.PKGPath, "/", c.Name) } return fmt.Errorf("%s", fmt.Sprintf("%s %s", s, strings.Join(pkgs, ", "))) case closer := <-doneClosers: delete(sentToClose, closer.Index) count-- if closer.Err != nil { failedClosers = append(failedClosers, closer) } d.log.Debug(count, " object(s) left") if count != 0 || len(sentToClose) != 0 { continue } if len(failedClosers) != 0 { errString := generateErrString(failedClosers) return fmt.Errorf("errors from closers: %s", errString) } return nil } } }
go
func (d *Death) closeInMass(closable ...io.Closer) (err error) { count := len(closable) sentToClose := make(map[int]closer) //call close async doneClosers := make(chan closer, count) for i, c := range closable { name, pkgPath := getPkgPath(c) closer := closer{Index: i, C: c, Name: name, PKGPath: pkgPath} go d.closeObjects(closer, doneClosers) sentToClose[i] = closer } // wait on channel for notifications. timer := time.NewTimer(d.timeout) failedClosers := []closer{} for { select { case <-timer.C: s := "failed to close: " pkgs := []string{} for _, c := range sentToClose { pkgs = append(pkgs, fmt.Sprintf("%s/%s", c.PKGPath, c.Name)) d.log.Error("Failed to close: ", c.PKGPath, "/", c.Name) } return fmt.Errorf("%s", fmt.Sprintf("%s %s", s, strings.Join(pkgs, ", "))) case closer := <-doneClosers: delete(sentToClose, closer.Index) count-- if closer.Err != nil { failedClosers = append(failedClosers, closer) } d.log.Debug(count, " object(s) left") if count != 0 || len(sentToClose) != 0 { continue } if len(failedClosers) != 0 { errString := generateErrString(failedClosers) return fmt.Errorf("errors from closers: %s", errString) } return nil } } }
[ "func", "(", "d", "*", "Death", ")", "closeInMass", "(", "closable", "...", "io", ".", "Closer", ")", "(", "err", "error", ")", "{", "count", ":=", "len", "(", "closable", ")", "\n", "sentToClose", ":=", "make", "(", "map", "[", "int", "]", "closer...
// closeInMass Close all the objects at once and wait for them to finish with a channel. Return an // error if you fail to close all the objects
[ "closeInMass", "Close", "all", "the", "objects", "at", "once", "and", "wait", "for", "them", "to", "finish", "with", "a", "channel", ".", "Return", "an", "error", "if", "you", "fail", "to", "close", "all", "the", "objects" ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L92-L138
9,925
vrecan/death
death.go
closeObjects
func (d *Death) closeObjects(closer closer, done chan<- closer) { err := closer.C.Close() if err != nil { d.log.Error(err) closer.Err = err } done <- closer }
go
func (d *Death) closeObjects(closer closer, done chan<- closer) { err := closer.C.Close() if err != nil { d.log.Error(err) closer.Err = err } done <- closer }
[ "func", "(", "d", "*", "Death", ")", "closeObjects", "(", "closer", "closer", ",", "done", "chan", "<-", "closer", ")", "{", "err", ":=", "closer", ".", "C", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "d", ".", "log", ".", "Er...
// closeObjects and return a bool when finished on a channel.
[ "closeObjects", "and", "return", "a", "bool", "when", "finished", "on", "a", "channel", "." ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L141-L148
9,926
vrecan/death
death.go
listenForSignal
func (d *Death) listenForSignal() { defer d.wg.Done() for { select { case <-d.sigChannel: return case <-d.callChannel: return } } }
go
func (d *Death) listenForSignal() { defer d.wg.Done() for { select { case <-d.sigChannel: return case <-d.callChannel: return } } }
[ "func", "(", "d", "*", "Death", ")", "listenForSignal", "(", ")", "{", "defer", "d", ".", "wg", ".", "Done", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "d", ".", "sigChannel", ":", "return", "\n", "case", "<-", "d", ".", "callChanne...
// ListenForSignal Manage death of application by signal.
[ "ListenForSignal", "Manage", "death", "of", "application", "by", "signal", "." ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L159-L169
9,927
vrecan/death
death.go
generateErrString
func generateErrString(failedClosers []closer) (errString string) { for i, fc := range failedClosers { if i == 0 { errString = fmt.Sprintf("%s/%s: %s", fc.PKGPath, fc.Name, fc.Err) continue } errString = fmt.Sprintf("%s, %s/%s: %s", errString, fc.PKGPath, fc.Name, fc.Err) } return errString }
go
func generateErrString(failedClosers []closer) (errString string) { for i, fc := range failedClosers { if i == 0 { errString = fmt.Sprintf("%s/%s: %s", fc.PKGPath, fc.Name, fc.Err) continue } errString = fmt.Sprintf("%s, %s/%s: %s", errString, fc.PKGPath, fc.Name, fc.Err) } return errString }
[ "func", "generateErrString", "(", "failedClosers", "[", "]", "closer", ")", "(", "errString", "string", ")", "{", "for", "i", ",", "fc", ":=", "range", "failedClosers", "{", "if", "i", "==", "0", "{", "errString", "=", "fmt", ".", "Sprintf", "(", "\"",...
// generateErrString generates a string containing a list of tuples of pkgname to error message
[ "generateErrString", "generates", "a", "string", "containing", "a", "list", "of", "tuples", "of", "pkgname", "to", "error", "message" ]
eb9a1d773e1be97f42a579c803d5b6bf5ba96768
https://github.com/vrecan/death/blob/eb9a1d773e1be97f42a579c803d5b6bf5ba96768/death.go#L172-L182
9,928
djherbis/times
ctime_windows.go
Stat
func Stat(name string) (Timespec, error) { ts, err := platformSpecficStat(name) if err == nil { return ts, err } return stat(name, os.Stat) }
go
func Stat(name string) (Timespec, error) { ts, err := platformSpecficStat(name) if err == nil { return ts, err } return stat(name, os.Stat) }
[ "func", "Stat", "(", "name", "string", ")", "(", "Timespec", ",", "error", ")", "{", "ts", ",", "err", ":=", "platformSpecficStat", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "return", "ts", ",", "err", "\n", "}", "\n\n", "return", "sta...
// Stat returns the Timespec for the given filename.
[ "Stat", "returns", "the", "Timespec", "for", "the", "given", "filename", "." ]
847c5208d8924cea0acea3376ff62aede93afe39
https://github.com/djherbis/times/blob/847c5208d8924cea0acea3376ff62aede93afe39/ctime_windows.go#L11-L18
9,929
djherbis/times
ctime_windows.go
Lstat
func Lstat(name string) (Timespec, error) { ts, err := platformSpecficLstat(name) if err == nil { return ts, err } return stat(name, os.Lstat) }
go
func Lstat(name string) (Timespec, error) { ts, err := platformSpecficLstat(name) if err == nil { return ts, err } return stat(name, os.Lstat) }
[ "func", "Lstat", "(", "name", "string", ")", "(", "Timespec", ",", "error", ")", "{", "ts", ",", "err", ":=", "platformSpecficLstat", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "return", "ts", ",", "err", "\n", "}", "\n\n", "return", "s...
// Lstat returns the Timespec for the given filename, and does not follow Symlinks.
[ "Lstat", "returns", "the", "Timespec", "for", "the", "given", "filename", "and", "does", "not", "follow", "Symlinks", "." ]
847c5208d8924cea0acea3376ff62aede93afe39
https://github.com/djherbis/times/blob/847c5208d8924cea0acea3376ff62aede93afe39/ctime_windows.go#L21-L28
9,930
djherbis/times
ctime_windows.go
StatFile
func StatFile(file *os.File) (Timespec, error) { return statFile(syscall.Handle(file.Fd())) }
go
func StatFile(file *os.File) (Timespec, error) { return statFile(syscall.Handle(file.Fd())) }
[ "func", "StatFile", "(", "file", "*", "os", ".", "File", ")", "(", "Timespec", ",", "error", ")", "{", "return", "statFile", "(", "syscall", ".", "Handle", "(", "file", ".", "Fd", "(", ")", ")", ")", "\n", "}" ]
// StatFile finds a Windows Timespec with ChangeTime.
[ "StatFile", "finds", "a", "Windows", "Timespec", "with", "ChangeTime", "." ]
847c5208d8924cea0acea3376ff62aede93afe39
https://github.com/djherbis/times/blob/847c5208d8924cea0acea3376ff62aede93afe39/ctime_windows.go#L38-L40
9,931
oskca/gopherjs-vue
component.go
NewComponent
func NewComponent( vmCreator func() (structPtr interface{}), templateStr string, replaceMountPoint ...bool, ) *Component { // args idx := len(creatorPool) creatorPool = append(creatorPool, new(pool)) creatorPool[idx].creator = vmCreator vmfn := func() interface{} { p := creatorPool[idx] if p.counter%3 == 0 { p.structPtr = p.creator() } p.counter += 1 return p.structPtr } // opts opt := NewOption() opt.Data = vmfn opt.Template = templateStr opt.OnLifeCycleEvent(EvtBeforeCreate, func(vm *ViewModel) { vm.Options.Set("methods", js.MakeWrapper(vmfn())) vMap[vmfn()] = vm }) return opt.NewComponent() }
go
func NewComponent( vmCreator func() (structPtr interface{}), templateStr string, replaceMountPoint ...bool, ) *Component { // args idx := len(creatorPool) creatorPool = append(creatorPool, new(pool)) creatorPool[idx].creator = vmCreator vmfn := func() interface{} { p := creatorPool[idx] if p.counter%3 == 0 { p.structPtr = p.creator() } p.counter += 1 return p.structPtr } // opts opt := NewOption() opt.Data = vmfn opt.Template = templateStr opt.OnLifeCycleEvent(EvtBeforeCreate, func(vm *ViewModel) { vm.Options.Set("methods", js.MakeWrapper(vmfn())) vMap[vmfn()] = vm }) return opt.NewComponent() }
[ "func", "NewComponent", "(", "vmCreator", "func", "(", ")", "(", "structPtr", "interface", "{", "}", ")", ",", "templateStr", "string", ",", "replaceMountPoint", "...", "bool", ",", ")", "*", "Component", "{", "// args", "idx", ":=", "len", "(", "creatorPo...
// NewComponent creates and registers a named global Component // // vmCreator should return a gopherjs struct pointer. see New for more details
[ "NewComponent", "creates", "and", "registers", "a", "named", "global", "Component", "vmCreator", "should", "return", "a", "gopherjs", "struct", "pointer", ".", "see", "New", "for", "more", "details" ]
ab40c9e57345d35375c820c8e885d28ed70f165e
https://github.com/oskca/gopherjs-vue/blob/ab40c9e57345d35375c820c8e885d28ed70f165e/component.go#L49-L75
9,932
oskca/gopherjs-vue
vue.go
Push
func Push(obj *js.Object, any interface{}) (idx int) { return obj.Call("push", any).Int() }
go
func Push(obj *js.Object, any interface{}) (idx int) { return obj.Call("push", any).Int() }
[ "func", "Push", "(", "obj", "*", "js", ".", "Object", ",", "any", "interface", "{", "}", ")", "(", "idx", "int", ")", "{", "return", "obj", ".", "Call", "(", "\"", "\"", ",", "any", ")", ".", "Int", "(", ")", "\n", "}" ]
// Add in the bottom of the array
[ "Add", "in", "the", "bottom", "of", "the", "array" ]
ab40c9e57345d35375c820c8e885d28ed70f165e
https://github.com/oskca/gopherjs-vue/blob/ab40c9e57345d35375c820c8e885d28ed70f165e/vue.go#L15-L17
9,933
oskca/gopherjs-vue
mapping.go
FromJS
func (v *ViewModel) FromJS(obj *js.Object) *ViewModel { for _, key := range js.Keys(obj) { // skip internal or unexported field if strings.HasPrefix(key, "$") || strings.HasPrefix(key, "_") { continue } v.Object.Set(key, obj.Get(key)) } return v }
go
func (v *ViewModel) FromJS(obj *js.Object) *ViewModel { for _, key := range js.Keys(obj) { // skip internal or unexported field if strings.HasPrefix(key, "$") || strings.HasPrefix(key, "_") { continue } v.Object.Set(key, obj.Get(key)) } return v }
[ "func", "(", "v", "*", "ViewModel", ")", "FromJS", "(", "obj", "*", "js", ".", "Object", ")", "*", "ViewModel", "{", "for", "_", ",", "key", ":=", "range", "js", ".", "Keys", "(", "obj", ")", "{", "// skip internal or unexported field", "if", "strings"...
// FromJS set the corresponding VueJS data model field from obj // new data model field will be created when not exist
[ "FromJS", "set", "the", "corresponding", "VueJS", "data", "model", "field", "from", "obj", "new", "data", "model", "field", "will", "be", "created", "when", "not", "exist" ]
ab40c9e57345d35375c820c8e885d28ed70f165e
https://github.com/oskca/gopherjs-vue/blob/ab40c9e57345d35375c820c8e885d28ed70f165e/mapping.go#L12-L21
9,934
oskca/gopherjs-vue
option.go
prepare
func (c *Option) prepare() (opts *js.Object) { if len(c.coms) > 0 { c.Set("components", c.coms) } if len(c.props) > 0 { c.Set("props", c.props) } if len(c.mixins) > 0 { c.Set("mixins", c.mixins) } return c.Object }
go
func (c *Option) prepare() (opts *js.Object) { if len(c.coms) > 0 { c.Set("components", c.coms) } if len(c.props) > 0 { c.Set("props", c.props) } if len(c.mixins) > 0 { c.Set("mixins", c.mixins) } return c.Object }
[ "func", "(", "c", "*", "Option", ")", "prepare", "(", ")", "(", "opts", "*", "js", ".", "Object", ")", "{", "if", "len", "(", "c", ".", "coms", ")", ">", "0", "{", "c", ".", "Set", "(", "\"", "\"", ",", "c", ".", "coms", ")", "\n", "}", ...
// prepare set the proper options into js.Object
[ "prepare", "set", "the", "proper", "options", "into", "js", ".", "Object" ]
ab40c9e57345d35375c820c8e885d28ed70f165e
https://github.com/oskca/gopherjs-vue/blob/ab40c9e57345d35375c820c8e885d28ed70f165e/option.go#L181-L192
9,935
oskca/gopherjs-vue
option.go
AddMethod
func (o *Option) AddMethod(name string, fn func(vm *ViewModel, args []*js.Object)) *Option { return o.addMixin("methods", js.M{ name: js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} { vm := newViewModel(this) fn(vm, arguments) return nil }), }) }
go
func (o *Option) AddMethod(name string, fn func(vm *ViewModel, args []*js.Object)) *Option { return o.addMixin("methods", js.M{ name: js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} { vm := newViewModel(this) fn(vm, arguments) return nil }), }) }
[ "func", "(", "o", "*", "Option", ")", "AddMethod", "(", "name", "string", ",", "fn", "func", "(", "vm", "*", "ViewModel", ",", "args", "[", "]", "*", "js", ".", "Object", ")", ")", "*", "Option", "{", "return", "o", ".", "addMixin", "(", "\"", ...
// AddMethod adds new method `name` to VueJS intance or component // using mixins thus will never conflict with Option.SetDataWithMethods
[ "AddMethod", "adds", "new", "method", "name", "to", "VueJS", "intance", "or", "component", "using", "mixins", "thus", "will", "never", "conflict", "with", "Option", ".", "SetDataWithMethods" ]
ab40c9e57345d35375c820c8e885d28ed70f165e
https://github.com/oskca/gopherjs-vue/blob/ab40c9e57345d35375c820c8e885d28ed70f165e/option.go#L207-L215
9,936
oskca/gopherjs-vue
option.go
AddComputed
func (o *Option) AddComputed(name string, getter func(vm *ViewModel) interface{}, setter ...func(vm *ViewModel, val *js.Object)) { conf := make(map[string]js.M) conf[name] = make(js.M) fnGetter := js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} { vm := newViewModel(this) return getter(vm) }) conf[name]["get"] = fnGetter if len(setter) > 0 { fnSetter := js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} { vm := newViewModel(this) setter[0](vm, arguments[0]) return nil }) conf[name]["set"] = fnSetter } // using mixin here o.addMixin("computed", conf) }
go
func (o *Option) AddComputed(name string, getter func(vm *ViewModel) interface{}, setter ...func(vm *ViewModel, val *js.Object)) { conf := make(map[string]js.M) conf[name] = make(js.M) fnGetter := js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} { vm := newViewModel(this) return getter(vm) }) conf[name]["get"] = fnGetter if len(setter) > 0 { fnSetter := js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} { vm := newViewModel(this) setter[0](vm, arguments[0]) return nil }) conf[name]["set"] = fnSetter } // using mixin here o.addMixin("computed", conf) }
[ "func", "(", "o", "*", "Option", ")", "AddComputed", "(", "name", "string", ",", "getter", "func", "(", "vm", "*", "ViewModel", ")", "interface", "{", "}", ",", "setter", "...", "func", "(", "vm", "*", "ViewModel", ",", "val", "*", "js", ".", "Obje...
// AddComputed set computed data
[ "AddComputed", "set", "computed", "data" ]
ab40c9e57345d35375c820c8e885d28ed70f165e
https://github.com/oskca/gopherjs-vue/blob/ab40c9e57345d35375c820c8e885d28ed70f165e/option.go#L234-L252
9,937
256dpi/gomqtt
transport/websocket_conn.go
NewWebSocketConn
func NewWebSocketConn(conn *websocket.Conn, maxWriteDelay time.Duration) *WebSocketConn { return &WebSocketConn{ BaseConn: NewBaseConn(&wsStream{conn: conn}, maxWriteDelay), conn: conn, } }
go
func NewWebSocketConn(conn *websocket.Conn, maxWriteDelay time.Duration) *WebSocketConn { return &WebSocketConn{ BaseConn: NewBaseConn(&wsStream{conn: conn}, maxWriteDelay), conn: conn, } }
[ "func", "NewWebSocketConn", "(", "conn", "*", "websocket", ".", "Conn", ",", "maxWriteDelay", "time", ".", "Duration", ")", "*", "WebSocketConn", "{", "return", "&", "WebSocketConn", "{", "BaseConn", ":", "NewBaseConn", "(", "&", "wsStream", "{", "conn", ":"...
// NewWebSocketConn returns a new WebSocketConn.
[ "NewWebSocketConn", "returns", "a", "new", "WebSocketConn", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/websocket_conn.go#L106-L111
9,938
256dpi/gomqtt
packet/packet.go
Successful
func (qos QOS) Successful() bool { return qos == QOSAtMostOnce || qos == QOSAtLeastOnce || qos == QOSExactlyOnce }
go
func (qos QOS) Successful() bool { return qos == QOSAtMostOnce || qos == QOSAtLeastOnce || qos == QOSExactlyOnce }
[ "func", "(", "qos", "QOS", ")", "Successful", "(", ")", "bool", "{", "return", "qos", "==", "QOSAtMostOnce", "||", "qos", "==", "QOSAtLeastOnce", "||", "qos", "==", "QOSExactlyOnce", "\n", "}" ]
// Successful returns if the provided quality of service level represents a // successful value.
[ "Successful", "returns", "if", "the", "provided", "quality", "of", "service", "level", "represents", "a", "successful", "value", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/packet.go#L27-L29
9,939
256dpi/gomqtt
packet/packet.go
DetectPacket
func DetectPacket(src []byte) (int, Type) { // check for minimum size if len(src) < 2 { return 0, 0 } // get type t := Type(src[0] >> 4) // get remaining length rl, n := binary.Uvarint(src[1:]) if n <= 0 { return 0, 0 } return 1 + n + int(rl), t }
go
func DetectPacket(src []byte) (int, Type) { // check for minimum size if len(src) < 2 { return 0, 0 } // get type t := Type(src[0] >> 4) // get remaining length rl, n := binary.Uvarint(src[1:]) if n <= 0 { return 0, 0 } return 1 + n + int(rl), t }
[ "func", "DetectPacket", "(", "src", "[", "]", "byte", ")", "(", "int", ",", "Type", ")", "{", "// check for minimum size", "if", "len", "(", "src", ")", "<", "2", "{", "return", "0", ",", "0", "\n", "}", "\n\n", "// get type", "t", ":=", "Type", "(...
// DetectPacket tries to detect the next packet in a buffer. It returns a length // greater than zero if the packet has been detected as well as its Type.
[ "DetectPacket", "tries", "to", "detect", "the", "next", "packet", "in", "a", "buffer", ".", "It", "returns", "a", "length", "greater", "than", "zero", "if", "the", "packet", "has", "been", "detected", "as", "well", "as", "its", "Type", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/packet.go#L63-L79
9,940
256dpi/gomqtt
packet/packet.go
GetID
func GetID(pkt Generic) (ID, bool) { switch pkt.Type() { case PUBLISH: return pkt.(*Publish).ID, true case PUBACK: return pkt.(*Puback).ID, true case PUBREC: return pkt.(*Pubrec).ID, true case PUBREL: return pkt.(*Pubrel).ID, true case PUBCOMP: return pkt.(*Pubcomp).ID, true case SUBSCRIBE: return pkt.(*Subscribe).ID, true case SUBACK: return pkt.(*Suback).ID, true case UNSUBSCRIBE: return pkt.(*Unsubscribe).ID, true case UNSUBACK: return pkt.(*Unsuback).ID, true } return 0, false }
go
func GetID(pkt Generic) (ID, bool) { switch pkt.Type() { case PUBLISH: return pkt.(*Publish).ID, true case PUBACK: return pkt.(*Puback).ID, true case PUBREC: return pkt.(*Pubrec).ID, true case PUBREL: return pkt.(*Pubrel).ID, true case PUBCOMP: return pkt.(*Pubcomp).ID, true case SUBSCRIBE: return pkt.(*Subscribe).ID, true case SUBACK: return pkt.(*Suback).ID, true case UNSUBSCRIBE: return pkt.(*Unsubscribe).ID, true case UNSUBACK: return pkt.(*Unsuback).ID, true } return 0, false }
[ "func", "GetID", "(", "pkt", "Generic", ")", "(", "ID", ",", "bool", ")", "{", "switch", "pkt", ".", "Type", "(", ")", "{", "case", "PUBLISH", ":", "return", "pkt", ".", "(", "*", "Publish", ")", ".", "ID", ",", "true", "\n", "case", "PUBACK", ...
// GetID checks the packets type and returns its ID and true, or if it // does not have a ID, zero and false.
[ "GetID", "checks", "the", "packets", "type", "and", "returns", "its", "ID", "and", "true", "or", "if", "it", "does", "not", "have", "a", "ID", "zero", "and", "false", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/packet.go#L83-L106
9,941
256dpi/gomqtt
transport/net_conn.go
NewNetConn
func NewNetConn(conn net.Conn, maxWriteDelay time.Duration) *NetConn { return &NetConn{ BaseConn: NewBaseConn(conn, maxWriteDelay), conn: conn, } }
go
func NewNetConn(conn net.Conn, maxWriteDelay time.Duration) *NetConn { return &NetConn{ BaseConn: NewBaseConn(conn, maxWriteDelay), conn: conn, } }
[ "func", "NewNetConn", "(", "conn", "net", ".", "Conn", ",", "maxWriteDelay", "time", ".", "Duration", ")", "*", "NetConn", "{", "return", "&", "NetConn", "{", "BaseConn", ":", "NewBaseConn", "(", "conn", ",", "maxWriteDelay", ")", ",", "conn", ":", "conn...
// NewNetConn returns a new NetConn.
[ "NewNetConn", "returns", "a", "new", "NetConn", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/net_conn.go#L16-L21
9,942
256dpi/gomqtt
transport/launcher.go
Launch
func (l *Launcher) Launch(urlString string) (Server, error) { urlParts, err := url.ParseRequestURI(urlString) if err != nil { return nil, err } switch urlParts.Scheme { case "tcp", "mqtt": return CreateNetServer(urlParts.Host) case "tls", "mqtts": return CreateSecureNetServer(urlParts.Host, l.TLSConfig) case "ws": return CreateWebSocketServer(urlParts.Host) case "wss": return CreateSecureWebSocketServer(urlParts.Host, l.TLSConfig) } return nil, ErrUnsupportedProtocol }
go
func (l *Launcher) Launch(urlString string) (Server, error) { urlParts, err := url.ParseRequestURI(urlString) if err != nil { return nil, err } switch urlParts.Scheme { case "tcp", "mqtt": return CreateNetServer(urlParts.Host) case "tls", "mqtts": return CreateSecureNetServer(urlParts.Host, l.TLSConfig) case "ws": return CreateWebSocketServer(urlParts.Host) case "wss": return CreateSecureWebSocketServer(urlParts.Host, l.TLSConfig) } return nil, ErrUnsupportedProtocol }
[ "func", "(", "l", "*", "Launcher", ")", "Launch", "(", "urlString", "string", ")", "(", "Server", ",", "error", ")", "{", "urlParts", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "urlString", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// Launch will launch a server based on information extracted from an URL.
[ "Launch", "will", "launch", "a", "server", "based", "on", "information", "extracted", "from", "an", "URL", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/launcher.go#L30-L48
9,943
256dpi/gomqtt
client/tracker.go
NewTracker
func NewTracker(timeout time.Duration) *Tracker { return &Tracker{ last: time.Now(), timeout: timeout, } }
go
func NewTracker(timeout time.Duration) *Tracker { return &Tracker{ last: time.Now(), timeout: timeout, } }
[ "func", "NewTracker", "(", "timeout", "time", ".", "Duration", ")", "*", "Tracker", "{", "return", "&", "Tracker", "{", "last", ":", "time", ".", "Now", "(", ")", ",", "timeout", ":", "timeout", ",", "}", "\n", "}" ]
// NewTracker returns a new tracker.
[ "NewTracker", "returns", "a", "new", "tracker", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/tracker.go#L18-L23
9,944
256dpi/gomqtt
client/tracker.go
Reset
func (t *Tracker) Reset() { t.Lock() defer t.Unlock() t.last = time.Now() }
go
func (t *Tracker) Reset() { t.Lock() defer t.Unlock() t.last = time.Now() }
[ "func", "(", "t", "*", "Tracker", ")", "Reset", "(", ")", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n\n", "t", ".", "last", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// Reset will reset the tracker.
[ "Reset", "will", "reset", "the", "tracker", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/tracker.go#L26-L31
9,945
256dpi/gomqtt
client/tracker.go
Window
func (t *Tracker) Window() time.Duration { t.RLock() defer t.RUnlock() return t.timeout - time.Since(t.last) }
go
func (t *Tracker) Window() time.Duration { t.RLock() defer t.RUnlock() return t.timeout - time.Since(t.last) }
[ "func", "(", "t", "*", "Tracker", ")", "Window", "(", ")", "time", ".", "Duration", "{", "t", ".", "RLock", "(", ")", "\n", "defer", "t", ".", "RUnlock", "(", ")", "\n\n", "return", "t", ".", "timeout", "-", "time", ".", "Since", "(", "t", ".",...
// Window returns the time until a new ping should be sent.
[ "Window", "returns", "the", "time", "until", "a", "new", "ping", "should", "be", "sent", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/tracker.go#L34-L39
9,946
256dpi/gomqtt
client/tracker.go
Pending
func (t *Tracker) Pending() bool { t.RLock() defer t.RUnlock() return t.pings > 0 }
go
func (t *Tracker) Pending() bool { t.RLock() defer t.RUnlock() return t.pings > 0 }
[ "func", "(", "t", "*", "Tracker", ")", "Pending", "(", ")", "bool", "{", "t", ".", "RLock", "(", ")", "\n", "defer", "t", ".", "RUnlock", "(", ")", "\n\n", "return", "t", ".", "pings", ">", "0", "\n", "}" ]
// Pending returns if pings are pending.
[ "Pending", "returns", "if", "pings", "are", "pending", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/tracker.go#L58-L63
9,947
256dpi/gomqtt
session/id_counter.go
NextID
func (c *IDCounter) NextID() packet.ID { c.mutex.Lock() defer c.mutex.Unlock() // ignore zeroes if c.next == 0 { c.next++ } // cache next id id := c.next // increment id c.next++ return id }
go
func (c *IDCounter) NextID() packet.ID { c.mutex.Lock() defer c.mutex.Unlock() // ignore zeroes if c.next == 0 { c.next++ } // cache next id id := c.next // increment id c.next++ return id }
[ "func", "(", "c", "*", "IDCounter", ")", "NextID", "(", ")", "packet", ".", "ID", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// ignore zeroes", "if", "c", ".", "next", "==", ...
// NextID will return the next id.
[ "NextID", "will", "return", "the", "next", "id", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/id_counter.go#L29-L45
9,948
256dpi/gomqtt
session/id_counter.go
Reset
func (c *IDCounter) Reset() { c.mutex.Lock() defer c.mutex.Unlock() c.next = 1 }
go
func (c *IDCounter) Reset() { c.mutex.Lock() defer c.mutex.Unlock() c.next = 1 }
[ "func", "(", "c", "*", "IDCounter", ")", "Reset", "(", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "c", ".", "next", "=", "1", "\n", "}" ]
// Reset will reset the counter.
[ "Reset", "will", "reset", "the", "counter", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/id_counter.go#L48-L53
9,949
256dpi/gomqtt
transport/flow/flow.go
Send
func (conn *Pipe) Send(pkt packet.Generic, _ bool) error { select { case conn.pipe <- pkt: return nil case <-conn.close: return errors.New("closed") } }
go
func (conn *Pipe) Send(pkt packet.Generic, _ bool) error { select { case conn.pipe <- pkt: return nil case <-conn.close: return errors.New("closed") } }
[ "func", "(", "conn", "*", "Pipe", ")", "Send", "(", "pkt", "packet", ".", "Generic", ",", "_", "bool", ")", "error", "{", "select", "{", "case", "conn", ".", "pipe", "<-", "pkt", ":", "return", "nil", "\n", "case", "<-", "conn", ".", "close", ":"...
// Send returns packet on next Receive call.
[ "Send", "returns", "packet", "on", "next", "Receive", "call", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L36-L43
9,950
256dpi/gomqtt
transport/flow/flow.go
Receive
func (conn *Pipe) Receive() (packet.Generic, error) { select { case pkt := <-conn.pipe: return pkt, nil case <-conn.close: return nil, io.EOF } }
go
func (conn *Pipe) Receive() (packet.Generic, error) { select { case pkt := <-conn.pipe: return pkt, nil case <-conn.close: return nil, io.EOF } }
[ "func", "(", "conn", "*", "Pipe", ")", "Receive", "(", ")", "(", "packet", ".", "Generic", ",", "error", ")", "{", "select", "{", "case", "pkt", ":=", "<-", "conn", ".", "pipe", ":", "return", "pkt", ",", "nil", "\n", "case", "<-", "conn", ".", ...
// Receive returns the packet being sent with Send.
[ "Receive", "returns", "the", "packet", "being", "sent", "with", "Send", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L46-L53
9,951
256dpi/gomqtt
transport/flow/flow.go
Send
func (f *Flow) Send(pkts ...packet.Generic) *Flow { f.add(action{ kind: actionSend, packets: pkts, }) return f }
go
func (f *Flow) Send(pkts ...packet.Generic) *Flow { f.add(action{ kind: actionSend, packets: pkts, }) return f }
[ "func", "(", "f", "*", "Flow", ")", "Send", "(", "pkts", "...", "packet", ".", "Generic", ")", "*", "Flow", "{", "f", ".", "add", "(", "action", "{", "kind", ":", "actionSend", ",", "packets", ":", "pkts", ",", "}", ")", "\n\n", "return", "f", ...
// Send will send the specified packets.
[ "Send", "will", "send", "the", "specified", "packets", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L100-L107
9,952
256dpi/gomqtt
transport/flow/flow.go
Receive
func (f *Flow) Receive(pkts ...packet.Generic) *Flow { f.add(action{ kind: actionReceive, packets: pkts, }) return f }
go
func (f *Flow) Receive(pkts ...packet.Generic) *Flow { f.add(action{ kind: actionReceive, packets: pkts, }) return f }
[ "func", "(", "f", "*", "Flow", ")", "Receive", "(", "pkts", "...", "packet", ".", "Generic", ")", "*", "Flow", "{", "f", ".", "add", "(", "action", "{", "kind", ":", "actionReceive", ",", "packets", ":", "pkts", ",", "}", ")", "\n\n", "return", "...
// Receive will receive and match the specified packets out of order.
[ "Receive", "will", "receive", "and", "match", "the", "specified", "packets", "out", "of", "order", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L110-L117
9,953
256dpi/gomqtt
transport/flow/flow.go
Skip
func (f *Flow) Skip(pkts ...packet.Generic) *Flow { f.add(action{ kind: actionSkip, packets: pkts, }) return f }
go
func (f *Flow) Skip(pkts ...packet.Generic) *Flow { f.add(action{ kind: actionSkip, packets: pkts, }) return f }
[ "func", "(", "f", "*", "Flow", ")", "Skip", "(", "pkts", "...", "packet", ".", "Generic", ")", "*", "Flow", "{", "f", ".", "add", "(", "action", "{", "kind", ":", "actionSkip", ",", "packets", ":", "pkts", ",", "}", ")", "\n\n", "return", "f", ...
// Skip will receive the specified packets without matching out of order.
[ "Skip", "will", "receive", "the", "specified", "packets", "without", "matching", "out", "of", "order", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L120-L127
9,954
256dpi/gomqtt
transport/flow/flow.go
Run
func (f *Flow) Run(fn func()) *Flow { f.add(action{ kind: actionRun, fn: fn, }) return f }
go
func (f *Flow) Run(fn func()) *Flow { f.add(action{ kind: actionRun, fn: fn, }) return f }
[ "func", "(", "f", "*", "Flow", ")", "Run", "(", "fn", "func", "(", ")", ")", "*", "Flow", "{", "f", ".", "add", "(", "action", "{", "kind", ":", "actionRun", ",", "fn", ":", "fn", ",", "}", ")", "\n\n", "return", "f", "\n", "}" ]
// Run will call the supplied function and wait until it returns.
[ "Run", "will", "call", "the", "supplied", "function", "and", "wait", "until", "it", "returns", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L130-L137
9,955
256dpi/gomqtt
transport/flow/flow.go
Close
func (f *Flow) Close() *Flow { f.add(action{ kind: actionClose, }) return f }
go
func (f *Flow) Close() *Flow { f.add(action{ kind: actionClose, }) return f }
[ "func", "(", "f", "*", "Flow", ")", "Close", "(", ")", "*", "Flow", "{", "f", ".", "add", "(", "action", "{", "kind", ":", "actionClose", ",", "}", ")", "\n\n", "return", "f", "\n", "}" ]
// Close will immediately close the connection.
[ "Close", "will", "immediately", "close", "the", "connection", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L140-L146
9,956
256dpi/gomqtt
transport/flow/flow.go
End
func (f *Flow) End() *Flow { f.add(action{ kind: actionEnd, }) return f }
go
func (f *Flow) End() *Flow { f.add(action{ kind: actionEnd, }) return f }
[ "func", "(", "f", "*", "Flow", ")", "End", "(", ")", "*", "Flow", "{", "f", ".", "add", "(", "action", "{", "kind", ":", "actionEnd", ",", "}", ")", "\n\n", "return", "f", "\n", "}" ]
// End will match proper connection close.
[ "End", "will", "match", "proper", "connection", "close", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L149-L155
9,957
256dpi/gomqtt
transport/flow/flow.go
add
func (f *Flow) add(action action) { f.actions = append(f.actions, action) }
go
func (f *Flow) add(action action) { f.actions = append(f.actions, action) }
[ "func", "(", "f", "*", "Flow", ")", "add", "(", "action", "action", ")", "{", "f", ".", "actions", "=", "append", "(", "f", ".", "actions", ",", "action", ")", "\n", "}" ]
// add will add the specified action.
[ "add", "will", "add", "the", "specified", "action", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/flow/flow.go#L304-L306
9,958
256dpi/gomqtt
session/memory_session.go
SavePacket
func (s *MemorySession) SavePacket(dir Direction, pkt packet.Generic) error { s.storeForDirection(dir).Save(pkt) return nil }
go
func (s *MemorySession) SavePacket(dir Direction, pkt packet.Generic) error { s.storeForDirection(dir).Save(pkt) return nil }
[ "func", "(", "s", "*", "MemorySession", ")", "SavePacket", "(", "dir", "Direction", ",", "pkt", "packet", ".", "Generic", ")", "error", "{", "s", ".", "storeForDirection", "(", "dir", ")", ".", "Save", "(", "pkt", ")", "\n", "return", "nil", "\n", "}...
// SavePacket will store a packet in the session. An eventual existing // packet with the same id gets quietly overwritten.
[ "SavePacket", "will", "store", "a", "packet", "in", "the", "session", ".", "An", "eventual", "existing", "packet", "with", "the", "same", "id", "gets", "quietly", "overwritten", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/memory_session.go#L43-L46
9,959
256dpi/gomqtt
session/memory_session.go
LookupPacket
func (s *MemorySession) LookupPacket(dir Direction, id packet.ID) (packet.Generic, error) { return s.storeForDirection(dir).Lookup(id), nil }
go
func (s *MemorySession) LookupPacket(dir Direction, id packet.ID) (packet.Generic, error) { return s.storeForDirection(dir).Lookup(id), nil }
[ "func", "(", "s", "*", "MemorySession", ")", "LookupPacket", "(", "dir", "Direction", ",", "id", "packet", ".", "ID", ")", "(", "packet", ".", "Generic", ",", "error", ")", "{", "return", "s", ".", "storeForDirection", "(", "dir", ")", ".", "Lookup", ...
// LookupPacket will retrieve a packet from the session using a packet id.
[ "LookupPacket", "will", "retrieve", "a", "packet", "from", "the", "session", "using", "a", "packet", "id", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/memory_session.go#L49-L51
9,960
256dpi/gomqtt
session/memory_session.go
DeletePacket
func (s *MemorySession) DeletePacket(dir Direction, id packet.ID) error { s.storeForDirection(dir).Delete(id) return nil }
go
func (s *MemorySession) DeletePacket(dir Direction, id packet.ID) error { s.storeForDirection(dir).Delete(id) return nil }
[ "func", "(", "s", "*", "MemorySession", ")", "DeletePacket", "(", "dir", "Direction", ",", "id", "packet", ".", "ID", ")", "error", "{", "s", ".", "storeForDirection", "(", "dir", ")", ".", "Delete", "(", "id", ")", "\n", "return", "nil", "\n", "}" ]
// DeletePacket will remove a packet from the session. The method must not // return an error if no packet with the specified id does exists.
[ "DeletePacket", "will", "remove", "a", "packet", "from", "the", "session", ".", "The", "method", "must", "not", "return", "an", "error", "if", "no", "packet", "with", "the", "specified", "id", "does", "exists", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/memory_session.go#L55-L58
9,961
256dpi/gomqtt
session/memory_session.go
AllPackets
func (s *MemorySession) AllPackets(dir Direction) ([]packet.Generic, error) { return s.storeForDirection(dir).All(), nil }
go
func (s *MemorySession) AllPackets(dir Direction) ([]packet.Generic, error) { return s.storeForDirection(dir).All(), nil }
[ "func", "(", "s", "*", "MemorySession", ")", "AllPackets", "(", "dir", "Direction", ")", "(", "[", "]", "packet", ".", "Generic", ",", "error", ")", "{", "return", "s", ".", "storeForDirection", "(", "dir", ")", ".", "All", "(", ")", ",", "nil", "\...
// AllPackets will return all packets currently saved in the session.
[ "AllPackets", "will", "return", "all", "packets", "currently", "saved", "in", "the", "session", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/memory_session.go#L61-L63
9,962
256dpi/gomqtt
session/memory_session.go
Reset
func (s *MemorySession) Reset() error { // reset counter and stores s.Counter.Reset() s.Incoming.Reset() s.Outgoing.Reset() return nil }
go
func (s *MemorySession) Reset() error { // reset counter and stores s.Counter.Reset() s.Incoming.Reset() s.Outgoing.Reset() return nil }
[ "func", "(", "s", "*", "MemorySession", ")", "Reset", "(", ")", "error", "{", "// reset counter and stores", "s", ".", "Counter", ".", "Reset", "(", ")", "\n", "s", ".", "Incoming", ".", "Reset", "(", ")", "\n", "s", ".", "Outgoing", ".", "Reset", "(...
// Reset will completely reset the session.
[ "Reset", "will", "completely", "reset", "the", "session", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/memory_session.go#L66-L73
9,963
256dpi/gomqtt
packet/stream.go
NewEncoder
func NewEncoder(writer io.Writer, maxWriteDelay time.Duration) *Encoder { return &Encoder{ writer: mercury.NewWriter(writer, maxWriteDelay), } }
go
func NewEncoder(writer io.Writer, maxWriteDelay time.Duration) *Encoder { return &Encoder{ writer: mercury.NewWriter(writer, maxWriteDelay), } }
[ "func", "NewEncoder", "(", "writer", "io", ".", "Writer", ",", "maxWriteDelay", "time", ".", "Duration", ")", "*", "Encoder", "{", "return", "&", "Encoder", "{", "writer", ":", "mercury", ".", "NewWriter", "(", "writer", ",", "maxWriteDelay", ")", ",", "...
// NewEncoder creates a new Encoder.
[ "NewEncoder", "creates", "a", "new", "Encoder", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/stream.go#L28-L32
9,964
256dpi/gomqtt
packet/stream.go
Write
func (e *Encoder) Write(pkt Generic, async bool) error { // reset and eventually grow buffer packetLength := pkt.Len() e.buffer.Reset() e.buffer.Grow(packetLength) buf := e.buffer.Bytes()[0:packetLength] // encode packet _, err := pkt.Encode(buf) if err != nil { return err } // write buffer if async { _, err = e.writer.Write(buf) } else { _, err = e.writer.WriteAndFlush(buf) } if err != nil { return err } return nil }
go
func (e *Encoder) Write(pkt Generic, async bool) error { // reset and eventually grow buffer packetLength := pkt.Len() e.buffer.Reset() e.buffer.Grow(packetLength) buf := e.buffer.Bytes()[0:packetLength] // encode packet _, err := pkt.Encode(buf) if err != nil { return err } // write buffer if async { _, err = e.writer.Write(buf) } else { _, err = e.writer.WriteAndFlush(buf) } if err != nil { return err } return nil }
[ "func", "(", "e", "*", "Encoder", ")", "Write", "(", "pkt", "Generic", ",", "async", "bool", ")", "error", "{", "// reset and eventually grow buffer", "packetLength", ":=", "pkt", ".", "Len", "(", ")", "\n", "e", ".", "buffer", ".", "Reset", "(", ")", ...
// Write encodes and writes the passed packet to the write buffer.
[ "Write", "encodes", "and", "writes", "the", "passed", "packet", "to", "the", "write", "buffer", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/stream.go#L35-L59
9,965
256dpi/gomqtt
packet/stream.go
NewDecoder
func NewDecoder(reader io.Reader) *Decoder { return &Decoder{ reader: bufio.NewReader(reader), } }
go
func NewDecoder(reader io.Reader) *Decoder { return &Decoder{ reader: bufio.NewReader(reader), } }
[ "func", "NewDecoder", "(", "reader", "io", ".", "Reader", ")", "*", "Decoder", "{", "return", "&", "Decoder", "{", "reader", ":", "bufio", ".", "NewReader", "(", "reader", ")", ",", "}", "\n", "}" ]
// NewDecoder returns a new Decoder.
[ "NewDecoder", "returns", "a", "new", "Decoder", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/stream.go#L75-L79
9,966
256dpi/gomqtt
packet/stream.go
Read
func (d *Decoder) Read() (Generic, error) { // initial detection length detectionLength := 2 for { // check length if detectionLength > 5 { return nil, ErrDetectionOverflow } // try read detection bytes header, err := d.reader.Peek(detectionLength) if err == io.EOF && len(header) != 0 { // an EOF with some data is unexpected return nil, io.ErrUnexpectedEOF } else if err != nil { return nil, err } // detect packet packetLength, packetType := DetectPacket(header) // on zero packet length: // increment detection length and try again if packetLength <= 0 { detectionLength++ continue } // check read limit if d.Limit > 0 && int64(packetLength) > d.Limit { return nil, ErrReadLimitExceeded } // create packet pkt, err := packetType.New() if err != nil { return nil, err } // reset and eventually grow buffer d.buffer.Reset() d.buffer.Grow(packetLength) buf := d.buffer.Bytes()[0:packetLength] // read whole packet (will not return EOF) _, err = io.ReadFull(d.reader, buf) if err != nil { return nil, err } // decode buffer _, err = pkt.Decode(buf) if err != nil { return nil, err } return pkt, nil } }
go
func (d *Decoder) Read() (Generic, error) { // initial detection length detectionLength := 2 for { // check length if detectionLength > 5 { return nil, ErrDetectionOverflow } // try read detection bytes header, err := d.reader.Peek(detectionLength) if err == io.EOF && len(header) != 0 { // an EOF with some data is unexpected return nil, io.ErrUnexpectedEOF } else if err != nil { return nil, err } // detect packet packetLength, packetType := DetectPacket(header) // on zero packet length: // increment detection length and try again if packetLength <= 0 { detectionLength++ continue } // check read limit if d.Limit > 0 && int64(packetLength) > d.Limit { return nil, ErrReadLimitExceeded } // create packet pkt, err := packetType.New() if err != nil { return nil, err } // reset and eventually grow buffer d.buffer.Reset() d.buffer.Grow(packetLength) buf := d.buffer.Bytes()[0:packetLength] // read whole packet (will not return EOF) _, err = io.ReadFull(d.reader, buf) if err != nil { return nil, err } // decode buffer _, err = pkt.Decode(buf) if err != nil { return nil, err } return pkt, nil } }
[ "func", "(", "d", "*", "Decoder", ")", "Read", "(", ")", "(", "Generic", ",", "error", ")", "{", "// initial detection length", "detectionLength", ":=", "2", "\n\n", "for", "{", "// check length", "if", "detectionLength", ">", "5", "{", "return", "nil", ",...
// Read reads the next packet from the buffered reader.
[ "Read", "reads", "the", "next", "packet", "from", "the", "buffered", "reader", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/stream.go#L82-L141
9,967
256dpi/gomqtt
packet/stream.go
NewStream
func NewStream(reader io.Reader, writer io.Writer, maxWriteDelay time.Duration) *Stream { return &Stream{ Decoder: NewDecoder(reader), Encoder: NewEncoder(writer, maxWriteDelay), } }
go
func NewStream(reader io.Reader, writer io.Writer, maxWriteDelay time.Duration) *Stream { return &Stream{ Decoder: NewDecoder(reader), Encoder: NewEncoder(writer, maxWriteDelay), } }
[ "func", "NewStream", "(", "reader", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ",", "maxWriteDelay", "time", ".", "Duration", ")", "*", "Stream", "{", "return", "&", "Stream", "{", "Decoder", ":", "NewDecoder", "(", "reader", ")", ",", "E...
// NewStream creates a new Stream.
[ "NewStream", "creates", "a", "new", "Stream", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/stream.go#L150-L155
9,968
256dpi/gomqtt
packet/message.go
String
func (m *Message) String() string { return fmt.Sprintf("<Message Topic=%q QOS=%d Retain=%t Payload=%v>", m.Topic, m.QOS, m.Retain, m.Payload) }
go
func (m *Message) String() string { return fmt.Sprintf("<Message Topic=%q QOS=%d Retain=%t Payload=%v>", m.Topic, m.QOS, m.Retain, m.Payload) }
[ "func", "(", "m", "*", "Message", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "Topic", ",", "m", ".", "QOS", ",", "m", ".", "Retain", ",", "m", ".", "Payload", ")", "\n", "}" ]
// String returns a string representation of the message.
[ "String", "returns", "a", "string", "representation", "of", "the", "message", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/message.go#L23-L26
9,969
256dpi/gomqtt
topic/topic.go
Parse
func Parse(topic string, allowWildcards bool) (string, error) { // check for zero length if topic == "" { return "", ErrZeroLength } // normalize topic topic = multiSlashRegex.ReplaceAllString(topic, "/") // remove trailing slashes topic = strings.TrimRight(topic, "/") // check again for zero length if topic == "" { return "", ErrZeroLength } // split to segments segments := strings.Split(topic, "/") // check all segments for i, s := range segments { // check use of wildcards if (strings.Contains(s, "+") || strings.Contains(s, "#")) && len(s) > 1 { return "", ErrWildcards } // check if wildcards are allowed if !allowWildcards && (s == "#" || s == "+") { return "", ErrWildcards } // check if hash is the last character if s == "#" && i != len(segments)-1 { return "", ErrWildcards } } return topic, nil }
go
func Parse(topic string, allowWildcards bool) (string, error) { // check for zero length if topic == "" { return "", ErrZeroLength } // normalize topic topic = multiSlashRegex.ReplaceAllString(topic, "/") // remove trailing slashes topic = strings.TrimRight(topic, "/") // check again for zero length if topic == "" { return "", ErrZeroLength } // split to segments segments := strings.Split(topic, "/") // check all segments for i, s := range segments { // check use of wildcards if (strings.Contains(s, "+") || strings.Contains(s, "#")) && len(s) > 1 { return "", ErrWildcards } // check if wildcards are allowed if !allowWildcards && (s == "#" || s == "+") { return "", ErrWildcards } // check if hash is the last character if s == "#" && i != len(segments)-1 { return "", ErrWildcards } } return topic, nil }
[ "func", "Parse", "(", "topic", "string", ",", "allowWildcards", "bool", ")", "(", "string", ",", "error", ")", "{", "// check for zero length", "if", "topic", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "ErrZeroLength", "\n", "}", "\n\n", "// normali...
// Parse removes duplicate and trailing slashes from the supplied // string and returns the normalized topic.
[ "Parse", "removes", "duplicate", "and", "trailing", "slashes", "from", "the", "supplied", "string", "and", "returns", "the", "normalized", "topic", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/topic/topic.go#L20-L59
9,970
256dpi/gomqtt
topic/topic.go
ContainsWildcards
func ContainsWildcards(topic string) bool { return strings.Contains(topic, "+") || strings.Contains(topic, "#") }
go
func ContainsWildcards(topic string) bool { return strings.Contains(topic, "+") || strings.Contains(topic, "#") }
[ "func", "ContainsWildcards", "(", "topic", "string", ")", "bool", "{", "return", "strings", ".", "Contains", "(", "topic", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "topic", ",", "\"", "\"", ")", "\n", "}" ]
// ContainsWildcards tests if the supplied topic contains wildcards. The topics // is expected to be tested and normalized using Parse beforehand.
[ "ContainsWildcards", "tests", "if", "the", "supplied", "topic", "contains", "wildcards", ".", "The", "topics", "is", "expected", "to", "be", "tested", "and", "normalized", "using", "Parse", "beforehand", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/topic/topic.go#L63-L65
9,971
256dpi/gomqtt
packet/naked.go
nakedDecode
func nakedDecode(src []byte, t Type) (int, error) { // decode header hl, _, rl, err := headerDecode(src, t) // check remaining length if rl != 0 { return hl, makeError(t, "expected zero remaining length") } return hl, err }
go
func nakedDecode(src []byte, t Type) (int, error) { // decode header hl, _, rl, err := headerDecode(src, t) // check remaining length if rl != 0 { return hl, makeError(t, "expected zero remaining length") } return hl, err }
[ "func", "nakedDecode", "(", "src", "[", "]", "byte", ",", "t", "Type", ")", "(", "int", ",", "error", ")", "{", "// decode header", "hl", ",", "_", ",", "rl", ",", "err", ":=", "headerDecode", "(", "src", ",", "t", ")", "\n\n", "// check remaining le...
// decodes a naked packet
[ "decodes", "a", "naked", "packet" ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/naked.go#L9-L19
9,972
256dpi/gomqtt
packet/naked.go
nakedEncode
func nakedEncode(dst []byte, t Type) (int, error) { // encode header return headerEncode(dst, 0, 0, nakedLen(), t) }
go
func nakedEncode(dst []byte, t Type) (int, error) { // encode header return headerEncode(dst, 0, 0, nakedLen(), t) }
[ "func", "nakedEncode", "(", "dst", "[", "]", "byte", ",", "t", "Type", ")", "(", "int", ",", "error", ")", "{", "// encode header", "return", "headerEncode", "(", "dst", ",", "0", ",", "0", ",", "nakedLen", "(", ")", ",", "t", ")", "\n", "}" ]
// encodes a naked packet
[ "encodes", "a", "naked", "packet" ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/packet/naked.go#L22-L25
9,973
256dpi/gomqtt
client/future/store.go
Put
func (s *Store) Put(id packet.ID, future *Future) { s.Lock() defer s.Unlock() s.store[id] = future }
go
func (s *Store) Put(id packet.ID, future *Future) { s.Lock() defer s.Unlock() s.store[id] = future }
[ "func", "(", "s", "*", "Store", ")", "Put", "(", "id", "packet", ".", "ID", ",", "future", "*", "Future", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "s", ".", "store", "[", "id", "]", "=", "fu...
// Put will save a future to the store.
[ "Put", "will", "save", "a", "future", "to", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L26-L31
9,974
256dpi/gomqtt
client/future/store.go
Get
func (s *Store) Get(id packet.ID) *Future { s.RLock() defer s.RUnlock() return s.store[id] }
go
func (s *Store) Get(id packet.ID) *Future { s.RLock() defer s.RUnlock() return s.store[id] }
[ "func", "(", "s", "*", "Store", ")", "Get", "(", "id", "packet", ".", "ID", ")", "*", "Future", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "store", "[", "id", "]", "\n", "}" ]
// Get will retrieve a future from the store.
[ "Get", "will", "retrieve", "a", "future", "from", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L34-L39
9,975
256dpi/gomqtt
client/future/store.go
Delete
func (s *Store) Delete(id packet.ID) { s.Lock() defer s.Unlock() delete(s.store, id) }
go
func (s *Store) Delete(id packet.ID) { s.Lock() defer s.Unlock() delete(s.store, id) }
[ "func", "(", "s", "*", "Store", ")", "Delete", "(", "id", "packet", ".", "ID", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "s", ".", "store", ",", "id", ")", "\n", "}" ]
// Delete will remove a future from the store.
[ "Delete", "will", "remove", "a", "future", "from", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L42-L47
9,976
256dpi/gomqtt
client/future/store.go
All
func (s *Store) All() []*Future { s.RLock() defer s.RUnlock() all := make([]*Future, 0, len(s.store)) for _, savedFuture := range s.store { all = append(all, savedFuture) } return all }
go
func (s *Store) All() []*Future { s.RLock() defer s.RUnlock() all := make([]*Future, 0, len(s.store)) for _, savedFuture := range s.store { all = append(all, savedFuture) } return all }
[ "func", "(", "s", "*", "Store", ")", "All", "(", ")", "[", "]", "*", "Future", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "all", ":=", "make", "(", "[", "]", "*", "Future", ",", "0", ",", "len", ...
// All will return a slice with all stored futures.
[ "All", "will", "return", "a", "slice", "with", "all", "stored", "futures", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L50-L61
9,977
256dpi/gomqtt
client/future/store.go
Protect
func (s *Store) Protect(value bool) { s.Lock() defer s.Unlock() s.protected = value }
go
func (s *Store) Protect(value bool) { s.Lock() defer s.Unlock() s.protected = value }
[ "func", "(", "s", "*", "Store", ")", "Protect", "(", "value", "bool", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "s", ".", "protected", "=", "value", "\n", "}" ]
// Protect will set the protection attribute and if true prevents the store from // being cleared.
[ "Protect", "will", "set", "the", "protection", "attribute", "and", "if", "true", "prevents", "the", "store", "from", "being", "cleared", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L65-L70
9,978
256dpi/gomqtt
client/future/store.go
Clear
func (s *Store) Clear() { s.Lock() defer s.Unlock() if s.protected { return } for _, savedFuture := range s.store { savedFuture.Cancel() } s.store = make(map[packet.ID]*Future) }
go
func (s *Store) Clear() { s.Lock() defer s.Unlock() if s.protected { return } for _, savedFuture := range s.store { savedFuture.Cancel() } s.store = make(map[packet.ID]*Future) }
[ "func", "(", "s", "*", "Store", ")", "Clear", "(", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "protected", "{", "return", "\n", "}", "\n\n", "for", "_", ",", "savedFuture", ":=", ...
// Clear will cancel all stored futures and remove them if the store is unprotected.
[ "Clear", "will", "cancel", "all", "stored", "futures", "and", "remove", "them", "if", "the", "store", "is", "unprotected", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L73-L86
9,979
256dpi/gomqtt
client/future/store.go
Await
func (s *Store) Await(timeout time.Duration) error { stop := time.Now().Add(timeout) for { // Get futures s.RLock() futures := s.All() s.RUnlock() // return if no futures are left if len(futures) == 0 { return nil } // wait for next future to complete err := futures[0].Wait(stop.Sub(time.Now())) if err != nil { return err } } }
go
func (s *Store) Await(timeout time.Duration) error { stop := time.Now().Add(timeout) for { // Get futures s.RLock() futures := s.All() s.RUnlock() // return if no futures are left if len(futures) == 0 { return nil } // wait for next future to complete err := futures[0].Wait(stop.Sub(time.Now())) if err != nil { return err } } }
[ "func", "(", "s", "*", "Store", ")", "Await", "(", "timeout", "time", ".", "Duration", ")", "error", "{", "stop", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "timeout", ")", "\n\n", "for", "{", "// Get futures", "s", ".", "RLock", "(", "...
// Await will wait until all futures have completed and removed or timeout is // reached.
[ "Await", "will", "wait", "until", "all", "futures", "have", "completed", "and", "removed", "or", "timeout", "is", "reached", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/future/store.go#L90-L110
9,980
256dpi/gomqtt
transport/base_conn.go
NewBaseConn
func NewBaseConn(c Carrier, maxWriteDelay time.Duration) *BaseConn { return &BaseConn{ carrier: c, stream: packet.NewStream(c, c, maxWriteDelay), } }
go
func NewBaseConn(c Carrier, maxWriteDelay time.Duration) *BaseConn { return &BaseConn{ carrier: c, stream: packet.NewStream(c, c, maxWriteDelay), } }
[ "func", "NewBaseConn", "(", "c", "Carrier", ",", "maxWriteDelay", "time", ".", "Duration", ")", "*", "BaseConn", "{", "return", "&", "BaseConn", "{", "carrier", ":", "c", ",", "stream", ":", "packet", ".", "NewStream", "(", "c", ",", "c", ",", "maxWrit...
// NewBaseConn creates a new BaseConn using the specified Carrier.
[ "NewBaseConn", "creates", "a", "new", "BaseConn", "using", "the", "specified", "Carrier", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/base_conn.go#L32-L37
9,981
256dpi/gomqtt
transport/base_conn.go
Close
func (c *BaseConn) Close() error { c.sMutex.Lock() defer c.sMutex.Unlock() // flush buffer err1 := c.stream.Flush() // close carrier err2 := c.carrier.Close() // handle errors if err1 != nil { return err1 } else if err2 != nil { return err2 } return nil }
go
func (c *BaseConn) Close() error { c.sMutex.Lock() defer c.sMutex.Unlock() // flush buffer err1 := c.stream.Flush() // close carrier err2 := c.carrier.Close() // handle errors if err1 != nil { return err1 } else if err2 != nil { return err2 } return nil }
[ "func", "(", "c", "*", "BaseConn", ")", "Close", "(", ")", "error", "{", "c", ".", "sMutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "sMutex", ".", "Unlock", "(", ")", "\n\n", "// flush buffer", "err1", ":=", "c", ".", "stream", ".", "Flu...
// Close will close the underlying connection and cleanup resources. It will // return an Error if there was an error while closing the underlying // connection.
[ "Close", "will", "close", "the", "underlying", "connection", "and", "cleanup", "resources", ".", "It", "will", "return", "an", "Error", "if", "there", "was", "an", "error", "while", "closing", "the", "underlying", "connection", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/base_conn.go#L91-L109
9,982
256dpi/gomqtt
transport/base_conn.go
SetReadLimit
func (c *BaseConn) SetReadLimit(limit int64) { c.stream.Decoder.Limit = limit }
go
func (c *BaseConn) SetReadLimit(limit int64) { c.stream.Decoder.Limit = limit }
[ "func", "(", "c", "*", "BaseConn", ")", "SetReadLimit", "(", "limit", "int64", ")", "{", "c", ".", "stream", ".", "Decoder", ".", "Limit", "=", "limit", "\n", "}" ]
// SetReadLimit sets the maximum size of a packet that can be received. // If the limit is greater than zero, Receive will close the connection and // return an Error if receiving the next packet will exceed the limit.
[ "SetReadLimit", "sets", "the", "maximum", "size", "of", "a", "packet", "that", "can", "be", "received", ".", "If", "the", "limit", "is", "greater", "than", "zero", "Receive", "will", "close", "the", "connection", "and", "return", "an", "Error", "if", "rece...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/base_conn.go#L114-L116
9,983
256dpi/gomqtt
transport/base_conn.go
SetReadTimeout
func (c *BaseConn) SetReadTimeout(timeout time.Duration) { c.readTimeout = timeout // apply new timeout immediately _ = c.resetTimeout() }
go
func (c *BaseConn) SetReadTimeout(timeout time.Duration) { c.readTimeout = timeout // apply new timeout immediately _ = c.resetTimeout() }
[ "func", "(", "c", "*", "BaseConn", ")", "SetReadTimeout", "(", "timeout", "time", ".", "Duration", ")", "{", "c", ".", "readTimeout", "=", "timeout", "\n\n", "// apply new timeout immediately", "_", "=", "c", ".", "resetTimeout", "(", ")", "\n", "}" ]
// SetReadTimeout sets the maximum time that can pass between reads. // If no data is received in the set duration the connection will be closed // and Read returns an error.
[ "SetReadTimeout", "sets", "the", "maximum", "time", "that", "can", "pass", "between", "reads", ".", "If", "no", "data", "is", "received", "in", "the", "set", "duration", "the", "connection", "will", "be", "closed", "and", "Read", "returns", "an", "error", ...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/transport/base_conn.go#L121-L126
9,984
256dpi/gomqtt
session/packet_store.go
NewPacketStoreWithPackets
func NewPacketStoreWithPackets(packets []packet.Generic) *PacketStore { // prepare store store := &PacketStore{ packets: make(map[packet.ID]packet.Generic), } // add packets for _, pkt := range packets { store.Save(pkt) } return store }
go
func NewPacketStoreWithPackets(packets []packet.Generic) *PacketStore { // prepare store store := &PacketStore{ packets: make(map[packet.ID]packet.Generic), } // add packets for _, pkt := range packets { store.Save(pkt) } return store }
[ "func", "NewPacketStoreWithPackets", "(", "packets", "[", "]", "packet", ".", "Generic", ")", "*", "PacketStore", "{", "// prepare store", "store", ":=", "&", "PacketStore", "{", "packets", ":", "make", "(", "map", "[", "packet", ".", "ID", "]", "packet", ...
// NewPacketStoreWithPackets returns a new PacketStore with the provided packets.
[ "NewPacketStoreWithPackets", "returns", "a", "new", "PacketStore", "with", "the", "provided", "packets", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/packet_store.go#L23-L35
9,985
256dpi/gomqtt
session/packet_store.go
Save
func (s *PacketStore) Save(pkt packet.Generic) { s.mutex.Lock() defer s.mutex.Unlock() id, ok := packet.GetID(pkt) if ok { s.packets[id] = pkt } }
go
func (s *PacketStore) Save(pkt packet.Generic) { s.mutex.Lock() defer s.mutex.Unlock() id, ok := packet.GetID(pkt) if ok { s.packets[id] = pkt } }
[ "func", "(", "s", "*", "PacketStore", ")", "Save", "(", "pkt", "packet", ".", "Generic", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "id", ",", "ok", ":=", "packet", "."...
// Save will store a packet in the store. An eventual existing packet with the // same id gets quietly overwritten.
[ "Save", "will", "store", "a", "packet", "in", "the", "store", ".", "An", "eventual", "existing", "packet", "with", "the", "same", "id", "gets", "quietly", "overwritten", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/packet_store.go#L39-L47
9,986
256dpi/gomqtt
session/packet_store.go
Lookup
func (s *PacketStore) Lookup(id packet.ID) packet.Generic { s.mutex.RLock() defer s.mutex.RUnlock() return s.packets[id] }
go
func (s *PacketStore) Lookup(id packet.ID) packet.Generic { s.mutex.RLock() defer s.mutex.RUnlock() return s.packets[id] }
[ "func", "(", "s", "*", "PacketStore", ")", "Lookup", "(", "id", "packet", ".", "ID", ")", "packet", ".", "Generic", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "return", "s",...
// Lookup will retrieve a packet from the store.
[ "Lookup", "will", "retrieve", "a", "packet", "from", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/packet_store.go#L50-L55
9,987
256dpi/gomqtt
session/packet_store.go
Delete
func (s *PacketStore) Delete(id packet.ID) { s.mutex.Lock() defer s.mutex.Unlock() delete(s.packets, id) }
go
func (s *PacketStore) Delete(id packet.ID) { s.mutex.Lock() defer s.mutex.Unlock() delete(s.packets, id) }
[ "func", "(", "s", "*", "PacketStore", ")", "Delete", "(", "id", "packet", ".", "ID", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "s", ".", "packets", ",",...
// Delete will remove a packet from the store.
[ "Delete", "will", "remove", "a", "packet", "from", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/packet_store.go#L58-L63
9,988
256dpi/gomqtt
session/packet_store.go
All
func (s *PacketStore) All() []packet.Generic { s.mutex.RLock() defer s.mutex.RUnlock() var all []packet.Generic for _, pkt := range s.packets { all = append(all, pkt) } return all }
go
func (s *PacketStore) All() []packet.Generic { s.mutex.RLock() defer s.mutex.RUnlock() var all []packet.Generic for _, pkt := range s.packets { all = append(all, pkt) } return all }
[ "func", "(", "s", "*", "PacketStore", ")", "All", "(", ")", "[", "]", "packet", ".", "Generic", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "var", "all", "[", "]", "packet"...
// All will return all packets currently saved in the store.
[ "All", "will", "return", "all", "packets", "currently", "saved", "in", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/packet_store.go#L66-L77
9,989
256dpi/gomqtt
session/packet_store.go
Reset
func (s *PacketStore) Reset() { s.mutex.Lock() defer s.mutex.Unlock() s.packets = make(map[packet.ID]packet.Generic) }
go
func (s *PacketStore) Reset() { s.mutex.Lock() defer s.mutex.Unlock() s.packets = make(map[packet.ID]packet.Generic) }
[ "func", "(", "s", "*", "PacketStore", ")", "Reset", "(", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "s", ".", "packets", "=", "make", "(", "map", "[", "packet", ".", ...
// Reset will reset the store.
[ "Reset", "will", "reset", "the", "store", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/session/packet_store.go#L80-L85
9,990
256dpi/gomqtt
client/client.go
New
func New() *Client { return &Client{ state: clientInitialized, Session: session.NewMemorySession(), futureStore: future.NewStore(), } }
go
func New() *Client { return &Client{ state: clientInitialized, Session: session.NewMemorySession(), futureStore: future.NewStore(), } }
[ "func", "New", "(", ")", "*", "Client", "{", "return", "&", "Client", "{", "state", ":", "clientInitialized", ",", "Session", ":", "session", ".", "NewMemorySession", "(", ")", ",", "futureStore", ":", "future", ".", "NewStore", "(", ")", ",", "}", "\n...
// New returns a new client that by default uses a fresh MemorySession.
[ "New", "returns", "a", "new", "client", "that", "by", "default", "uses", "a", "fresh", "MemorySession", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L135-L141
9,991
256dpi/gomqtt
client/client.go
Connect
func (c *Client) Connect(config *Config) (ConnectFuture, error) { if config == nil { panic("no config specified") } c.mutex.Lock() defer c.mutex.Unlock() // check if already connecting if atomic.LoadUint32(&c.state) >= clientConnecting { return nil, ErrClientAlreadyConnecting } // save config c.config = config // parse url urlParts, err := url.ParseRequestURI(config.BrokerURL) if err != nil { return nil, err } // check client id if !config.CleanSession && config.ClientID == "" { return nil, ErrClientMissingID } // parse keep alive keepAlive, err := time.ParseDuration(config.KeepAlive) if err != nil { return nil, err } // allocate and initialize tracker c.keepAlive = keepAlive c.tracker = NewTracker(keepAlive) // dial broker (with custom dialer if present) if config.Dialer != nil { c.conn, err = config.Dialer.Dial(config.BrokerURL) if err != nil { return nil, err } } else { c.conn, err = transport.Dial(config.BrokerURL) if err != nil { return nil, err } } // set to connecting as from this point the client cannot be reused atomic.StoreUint32(&c.state, clientConnecting) // from now on the connection has been used and we have to close the // connection and cleanup on any subsequent error // save clean c.clean = config.CleanSession // reset store if c.clean { err = c.Session.Reset() if err != nil { return nil, c.cleanup(err, true, false) } } // allocate packet connect := packet.NewConnect() connect.ClientID = config.ClientID connect.KeepAlive = uint16(keepAlive.Seconds()) connect.CleanSession = config.CleanSession // check for credentials if urlParts.User != nil { connect.Username = urlParts.User.Username() connect.Password, _ = urlParts.User.Password() } // set will connect.Will = config.WillMessage // create new ConnectFuture c.connectFuture = future.New() // send connect packet err = c.send(connect, false) if err != nil { return nil, c.cleanup(err, false, false) } // start process routine c.tomb.Go(c.processor) // wrap future wrappedFuture := &connectFuture{c.connectFuture} return wrappedFuture, nil }
go
func (c *Client) Connect(config *Config) (ConnectFuture, error) { if config == nil { panic("no config specified") } c.mutex.Lock() defer c.mutex.Unlock() // check if already connecting if atomic.LoadUint32(&c.state) >= clientConnecting { return nil, ErrClientAlreadyConnecting } // save config c.config = config // parse url urlParts, err := url.ParseRequestURI(config.BrokerURL) if err != nil { return nil, err } // check client id if !config.CleanSession && config.ClientID == "" { return nil, ErrClientMissingID } // parse keep alive keepAlive, err := time.ParseDuration(config.KeepAlive) if err != nil { return nil, err } // allocate and initialize tracker c.keepAlive = keepAlive c.tracker = NewTracker(keepAlive) // dial broker (with custom dialer if present) if config.Dialer != nil { c.conn, err = config.Dialer.Dial(config.BrokerURL) if err != nil { return nil, err } } else { c.conn, err = transport.Dial(config.BrokerURL) if err != nil { return nil, err } } // set to connecting as from this point the client cannot be reused atomic.StoreUint32(&c.state, clientConnecting) // from now on the connection has been used and we have to close the // connection and cleanup on any subsequent error // save clean c.clean = config.CleanSession // reset store if c.clean { err = c.Session.Reset() if err != nil { return nil, c.cleanup(err, true, false) } } // allocate packet connect := packet.NewConnect() connect.ClientID = config.ClientID connect.KeepAlive = uint16(keepAlive.Seconds()) connect.CleanSession = config.CleanSession // check for credentials if urlParts.User != nil { connect.Username = urlParts.User.Username() connect.Password, _ = urlParts.User.Password() } // set will connect.Will = config.WillMessage // create new ConnectFuture c.connectFuture = future.New() // send connect packet err = c.send(connect, false) if err != nil { return nil, c.cleanup(err, false, false) } // start process routine c.tomb.Go(c.processor) // wrap future wrappedFuture := &connectFuture{c.connectFuture} return wrappedFuture, nil }
[ "func", "(", "c", "*", "Client", ")", "Connect", "(", "config", "*", "Config", ")", "(", "ConnectFuture", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "c", ".", "mutex", ".", "Lock", ...
// Connect opens the connection to the broker and sends a Connect packet. It will // return a ConnectFuture that gets completed once a Connack has been // received. If the Connect packet couldn't be transmitted it will return an error.
[ "Connect", "opens", "the", "connection", "to", "the", "broker", "and", "sends", "a", "Connect", "packet", ".", "It", "will", "return", "a", "ConnectFuture", "that", "gets", "completed", "once", "a", "Connack", "has", "been", "received", ".", "If", "the", "...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L146-L244
9,992
256dpi/gomqtt
client/client.go
PublishMessage
func (c *Client) PublishMessage(msg *packet.Message) (GenericFuture, error) { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return nil, ErrClientNotConnected } // allocate publish packet publish := packet.NewPublish() publish.Message = *msg // set packet id if msg.QOS > 0 { publish.ID = c.Session.NextID() } // create future publishFuture := future.New() // store future c.futureStore.Put(publish.ID, publishFuture) // store packet if at least qos 1 if msg.QOS > 0 { err := c.Session.SavePacket(session.Outgoing, publish) if err != nil { return nil, c.cleanup(err, true, false) } } // send packet err := c.send(publish, true) if err != nil { return nil, c.cleanup(err, false, false) } // complete and remove qos 0 future if msg.QOS == 0 { publishFuture.Complete() c.futureStore.Delete(publish.ID) } return publishFuture, nil }
go
func (c *Client) PublishMessage(msg *packet.Message) (GenericFuture, error) { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return nil, ErrClientNotConnected } // allocate publish packet publish := packet.NewPublish() publish.Message = *msg // set packet id if msg.QOS > 0 { publish.ID = c.Session.NextID() } // create future publishFuture := future.New() // store future c.futureStore.Put(publish.ID, publishFuture) // store packet if at least qos 1 if msg.QOS > 0 { err := c.Session.SavePacket(session.Outgoing, publish) if err != nil { return nil, c.cleanup(err, true, false) } } // send packet err := c.send(publish, true) if err != nil { return nil, c.cleanup(err, false, false) } // complete and remove qos 0 future if msg.QOS == 0 { publishFuture.Complete() c.futureStore.Delete(publish.ID) } return publishFuture, nil }
[ "func", "(", "c", "*", "Client", ")", "PublishMessage", "(", "msg", "*", "packet", ".", "Message", ")", "(", "GenericFuture", ",", "error", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ...
// PublishMessage will send a Publish containing the passed message. It will // return a PublishFuture that gets completed once the quality of service flow // has been completed.
[ "PublishMessage", "will", "send", "a", "Publish", "containing", "the", "passed", "message", ".", "It", "will", "return", "a", "PublishFuture", "that", "gets", "completed", "once", "the", "quality", "of", "service", "flow", "has", "been", "completed", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L263-L308
9,993
256dpi/gomqtt
client/client.go
Subscribe
func (c *Client) Subscribe(topic string, qos packet.QOS) (SubscribeFuture, error) { return c.SubscribeMultiple([]packet.Subscription{ {Topic: topic, QOS: qos}, }) }
go
func (c *Client) Subscribe(topic string, qos packet.QOS) (SubscribeFuture, error) { return c.SubscribeMultiple([]packet.Subscription{ {Topic: topic, QOS: qos}, }) }
[ "func", "(", "c", "*", "Client", ")", "Subscribe", "(", "topic", "string", ",", "qos", "packet", ".", "QOS", ")", "(", "SubscribeFuture", ",", "error", ")", "{", "return", "c", ".", "SubscribeMultiple", "(", "[", "]", "packet", ".", "Subscription", "{"...
// Subscribe will send a Subscribe packet containing one topic to subscribe. It // will return a SubscribeFuture that gets completed once a Suback packet has // been received.
[ "Subscribe", "will", "send", "a", "Subscribe", "packet", "containing", "one", "topic", "to", "subscribe", ".", "It", "will", "return", "a", "SubscribeFuture", "that", "gets", "completed", "once", "a", "Suback", "packet", "has", "been", "received", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L313-L317
9,994
256dpi/gomqtt
client/client.go
SubscribeMultiple
func (c *Client) SubscribeMultiple(subscriptions []packet.Subscription) (SubscribeFuture, error) { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return nil, ErrClientNotConnected } // allocate subscribe packet subscribe := packet.NewSubscribe() subscribe.ID = c.Session.NextID() subscribe.Subscriptions = subscriptions // create future subFuture := future.New() // store future c.futureStore.Put(subscribe.ID, subFuture) // send packet err := c.send(subscribe, true) if err != nil { return nil, c.cleanup(err, false, false) } // wrap future wrappedFuture := &subscribeFuture{subFuture} return wrappedFuture, nil }
go
func (c *Client) SubscribeMultiple(subscriptions []packet.Subscription) (SubscribeFuture, error) { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return nil, ErrClientNotConnected } // allocate subscribe packet subscribe := packet.NewSubscribe() subscribe.ID = c.Session.NextID() subscribe.Subscriptions = subscriptions // create future subFuture := future.New() // store future c.futureStore.Put(subscribe.ID, subFuture) // send packet err := c.send(subscribe, true) if err != nil { return nil, c.cleanup(err, false, false) } // wrap future wrappedFuture := &subscribeFuture{subFuture} return wrappedFuture, nil }
[ "func", "(", "c", "*", "Client", ")", "SubscribeMultiple", "(", "subscriptions", "[", "]", "packet", ".", "Subscription", ")", "(", "SubscribeFuture", ",", "error", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ...
// SubscribeMultiple will send a Subscribe packet containing multiple topics to // subscribe. It will return a SubscribeFuture that gets completed once a // Suback packet has been received.
[ "SubscribeMultiple", "will", "send", "a", "Subscribe", "packet", "containing", "multiple", "topics", "to", "subscribe", ".", "It", "will", "return", "a", "SubscribeFuture", "that", "gets", "completed", "once", "a", "Suback", "packet", "has", "been", "received", ...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L322-L352
9,995
256dpi/gomqtt
client/client.go
Unsubscribe
func (c *Client) Unsubscribe(topic string) (GenericFuture, error) { return c.UnsubscribeMultiple([]string{topic}) }
go
func (c *Client) Unsubscribe(topic string) (GenericFuture, error) { return c.UnsubscribeMultiple([]string{topic}) }
[ "func", "(", "c", "*", "Client", ")", "Unsubscribe", "(", "topic", "string", ")", "(", "GenericFuture", ",", "error", ")", "{", "return", "c", ".", "UnsubscribeMultiple", "(", "[", "]", "string", "{", "topic", "}", ")", "\n", "}" ]
// Unsubscribe will send a Unsubscribe packet containing one topic to unsubscribe. // It will return a UnsubscribeFuture that gets completed once an Unsuback packet // has been received.
[ "Unsubscribe", "will", "send", "a", "Unsubscribe", "packet", "containing", "one", "topic", "to", "unsubscribe", ".", "It", "will", "return", "a", "UnsubscribeFuture", "that", "gets", "completed", "once", "an", "Unsuback", "packet", "has", "been", "received", "."...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L357-L359
9,996
256dpi/gomqtt
client/client.go
UnsubscribeMultiple
func (c *Client) UnsubscribeMultiple(topics []string) (GenericFuture, error) { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return nil, ErrClientNotConnected } // allocate unsubscribe packet unsubscribe := packet.NewUnsubscribe() unsubscribe.Topics = topics unsubscribe.ID = c.Session.NextID() // create future unsubscribeFuture := future.New() // store future c.futureStore.Put(unsubscribe.ID, unsubscribeFuture) // send packet err := c.send(unsubscribe, true) if err != nil { return nil, c.cleanup(err, false, false) } return unsubscribeFuture, nil }
go
func (c *Client) UnsubscribeMultiple(topics []string) (GenericFuture, error) { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return nil, ErrClientNotConnected } // allocate unsubscribe packet unsubscribe := packet.NewUnsubscribe() unsubscribe.Topics = topics unsubscribe.ID = c.Session.NextID() // create future unsubscribeFuture := future.New() // store future c.futureStore.Put(unsubscribe.ID, unsubscribeFuture) // send packet err := c.send(unsubscribe, true) if err != nil { return nil, c.cleanup(err, false, false) } return unsubscribeFuture, nil }
[ "func", "(", "c", "*", "Client", ")", "UnsubscribeMultiple", "(", "topics", "[", "]", "string", ")", "(", "GenericFuture", ",", "error", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", ...
// UnsubscribeMultiple will send a Unsubscribe packet containing multiple // topics to unsubscribe. It will return a UnsubscribeFuture that gets completed // once an Unsuback packet has been received.
[ "UnsubscribeMultiple", "will", "send", "a", "Unsubscribe", "packet", "containing", "multiple", "topics", "to", "unsubscribe", ".", "It", "will", "return", "a", "UnsubscribeFuture", "that", "gets", "completed", "once", "an", "Unsuback", "packet", "has", "been", "re...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L364-L391
9,997
256dpi/gomqtt
client/client.go
Disconnect
func (c *Client) Disconnect(timeout ...time.Duration) error { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return ErrClientNotConnected } // finish current packets if len(timeout) > 0 { c.futureStore.Await(timeout[0]) } // set state atomic.StoreUint32(&c.state, clientDisconnecting) // send disconnect packet err := c.send(packet.NewDisconnect(), false) return c.end(err, true) }
go
func (c *Client) Disconnect(timeout ...time.Duration) error { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) != clientConnected { return ErrClientNotConnected } // finish current packets if len(timeout) > 0 { c.futureStore.Await(timeout[0]) } // set state atomic.StoreUint32(&c.state, clientDisconnecting) // send disconnect packet err := c.send(packet.NewDisconnect(), false) return c.end(err, true) }
[ "func", "(", "c", "*", "Client", ")", "Disconnect", "(", "timeout", "...", "time", ".", "Duration", ")", "error", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// check if connected...
// Disconnect will send a Disconnect packet and close the connection. // // If a timeout is specified, the client will wait the specified amount of time // for all queued futures to complete or cancel. If no timeout is specified it // will not wait at all.
[ "Disconnect", "will", "send", "a", "Disconnect", "packet", "and", "close", "the", "connection", ".", "If", "a", "timeout", "is", "specified", "the", "client", "will", "wait", "the", "specified", "amount", "of", "time", "for", "all", "queued", "futures", "to"...
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L398-L419
9,998
256dpi/gomqtt
client/client.go
Close
func (c *Client) Close() error { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) < clientConnecting { return ErrClientNotConnected } return c.end(nil, false) }
go
func (c *Client) Close() error { c.mutex.Lock() defer c.mutex.Unlock() // check if connected if atomic.LoadUint32(&c.state) < clientConnecting { return ErrClientNotConnected } return c.end(nil, false) }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", ")", "error", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// check if connected", "if", "atomic", ".", "LoadUint32", "(", "&"...
// Close closes the client immediately without sending a Disconnect packet and // waiting for outgoing transmissions to finish.
[ "Close", "closes", "the", "client", "immediately", "without", "sending", "a", "Disconnect", "packet", "and", "waiting", "for", "outgoing", "transmissions", "to", "finish", "." ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L423-L433
9,999
256dpi/gomqtt
client/client.go
processConnack
func (c *Client) processConnack(connack *packet.Connack) error { // check state if atomic.LoadUint32(&c.state) != clientConnecting { return nil // ignore wrongly sent Connack packet } // set state atomic.StoreUint32(&c.state, clientConnacked) // fill future c.connectFuture.Data.Store(sessionPresentKey, connack.SessionPresent) c.connectFuture.Data.Store(returnCodeKey, connack.ReturnCode) // return connection denied error and close connection if not accepted if connack.ReturnCode != packet.ConnectionAccepted { err := c.die(ErrClientConnectionDenied, true, false) c.connectFuture.Cancel() return err } // set state to connected atomic.StoreUint32(&c.state, clientConnected) // complete future c.connectFuture.Complete() // retrieve stored packets packets, err := c.Session.AllPackets(session.Outgoing) if err != nil { return c.die(err, true, false) } // resend stored packets for _, pkt := range packets { // check for publish packets publish, ok := pkt.(*packet.Publish) if ok { // set the dup flag on a publish packet publish.Dup = true } // resend packet err = c.send(pkt, true) if err != nil { return c.die(err, false, false) } } return nil }
go
func (c *Client) processConnack(connack *packet.Connack) error { // check state if atomic.LoadUint32(&c.state) != clientConnecting { return nil // ignore wrongly sent Connack packet } // set state atomic.StoreUint32(&c.state, clientConnacked) // fill future c.connectFuture.Data.Store(sessionPresentKey, connack.SessionPresent) c.connectFuture.Data.Store(returnCodeKey, connack.ReturnCode) // return connection denied error and close connection if not accepted if connack.ReturnCode != packet.ConnectionAccepted { err := c.die(ErrClientConnectionDenied, true, false) c.connectFuture.Cancel() return err } // set state to connected atomic.StoreUint32(&c.state, clientConnected) // complete future c.connectFuture.Complete() // retrieve stored packets packets, err := c.Session.AllPackets(session.Outgoing) if err != nil { return c.die(err, true, false) } // resend stored packets for _, pkt := range packets { // check for publish packets publish, ok := pkt.(*packet.Publish) if ok { // set the dup flag on a publish packet publish.Dup = true } // resend packet err = c.send(pkt, true) if err != nil { return c.die(err, false, false) } } return nil }
[ "func", "(", "c", "*", "Client", ")", "processConnack", "(", "connack", "*", "packet", ".", "Connack", ")", "error", "{", "// check state", "if", "atomic", ".", "LoadUint32", "(", "&", "c", ".", "state", ")", "!=", "clientConnecting", "{", "return", "nil...
// handle the incoming Connack packet
[ "handle", "the", "incoming", "Connack", "packet" ]
84c68b46ee22292c5ac9c44c7678ac33ae14f130
https://github.com/256dpi/gomqtt/blob/84c68b46ee22292c5ac9c44c7678ac33ae14f130/client/client.go#L507-L556