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
partition
stringclasses
1 value
uber/ringpop-go
swim/handlers.go
errorHandler
func (n *Node) errorHandler(ctx context.Context, err error) { n.logger.WithField("error", err).Info("error occurred") }
go
func (n *Node) errorHandler(ctx context.Context, err error) { n.logger.WithField("error", err).Info("error occurred") }
[ "func", "(", "n", "*", "Node", ")", "errorHandler", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "{", "n", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "err", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// errorHandler is called when one of the handlers returns an error.
[ "errorHandler", "is", "called", "when", "one", "of", "the", "handlers", "returns", "an", "error", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/handlers.go#L166-L168
train
uber/ringpop-go
logging/level.go
String
func (lvl Level) String() string { switch lvl { case Panic: return "panic" case Fatal: return "fatal" case Error: return "error" case Warn: return "warn" case Info: return "info" case Debug: return "debug" } return strconv.Itoa(int(lvl)) }
go
func (lvl Level) String() string { switch lvl { case Panic: return "panic" case Fatal: return "fatal" case Error: return "error" case Warn: return "warn" case Info: return "info" case Debug: return "debug" } return strconv.Itoa(int(lvl)) }
[ "func", "(", "lvl", "Level", ")", "String", "(", ")", "string", "{", "switch", "lvl", "{", "case", "Panic", ":", "return", "\"", "\"", "\n", "case", "Fatal", ":", "return", "\"", "\"", "\n", "case", "Error", ":", "return", "\"", "\"", "\n", "case", "Warn", ":", "return", "\"", "\"", "\n", "case", "Info", ":", "return", "\"", "\"", "\n", "case", "Debug", ":", "return", "\"", "\"", "\n", "}", "\n", "return", "strconv", ".", "Itoa", "(", "int", "(", "lvl", ")", ")", "\n", "}" ]
// String converts a log level to its string representation.
[ "String", "converts", "a", "log", "level", "to", "its", "string", "representation", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/level.go#L52-L68
train
uber/ringpop-go
logging/level.go
Parse
func Parse(lvl string) (Level, error) { switch lvl { case "fatal": return Fatal, nil case "panic": return Panic, nil case "error": return Error, nil case "warn": return Warn, nil case "info": return Info, nil case "debug": return Debug, nil } level, err := strconv.Atoi(lvl) if level > maxLevel { err = fmt.Errorf("invalid level value: %s", lvl) } return Level(level), err }
go
func Parse(lvl string) (Level, error) { switch lvl { case "fatal": return Fatal, nil case "panic": return Panic, nil case "error": return Error, nil case "warn": return Warn, nil case "info": return Info, nil case "debug": return Debug, nil } level, err := strconv.Atoi(lvl) if level > maxLevel { err = fmt.Errorf("invalid level value: %s", lvl) } return Level(level), err }
[ "func", "Parse", "(", "lvl", "string", ")", "(", "Level", ",", "error", ")", "{", "switch", "lvl", "{", "case", "\"", "\"", ":", "return", "Fatal", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Panic", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Error", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Warn", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Info", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Debug", ",", "nil", "\n", "}", "\n\n", "level", ",", "err", ":=", "strconv", ".", "Atoi", "(", "lvl", ")", "\n", "if", "level", ">", "maxLevel", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "lvl", ")", "\n", "}", "\n", "return", "Level", "(", "level", ")", ",", "err", "\n", "}" ]
// Parse converts a string to a log level.
[ "Parse", "converts", "a", "string", "to", "a", "log", "level", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/level.go#L71-L92
train
uber/ringpop-go
swim/join_sender.go
newJoinSender
func newJoinSender(node *Node, opts *joinOpts) (*joinSender, error) { if opts == nil { opts = &joinOpts{} } if node.discoverProvider == nil { return nil, errors.New("no discover provider") } // Resolve/retrieve bootstrap hosts from the provider specified in the // join options. bootstrapHosts, err := node.discoverProvider.Hosts() if err != nil { return nil, err } // Check we're in the bootstrap host list and add ourselves if we're not // there. If the host list is empty, this will create a single-node // cluster. if !util.StringInSlice(bootstrapHosts, node.Address()) { bootstrapHosts = append(bootstrapHosts, node.Address()) } js := &joinSender{ node: node, logger: logging.Logger("join").WithField("local", node.Address()), } // Parse bootstrap hosts into a map js.parseHosts(bootstrapHosts) js.potentialNodes = js.CollectPotentialNodes(nil) js.timeout = util.SelectDuration(opts.timeout, defaultJoinTimeout) js.maxJoinDuration = util.SelectDuration(opts.maxJoinDuration, defaultMaxJoinDuration) js.parallelismFactor = util.SelectInt(opts.parallelismFactor, defaultParallelismFactor) js.size = util.SelectInt(opts.size, defaultJoinSize) js.size = util.Min(js.size, len(js.potentialNodes)) js.delayer = opts.delayer if js.delayer == nil { // Create and use exponential delayer as the delay mechanism. Create it // with nil opts which uses default delayOpts. js.delayer, err = newExponentialDelayer(js.node.address, nil) if err != nil { return nil, err } } return js, nil }
go
func newJoinSender(node *Node, opts *joinOpts) (*joinSender, error) { if opts == nil { opts = &joinOpts{} } if node.discoverProvider == nil { return nil, errors.New("no discover provider") } // Resolve/retrieve bootstrap hosts from the provider specified in the // join options. bootstrapHosts, err := node.discoverProvider.Hosts() if err != nil { return nil, err } // Check we're in the bootstrap host list and add ourselves if we're not // there. If the host list is empty, this will create a single-node // cluster. if !util.StringInSlice(bootstrapHosts, node.Address()) { bootstrapHosts = append(bootstrapHosts, node.Address()) } js := &joinSender{ node: node, logger: logging.Logger("join").WithField("local", node.Address()), } // Parse bootstrap hosts into a map js.parseHosts(bootstrapHosts) js.potentialNodes = js.CollectPotentialNodes(nil) js.timeout = util.SelectDuration(opts.timeout, defaultJoinTimeout) js.maxJoinDuration = util.SelectDuration(opts.maxJoinDuration, defaultMaxJoinDuration) js.parallelismFactor = util.SelectInt(opts.parallelismFactor, defaultParallelismFactor) js.size = util.SelectInt(opts.size, defaultJoinSize) js.size = util.Min(js.size, len(js.potentialNodes)) js.delayer = opts.delayer if js.delayer == nil { // Create and use exponential delayer as the delay mechanism. Create it // with nil opts which uses default delayOpts. js.delayer, err = newExponentialDelayer(js.node.address, nil) if err != nil { return nil, err } } return js, nil }
[ "func", "newJoinSender", "(", "node", "*", "Node", ",", "opts", "*", "joinOpts", ")", "(", "*", "joinSender", ",", "error", ")", "{", "if", "opts", "==", "nil", "{", "opts", "=", "&", "joinOpts", "{", "}", "\n", "}", "\n\n", "if", "node", ".", "discoverProvider", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Resolve/retrieve bootstrap hosts from the provider specified in the", "// join options.", "bootstrapHosts", ",", "err", ":=", "node", ".", "discoverProvider", ".", "Hosts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check we're in the bootstrap host list and add ourselves if we're not", "// there. If the host list is empty, this will create a single-node", "// cluster.", "if", "!", "util", ".", "StringInSlice", "(", "bootstrapHosts", ",", "node", ".", "Address", "(", ")", ")", "{", "bootstrapHosts", "=", "append", "(", "bootstrapHosts", ",", "node", ".", "Address", "(", ")", ")", "\n", "}", "\n\n", "js", ":=", "&", "joinSender", "{", "node", ":", "node", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "node", ".", "Address", "(", ")", ")", ",", "}", "\n\n", "// Parse bootstrap hosts into a map", "js", ".", "parseHosts", "(", "bootstrapHosts", ")", "\n\n", "js", ".", "potentialNodes", "=", "js", ".", "CollectPotentialNodes", "(", "nil", ")", "\n\n", "js", ".", "timeout", "=", "util", ".", "SelectDuration", "(", "opts", ".", "timeout", ",", "defaultJoinTimeout", ")", "\n", "js", ".", "maxJoinDuration", "=", "util", ".", "SelectDuration", "(", "opts", ".", "maxJoinDuration", ",", "defaultMaxJoinDuration", ")", "\n", "js", ".", "parallelismFactor", "=", "util", ".", "SelectInt", "(", "opts", ".", "parallelismFactor", ",", "defaultParallelismFactor", ")", "\n", "js", ".", "size", "=", "util", ".", "SelectInt", "(", "opts", ".", "size", ",", "defaultJoinSize", ")", "\n", "js", ".", "size", "=", "util", ".", "Min", "(", "js", ".", "size", ",", "len", "(", "js", ".", "potentialNodes", ")", ")", "\n", "js", ".", "delayer", "=", "opts", ".", "delayer", "\n\n", "if", "js", ".", "delayer", "==", "nil", "{", "// Create and use exponential delayer as the delay mechanism. Create it", "// with nil opts which uses default delayOpts.", "js", ".", "delayer", ",", "err", "=", "newExponentialDelayer", "(", "js", ".", "node", ".", "address", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "js", ",", "nil", "\n", "}" ]
// newJoinSender returns a new JoinSender to join a cluster with
[ "newJoinSender", "returns", "a", "new", "JoinSender", "to", "join", "a", "cluster", "with" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L118-L168
train
uber/ringpop-go
swim/join_sender.go
parseHosts
func (j *joinSender) parseHosts(hostports []string) { // Parse bootstrap hosts into a map j.bootstrapHostsMap = util.HostPortsByHost(hostports) // Perform some sanity checks on the bootstrap hosts err := util.CheckLocalMissing(j.node.address, j.bootstrapHostsMap[util.CaptureHost(j.node.address)]) if err != nil { j.logger.Warn(err.Error()) } mismatched, err := util.CheckHostnameIPMismatch(j.node.address, j.bootstrapHostsMap) if err != nil { j.logger.WithField("mismatched", mismatched).Warn(err.Error()) } }
go
func (j *joinSender) parseHosts(hostports []string) { // Parse bootstrap hosts into a map j.bootstrapHostsMap = util.HostPortsByHost(hostports) // Perform some sanity checks on the bootstrap hosts err := util.CheckLocalMissing(j.node.address, j.bootstrapHostsMap[util.CaptureHost(j.node.address)]) if err != nil { j.logger.Warn(err.Error()) } mismatched, err := util.CheckHostnameIPMismatch(j.node.address, j.bootstrapHostsMap) if err != nil { j.logger.WithField("mismatched", mismatched).Warn(err.Error()) } }
[ "func", "(", "j", "*", "joinSender", ")", "parseHosts", "(", "hostports", "[", "]", "string", ")", "{", "// Parse bootstrap hosts into a map", "j", ".", "bootstrapHostsMap", "=", "util", ".", "HostPortsByHost", "(", "hostports", ")", "\n\n", "// Perform some sanity checks on the bootstrap hosts", "err", ":=", "util", ".", "CheckLocalMissing", "(", "j", ".", "node", ".", "address", ",", "j", ".", "bootstrapHostsMap", "[", "util", ".", "CaptureHost", "(", "j", ".", "node", ".", "address", ")", "]", ")", "\n", "if", "err", "!=", "nil", "{", "j", ".", "logger", ".", "Warn", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "mismatched", ",", "err", ":=", "util", ".", "CheckHostnameIPMismatch", "(", "j", ".", "node", ".", "address", ",", "j", ".", "bootstrapHostsMap", ")", "\n", "if", "err", "!=", "nil", "{", "j", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "mismatched", ")", ".", "Warn", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// parseHosts populates the bootstrap hosts map from the provided slice of // hostports.
[ "parseHosts", "populates", "the", "bootstrap", "hosts", "map", "from", "the", "provided", "slice", "of", "hostports", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L172-L186
train
uber/ringpop-go
swim/join_sender.go
CollectPotentialNodes
func (j *joinSender) CollectPotentialNodes(nodesJoined []string) []string { if nodesJoined == nil { nodesJoined = make([]string, 0) } var potentialNodes []string for _, hostports := range j.bootstrapHostsMap { for _, hostport := range hostports { if j.node.address != hostport && !util.StringInSlice(nodesJoined, hostport) { potentialNodes = append(potentialNodes, hostport) } } } return potentialNodes }
go
func (j *joinSender) CollectPotentialNodes(nodesJoined []string) []string { if nodesJoined == nil { nodesJoined = make([]string, 0) } var potentialNodes []string for _, hostports := range j.bootstrapHostsMap { for _, hostport := range hostports { if j.node.address != hostport && !util.StringInSlice(nodesJoined, hostport) { potentialNodes = append(potentialNodes, hostport) } } } return potentialNodes }
[ "func", "(", "j", "*", "joinSender", ")", "CollectPotentialNodes", "(", "nodesJoined", "[", "]", "string", ")", "[", "]", "string", "{", "if", "nodesJoined", "==", "nil", "{", "nodesJoined", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "}", "\n\n", "var", "potentialNodes", "[", "]", "string", "\n\n", "for", "_", ",", "hostports", ":=", "range", "j", ".", "bootstrapHostsMap", "{", "for", "_", ",", "hostport", ":=", "range", "hostports", "{", "if", "j", ".", "node", ".", "address", "!=", "hostport", "&&", "!", "util", ".", "StringInSlice", "(", "nodesJoined", ",", "hostport", ")", "{", "potentialNodes", "=", "append", "(", "potentialNodes", ",", "hostport", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "potentialNodes", "\n", "}" ]
// potential nodes are nodes that can be joined that are not the local node
[ "potential", "nodes", "are", "nodes", "that", "can", "be", "joined", "that", "are", "not", "the", "local", "node" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L189-L205
train
uber/ringpop-go
swim/join_sender.go
CollectPreferredNodes
func (j *joinSender) CollectPreferredNodes() []string { var preferredNodes []string for host, hostports := range j.bootstrapHostsMap { if host != util.CaptureHost(j.node.address) { preferredNodes = append(preferredNodes, hostports...) } } return preferredNodes }
go
func (j *joinSender) CollectPreferredNodes() []string { var preferredNodes []string for host, hostports := range j.bootstrapHostsMap { if host != util.CaptureHost(j.node.address) { preferredNodes = append(preferredNodes, hostports...) } } return preferredNodes }
[ "func", "(", "j", "*", "joinSender", ")", "CollectPreferredNodes", "(", ")", "[", "]", "string", "{", "var", "preferredNodes", "[", "]", "string", "\n\n", "for", "host", ",", "hostports", ":=", "range", "j", ".", "bootstrapHostsMap", "{", "if", "host", "!=", "util", ".", "CaptureHost", "(", "j", ".", "node", ".", "address", ")", "{", "preferredNodes", "=", "append", "(", "preferredNodes", ",", "hostports", "...", ")", "\n", "}", "\n", "}", "\n\n", "return", "preferredNodes", "\n", "}" ]
// preferred nodes are nodes that are not on the same host as the local node
[ "preferred", "nodes", "are", "nodes", "that", "are", "not", "on", "the", "same", "host", "as", "the", "local", "node" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L208-L218
train
uber/ringpop-go
swim/join_sender.go
CollectNonPreferredNodes
func (j *joinSender) CollectNonPreferredNodes() []string { if len(j.preferredNodes) == 0 { return j.potentialNodes } var nonPreferredNodes []string for _, host := range j.bootstrapHostsMap[util.CaptureHost(j.node.address)] { if host != j.node.address { nonPreferredNodes = append(nonPreferredNodes, host) } } return nonPreferredNodes }
go
func (j *joinSender) CollectNonPreferredNodes() []string { if len(j.preferredNodes) == 0 { return j.potentialNodes } var nonPreferredNodes []string for _, host := range j.bootstrapHostsMap[util.CaptureHost(j.node.address)] { if host != j.node.address { nonPreferredNodes = append(nonPreferredNodes, host) } } return nonPreferredNodes }
[ "func", "(", "j", "*", "joinSender", ")", "CollectNonPreferredNodes", "(", ")", "[", "]", "string", "{", "if", "len", "(", "j", ".", "preferredNodes", ")", "==", "0", "{", "return", "j", ".", "potentialNodes", "\n", "}", "\n\n", "var", "nonPreferredNodes", "[", "]", "string", "\n\n", "for", "_", ",", "host", ":=", "range", "j", ".", "bootstrapHostsMap", "[", "util", ".", "CaptureHost", "(", "j", ".", "node", ".", "address", ")", "]", "{", "if", "host", "!=", "j", ".", "node", ".", "address", "{", "nonPreferredNodes", "=", "append", "(", "nonPreferredNodes", ",", "host", ")", "\n", "}", "\n", "}", "\n", "return", "nonPreferredNodes", "\n", "}" ]
// non-preferred nodes are everyone else
[ "non", "-", "preferred", "nodes", "are", "everyone", "else" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L221-L234
train
uber/ringpop-go
swim/join_sender.go
SelectGroup
func (j *joinSender) SelectGroup(nodesJoined []string) []string { var group []string // if fully exhausted or first round, initialize this round's nodes if len(j.roundPreferredNodes) == 0 && len(j.roundNonPreferredNodes) == 0 { j.Init(nodesJoined) } numNodesLeft := j.size - len(nodesJoined) cont := func() bool { if len(group) == numNodesLeft*j.parallelismFactor { return false } nodesAvailable := len(j.roundPreferredNodes) + len(j.roundNonPreferredNodes) if nodesAvailable == 0 { return false } return true } for cont() { if len(j.roundPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundPreferredNodes, -1)) } else if len(j.roundNonPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundNonPreferredNodes, -1)) } } return group }
go
func (j *joinSender) SelectGroup(nodesJoined []string) []string { var group []string // if fully exhausted or first round, initialize this round's nodes if len(j.roundPreferredNodes) == 0 && len(j.roundNonPreferredNodes) == 0 { j.Init(nodesJoined) } numNodesLeft := j.size - len(nodesJoined) cont := func() bool { if len(group) == numNodesLeft*j.parallelismFactor { return false } nodesAvailable := len(j.roundPreferredNodes) + len(j.roundNonPreferredNodes) if nodesAvailable == 0 { return false } return true } for cont() { if len(j.roundPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundPreferredNodes, -1)) } else if len(j.roundNonPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundNonPreferredNodes, -1)) } } return group }
[ "func", "(", "j", "*", "joinSender", ")", "SelectGroup", "(", "nodesJoined", "[", "]", "string", ")", "[", "]", "string", "{", "var", "group", "[", "]", "string", "\n", "// if fully exhausted or first round, initialize this round's nodes", "if", "len", "(", "j", ".", "roundPreferredNodes", ")", "==", "0", "&&", "len", "(", "j", ".", "roundNonPreferredNodes", ")", "==", "0", "{", "j", ".", "Init", "(", "nodesJoined", ")", "\n", "}", "\n\n", "numNodesLeft", ":=", "j", ".", "size", "-", "len", "(", "nodesJoined", ")", "\n\n", "cont", ":=", "func", "(", ")", "bool", "{", "if", "len", "(", "group", ")", "==", "numNodesLeft", "*", "j", ".", "parallelismFactor", "{", "return", "false", "\n", "}", "\n\n", "nodesAvailable", ":=", "len", "(", "j", ".", "roundPreferredNodes", ")", "+", "len", "(", "j", ".", "roundNonPreferredNodes", ")", "\n", "if", "nodesAvailable", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n\n", "for", "cont", "(", ")", "{", "if", "len", "(", "j", ".", "roundPreferredNodes", ")", ">", "0", "{", "group", "=", "append", "(", "group", ",", "util", ".", "TakeNode", "(", "&", "j", ".", "roundPreferredNodes", ",", "-", "1", ")", ")", "\n", "}", "else", "if", "len", "(", "j", ".", "roundNonPreferredNodes", ")", ">", "0", "{", "group", "=", "append", "(", "group", ",", "util", ".", "TakeNode", "(", "&", "j", ".", "roundNonPreferredNodes", ",", "-", "1", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "group", "\n", "}" ]
// selects a group of nodes
[ "selects", "a", "group", "of", "nodes" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L249-L280
train
uber/ringpop-go
swim/join_sender.go
JoinGroup
func (j *joinSender) JoinGroup(nodesJoined []string) ([]string, []string) { group := j.SelectGroup(nodesJoined) var responses struct { successes []string failures []string sync.Mutex } var numNodesLeft = j.size - len(nodesJoined) var startTime = time.Now() var wg sync.WaitGroup j.numTries++ j.node.EmitEvent(JoinTriesUpdateEvent{j.numTries}) for _, target := range group { wg.Add(1) go func(target string) { defer wg.Done() res, err := sendJoinRequest(j.node, target, j.timeout) if err != nil { msg := "attempt to join node failed" if err == errJoinTimeout { msg = "attempt to join node timed out" } j.logger.WithFields(log.Fields{ "remote": target, "timeout": j.timeout, }).Debug(msg) responses.Lock() responses.failures = append(responses.failures, target) responses.Unlock() return } responses.Lock() responses.successes = append(responses.successes, target) responses.Unlock() start := time.Now() j.node.memberlist.AddJoinList(res.Membership) j.node.EmitEvent(AddJoinListEvent{ Duration: time.Now().Sub(start), }) }(target) } // wait for joins to complete wg.Wait() // don't need to lock successes/failures since we're finished writing to them j.logger.WithFields(log.Fields{ "groupSize": len(group), "joinSize": j.size, "joinTime": time.Now().Sub(startTime), "numNodesLeft": numNodesLeft, "numFailures": len(responses.failures), "failures": responses.failures, "numSuccesses": len(responses.successes), "successes": responses.successes, }).Debug("join group complete") return responses.successes, responses.failures }
go
func (j *joinSender) JoinGroup(nodesJoined []string) ([]string, []string) { group := j.SelectGroup(nodesJoined) var responses struct { successes []string failures []string sync.Mutex } var numNodesLeft = j.size - len(nodesJoined) var startTime = time.Now() var wg sync.WaitGroup j.numTries++ j.node.EmitEvent(JoinTriesUpdateEvent{j.numTries}) for _, target := range group { wg.Add(1) go func(target string) { defer wg.Done() res, err := sendJoinRequest(j.node, target, j.timeout) if err != nil { msg := "attempt to join node failed" if err == errJoinTimeout { msg = "attempt to join node timed out" } j.logger.WithFields(log.Fields{ "remote": target, "timeout": j.timeout, }).Debug(msg) responses.Lock() responses.failures = append(responses.failures, target) responses.Unlock() return } responses.Lock() responses.successes = append(responses.successes, target) responses.Unlock() start := time.Now() j.node.memberlist.AddJoinList(res.Membership) j.node.EmitEvent(AddJoinListEvent{ Duration: time.Now().Sub(start), }) }(target) } // wait for joins to complete wg.Wait() // don't need to lock successes/failures since we're finished writing to them j.logger.WithFields(log.Fields{ "groupSize": len(group), "joinSize": j.size, "joinTime": time.Now().Sub(startTime), "numNodesLeft": numNodesLeft, "numFailures": len(responses.failures), "failures": responses.failures, "numSuccesses": len(responses.successes), "successes": responses.successes, }).Debug("join group complete") return responses.successes, responses.failures }
[ "func", "(", "j", "*", "joinSender", ")", "JoinGroup", "(", "nodesJoined", "[", "]", "string", ")", "(", "[", "]", "string", ",", "[", "]", "string", ")", "{", "group", ":=", "j", ".", "SelectGroup", "(", "nodesJoined", ")", "\n\n", "var", "responses", "struct", "{", "successes", "[", "]", "string", "\n", "failures", "[", "]", "string", "\n", "sync", ".", "Mutex", "\n", "}", "\n\n", "var", "numNodesLeft", "=", "j", ".", "size", "-", "len", "(", "nodesJoined", ")", "\n", "var", "startTime", "=", "time", ".", "Now", "(", ")", "\n\n", "var", "wg", "sync", ".", "WaitGroup", "\n\n", "j", ".", "numTries", "++", "\n", "j", ".", "node", ".", "EmitEvent", "(", "JoinTriesUpdateEvent", "{", "j", ".", "numTries", "}", ")", "\n\n", "for", "_", ",", "target", ":=", "range", "group", "{", "wg", ".", "Add", "(", "1", ")", "\n\n", "go", "func", "(", "target", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "res", ",", "err", ":=", "sendJoinRequest", "(", "j", ".", "node", ",", "target", ",", "j", ".", "timeout", ")", "\n\n", "if", "err", "!=", "nil", "{", "msg", ":=", "\"", "\"", "\n", "if", "err", "==", "errJoinTimeout", "{", "msg", "=", "\"", "\"", "\n", "}", "\n\n", "j", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "j", ".", "timeout", ",", "}", ")", ".", "Debug", "(", "msg", ")", "\n\n", "responses", ".", "Lock", "(", ")", "\n", "responses", ".", "failures", "=", "append", "(", "responses", ".", "failures", ",", "target", ")", "\n", "responses", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "responses", ".", "Lock", "(", ")", "\n", "responses", ".", "successes", "=", "append", "(", "responses", ".", "successes", ",", "target", ")", "\n", "responses", ".", "Unlock", "(", ")", "\n\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "j", ".", "node", ".", "memberlist", ".", "AddJoinList", "(", "res", ".", "Membership", ")", "\n\n", "j", ".", "node", ".", "EmitEvent", "(", "AddJoinListEvent", "{", "Duration", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ",", "}", ")", "\n", "}", "(", "target", ")", "\n", "}", "\n\n", "// wait for joins to complete", "wg", ".", "Wait", "(", ")", "\n\n", "// don't need to lock successes/failures since we're finished writing to them", "j", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "len", "(", "group", ")", ",", "\"", "\"", ":", "j", ".", "size", ",", "\"", "\"", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "startTime", ")", ",", "\"", "\"", ":", "numNodesLeft", ",", "\"", "\"", ":", "len", "(", "responses", ".", "failures", ")", ",", "\"", "\"", ":", "responses", ".", "failures", ",", "\"", "\"", ":", "len", "(", "responses", ".", "successes", ")", ",", "\"", "\"", ":", "responses", ".", "successes", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "responses", ".", "successes", ",", "responses", ".", "failures", "\n", "}" ]
// JoinGroup collects a number of nodes to join and sends join requests to them. // nodesJoined contains the nodes that are already joined. The method returns // the nodes that are succesfully joined, and the nodes that failed respond.
[ "JoinGroup", "collects", "a", "number", "of", "nodes", "to", "join", "and", "sends", "join", "requests", "to", "them", ".", "nodesJoined", "contains", "the", "nodes", "that", "are", "already", "joined", ".", "The", "method", "returns", "the", "nodes", "that", "are", "succesfully", "joined", "and", "the", "nodes", "that", "failed", "respond", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L365-L436
train
uber/ringpop-go
swim/join_sender.go
sendJoinRequest
func sendJoinRequest(node *Node, target string, timeout time.Duration) (*joinResponse, error) { ctx, cancel := shared.NewTChannelContext(timeout) defer cancel() peer := node.channel.Peers().GetOrAdd(target) req := joinRequest{ App: node.app, Source: node.address, Incarnation: node.Incarnation(), Timeout: timeout, Labels: node.Labels().AsMap(), } res := &joinResponse{} // make request errC := make(chan error, 1) go func() { errC <- json.CallPeer(ctx, peer, node.service, "/protocol/join", req, res) }() // wait for result or timeout var err error select { case err = <-errC: case <-ctx.Done(): err = errJoinTimeout } if err != nil { logging.Logger("join").WithFields(log.Fields{ "local": node.Address(), "error": err, }).Debug("could not complete join") return nil, err } return res, err }
go
func sendJoinRequest(node *Node, target string, timeout time.Duration) (*joinResponse, error) { ctx, cancel := shared.NewTChannelContext(timeout) defer cancel() peer := node.channel.Peers().GetOrAdd(target) req := joinRequest{ App: node.app, Source: node.address, Incarnation: node.Incarnation(), Timeout: timeout, Labels: node.Labels().AsMap(), } res := &joinResponse{} // make request errC := make(chan error, 1) go func() { errC <- json.CallPeer(ctx, peer, node.service, "/protocol/join", req, res) }() // wait for result or timeout var err error select { case err = <-errC: case <-ctx.Done(): err = errJoinTimeout } if err != nil { logging.Logger("join").WithFields(log.Fields{ "local": node.Address(), "error": err, }).Debug("could not complete join") return nil, err } return res, err }
[ "func", "sendJoinRequest", "(", "node", "*", "Node", ",", "target", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "joinResponse", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "shared", ".", "NewTChannelContext", "(", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "peer", ":=", "node", ".", "channel", ".", "Peers", "(", ")", ".", "GetOrAdd", "(", "target", ")", "\n\n", "req", ":=", "joinRequest", "{", "App", ":", "node", ".", "app", ",", "Source", ":", "node", ".", "address", ",", "Incarnation", ":", "node", ".", "Incarnation", "(", ")", ",", "Timeout", ":", "timeout", ",", "Labels", ":", "node", ".", "Labels", "(", ")", ".", "AsMap", "(", ")", ",", "}", "\n", "res", ":=", "&", "joinResponse", "{", "}", "\n\n", "// make request", "errC", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "errC", "<-", "json", ".", "CallPeer", "(", "ctx", ",", "peer", ",", "node", ".", "service", ",", "\"", "\"", ",", "req", ",", "res", ")", "\n", "}", "(", ")", "\n\n", "// wait for result or timeout", "var", "err", "error", "\n", "select", "{", "case", "err", "=", "<-", "errC", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "err", "=", "errJoinTimeout", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "node", ".", "Address", "(", ")", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "res", ",", "err", "\n", "}" ]
// sendJoinRequest sends a join request to the specified target.
[ "sendJoinRequest", "sends", "a", "join", "request", "to", "the", "specified", "target", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L439-L478
train
uber/ringpop-go
swim/join_sender.go
sendJoin
func sendJoin(node *Node, opts *joinOpts) ([]string, error) { joiner, err := newJoinSender(node, opts) if err != nil { return nil, err } return joiner.JoinCluster() }
go
func sendJoin(node *Node, opts *joinOpts) ([]string, error) { joiner, err := newJoinSender(node, opts) if err != nil { return nil, err } return joiner.JoinCluster() }
[ "func", "sendJoin", "(", "node", "*", "Node", ",", "opts", "*", "joinOpts", ")", "(", "[", "]", "string", ",", "error", ")", "{", "joiner", ",", "err", ":=", "newJoinSender", "(", "node", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "joiner", ".", "JoinCluster", "(", ")", "\n", "}" ]
// SendJoin creates a new JoinSender and attempts to join the cluster defined by // the nodes bootstrap hosts
[ "SendJoin", "creates", "a", "new", "JoinSender", "and", "attempts", "to", "join", "the", "cluster", "defined", "by", "the", "nodes", "bootstrap", "hosts" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L482-L488
train
uber/ringpop-go
swim/node.go
NewNode
func NewNode(app, address string, channel shared.SubChannel, opts *Options) *Node { // use defaults for options that are unspecified opts = mergeDefaultOptions(opts) node := &Node{ address: address, app: app, channel: channel, logger: logging.Logger("node").WithField("local", address), joinTimeout: opts.JoinTimeout, pingTimeout: opts.PingTimeout, pingRequestTimeout: opts.PingRequestTimeout, pingRequestSize: opts.PingRequestSize, maxReverseFullSyncJobs: opts.MaxReverseFullSyncJobs, clientRate: metrics.NewMeter(), serverRate: metrics.NewMeter(), totalRate: metrics.NewMeter(), clock: opts.Clock, } node.selfEvict = newSelfEvict(node, opts.SelfEvict) node.requiresAppInPing = opts.RequiresAppInPing node.labelLimits = opts.LabelLimits node.memberlist = newMemberlist(node, opts.InitialLabels) node.memberiter = newMemberlistIter(node.memberlist) node.stateTransitions = newStateTransitions(node, opts.StateTimeouts) node.healer = newDiscoverProviderHealer( node, opts.PartitionHealBaseProbabillity, opts.PartitionHealPeriod, ) node.gossip = newGossip(node, opts.MinProtocolPeriod) node.disseminator = newDisseminator(node) for _, member := range node.memberlist.GetMembers() { change := Change{} change.populateSubject(&member) node.disseminator.RecordChange(change) } if node.channel != nil { node.registerHandlers() node.service = node.channel.ServiceName() } return node }
go
func NewNode(app, address string, channel shared.SubChannel, opts *Options) *Node { // use defaults for options that are unspecified opts = mergeDefaultOptions(opts) node := &Node{ address: address, app: app, channel: channel, logger: logging.Logger("node").WithField("local", address), joinTimeout: opts.JoinTimeout, pingTimeout: opts.PingTimeout, pingRequestTimeout: opts.PingRequestTimeout, pingRequestSize: opts.PingRequestSize, maxReverseFullSyncJobs: opts.MaxReverseFullSyncJobs, clientRate: metrics.NewMeter(), serverRate: metrics.NewMeter(), totalRate: metrics.NewMeter(), clock: opts.Clock, } node.selfEvict = newSelfEvict(node, opts.SelfEvict) node.requiresAppInPing = opts.RequiresAppInPing node.labelLimits = opts.LabelLimits node.memberlist = newMemberlist(node, opts.InitialLabels) node.memberiter = newMemberlistIter(node.memberlist) node.stateTransitions = newStateTransitions(node, opts.StateTimeouts) node.healer = newDiscoverProviderHealer( node, opts.PartitionHealBaseProbabillity, opts.PartitionHealPeriod, ) node.gossip = newGossip(node, opts.MinProtocolPeriod) node.disseminator = newDisseminator(node) for _, member := range node.memberlist.GetMembers() { change := Change{} change.populateSubject(&member) node.disseminator.RecordChange(change) } if node.channel != nil { node.registerHandlers() node.service = node.channel.ServiceName() } return node }
[ "func", "NewNode", "(", "app", ",", "address", "string", ",", "channel", "shared", ".", "SubChannel", ",", "opts", "*", "Options", ")", "*", "Node", "{", "// use defaults for options that are unspecified", "opts", "=", "mergeDefaultOptions", "(", "opts", ")", "\n\n", "node", ":=", "&", "Node", "{", "address", ":", "address", ",", "app", ":", "app", ",", "channel", ":", "channel", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "address", ")", ",", "joinTimeout", ":", "opts", ".", "JoinTimeout", ",", "pingTimeout", ":", "opts", ".", "PingTimeout", ",", "pingRequestTimeout", ":", "opts", ".", "PingRequestTimeout", ",", "pingRequestSize", ":", "opts", ".", "PingRequestSize", ",", "maxReverseFullSyncJobs", ":", "opts", ".", "MaxReverseFullSyncJobs", ",", "clientRate", ":", "metrics", ".", "NewMeter", "(", ")", ",", "serverRate", ":", "metrics", ".", "NewMeter", "(", ")", ",", "totalRate", ":", "metrics", ".", "NewMeter", "(", ")", ",", "clock", ":", "opts", ".", "Clock", ",", "}", "\n", "node", ".", "selfEvict", "=", "newSelfEvict", "(", "node", ",", "opts", ".", "SelfEvict", ")", "\n", "node", ".", "requiresAppInPing", "=", "opts", ".", "RequiresAppInPing", "\n\n", "node", ".", "labelLimits", "=", "opts", ".", "LabelLimits", "\n\n", "node", ".", "memberlist", "=", "newMemberlist", "(", "node", ",", "opts", ".", "InitialLabels", ")", "\n", "node", ".", "memberiter", "=", "newMemberlistIter", "(", "node", ".", "memberlist", ")", "\n", "node", ".", "stateTransitions", "=", "newStateTransitions", "(", "node", ",", "opts", ".", "StateTimeouts", ")", "\n\n", "node", ".", "healer", "=", "newDiscoverProviderHealer", "(", "node", ",", "opts", ".", "PartitionHealBaseProbabillity", ",", "opts", ".", "PartitionHealPeriod", ",", ")", "\n", "node", ".", "gossip", "=", "newGossip", "(", "node", ",", "opts", ".", "MinProtocolPeriod", ")", "\n", "node", ".", "disseminator", "=", "newDisseminator", "(", "node", ")", "\n\n", "for", "_", ",", "member", ":=", "range", "node", ".", "memberlist", ".", "GetMembers", "(", ")", "{", "change", ":=", "Change", "{", "}", "\n", "change", ".", "populateSubject", "(", "&", "member", ")", "\n", "node", ".", "disseminator", ".", "RecordChange", "(", "change", ")", "\n", "}", "\n\n", "if", "node", ".", "channel", "!=", "nil", "{", "node", ".", "registerHandlers", "(", ")", "\n", "node", ".", "service", "=", "node", ".", "channel", ".", "ServiceName", "(", ")", "\n", "}", "\n\n", "return", "node", "\n", "}" ]
// NewNode returns a new SWIM Node.
[ "NewNode", "returns", "a", "new", "SWIM", "Node", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L231-L283
train
uber/ringpop-go
swim/node.go
Incarnation
func (n *Node) Incarnation() int64 { if n.memberlist != nil && n.memberlist.local != nil { n.memberlist.members.RLock() incarnation := n.memberlist.local.Incarnation n.memberlist.members.RUnlock() return incarnation } return -1 }
go
func (n *Node) Incarnation() int64 { if n.memberlist != nil && n.memberlist.local != nil { n.memberlist.members.RLock() incarnation := n.memberlist.local.Incarnation n.memberlist.members.RUnlock() return incarnation } return -1 }
[ "func", "(", "n", "*", "Node", ")", "Incarnation", "(", ")", "int64", "{", "if", "n", ".", "memberlist", "!=", "nil", "&&", "n", ".", "memberlist", ".", "local", "!=", "nil", "{", "n", ".", "memberlist", ".", "members", ".", "RLock", "(", ")", "\n", "incarnation", ":=", "n", ".", "memberlist", ".", "local", ".", "Incarnation", "\n", "n", ".", "memberlist", ".", "members", ".", "RUnlock", "(", ")", "\n", "return", "incarnation", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Incarnation returns the incarnation number of the Node.
[ "Incarnation", "returns", "the", "incarnation", "number", "of", "the", "Node", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L301-L309
train
uber/ringpop-go
swim/node.go
Start
func (n *Node) Start() { n.gossip.Start() n.stateTransitions.Enable() n.healer.Start() n.state.Lock() n.state.stopped = false n.state.Unlock() }
go
func (n *Node) Start() { n.gossip.Start() n.stateTransitions.Enable() n.healer.Start() n.state.Lock() n.state.stopped = false n.state.Unlock() }
[ "func", "(", "n", "*", "Node", ")", "Start", "(", ")", "{", "n", ".", "gossip", ".", "Start", "(", ")", "\n", "n", ".", "stateTransitions", ".", "Enable", "(", ")", "\n", "n", ".", "healer", ".", "Start", "(", ")", "\n\n", "n", ".", "state", ".", "Lock", "(", ")", "\n", "n", ".", "state", ".", "stopped", "=", "false", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n", "}" ]
// Start starts the SWIM protocol and all sub-protocols.
[ "Start", "starts", "the", "SWIM", "protocol", "and", "all", "sub", "-", "protocols", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L312-L320
train
uber/ringpop-go
swim/node.go
Stop
func (n *Node) Stop() { n.gossip.Stop() n.stateTransitions.Disable() n.healer.Stop() n.state.Lock() n.state.stopped = true n.state.Unlock() }
go
func (n *Node) Stop() { n.gossip.Stop() n.stateTransitions.Disable() n.healer.Stop() n.state.Lock() n.state.stopped = true n.state.Unlock() }
[ "func", "(", "n", "*", "Node", ")", "Stop", "(", ")", "{", "n", ".", "gossip", ".", "Stop", "(", ")", "\n", "n", ".", "stateTransitions", ".", "Disable", "(", ")", "\n", "n", ".", "healer", ".", "Stop", "(", ")", "\n\n", "n", ".", "state", ".", "Lock", "(", ")", "\n", "n", ".", "state", ".", "stopped", "=", "true", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n", "}" ]
// Stop stops the SWIM protocol and all sub-protocols.
[ "Stop", "stops", "the", "SWIM", "protocol", "and", "all", "sub", "-", "protocols", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L323-L331
train
uber/ringpop-go
swim/node.go
Stopped
func (n *Node) Stopped() bool { n.state.RLock() stopped := n.state.stopped n.state.RUnlock() return stopped }
go
func (n *Node) Stopped() bool { n.state.RLock() stopped := n.state.stopped n.state.RUnlock() return stopped }
[ "func", "(", "n", "*", "Node", ")", "Stopped", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "stopped", ":=", "n", ".", "state", ".", "stopped", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "stopped", "\n", "}" ]
// Stopped returns whether or not the SWIM protocol is currently running.
[ "Stopped", "returns", "whether", "or", "not", "the", "SWIM", "protocol", "is", "currently", "running", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L334-L340
train
uber/ringpop-go
swim/node.go
Destroy
func (n *Node) Destroy() { n.state.Lock() if n.state.destroyed { n.state.Unlock() return } n.state.destroyed = true n.state.Unlock() n.Stop() }
go
func (n *Node) Destroy() { n.state.Lock() if n.state.destroyed { n.state.Unlock() return } n.state.destroyed = true n.state.Unlock() n.Stop() }
[ "func", "(", "n", "*", "Node", ")", "Destroy", "(", ")", "{", "n", ".", "state", ".", "Lock", "(", ")", "\n", "if", "n", ".", "state", ".", "destroyed", "{", "n", ".", "state", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "n", ".", "state", ".", "destroyed", "=", "true", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n\n", "n", ".", "Stop", "(", ")", "\n", "}" ]
// Destroy stops the SWIM protocol and all sub-protocols.
[ "Destroy", "stops", "the", "SWIM", "protocol", "and", "all", "sub", "-", "protocols", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L343-L353
train
uber/ringpop-go
swim/node.go
Destroyed
func (n *Node) Destroyed() bool { n.state.RLock() destroyed := n.state.destroyed n.state.RUnlock() return destroyed }
go
func (n *Node) Destroyed() bool { n.state.RLock() destroyed := n.state.destroyed n.state.RUnlock() return destroyed }
[ "func", "(", "n", "*", "Node", ")", "Destroyed", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "destroyed", ":=", "n", ".", "state", ".", "destroyed", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "destroyed", "\n", "}" ]
// Destroyed returns whether or not the node has been destroyed.
[ "Destroyed", "returns", "whether", "or", "not", "the", "node", "has", "been", "destroyed", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L356-L362
train
uber/ringpop-go
swim/node.go
Ready
func (n *Node) Ready() bool { n.state.RLock() ready := n.state.ready n.state.RUnlock() return ready }
go
func (n *Node) Ready() bool { n.state.RLock() ready := n.state.ready n.state.RUnlock() return ready }
[ "func", "(", "n", "*", "Node", ")", "Ready", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "ready", ":=", "n", ".", "state", ".", "ready", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "ready", "\n", "}" ]
// Ready returns whether or not the node has bootstrapped and is ready for use.
[ "Ready", "returns", "whether", "or", "not", "the", "node", "has", "bootstrapped", "and", "is", "ready", "for", "use", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L365-L371
train
uber/ringpop-go
swim/node.go
RegisterSelfEvictHook
func (n *Node) RegisterSelfEvictHook(hooks SelfEvictHook) error { return n.selfEvict.RegisterSelfEvictHook(hooks) }
go
func (n *Node) RegisterSelfEvictHook(hooks SelfEvictHook) error { return n.selfEvict.RegisterSelfEvictHook(hooks) }
[ "func", "(", "n", "*", "Node", ")", "RegisterSelfEvictHook", "(", "hooks", "SelfEvictHook", ")", "error", "{", "return", "n", ".", "selfEvict", ".", "RegisterSelfEvictHook", "(", "hooks", ")", "\n", "}" ]
// RegisterSelfEvictHook registers systems that want to hook into the eviction // sequence of the swim protocol.
[ "RegisterSelfEvictHook", "registers", "systems", "that", "want", "to", "hook", "into", "the", "eviction", "sequence", "of", "the", "swim", "protocol", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L375-L377
train
uber/ringpop-go
swim/node.go
Bootstrap
func (n *Node) Bootstrap(opts *BootstrapOptions) ([]string, error) { if n.channel == nil { return nil, errors.New("channel required") } if opts == nil { opts = &BootstrapOptions{} } n.discoverProvider = opts.DiscoverProvider joinOpts := &joinOpts{ timeout: opts.JoinTimeout, size: opts.JoinSize, maxJoinDuration: opts.MaxJoinDuration, parallelismFactor: opts.ParallelismFactor, } joined, err := sendJoin(n, joinOpts) if err != nil { n.logger.WithFields(log.Fields{ "err": err.Error(), }).Error("bootstrap failed") return nil, err } if !opts.Stopped { n.gossip.Start() n.healer.Start() } n.state.Lock() n.state.ready = true n.state.Unlock() n.startTime = time.Now() return joined, nil }
go
func (n *Node) Bootstrap(opts *BootstrapOptions) ([]string, error) { if n.channel == nil { return nil, errors.New("channel required") } if opts == nil { opts = &BootstrapOptions{} } n.discoverProvider = opts.DiscoverProvider joinOpts := &joinOpts{ timeout: opts.JoinTimeout, size: opts.JoinSize, maxJoinDuration: opts.MaxJoinDuration, parallelismFactor: opts.ParallelismFactor, } joined, err := sendJoin(n, joinOpts) if err != nil { n.logger.WithFields(log.Fields{ "err": err.Error(), }).Error("bootstrap failed") return nil, err } if !opts.Stopped { n.gossip.Start() n.healer.Start() } n.state.Lock() n.state.ready = true n.state.Unlock() n.startTime = time.Now() return joined, nil }
[ "func", "(", "n", "*", "Node", ")", "Bootstrap", "(", "opts", "*", "BootstrapOptions", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "n", ".", "channel", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "opts", "==", "nil", "{", "opts", "=", "&", "BootstrapOptions", "{", "}", "\n", "}", "\n\n", "n", ".", "discoverProvider", "=", "opts", ".", "DiscoverProvider", "\n", "joinOpts", ":=", "&", "joinOpts", "{", "timeout", ":", "opts", ".", "JoinTimeout", ",", "size", ":", "opts", ".", "JoinSize", ",", "maxJoinDuration", ":", "opts", ".", "MaxJoinDuration", ",", "parallelismFactor", ":", "opts", ".", "ParallelismFactor", ",", "}", "\n\n", "joined", ",", "err", ":=", "sendJoin", "(", "n", ",", "joinOpts", ")", "\n", "if", "err", "!=", "nil", "{", "n", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "opts", ".", "Stopped", "{", "n", ".", "gossip", ".", "Start", "(", ")", "\n", "n", ".", "healer", ".", "Start", "(", ")", "\n", "}", "\n\n", "n", ".", "state", ".", "Lock", "(", ")", "\n", "n", ".", "state", ".", "ready", "=", "true", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n\n", "n", ".", "startTime", "=", "time", ".", "Now", "(", ")", "\n\n", "return", "joined", ",", "nil", "\n", "}" ]
// Bootstrap joins a node to a cluster. The channel provided to the node must be // listening for the bootstrap to complete.
[ "Bootstrap", "joins", "a", "node", "to", "a", "cluster", ".", "The", "channel", "provided", "to", "the", "node", "must", "be", "listening", "for", "the", "bootstrap", "to", "complete", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L420-L457
train
uber/ringpop-go
swim/node.go
handleChanges
func (n *Node) handleChanges(changes []Change) { n.disseminator.AdjustMaxPropagations() for _, change := range changes { n.disseminator.RecordChange(change) switch change.Status { case Alive: n.stateTransitions.Cancel(change) case Suspect: n.stateTransitions.ScheduleSuspectToFaulty(change) case Faulty: n.stateTransitions.ScheduleFaultyToTombstone(change) case Leave: // XXX: should this also reap? n.stateTransitions.Cancel(change) case Tombstone: n.stateTransitions.ScheduleTombstoneToEvict(change) } } }
go
func (n *Node) handleChanges(changes []Change) { n.disseminator.AdjustMaxPropagations() for _, change := range changes { n.disseminator.RecordChange(change) switch change.Status { case Alive: n.stateTransitions.Cancel(change) case Suspect: n.stateTransitions.ScheduleSuspectToFaulty(change) case Faulty: n.stateTransitions.ScheduleFaultyToTombstone(change) case Leave: // XXX: should this also reap? n.stateTransitions.Cancel(change) case Tombstone: n.stateTransitions.ScheduleTombstoneToEvict(change) } } }
[ "func", "(", "n", "*", "Node", ")", "handleChanges", "(", "changes", "[", "]", "Change", ")", "{", "n", ".", "disseminator", ".", "AdjustMaxPropagations", "(", ")", "\n", "for", "_", ",", "change", ":=", "range", "changes", "{", "n", ".", "disseminator", ".", "RecordChange", "(", "change", ")", "\n\n", "switch", "change", ".", "Status", "{", "case", "Alive", ":", "n", ".", "stateTransitions", ".", "Cancel", "(", "change", ")", "\n\n", "case", "Suspect", ":", "n", ".", "stateTransitions", ".", "ScheduleSuspectToFaulty", "(", "change", ")", "\n\n", "case", "Faulty", ":", "n", ".", "stateTransitions", ".", "ScheduleFaultyToTombstone", "(", "change", ")", "\n\n", "case", "Leave", ":", "// XXX: should this also reap?", "n", ".", "stateTransitions", ".", "Cancel", "(", "change", ")", "\n\n", "case", "Tombstone", ":", "n", ".", "stateTransitions", ".", "ScheduleTombstoneToEvict", "(", "change", ")", "\n", "}", "\n", "}", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Change Handling // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Change", "Handling", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L465-L488
train
uber/ringpop-go
swim/node.go
pinging
func (n *Node) pinging() bool { n.state.RLock() pinging := n.state.pinging n.state.RUnlock() return pinging }
go
func (n *Node) pinging() bool { n.state.RLock() pinging := n.state.pinging n.state.RUnlock() return pinging }
[ "func", "(", "n", "*", "Node", ")", "pinging", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "pinging", ":=", "n", ".", "state", ".", "pinging", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "pinging", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Gossip // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Gossip", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L496-L502
train
uber/ringpop-go
swim/node.go
pingNextMember
func (n *Node) pingNextMember() { member, ok := n.memberiter.Next() if !ok { n.logger.Warn("no pingable members") return } if n.pinging() { n.logger.Warn("node already pinging") return } n.setPinging(true) defer n.setPinging(false) // send ping res, err := sendPing(n, member.Address, n.pingTimeout) if err == nil { n.memberlist.Update(res.Changes) return } // ping failed, send ping requests target := member.Address targetReached, errs := indirectPing(n, target, n.pingRequestSize, n.pingRequestTimeout) // if all helper nodes are unreachable, the indirectPing is inconclusive if len(errs) == n.pingRequestSize { n.logger.WithFields(log.Fields{ "target": target, "errors": errs, "numErrors": len(errs), }).Warn("ping request inconclusive due to errors") return } if !targetReached { n.logger.WithField("target", target).Info("ping request target unreachable") n.memberlist.MakeSuspect(member.Address, member.Incarnation) return } n.logger.WithField("target", target).Info("ping request target reachable") }
go
func (n *Node) pingNextMember() { member, ok := n.memberiter.Next() if !ok { n.logger.Warn("no pingable members") return } if n.pinging() { n.logger.Warn("node already pinging") return } n.setPinging(true) defer n.setPinging(false) // send ping res, err := sendPing(n, member.Address, n.pingTimeout) if err == nil { n.memberlist.Update(res.Changes) return } // ping failed, send ping requests target := member.Address targetReached, errs := indirectPing(n, target, n.pingRequestSize, n.pingRequestTimeout) // if all helper nodes are unreachable, the indirectPing is inconclusive if len(errs) == n.pingRequestSize { n.logger.WithFields(log.Fields{ "target": target, "errors": errs, "numErrors": len(errs), }).Warn("ping request inconclusive due to errors") return } if !targetReached { n.logger.WithField("target", target).Info("ping request target unreachable") n.memberlist.MakeSuspect(member.Address, member.Incarnation) return } n.logger.WithField("target", target).Info("ping request target reachable") }
[ "func", "(", "n", "*", "Node", ")", "pingNextMember", "(", ")", "{", "member", ",", "ok", ":=", "n", ".", "memberiter", ".", "Next", "(", ")", "\n", "if", "!", "ok", "{", "n", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "n", ".", "pinging", "(", ")", "{", "n", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "n", ".", "setPinging", "(", "true", ")", "\n", "defer", "n", ".", "setPinging", "(", "false", ")", "\n\n", "// send ping", "res", ",", "err", ":=", "sendPing", "(", "n", ",", "member", ".", "Address", ",", "n", ".", "pingTimeout", ")", "\n", "if", "err", "==", "nil", "{", "n", ".", "memberlist", ".", "Update", "(", "res", ".", "Changes", ")", "\n", "return", "\n", "}", "\n\n", "// ping failed, send ping requests", "target", ":=", "member", ".", "Address", "\n", "targetReached", ",", "errs", ":=", "indirectPing", "(", "n", ",", "target", ",", "n", ".", "pingRequestSize", ",", "n", ".", "pingRequestTimeout", ")", "\n\n", "// if all helper nodes are unreachable, the indirectPing is inconclusive", "if", "len", "(", "errs", ")", "==", "n", ".", "pingRequestSize", "{", "n", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "errs", ",", "\"", "\"", ":", "len", "(", "errs", ")", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "!", "targetReached", "{", "n", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "target", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "n", ".", "memberlist", ".", "MakeSuspect", "(", "member", ".", "Address", ",", "member", ".", "Incarnation", ")", "\n", "return", "\n", "}", "\n\n", "n", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "target", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// pingNextMember pings the next member in the memberlist
[ "pingNextMember", "pings", "the", "next", "member", "in", "the", "memberlist" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L511-L554
train
uber/ringpop-go
swim/node.go
GetReachableMembers
func (n *Node) GetReachableMembers(predicates ...MemberPredicate) []Member { predicates = append(predicates, memberIsReachable) return n.memberlist.GetMembers(predicates...) }
go
func (n *Node) GetReachableMembers(predicates ...MemberPredicate) []Member { predicates = append(predicates, memberIsReachable) return n.memberlist.GetMembers(predicates...) }
[ "func", "(", "n", "*", "Node", ")", "GetReachableMembers", "(", "predicates", "...", "MemberPredicate", ")", "[", "]", "Member", "{", "predicates", "=", "append", "(", "predicates", ",", "memberIsReachable", ")", "\n", "return", "n", ".", "memberlist", ".", "GetMembers", "(", "predicates", "...", ")", "\n", "}" ]
// GetReachableMembers returns a slice of members containing only the reachable // members that satisfies the predicates passed in.
[ "GetReachableMembers", "returns", "a", "slice", "of", "members", "containing", "only", "the", "reachable", "members", "that", "satisfies", "the", "predicates", "passed", "in", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L558-L561
train
uber/ringpop-go
swim/node.go
CountReachableMembers
func (n *Node) CountReachableMembers(predicates ...MemberPredicate) int { predicates = append(predicates, memberIsReachable) return n.memberlist.CountMembers(predicates...) }
go
func (n *Node) CountReachableMembers(predicates ...MemberPredicate) int { predicates = append(predicates, memberIsReachable) return n.memberlist.CountMembers(predicates...) }
[ "func", "(", "n", "*", "Node", ")", "CountReachableMembers", "(", "predicates", "...", "MemberPredicate", ")", "int", "{", "predicates", "=", "append", "(", "predicates", ",", "memberIsReachable", ")", "\n", "return", "n", ".", "memberlist", ".", "CountMembers", "(", "predicates", "...", ")", "\n", "}" ]
// CountReachableMembers returns the number of reachable members currently in // this node's membership list that satisfies all predicates passed in.
[ "CountReachableMembers", "returns", "the", "number", "of", "reachable", "members", "currently", "in", "this", "node", "s", "membership", "list", "that", "satisfies", "all", "predicates", "passed", "in", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L565-L568
train
uber/ringpop-go
swim/node.go
SetIdentity
func (n *Node) SetIdentity(identity string) error { return n.memberlist.SetLocalLabel(membership.IdentityLabelKey, identity) }
go
func (n *Node) SetIdentity(identity string) error { return n.memberlist.SetLocalLabel(membership.IdentityLabelKey, identity) }
[ "func", "(", "n", "*", "Node", ")", "SetIdentity", "(", "identity", "string", ")", "error", "{", "return", "n", ".", "memberlist", ".", "SetLocalLabel", "(", "membership", ".", "IdentityLabelKey", ",", "identity", ")", "\n", "}" ]
// SetIdentity changes the identity of the local node. This will change the // state of the local node and will be gossiped around in the network.
[ "SetIdentity", "changes", "the", "identity", "of", "the", "local", "node", ".", "This", "will", "change", "the", "state", "of", "the", "local", "node", "and", "will", "be", "gossiped", "around", "in", "the", "network", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L579-L581
train
uber/ringpop-go
events/events.go
AddListener
func (a *sharedEventEmitter) AddListener(l EventListener) bool { if l == nil { // do not register nil listener, will cause nil pointer dereference during // event emitting return false } a.listenersLock.Lock() defer a.listenersLock.Unlock() // Check if listener is already registered for _, listener := range a.listeners { if listener == l { return false } } // by making a copy the backing array will never be changed after its creation. // this allowes to copy the slice while locked but iterate while not locked // preventing deadlocks when listeners are added/removed in the handler of a // listener listenersCopy := make([]EventListener, 0, len(a.listeners)+1) listenersCopy = append(listenersCopy, a.listeners...) listenersCopy = append(listenersCopy, l) a.listeners = listenersCopy return true }
go
func (a *sharedEventEmitter) AddListener(l EventListener) bool { if l == nil { // do not register nil listener, will cause nil pointer dereference during // event emitting return false } a.listenersLock.Lock() defer a.listenersLock.Unlock() // Check if listener is already registered for _, listener := range a.listeners { if listener == l { return false } } // by making a copy the backing array will never be changed after its creation. // this allowes to copy the slice while locked but iterate while not locked // preventing deadlocks when listeners are added/removed in the handler of a // listener listenersCopy := make([]EventListener, 0, len(a.listeners)+1) listenersCopy = append(listenersCopy, a.listeners...) listenersCopy = append(listenersCopy, l) a.listeners = listenersCopy return true }
[ "func", "(", "a", "*", "sharedEventEmitter", ")", "AddListener", "(", "l", "EventListener", ")", "bool", "{", "if", "l", "==", "nil", "{", "// do not register nil listener, will cause nil pointer dereference during", "// event emitting", "return", "false", "\n", "}", "\n\n", "a", ".", "listenersLock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "listenersLock", ".", "Unlock", "(", ")", "\n\n", "// Check if listener is already registered", "for", "_", ",", "listener", ":=", "range", "a", ".", "listeners", "{", "if", "listener", "==", "l", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// by making a copy the backing array will never be changed after its creation.", "// this allowes to copy the slice while locked but iterate while not locked", "// preventing deadlocks when listeners are added/removed in the handler of a", "// listener", "listenersCopy", ":=", "make", "(", "[", "]", "EventListener", ",", "0", ",", "len", "(", "a", ".", "listeners", ")", "+", "1", ")", "\n", "listenersCopy", "=", "append", "(", "listenersCopy", ",", "a", ".", "listeners", "...", ")", "\n", "listenersCopy", "=", "append", "(", "listenersCopy", ",", "l", ")", "\n\n", "a", ".", "listeners", "=", "listenersCopy", "\n\n", "return", "true", "\n", "}" ]
// AddListener adds a listener to the EventEmitter. Events emitted on this // emitter will be invoked on the listener. The return value indicates if the // listener has been added or not. It can't be added if it is already added and // therefore registered to receive events
[ "AddListener", "adds", "a", "listener", "to", "the", "EventEmitter", ".", "Events", "emitted", "on", "this", "emitter", "will", "be", "invoked", "on", "the", "listener", ".", "The", "return", "value", "indicates", "if", "the", "listener", "has", "been", "added", "or", "not", ".", "It", "can", "t", "be", "added", "if", "it", "is", "already", "added", "and", "therefore", "registered", "to", "receive", "events" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/events/events.go#L70-L98
train
uber/ringpop-go
events/events.go
RemoveListener
func (a *sharedEventEmitter) RemoveListener(l EventListener) bool { a.listenersLock.Lock() defer a.listenersLock.Unlock() for i := range a.listeners { if a.listeners[i] == l { // create a new list excluding the listener that needs removal listenersCopy := make([]EventListener, 0, len(a.listeners)-1) listenersCopy = append(listenersCopy, a.listeners[:i]...) listenersCopy = append(listenersCopy, a.listeners[i+1:]...) a.listeners = listenersCopy return true } } return false }
go
func (a *sharedEventEmitter) RemoveListener(l EventListener) bool { a.listenersLock.Lock() defer a.listenersLock.Unlock() for i := range a.listeners { if a.listeners[i] == l { // create a new list excluding the listener that needs removal listenersCopy := make([]EventListener, 0, len(a.listeners)-1) listenersCopy = append(listenersCopy, a.listeners[:i]...) listenersCopy = append(listenersCopy, a.listeners[i+1:]...) a.listeners = listenersCopy return true } } return false }
[ "func", "(", "a", "*", "sharedEventEmitter", ")", "RemoveListener", "(", "l", "EventListener", ")", "bool", "{", "a", ".", "listenersLock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "listenersLock", ".", "Unlock", "(", ")", "\n\n", "for", "i", ":=", "range", "a", ".", "listeners", "{", "if", "a", ".", "listeners", "[", "i", "]", "==", "l", "{", "// create a new list excluding the listener that needs removal", "listenersCopy", ":=", "make", "(", "[", "]", "EventListener", ",", "0", ",", "len", "(", "a", ".", "listeners", ")", "-", "1", ")", "\n", "listenersCopy", "=", "append", "(", "listenersCopy", ",", "a", ".", "listeners", "[", ":", "i", "]", "...", ")", "\n", "listenersCopy", "=", "append", "(", "listenersCopy", ",", "a", ".", "listeners", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "a", ".", "listeners", "=", "listenersCopy", "\n\n", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// RemoveListener removes a listener from the EventEmitter. Subsequent calls to // EmitEvent will not cause HandleEvent to be called on this listener. The // return value indicates if a listener has been removed or not. The listener // can't be removed if it was not present before.
[ "RemoveListener", "removes", "a", "listener", "from", "the", "EventEmitter", ".", "Subsequent", "calls", "to", "EmitEvent", "will", "not", "cause", "HandleEvent", "to", "be", "called", "on", "this", "listener", ".", "The", "return", "value", "indicates", "if", "a", "listener", "has", "been", "removed", "or", "not", ".", "The", "listener", "can", "t", "be", "removed", "if", "it", "was", "not", "present", "before", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/events/events.go#L104-L121
train
uber/ringpop-go
events/events.go
EmitEvent
func (a *AsyncEventEmitter) EmitEvent(event Event) { a.listenersLock.RLock() for _, listener := range a.listeners { go listener.HandleEvent(event) } a.listenersLock.RUnlock() }
go
func (a *AsyncEventEmitter) EmitEvent(event Event) { a.listenersLock.RLock() for _, listener := range a.listeners { go listener.HandleEvent(event) } a.listenersLock.RUnlock() }
[ "func", "(", "a", "*", "AsyncEventEmitter", ")", "EmitEvent", "(", "event", "Event", ")", "{", "a", ".", "listenersLock", ".", "RLock", "(", ")", "\n", "for", "_", ",", "listener", ":=", "range", "a", ".", "listeners", "{", "go", "listener", ".", "HandleEvent", "(", "event", ")", "\n", "}", "\n", "a", ".", "listenersLock", ".", "RUnlock", "(", ")", "\n", "}" ]
// EmitEvent will send the event to all registered listeners
[ "EmitEvent", "will", "send", "the", "event", "to", "all", "registered", "listeners" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/events/events.go#L130-L136
train
uber/ringpop-go
swim/memberlist_iter.go
newMemberlistIter
func newMemberlistIter(m *memberlist) *memberlistIter { iter := &memberlistIter{ m: m, currentIndex: -1, currentRound: 0, } iter.m.Shuffle() return iter }
go
func newMemberlistIter(m *memberlist) *memberlistIter { iter := &memberlistIter{ m: m, currentIndex: -1, currentRound: 0, } iter.m.Shuffle() return iter }
[ "func", "newMemberlistIter", "(", "m", "*", "memberlist", ")", "*", "memberlistIter", "{", "iter", ":=", "&", "memberlistIter", "{", "m", ":", "m", ",", "currentIndex", ":", "-", "1", ",", "currentRound", ":", "0", ",", "}", "\n\n", "iter", ".", "m", ".", "Shuffle", "(", ")", "\n\n", "return", "iter", "\n", "}" ]
// NewMemberlistIter returns a new MemberlistIter
[ "NewMemberlistIter", "returns", "a", "new", "MemberlistIter" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist_iter.go#L36-L46
train
uber/ringpop-go
swim/memberlist_iter.go
Next
func (i *memberlistIter) Next() (*Member, bool) { maxToVisit := i.m.NumMembers() visited := make(map[string]bool) for len(visited) < maxToVisit { i.currentIndex++ if i.currentIndex >= i.m.NumMembers() { i.currentIndex = 0 i.currentRound++ i.m.Shuffle() } member := i.m.MemberAt(i.currentIndex) visited[member.Address] = true if i.m.Pingable(*member) { return member, true } } return nil, false }
go
func (i *memberlistIter) Next() (*Member, bool) { maxToVisit := i.m.NumMembers() visited := make(map[string]bool) for len(visited) < maxToVisit { i.currentIndex++ if i.currentIndex >= i.m.NumMembers() { i.currentIndex = 0 i.currentRound++ i.m.Shuffle() } member := i.m.MemberAt(i.currentIndex) visited[member.Address] = true if i.m.Pingable(*member) { return member, true } } return nil, false }
[ "func", "(", "i", "*", "memberlistIter", ")", "Next", "(", ")", "(", "*", "Member", ",", "bool", ")", "{", "maxToVisit", ":=", "i", ".", "m", ".", "NumMembers", "(", ")", "\n", "visited", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "for", "len", "(", "visited", ")", "<", "maxToVisit", "{", "i", ".", "currentIndex", "++", "\n\n", "if", "i", ".", "currentIndex", ">=", "i", ".", "m", ".", "NumMembers", "(", ")", "{", "i", ".", "currentIndex", "=", "0", "\n", "i", ".", "currentRound", "++", "\n", "i", ".", "m", ".", "Shuffle", "(", ")", "\n", "}", "\n\n", "member", ":=", "i", ".", "m", ".", "MemberAt", "(", "i", ".", "currentIndex", ")", "\n", "visited", "[", "member", ".", "Address", "]", "=", "true", "\n\n", "if", "i", ".", "m", ".", "Pingable", "(", "*", "member", ")", "{", "return", "member", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "false", "\n", "}" ]
// Next returns the next pingable member in the member list, if it // visits all members but none are pingable returns nil, false
[ "Next", "returns", "the", "next", "pingable", "member", "in", "the", "member", "list", "if", "it", "visits", "all", "members", "but", "none", "are", "pingable", "returns", "nil", "false" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist_iter.go#L50-L72
train
beanstalkd/go-beanstalk
conn.go
Dial
func Dial(network, addr string) (*Conn, error) { return DialTimeout(network, addr, DefaultDialTimeout) }
go
func Dial(network, addr string) (*Conn, error) { return DialTimeout(network, addr, DefaultDialTimeout) }
[ "func", "Dial", "(", "network", ",", "addr", "string", ")", "(", "*", "Conn", ",", "error", ")", "{", "return", "DialTimeout", "(", "network", ",", "addr", ",", "DefaultDialTimeout", ")", "\n", "}" ]
// Dial connects addr on the given network using net.DialTimeout // with a default timeout of 10s and then returns a new Conn for the connection.
[ "Dial", "connects", "addr", "on", "the", "given", "network", "using", "net", ".", "DialTimeout", "with", "a", "default", "timeout", "of", "10s", "and", "then", "returns", "a", "new", "Conn", "for", "the", "connection", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L52-L54
train
beanstalkd/go-beanstalk
conn.go
DialTimeout
func DialTimeout(network, addr string, timeout time.Duration) (*Conn, error) { dialer := &net.Dialer{ Timeout: timeout, KeepAlive: DefaultKeepAlivePeriod, } c, err := dialer.Dial(network, addr) if err != nil { return nil, err } return NewConn(c), nil }
go
func DialTimeout(network, addr string, timeout time.Duration) (*Conn, error) { dialer := &net.Dialer{ Timeout: timeout, KeepAlive: DefaultKeepAlivePeriod, } c, err := dialer.Dial(network, addr) if err != nil { return nil, err } return NewConn(c), nil }
[ "func", "DialTimeout", "(", "network", ",", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "Conn", ",", "error", ")", "{", "dialer", ":=", "&", "net", ".", "Dialer", "{", "Timeout", ":", "timeout", ",", "KeepAlive", ":", "DefaultKeepAlivePeriod", ",", "}", "\n", "c", ",", "err", ":=", "dialer", ".", "Dial", "(", "network", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewConn", "(", "c", ")", ",", "nil", "\n", "}" ]
// DialTimeout connects addr on the given network using net.DialTimeout // with a supplied timeout and then returns a new Conn for the connection.
[ "DialTimeout", "connects", "addr", "on", "the", "given", "network", "using", "net", ".", "DialTimeout", "with", "a", "supplied", "timeout", "and", "then", "returns", "a", "new", "Conn", "for", "the", "connection", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L58-L68
train
beanstalkd/go-beanstalk
conn.go
printLine
func (c *Conn) printLine(cmd string, args ...interface{}) { io.WriteString(c.c.W, cmd) for _, a := range args { c.c.W.Write(space) fmt.Fprint(c.c.W, a) } c.c.W.Write(crnl) }
go
func (c *Conn) printLine(cmd string, args ...interface{}) { io.WriteString(c.c.W, cmd) for _, a := range args { c.c.W.Write(space) fmt.Fprint(c.c.W, a) } c.c.W.Write(crnl) }
[ "func", "(", "c", "*", "Conn", ")", "printLine", "(", "cmd", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "io", ".", "WriteString", "(", "c", ".", "c", ".", "W", ",", "cmd", ")", "\n", "for", "_", ",", "a", ":=", "range", "args", "{", "c", ".", "c", ".", "W", ".", "Write", "(", "space", ")", "\n", "fmt", ".", "Fprint", "(", "c", ".", "c", ".", "W", ",", "a", ")", "\n", "}", "\n", "c", ".", "c", ".", "W", ".", "Write", "(", "crnl", ")", "\n", "}" ]
// does not flush
[ "does", "not", "flush" ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L129-L136
train
beanstalkd/go-beanstalk
conn.go
Delete
func (c *Conn) Delete(id uint64) error { r, err := c.cmd(nil, nil, nil, "delete", id) if err != nil { return err } _, err = c.readResp(r, false, "DELETED") return err }
go
func (c *Conn) Delete(id uint64) error { r, err := c.cmd(nil, nil, nil, "delete", id) if err != nil { return err } _, err = c.readResp(r, false, "DELETED") return err }
[ "func", "(", "c", "*", "Conn", ")", "Delete", "(", "id", "uint64", ")", "error", "{", "r", ",", "err", ":=", "c", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "readResp", "(", "r", ",", "false", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// Delete deletes the given job.
[ "Delete", "deletes", "the", "given", "job", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L171-L178
train
beanstalkd/go-beanstalk
conn.go
Bury
func (c *Conn) Bury(id uint64, pri uint32) error { r, err := c.cmd(nil, nil, nil, "bury", id, pri) if err != nil { return err } _, err = c.readResp(r, false, "BURIED") return err }
go
func (c *Conn) Bury(id uint64, pri uint32) error { r, err := c.cmd(nil, nil, nil, "bury", id, pri) if err != nil { return err } _, err = c.readResp(r, false, "BURIED") return err }
[ "func", "(", "c", "*", "Conn", ")", "Bury", "(", "id", "uint64", ",", "pri", "uint32", ")", "error", "{", "r", ",", "err", ":=", "c", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "id", ",", "pri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "readResp", "(", "r", ",", "false", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// Bury places the given job in a holding area in the job's tube and // sets its priority to pri. The job will not be scheduled again until it // has been kicked; see also the documentation of Kick.
[ "Bury", "places", "the", "given", "job", "in", "a", "holding", "area", "in", "the", "job", "s", "tube", "and", "sets", "its", "priority", "to", "pri", ".", "The", "job", "will", "not", "be", "scheduled", "again", "until", "it", "has", "been", "kicked", ";", "see", "also", "the", "documentation", "of", "Kick", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L196-L203
train
beanstalkd/go-beanstalk
conn.go
Peek
func (c *Conn) Peek(id uint64) (body []byte, err error) { r, err := c.cmd(nil, nil, nil, "peek", id) if err != nil { return nil, err } return c.readResp(r, true, "FOUND %d", &id) }
go
func (c *Conn) Peek(id uint64) (body []byte, err error) { r, err := c.cmd(nil, nil, nil, "peek", id) if err != nil { return nil, err } return c.readResp(r, true, "FOUND %d", &id) }
[ "func", "(", "c", "*", "Conn", ")", "Peek", "(", "id", "uint64", ")", "(", "body", "[", "]", "byte", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "c", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "c", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ",", "&", "id", ")", "\n", "}" ]
// Peek gets a copy of the specified job from the server.
[ "Peek", "gets", "a", "copy", "of", "the", "specified", "job", "from", "the", "server", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L229-L235
train
beanstalkd/go-beanstalk
conn.go
Stats
func (c *Conn) Stats() (map[string]string, error) { r, err := c.cmd(nil, nil, nil, "stats") if err != nil { return nil, err } body, err := c.readResp(r, true, "OK") return parseDict(body), err }
go
func (c *Conn) Stats() (map[string]string, error) { r, err := c.cmd(nil, nil, nil, "stats") if err != nil { return nil, err } body, err := c.readResp(r, true, "OK") return parseDict(body), err }
[ "func", "(", "c", "*", "Conn", ")", "Stats", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "r", ",", "err", ":=", "c", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "body", ",", "err", ":=", "c", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ")", "\n", "return", "parseDict", "(", "body", ")", ",", "err", "\n", "}" ]
// Stats retrieves global statistics from the server.
[ "Stats", "retrieves", "global", "statistics", "from", "the", "server", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L238-L245
train
beanstalkd/go-beanstalk
conn.go
StatsJob
func (c *Conn) StatsJob(id uint64) (map[string]string, error) { r, err := c.cmd(nil, nil, nil, "stats-job", id) if err != nil { return nil, err } body, err := c.readResp(r, true, "OK") return parseDict(body), err }
go
func (c *Conn) StatsJob(id uint64) (map[string]string, error) { r, err := c.cmd(nil, nil, nil, "stats-job", id) if err != nil { return nil, err } body, err := c.readResp(r, true, "OK") return parseDict(body), err }
[ "func", "(", "c", "*", "Conn", ")", "StatsJob", "(", "id", "uint64", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "r", ",", "err", ":=", "c", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "body", ",", "err", ":=", "c", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ")", "\n", "return", "parseDict", "(", "body", ")", ",", "err", "\n", "}" ]
// StatsJob retrieves statistics about the given job.
[ "StatsJob", "retrieves", "statistics", "about", "the", "given", "job", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L248-L255
train
beanstalkd/go-beanstalk
conn.go
ListTubes
func (c *Conn) ListTubes() ([]string, error) { r, err := c.cmd(nil, nil, nil, "list-tubes") if err != nil { return nil, err } body, err := c.readResp(r, true, "OK") return parseList(body), err }
go
func (c *Conn) ListTubes() ([]string, error) { r, err := c.cmd(nil, nil, nil, "list-tubes") if err != nil { return nil, err } body, err := c.readResp(r, true, "OK") return parseList(body), err }
[ "func", "(", "c", "*", "Conn", ")", "ListTubes", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "r", ",", "err", ":=", "c", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "body", ",", "err", ":=", "c", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ")", "\n", "return", "parseList", "(", "body", ")", ",", "err", "\n", "}" ]
// ListTubes returns the names of the tubes that currently // exist on the server.
[ "ListTubes", "returns", "the", "names", "of", "the", "tubes", "that", "currently", "exist", "on", "the", "server", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/conn.go#L259-L266
train
beanstalkd/go-beanstalk
tubeset.go
NewTubeSet
func NewTubeSet(c *Conn, name ...string) *TubeSet { ts := &TubeSet{c, make(map[string]bool)} for _, s := range name { ts.Name[s] = true } return ts }
go
func NewTubeSet(c *Conn, name ...string) *TubeSet { ts := &TubeSet{c, make(map[string]bool)} for _, s := range name { ts.Name[s] = true } return ts }
[ "func", "NewTubeSet", "(", "c", "*", "Conn", ",", "name", "...", "string", ")", "*", "TubeSet", "{", "ts", ":=", "&", "TubeSet", "{", "c", ",", "make", "(", "map", "[", "string", "]", "bool", ")", "}", "\n", "for", "_", ",", "s", ":=", "range", "name", "{", "ts", ".", "Name", "[", "s", "]", "=", "true", "\n", "}", "\n", "return", "ts", "\n", "}" ]
// NewTubeSet returns a new TubeSet representing the given names.
[ "NewTubeSet", "returns", "a", "new", "TubeSet", "representing", "the", "given", "names", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tubeset.go#L15-L21
train
beanstalkd/go-beanstalk
tubeset.go
Reserve
func (t *TubeSet) Reserve(timeout time.Duration) (id uint64, body []byte, err error) { r, err := t.Conn.cmd(nil, t, nil, "reserve-with-timeout", dur(timeout)) if err != nil { return 0, nil, err } body, err = t.Conn.readResp(r, true, "RESERVED %d", &id) if err != nil { return 0, nil, err } return id, body, nil }
go
func (t *TubeSet) Reserve(timeout time.Duration) (id uint64, body []byte, err error) { r, err := t.Conn.cmd(nil, t, nil, "reserve-with-timeout", dur(timeout)) if err != nil { return 0, nil, err } body, err = t.Conn.readResp(r, true, "RESERVED %d", &id) if err != nil { return 0, nil, err } return id, body, nil }
[ "func", "(", "t", "*", "TubeSet", ")", "Reserve", "(", "timeout", "time", ".", "Duration", ")", "(", "id", "uint64", ",", "body", "[", "]", "byte", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "t", ".", "Conn", ".", "cmd", "(", "nil", ",", "t", ",", "nil", ",", "\"", "\"", ",", "dur", "(", "timeout", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "body", ",", "err", "=", "t", ".", "Conn", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ",", "&", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "return", "id", ",", "body", ",", "nil", "\n", "}" ]
// Reserve reserves and returns a job from one of the tubes in t. If no // job is available before time timeout has passed, Reserve returns a // ConnError recording ErrTimeout. // // Typically, a client will reserve a job, perform some work, then delete // the job with Conn.Delete.
[ "Reserve", "reserves", "and", "returns", "a", "job", "from", "one", "of", "the", "tubes", "in", "t", ".", "If", "no", "job", "is", "available", "before", "time", "timeout", "has", "passed", "Reserve", "returns", "a", "ConnError", "recording", "ErrTimeout", ".", "Typically", "a", "client", "will", "reserve", "a", "job", "perform", "some", "work", "then", "delete", "the", "job", "with", "Conn", ".", "Delete", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tubeset.go#L29-L39
train
beanstalkd/go-beanstalk
tube.go
Put
func (t *Tube) Put(body []byte, pri uint32, delay, ttr time.Duration) (id uint64, err error) { r, err := t.Conn.cmd(t, nil, body, "put", pri, dur(delay), dur(ttr)) if err != nil { return 0, err } _, err = t.Conn.readResp(r, false, "INSERTED %d", &id) if err != nil { return 0, err } return id, nil }
go
func (t *Tube) Put(body []byte, pri uint32, delay, ttr time.Duration) (id uint64, err error) { r, err := t.Conn.cmd(t, nil, body, "put", pri, dur(delay), dur(ttr)) if err != nil { return 0, err } _, err = t.Conn.readResp(r, false, "INSERTED %d", &id) if err != nil { return 0, err } return id, nil }
[ "func", "(", "t", "*", "Tube", ")", "Put", "(", "body", "[", "]", "byte", ",", "pri", "uint32", ",", "delay", ",", "ttr", "time", ".", "Duration", ")", "(", "id", "uint64", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "t", ".", "Conn", ".", "cmd", "(", "t", ",", "nil", ",", "body", ",", "\"", "\"", ",", "pri", ",", "dur", "(", "delay", ")", ",", "dur", "(", "ttr", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "t", ".", "Conn", ".", "readResp", "(", "r", ",", "false", ",", "\"", "\"", ",", "&", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "id", ",", "nil", "\n", "}" ]
// Put puts a job into tube t with priority pri and TTR ttr, and returns // the id of the newly-created job. If delay is nonzero, the server will // wait the given amount of time after returning to the client and before // putting the job into the ready queue.
[ "Put", "puts", "a", "job", "into", "tube", "t", "with", "priority", "pri", "and", "TTR", "ttr", "and", "returns", "the", "id", "of", "the", "newly", "-", "created", "job", ".", "If", "delay", "is", "nonzero", "the", "server", "will", "wait", "the", "given", "amount", "of", "time", "after", "returning", "to", "the", "client", "and", "before", "putting", "the", "job", "into", "the", "ready", "queue", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tube.go#L18-L28
train
beanstalkd/go-beanstalk
tube.go
PeekDelayed
func (t *Tube) PeekDelayed() (id uint64, body []byte, err error) { r, err := t.Conn.cmd(t, nil, nil, "peek-delayed") if err != nil { return 0, nil, err } body, err = t.Conn.readResp(r, true, "FOUND %d", &id) if err != nil { return 0, nil, err } return id, body, nil }
go
func (t *Tube) PeekDelayed() (id uint64, body []byte, err error) { r, err := t.Conn.cmd(t, nil, nil, "peek-delayed") if err != nil { return 0, nil, err } body, err = t.Conn.readResp(r, true, "FOUND %d", &id) if err != nil { return 0, nil, err } return id, body, nil }
[ "func", "(", "t", "*", "Tube", ")", "PeekDelayed", "(", ")", "(", "id", "uint64", ",", "body", "[", "]", "byte", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "t", ".", "Conn", ".", "cmd", "(", "t", ",", "nil", ",", "nil", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "body", ",", "err", "=", "t", ".", "Conn", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ",", "&", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "return", "id", ",", "body", ",", "nil", "\n", "}" ]
// PeekDelayed gets a copy of the delayed job that is next to be // put in t's ready queue.
[ "PeekDelayed", "gets", "a", "copy", "of", "the", "delayed", "job", "that", "is", "next", "to", "be", "put", "in", "t", "s", "ready", "queue", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tube.go#L45-L55
train
beanstalkd/go-beanstalk
tube.go
Kick
func (t *Tube) Kick(bound int) (n int, err error) { r, err := t.Conn.cmd(t, nil, nil, "kick", bound) if err != nil { return 0, err } _, err = t.Conn.readResp(r, false, "KICKED %d", &n) if err != nil { return 0, err } return n, nil }
go
func (t *Tube) Kick(bound int) (n int, err error) { r, err := t.Conn.cmd(t, nil, nil, "kick", bound) if err != nil { return 0, err } _, err = t.Conn.readResp(r, false, "KICKED %d", &n) if err != nil { return 0, err } return n, nil }
[ "func", "(", "t", "*", "Tube", ")", "Kick", "(", "bound", "int", ")", "(", "n", "int", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "t", ".", "Conn", ".", "cmd", "(", "t", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "bound", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "t", ".", "Conn", ".", "readResp", "(", "r", ",", "false", ",", "\"", "\"", ",", "&", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
// Kick takes up to bound jobs from the holding area and moves them into // the ready queue, then returns the number of jobs moved. Jobs will be // taken in the order in which they were last buried.
[ "Kick", "takes", "up", "to", "bound", "jobs", "from", "the", "holding", "area", "and", "moves", "them", "into", "the", "ready", "queue", "then", "returns", "the", "number", "of", "jobs", "moved", ".", "Jobs", "will", "be", "taken", "in", "the", "order", "in", "which", "they", "were", "last", "buried", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tube.go#L74-L84
train
beanstalkd/go-beanstalk
tube.go
Stats
func (t *Tube) Stats() (map[string]string, error) { r, err := t.Conn.cmd(nil, nil, nil, "stats-tube", t.Name) if err != nil { return nil, err } body, err := t.Conn.readResp(r, true, "OK") return parseDict(body), err }
go
func (t *Tube) Stats() (map[string]string, error) { r, err := t.Conn.cmd(nil, nil, nil, "stats-tube", t.Name) if err != nil { return nil, err } body, err := t.Conn.readResp(r, true, "OK") return parseDict(body), err }
[ "func", "(", "t", "*", "Tube", ")", "Stats", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "r", ",", "err", ":=", "t", ".", "Conn", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "t", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "body", ",", "err", ":=", "t", ".", "Conn", ".", "readResp", "(", "r", ",", "true", ",", "\"", "\"", ")", "\n", "return", "parseDict", "(", "body", ")", ",", "err", "\n", "}" ]
// Stats retrieves statistics about tube t.
[ "Stats", "retrieves", "statistics", "about", "tube", "t", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tube.go#L87-L94
train
beanstalkd/go-beanstalk
tube.go
Pause
func (t *Tube) Pause(d time.Duration) error { r, err := t.Conn.cmd(nil, nil, nil, "pause-tube", t.Name, dur(d)) if err != nil { return err } _, err = t.Conn.readResp(r, false, "PAUSED") if err != nil { return err } return nil }
go
func (t *Tube) Pause(d time.Duration) error { r, err := t.Conn.cmd(nil, nil, nil, "pause-tube", t.Name, dur(d)) if err != nil { return err } _, err = t.Conn.readResp(r, false, "PAUSED") if err != nil { return err } return nil }
[ "func", "(", "t", "*", "Tube", ")", "Pause", "(", "d", "time", ".", "Duration", ")", "error", "{", "r", ",", "err", ":=", "t", ".", "Conn", ".", "cmd", "(", "nil", ",", "nil", ",", "nil", ",", "\"", "\"", ",", "t", ".", "Name", ",", "dur", "(", "d", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "t", ".", "Conn", ".", "readResp", "(", "r", ",", "false", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Pause pauses new reservations in t for time d.
[ "Pause", "pauses", "new", "reservations", "in", "t", "for", "time", "d", "." ]
7a112881e6c4f85f0d98f8929536e775d31fb4de
https://github.com/beanstalkd/go-beanstalk/blob/7a112881e6c4f85f0d98f8929536e775d31fb4de/tube.go#L97-L107
train
hashicorp/go-immutable-radix
iradix.go
Txn
func (t *Tree) Txn() *Txn { txn := &Txn{ root: t.root, snap: t.root, size: t.size, } return txn }
go
func (t *Tree) Txn() *Txn { txn := &Txn{ root: t.root, snap: t.root, size: t.size, } return txn }
[ "func", "(", "t", "*", "Tree", ")", "Txn", "(", ")", "*", "Txn", "{", "txn", ":=", "&", "Txn", "{", "root", ":", "t", ".", "root", ",", "snap", ":", "t", ".", "root", ",", "size", ":", "t", ".", "size", ",", "}", "\n", "return", "txn", "\n", "}" ]
// Txn starts a new transaction that can be used to mutate the tree
[ "Txn", "starts", "a", "new", "transaction", "that", "can", "be", "used", "to", "mutate", "the", "tree" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L80-L87
train
hashicorp/go-immutable-radix
iradix.go
trackChannel
func (t *Txn) trackChannel(ch chan struct{}) { // In overflow, make sure we don't store any more objects. if t.trackOverflow { return } // If this would overflow the state we reject it and set the flag (since // we aren't tracking everything that's required any longer). if len(t.trackChannels) >= defaultModifiedCache { // Mark that we are in the overflow state t.trackOverflow = true // Clear the map so that the channels can be garbage collected. It is // safe to do this since we have already overflowed and will be using // the slow notify algorithm. t.trackChannels = nil return } // Create the map on the fly when we need it. if t.trackChannels == nil { t.trackChannels = make(map[chan struct{}]struct{}) } // Otherwise we are good to track it. t.trackChannels[ch] = struct{}{} }
go
func (t *Txn) trackChannel(ch chan struct{}) { // In overflow, make sure we don't store any more objects. if t.trackOverflow { return } // If this would overflow the state we reject it and set the flag (since // we aren't tracking everything that's required any longer). if len(t.trackChannels) >= defaultModifiedCache { // Mark that we are in the overflow state t.trackOverflow = true // Clear the map so that the channels can be garbage collected. It is // safe to do this since we have already overflowed and will be using // the slow notify algorithm. t.trackChannels = nil return } // Create the map on the fly when we need it. if t.trackChannels == nil { t.trackChannels = make(map[chan struct{}]struct{}) } // Otherwise we are good to track it. t.trackChannels[ch] = struct{}{} }
[ "func", "(", "t", "*", "Txn", ")", "trackChannel", "(", "ch", "chan", "struct", "{", "}", ")", "{", "// In overflow, make sure we don't store any more objects.", "if", "t", ".", "trackOverflow", "{", "return", "\n", "}", "\n\n", "// If this would overflow the state we reject it and set the flag (since", "// we aren't tracking everything that's required any longer).", "if", "len", "(", "t", ".", "trackChannels", ")", ">=", "defaultModifiedCache", "{", "// Mark that we are in the overflow state", "t", ".", "trackOverflow", "=", "true", "\n\n", "// Clear the map so that the channels can be garbage collected. It is", "// safe to do this since we have already overflowed and will be using", "// the slow notify algorithm.", "t", ".", "trackChannels", "=", "nil", "\n", "return", "\n", "}", "\n\n", "// Create the map on the fly when we need it.", "if", "t", ".", "trackChannels", "==", "nil", "{", "t", ".", "trackChannels", "=", "make", "(", "map", "[", "chan", "struct", "{", "}", "]", "struct", "{", "}", ")", "\n", "}", "\n\n", "// Otherwise we are good to track it.", "t", ".", "trackChannels", "[", "ch", "]", "=", "struct", "{", "}", "{", "}", "\n", "}" ]
// trackChannel safely attempts to track the given mutation channel, setting the // overflow flag if we can no longer track any more. This limits the amount of // state that will accumulate during a transaction and we have a slower algorithm // to switch to if we overflow.
[ "trackChannel", "safely", "attempts", "to", "track", "the", "given", "mutation", "channel", "setting", "the", "overflow", "flag", "if", "we", "can", "no", "longer", "track", "any", "more", ".", "This", "limits", "the", "amount", "of", "state", "that", "will", "accumulate", "during", "a", "transaction", "and", "we", "have", "a", "slower", "algorithm", "to", "switch", "to", "if", "we", "overflow", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L100-L126
train
hashicorp/go-immutable-radix
iradix.go
writeNode
func (t *Txn) writeNode(n *Node, forLeafUpdate bool) *Node { // Ensure the writable set exists. if t.writable == nil { lru, err := simplelru.NewLRU(defaultModifiedCache, nil) if err != nil { panic(err) } t.writable = lru } // If this node has already been modified, we can continue to use it // during this transaction. We know that we don't need to track it for // a node update since the node is writable, but if this is for a leaf // update we track it, in case the initial write to this node didn't // update the leaf. if _, ok := t.writable.Get(n); ok { if t.trackMutate && forLeafUpdate && n.leaf != nil { t.trackChannel(n.leaf.mutateCh) } return n } // Mark this node as being mutated. if t.trackMutate { t.trackChannel(n.mutateCh) } // Mark its leaf as being mutated, if appropriate. if t.trackMutate && forLeafUpdate && n.leaf != nil { t.trackChannel(n.leaf.mutateCh) } // Copy the existing node. If you have set forLeafUpdate it will be // safe to replace this leaf with another after you get your node for // writing. You MUST replace it, because the channel associated with // this leaf will be closed when this transaction is committed. nc := &Node{ mutateCh: make(chan struct{}), leaf: n.leaf, } if n.prefix != nil { nc.prefix = make([]byte, len(n.prefix)) copy(nc.prefix, n.prefix) } if len(n.edges) != 0 { nc.edges = make([]edge, len(n.edges)) copy(nc.edges, n.edges) } // Mark this node as writable. t.writable.Add(nc, nil) return nc }
go
func (t *Txn) writeNode(n *Node, forLeafUpdate bool) *Node { // Ensure the writable set exists. if t.writable == nil { lru, err := simplelru.NewLRU(defaultModifiedCache, nil) if err != nil { panic(err) } t.writable = lru } // If this node has already been modified, we can continue to use it // during this transaction. We know that we don't need to track it for // a node update since the node is writable, but if this is for a leaf // update we track it, in case the initial write to this node didn't // update the leaf. if _, ok := t.writable.Get(n); ok { if t.trackMutate && forLeafUpdate && n.leaf != nil { t.trackChannel(n.leaf.mutateCh) } return n } // Mark this node as being mutated. if t.trackMutate { t.trackChannel(n.mutateCh) } // Mark its leaf as being mutated, if appropriate. if t.trackMutate && forLeafUpdate && n.leaf != nil { t.trackChannel(n.leaf.mutateCh) } // Copy the existing node. If you have set forLeafUpdate it will be // safe to replace this leaf with another after you get your node for // writing. You MUST replace it, because the channel associated with // this leaf will be closed when this transaction is committed. nc := &Node{ mutateCh: make(chan struct{}), leaf: n.leaf, } if n.prefix != nil { nc.prefix = make([]byte, len(n.prefix)) copy(nc.prefix, n.prefix) } if len(n.edges) != 0 { nc.edges = make([]edge, len(n.edges)) copy(nc.edges, n.edges) } // Mark this node as writable. t.writable.Add(nc, nil) return nc }
[ "func", "(", "t", "*", "Txn", ")", "writeNode", "(", "n", "*", "Node", ",", "forLeafUpdate", "bool", ")", "*", "Node", "{", "// Ensure the writable set exists.", "if", "t", ".", "writable", "==", "nil", "{", "lru", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "defaultModifiedCache", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "t", ".", "writable", "=", "lru", "\n", "}", "\n\n", "// If this node has already been modified, we can continue to use it", "// during this transaction. We know that we don't need to track it for", "// a node update since the node is writable, but if this is for a leaf", "// update we track it, in case the initial write to this node didn't", "// update the leaf.", "if", "_", ",", "ok", ":=", "t", ".", "writable", ".", "Get", "(", "n", ")", ";", "ok", "{", "if", "t", ".", "trackMutate", "&&", "forLeafUpdate", "&&", "n", ".", "leaf", "!=", "nil", "{", "t", ".", "trackChannel", "(", "n", ".", "leaf", ".", "mutateCh", ")", "\n", "}", "\n", "return", "n", "\n", "}", "\n\n", "// Mark this node as being mutated.", "if", "t", ".", "trackMutate", "{", "t", ".", "trackChannel", "(", "n", ".", "mutateCh", ")", "\n", "}", "\n\n", "// Mark its leaf as being mutated, if appropriate.", "if", "t", ".", "trackMutate", "&&", "forLeafUpdate", "&&", "n", ".", "leaf", "!=", "nil", "{", "t", ".", "trackChannel", "(", "n", ".", "leaf", ".", "mutateCh", ")", "\n", "}", "\n\n", "// Copy the existing node. If you have set forLeafUpdate it will be", "// safe to replace this leaf with another after you get your node for", "// writing. You MUST replace it, because the channel associated with", "// this leaf will be closed when this transaction is committed.", "nc", ":=", "&", "Node", "{", "mutateCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "leaf", ":", "n", ".", "leaf", ",", "}", "\n", "if", "n", ".", "prefix", "!=", "nil", "{", "nc", ".", "prefix", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "n", ".", "prefix", ")", ")", "\n", "copy", "(", "nc", ".", "prefix", ",", "n", ".", "prefix", ")", "\n", "}", "\n", "if", "len", "(", "n", ".", "edges", ")", "!=", "0", "{", "nc", ".", "edges", "=", "make", "(", "[", "]", "edge", ",", "len", "(", "n", ".", "edges", ")", ")", "\n", "copy", "(", "nc", ".", "edges", ",", "n", ".", "edges", ")", "\n", "}", "\n\n", "// Mark this node as writable.", "t", ".", "writable", ".", "Add", "(", "nc", ",", "nil", ")", "\n", "return", "nc", "\n", "}" ]
// writeNode returns a node to be modified, if the current node has already been // modified during the course of the transaction, it is used in-place. Set // forLeafUpdate to true if you are getting a write node to update the leaf, // which will set leaf mutation tracking appropriately as well.
[ "writeNode", "returns", "a", "node", "to", "be", "modified", "if", "the", "current", "node", "has", "already", "been", "modified", "during", "the", "course", "of", "the", "transaction", "it", "is", "used", "in", "-", "place", ".", "Set", "forLeafUpdate", "to", "true", "if", "you", "are", "getting", "a", "write", "node", "to", "update", "the", "leaf", "which", "will", "set", "leaf", "mutation", "tracking", "appropriately", "as", "well", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L132-L184
train
hashicorp/go-immutable-radix
iradix.go
trackChannelsAndCount
func (t *Txn) trackChannelsAndCount(n *Node) int { // Count only leaf nodes leaves := 0 if n.leaf != nil { leaves = 1 } // Mark this node as being mutated. if t.trackMutate { t.trackChannel(n.mutateCh) } // Mark its leaf as being mutated, if appropriate. if t.trackMutate && n.leaf != nil { t.trackChannel(n.leaf.mutateCh) } // Recurse on the children for _, e := range n.edges { leaves += t.trackChannelsAndCount(e.node) } return leaves }
go
func (t *Txn) trackChannelsAndCount(n *Node) int { // Count only leaf nodes leaves := 0 if n.leaf != nil { leaves = 1 } // Mark this node as being mutated. if t.trackMutate { t.trackChannel(n.mutateCh) } // Mark its leaf as being mutated, if appropriate. if t.trackMutate && n.leaf != nil { t.trackChannel(n.leaf.mutateCh) } // Recurse on the children for _, e := range n.edges { leaves += t.trackChannelsAndCount(e.node) } return leaves }
[ "func", "(", "t", "*", "Txn", ")", "trackChannelsAndCount", "(", "n", "*", "Node", ")", "int", "{", "// Count only leaf nodes", "leaves", ":=", "0", "\n", "if", "n", ".", "leaf", "!=", "nil", "{", "leaves", "=", "1", "\n", "}", "\n", "// Mark this node as being mutated.", "if", "t", ".", "trackMutate", "{", "t", ".", "trackChannel", "(", "n", ".", "mutateCh", ")", "\n", "}", "\n\n", "// Mark its leaf as being mutated, if appropriate.", "if", "t", ".", "trackMutate", "&&", "n", ".", "leaf", "!=", "nil", "{", "t", ".", "trackChannel", "(", "n", ".", "leaf", ".", "mutateCh", ")", "\n", "}", "\n\n", "// Recurse on the children", "for", "_", ",", "e", ":=", "range", "n", ".", "edges", "{", "leaves", "+=", "t", ".", "trackChannelsAndCount", "(", "e", ".", "node", ")", "\n", "}", "\n", "return", "leaves", "\n", "}" ]
// Visit all the nodes in the tree under n, and add their mutateChannels to the transaction // Returns the size of the subtree visited
[ "Visit", "all", "the", "nodes", "in", "the", "tree", "under", "n", "and", "add", "their", "mutateChannels", "to", "the", "transaction", "Returns", "the", "size", "of", "the", "subtree", "visited" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L188-L209
train
hashicorp/go-immutable-radix
iradix.go
mergeChild
func (t *Txn) mergeChild(n *Node) { // Mark the child node as being mutated since we are about to abandon // it. We don't need to mark the leaf since we are retaining it if it // is there. e := n.edges[0] child := e.node if t.trackMutate { t.trackChannel(child.mutateCh) } // Merge the nodes. n.prefix = concat(n.prefix, child.prefix) n.leaf = child.leaf if len(child.edges) != 0 { n.edges = make([]edge, len(child.edges)) copy(n.edges, child.edges) } else { n.edges = nil } }
go
func (t *Txn) mergeChild(n *Node) { // Mark the child node as being mutated since we are about to abandon // it. We don't need to mark the leaf since we are retaining it if it // is there. e := n.edges[0] child := e.node if t.trackMutate { t.trackChannel(child.mutateCh) } // Merge the nodes. n.prefix = concat(n.prefix, child.prefix) n.leaf = child.leaf if len(child.edges) != 0 { n.edges = make([]edge, len(child.edges)) copy(n.edges, child.edges) } else { n.edges = nil } }
[ "func", "(", "t", "*", "Txn", ")", "mergeChild", "(", "n", "*", "Node", ")", "{", "// Mark the child node as being mutated since we are about to abandon", "// it. We don't need to mark the leaf since we are retaining it if it", "// is there.", "e", ":=", "n", ".", "edges", "[", "0", "]", "\n", "child", ":=", "e", ".", "node", "\n", "if", "t", ".", "trackMutate", "{", "t", ".", "trackChannel", "(", "child", ".", "mutateCh", ")", "\n", "}", "\n\n", "// Merge the nodes.", "n", ".", "prefix", "=", "concat", "(", "n", ".", "prefix", ",", "child", ".", "prefix", ")", "\n", "n", ".", "leaf", "=", "child", ".", "leaf", "\n", "if", "len", "(", "child", ".", "edges", ")", "!=", "0", "{", "n", ".", "edges", "=", "make", "(", "[", "]", "edge", ",", "len", "(", "child", ".", "edges", ")", ")", "\n", "copy", "(", "n", ".", "edges", ",", "child", ".", "edges", ")", "\n", "}", "else", "{", "n", ".", "edges", "=", "nil", "\n", "}", "\n", "}" ]
// mergeChild is called to collapse the given node with its child. This is only // called when the given node is not a leaf and has a single edge.
[ "mergeChild", "is", "called", "to", "collapse", "the", "given", "node", "with", "its", "child", ".", "This", "is", "only", "called", "when", "the", "given", "node", "is", "not", "a", "leaf", "and", "has", "a", "single", "edge", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L213-L232
train
hashicorp/go-immutable-radix
iradix.go
delete
func (t *Txn) delete(parent, n *Node, search []byte) (*Node, *leafNode) { // Check for key exhaustion if len(search) == 0 { if !n.isLeaf() { return nil, nil } // Copy the pointer in case we are in a transaction that already // modified this node since the node will be reused. Any changes // made to the node will not affect returning the original leaf // value. oldLeaf := n.leaf // Remove the leaf node nc := t.writeNode(n, true) nc.leaf = nil // Check if this node should be merged if n != t.root && len(nc.edges) == 1 { t.mergeChild(nc) } return nc, oldLeaf } // Look for an edge label := search[0] idx, child := n.getEdge(label) if child == nil || !bytes.HasPrefix(search, child.prefix) { return nil, nil } // Consume the search prefix search = search[len(child.prefix):] newChild, leaf := t.delete(n, child, search) if newChild == nil { return nil, nil } // Copy this node. WATCH OUT - it's safe to pass "false" here because we // will only ADD a leaf via nc.mergeChild() if there isn't one due to // the !nc.isLeaf() check in the logic just below. This is pretty subtle, // so be careful if you change any of the logic here. nc := t.writeNode(n, false) // Delete the edge if the node has no edges if newChild.leaf == nil && len(newChild.edges) == 0 { nc.delEdge(label) if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() { t.mergeChild(nc) } } else { nc.edges[idx].node = newChild } return nc, leaf }
go
func (t *Txn) delete(parent, n *Node, search []byte) (*Node, *leafNode) { // Check for key exhaustion if len(search) == 0 { if !n.isLeaf() { return nil, nil } // Copy the pointer in case we are in a transaction that already // modified this node since the node will be reused. Any changes // made to the node will not affect returning the original leaf // value. oldLeaf := n.leaf // Remove the leaf node nc := t.writeNode(n, true) nc.leaf = nil // Check if this node should be merged if n != t.root && len(nc.edges) == 1 { t.mergeChild(nc) } return nc, oldLeaf } // Look for an edge label := search[0] idx, child := n.getEdge(label) if child == nil || !bytes.HasPrefix(search, child.prefix) { return nil, nil } // Consume the search prefix search = search[len(child.prefix):] newChild, leaf := t.delete(n, child, search) if newChild == nil { return nil, nil } // Copy this node. WATCH OUT - it's safe to pass "false" here because we // will only ADD a leaf via nc.mergeChild() if there isn't one due to // the !nc.isLeaf() check in the logic just below. This is pretty subtle, // so be careful if you change any of the logic here. nc := t.writeNode(n, false) // Delete the edge if the node has no edges if newChild.leaf == nil && len(newChild.edges) == 0 { nc.delEdge(label) if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() { t.mergeChild(nc) } } else { nc.edges[idx].node = newChild } return nc, leaf }
[ "func", "(", "t", "*", "Txn", ")", "delete", "(", "parent", ",", "n", "*", "Node", ",", "search", "[", "]", "byte", ")", "(", "*", "Node", ",", "*", "leafNode", ")", "{", "// Check for key exhaustion", "if", "len", "(", "search", ")", "==", "0", "{", "if", "!", "n", ".", "isLeaf", "(", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "// Copy the pointer in case we are in a transaction that already", "// modified this node since the node will be reused. Any changes", "// made to the node will not affect returning the original leaf", "// value.", "oldLeaf", ":=", "n", ".", "leaf", "\n\n", "// Remove the leaf node", "nc", ":=", "t", ".", "writeNode", "(", "n", ",", "true", ")", "\n", "nc", ".", "leaf", "=", "nil", "\n\n", "// Check if this node should be merged", "if", "n", "!=", "t", ".", "root", "&&", "len", "(", "nc", ".", "edges", ")", "==", "1", "{", "t", ".", "mergeChild", "(", "nc", ")", "\n", "}", "\n", "return", "nc", ",", "oldLeaf", "\n", "}", "\n\n", "// Look for an edge", "label", ":=", "search", "[", "0", "]", "\n", "idx", ",", "child", ":=", "n", ".", "getEdge", "(", "label", ")", "\n", "if", "child", "==", "nil", "||", "!", "bytes", ".", "HasPrefix", "(", "search", ",", "child", ".", "prefix", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "// Consume the search prefix", "search", "=", "search", "[", "len", "(", "child", ".", "prefix", ")", ":", "]", "\n", "newChild", ",", "leaf", ":=", "t", ".", "delete", "(", "n", ",", "child", ",", "search", ")", "\n", "if", "newChild", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "// Copy this node. WATCH OUT - it's safe to pass \"false\" here because we", "// will only ADD a leaf via nc.mergeChild() if there isn't one due to", "// the !nc.isLeaf() check in the logic just below. This is pretty subtle,", "// so be careful if you change any of the logic here.", "nc", ":=", "t", ".", "writeNode", "(", "n", ",", "false", ")", "\n\n", "// Delete the edge if the node has no edges", "if", "newChild", ".", "leaf", "==", "nil", "&&", "len", "(", "newChild", ".", "edges", ")", "==", "0", "{", "nc", ".", "delEdge", "(", "label", ")", "\n", "if", "n", "!=", "t", ".", "root", "&&", "len", "(", "nc", ".", "edges", ")", "==", "1", "&&", "!", "nc", ".", "isLeaf", "(", ")", "{", "t", ".", "mergeChild", "(", "nc", ")", "\n", "}", "\n", "}", "else", "{", "nc", ".", "edges", "[", "idx", "]", ".", "node", "=", "newChild", "\n", "}", "\n", "return", "nc", ",", "leaf", "\n", "}" ]
// delete does a recursive deletion
[ "delete", "does", "a", "recursive", "deletion" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L335-L388
train
hashicorp/go-immutable-radix
iradix.go
Insert
func (t *Txn) Insert(k []byte, v interface{}) (interface{}, bool) { newRoot, oldVal, didUpdate := t.insert(t.root, k, k, v) if newRoot != nil { t.root = newRoot } if !didUpdate { t.size++ } return oldVal, didUpdate }
go
func (t *Txn) Insert(k []byte, v interface{}) (interface{}, bool) { newRoot, oldVal, didUpdate := t.insert(t.root, k, k, v) if newRoot != nil { t.root = newRoot } if !didUpdate { t.size++ } return oldVal, didUpdate }
[ "func", "(", "t", "*", "Txn", ")", "Insert", "(", "k", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "newRoot", ",", "oldVal", ",", "didUpdate", ":=", "t", ".", "insert", "(", "t", ".", "root", ",", "k", ",", "k", ",", "v", ")", "\n", "if", "newRoot", "!=", "nil", "{", "t", ".", "root", "=", "newRoot", "\n", "}", "\n", "if", "!", "didUpdate", "{", "t", ".", "size", "++", "\n", "}", "\n", "return", "oldVal", ",", "didUpdate", "\n", "}" ]
// Insert is used to add or update a given key. The return provides // the previous value and a bool indicating if any was set.
[ "Insert", "is", "used", "to", "add", "or", "update", "a", "given", "key", ".", "The", "return", "provides", "the", "previous", "value", "and", "a", "bool", "indicating", "if", "any", "was", "set", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L442-L451
train
hashicorp/go-immutable-radix
iradix.go
Delete
func (t *Txn) Delete(k []byte) (interface{}, bool) { newRoot, leaf := t.delete(nil, t.root, k) if newRoot != nil { t.root = newRoot } if leaf != nil { t.size-- return leaf.val, true } return nil, false }
go
func (t *Txn) Delete(k []byte) (interface{}, bool) { newRoot, leaf := t.delete(nil, t.root, k) if newRoot != nil { t.root = newRoot } if leaf != nil { t.size-- return leaf.val, true } return nil, false }
[ "func", "(", "t", "*", "Txn", ")", "Delete", "(", "k", "[", "]", "byte", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "newRoot", ",", "leaf", ":=", "t", ".", "delete", "(", "nil", ",", "t", ".", "root", ",", "k", ")", "\n", "if", "newRoot", "!=", "nil", "{", "t", ".", "root", "=", "newRoot", "\n", "}", "\n", "if", "leaf", "!=", "nil", "{", "t", ".", "size", "--", "\n", "return", "leaf", ".", "val", ",", "true", "\n", "}", "\n", "return", "nil", ",", "false", "\n", "}" ]
// Delete is used to delete a given key. Returns the old value if any, // and a bool indicating if the key was set.
[ "Delete", "is", "used", "to", "delete", "a", "given", "key", ".", "Returns", "the", "old", "value", "if", "any", "and", "a", "bool", "indicating", "if", "the", "key", "was", "set", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L455-L465
train
hashicorp/go-immutable-radix
iradix.go
DeletePrefix
func (t *Txn) DeletePrefix(prefix []byte) bool { newRoot, numDeletions := t.deletePrefix(nil, t.root, prefix) if newRoot != nil { t.root = newRoot t.size = t.size - numDeletions return true } return false }
go
func (t *Txn) DeletePrefix(prefix []byte) bool { newRoot, numDeletions := t.deletePrefix(nil, t.root, prefix) if newRoot != nil { t.root = newRoot t.size = t.size - numDeletions return true } return false }
[ "func", "(", "t", "*", "Txn", ")", "DeletePrefix", "(", "prefix", "[", "]", "byte", ")", "bool", "{", "newRoot", ",", "numDeletions", ":=", "t", ".", "deletePrefix", "(", "nil", ",", "t", ".", "root", ",", "prefix", ")", "\n", "if", "newRoot", "!=", "nil", "{", "t", ".", "root", "=", "newRoot", "\n", "t", ".", "size", "=", "t", ".", "size", "-", "numDeletions", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n\n", "}" ]
// DeletePrefix is used to delete an entire subtree that matches the prefix // This will delete all nodes under that prefix
[ "DeletePrefix", "is", "used", "to", "delete", "an", "entire", "subtree", "that", "matches", "the", "prefix", "This", "will", "delete", "all", "nodes", "under", "that", "prefix" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L469-L478
train
hashicorp/go-immutable-radix
iradix.go
GetWatch
func (t *Txn) GetWatch(k []byte) (<-chan struct{}, interface{}, bool) { return t.root.GetWatch(k) }
go
func (t *Txn) GetWatch(k []byte) (<-chan struct{}, interface{}, bool) { return t.root.GetWatch(k) }
[ "func", "(", "t", "*", "Txn", ")", "GetWatch", "(", "k", "[", "]", "byte", ")", "(", "<-", "chan", "struct", "{", "}", ",", "interface", "{", "}", ",", "bool", ")", "{", "return", "t", ".", "root", ".", "GetWatch", "(", "k", ")", "\n", "}" ]
// GetWatch is used to lookup a specific key, returning // the watch channel, value and if it was found
[ "GetWatch", "is", "used", "to", "lookup", "a", "specific", "key", "returning", "the", "watch", "channel", "value", "and", "if", "it", "was", "found" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L495-L497
train
hashicorp/go-immutable-radix
iradix.go
Commit
func (t *Txn) Commit() *Tree { nt := t.CommitOnly() if t.trackMutate { t.Notify() } return nt }
go
func (t *Txn) Commit() *Tree { nt := t.CommitOnly() if t.trackMutate { t.Notify() } return nt }
[ "func", "(", "t", "*", "Txn", ")", "Commit", "(", ")", "*", "Tree", "{", "nt", ":=", "t", ".", "CommitOnly", "(", ")", "\n", "if", "t", ".", "trackMutate", "{", "t", ".", "Notify", "(", ")", "\n", "}", "\n", "return", "nt", "\n", "}" ]
// Commit is used to finalize the transaction and return a new tree. If mutation // tracking is turned on then notifications will also be issued.
[ "Commit", "is", "used", "to", "finalize", "the", "transaction", "and", "return", "a", "new", "tree", ".", "If", "mutation", "tracking", "is", "turned", "on", "then", "notifications", "will", "also", "be", "issued", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L501-L507
train
hashicorp/go-immutable-radix
iradix.go
CommitOnly
func (t *Txn) CommitOnly() *Tree { nt := &Tree{t.root, t.size} t.writable = nil return nt }
go
func (t *Txn) CommitOnly() *Tree { nt := &Tree{t.root, t.size} t.writable = nil return nt }
[ "func", "(", "t", "*", "Txn", ")", "CommitOnly", "(", ")", "*", "Tree", "{", "nt", ":=", "&", "Tree", "{", "t", ".", "root", ",", "t", ".", "size", "}", "\n", "t", ".", "writable", "=", "nil", "\n", "return", "nt", "\n", "}" ]
// CommitOnly is used to finalize the transaction and return a new tree, but // does not issue any notifications until Notify is called.
[ "CommitOnly", "is", "used", "to", "finalize", "the", "transaction", "and", "return", "a", "new", "tree", "but", "does", "not", "issue", "any", "notifications", "until", "Notify", "is", "called", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L511-L515
train
hashicorp/go-immutable-radix
iradix.go
slowNotify
func (t *Txn) slowNotify() { snapIter := t.snap.rawIterator() rootIter := t.root.rawIterator() for snapIter.Front() != nil || rootIter.Front() != nil { // If we've exhausted the nodes in the old snapshot, we know // there's nothing remaining to notify. if snapIter.Front() == nil { return } snapElem := snapIter.Front() // If we've exhausted the nodes in the new root, we know we need // to invalidate everything that remains in the old snapshot. We // know from the loop condition there's something in the old // snapshot. if rootIter.Front() == nil { close(snapElem.mutateCh) if snapElem.isLeaf() { close(snapElem.leaf.mutateCh) } snapIter.Next() continue } // Do one string compare so we can check the various conditions // below without repeating the compare. cmp := strings.Compare(snapIter.Path(), rootIter.Path()) // If the snapshot is behind the root, then we must have deleted // this node during the transaction. if cmp < 0 { close(snapElem.mutateCh) if snapElem.isLeaf() { close(snapElem.leaf.mutateCh) } snapIter.Next() continue } // If the snapshot is ahead of the root, then we must have added // this node during the transaction. if cmp > 0 { rootIter.Next() continue } // If we have the same path, then we need to see if we mutated a // node and possibly the leaf. rootElem := rootIter.Front() if snapElem != rootElem { close(snapElem.mutateCh) if snapElem.leaf != nil && (snapElem.leaf != rootElem.leaf) { close(snapElem.leaf.mutateCh) } } snapIter.Next() rootIter.Next() } }
go
func (t *Txn) slowNotify() { snapIter := t.snap.rawIterator() rootIter := t.root.rawIterator() for snapIter.Front() != nil || rootIter.Front() != nil { // If we've exhausted the nodes in the old snapshot, we know // there's nothing remaining to notify. if snapIter.Front() == nil { return } snapElem := snapIter.Front() // If we've exhausted the nodes in the new root, we know we need // to invalidate everything that remains in the old snapshot. We // know from the loop condition there's something in the old // snapshot. if rootIter.Front() == nil { close(snapElem.mutateCh) if snapElem.isLeaf() { close(snapElem.leaf.mutateCh) } snapIter.Next() continue } // Do one string compare so we can check the various conditions // below without repeating the compare. cmp := strings.Compare(snapIter.Path(), rootIter.Path()) // If the snapshot is behind the root, then we must have deleted // this node during the transaction. if cmp < 0 { close(snapElem.mutateCh) if snapElem.isLeaf() { close(snapElem.leaf.mutateCh) } snapIter.Next() continue } // If the snapshot is ahead of the root, then we must have added // this node during the transaction. if cmp > 0 { rootIter.Next() continue } // If we have the same path, then we need to see if we mutated a // node and possibly the leaf. rootElem := rootIter.Front() if snapElem != rootElem { close(snapElem.mutateCh) if snapElem.leaf != nil && (snapElem.leaf != rootElem.leaf) { close(snapElem.leaf.mutateCh) } } snapIter.Next() rootIter.Next() } }
[ "func", "(", "t", "*", "Txn", ")", "slowNotify", "(", ")", "{", "snapIter", ":=", "t", ".", "snap", ".", "rawIterator", "(", ")", "\n", "rootIter", ":=", "t", ".", "root", ".", "rawIterator", "(", ")", "\n", "for", "snapIter", ".", "Front", "(", ")", "!=", "nil", "||", "rootIter", ".", "Front", "(", ")", "!=", "nil", "{", "// If we've exhausted the nodes in the old snapshot, we know", "// there's nothing remaining to notify.", "if", "snapIter", ".", "Front", "(", ")", "==", "nil", "{", "return", "\n", "}", "\n", "snapElem", ":=", "snapIter", ".", "Front", "(", ")", "\n\n", "// If we've exhausted the nodes in the new root, we know we need", "// to invalidate everything that remains in the old snapshot. We", "// know from the loop condition there's something in the old", "// snapshot.", "if", "rootIter", ".", "Front", "(", ")", "==", "nil", "{", "close", "(", "snapElem", ".", "mutateCh", ")", "\n", "if", "snapElem", ".", "isLeaf", "(", ")", "{", "close", "(", "snapElem", ".", "leaf", ".", "mutateCh", ")", "\n", "}", "\n", "snapIter", ".", "Next", "(", ")", "\n", "continue", "\n", "}", "\n\n", "// Do one string compare so we can check the various conditions", "// below without repeating the compare.", "cmp", ":=", "strings", ".", "Compare", "(", "snapIter", ".", "Path", "(", ")", ",", "rootIter", ".", "Path", "(", ")", ")", "\n\n", "// If the snapshot is behind the root, then we must have deleted", "// this node during the transaction.", "if", "cmp", "<", "0", "{", "close", "(", "snapElem", ".", "mutateCh", ")", "\n", "if", "snapElem", ".", "isLeaf", "(", ")", "{", "close", "(", "snapElem", ".", "leaf", ".", "mutateCh", ")", "\n", "}", "\n", "snapIter", ".", "Next", "(", ")", "\n", "continue", "\n", "}", "\n\n", "// If the snapshot is ahead of the root, then we must have added", "// this node during the transaction.", "if", "cmp", ">", "0", "{", "rootIter", ".", "Next", "(", ")", "\n", "continue", "\n", "}", "\n\n", "// If we have the same path, then we need to see if we mutated a", "// node and possibly the leaf.", "rootElem", ":=", "rootIter", ".", "Front", "(", ")", "\n", "if", "snapElem", "!=", "rootElem", "{", "close", "(", "snapElem", ".", "mutateCh", ")", "\n", "if", "snapElem", ".", "leaf", "!=", "nil", "&&", "(", "snapElem", ".", "leaf", "!=", "rootElem", ".", "leaf", ")", "{", "close", "(", "snapElem", ".", "leaf", ".", "mutateCh", ")", "\n", "}", "\n", "}", "\n", "snapIter", ".", "Next", "(", ")", "\n", "rootIter", ".", "Next", "(", ")", "\n", "}", "\n", "}" ]
// slowNotify does a complete comparison of the before and after trees in order // to trigger notifications. This doesn't require any additional state but it // is very expensive to compute.
[ "slowNotify", "does", "a", "complete", "comparison", "of", "the", "before", "and", "after", "trees", "in", "order", "to", "trigger", "notifications", ".", "This", "doesn", "t", "require", "any", "additional", "state", "but", "it", "is", "very", "expensive", "to", "compute", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L520-L578
train
hashicorp/go-immutable-radix
iradix.go
Notify
func (t *Txn) Notify() { if !t.trackMutate { return } // If we've overflowed the tracking state we can't use it in any way and // need to do a full tree compare. if t.trackOverflow { t.slowNotify() } else { for ch := range t.trackChannels { close(ch) } } // Clean up the tracking state so that a re-notify is safe (will trigger // the else clause above which will be a no-op). t.trackChannels = nil t.trackOverflow = false }
go
func (t *Txn) Notify() { if !t.trackMutate { return } // If we've overflowed the tracking state we can't use it in any way and // need to do a full tree compare. if t.trackOverflow { t.slowNotify() } else { for ch := range t.trackChannels { close(ch) } } // Clean up the tracking state so that a re-notify is safe (will trigger // the else clause above which will be a no-op). t.trackChannels = nil t.trackOverflow = false }
[ "func", "(", "t", "*", "Txn", ")", "Notify", "(", ")", "{", "if", "!", "t", ".", "trackMutate", "{", "return", "\n", "}", "\n\n", "// If we've overflowed the tracking state we can't use it in any way and", "// need to do a full tree compare.", "if", "t", ".", "trackOverflow", "{", "t", ".", "slowNotify", "(", ")", "\n", "}", "else", "{", "for", "ch", ":=", "range", "t", ".", "trackChannels", "{", "close", "(", "ch", ")", "\n", "}", "\n", "}", "\n\n", "// Clean up the tracking state so that a re-notify is safe (will trigger", "// the else clause above which will be a no-op).", "t", ".", "trackChannels", "=", "nil", "\n", "t", ".", "trackOverflow", "=", "false", "\n", "}" ]
// Notify is used along with TrackMutate to trigger notifications. This must // only be done once a transaction is committed via CommitOnly, and it is called // automatically by Commit.
[ "Notify", "is", "used", "along", "with", "TrackMutate", "to", "trigger", "notifications", ".", "This", "must", "only", "be", "done", "once", "a", "transaction", "is", "committed", "via", "CommitOnly", "and", "it", "is", "called", "automatically", "by", "Commit", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L583-L602
train
hashicorp/go-immutable-radix
iradix.go
Insert
func (t *Tree) Insert(k []byte, v interface{}) (*Tree, interface{}, bool) { txn := t.Txn() old, ok := txn.Insert(k, v) return txn.Commit(), old, ok }
go
func (t *Tree) Insert(k []byte, v interface{}) (*Tree, interface{}, bool) { txn := t.Txn() old, ok := txn.Insert(k, v) return txn.Commit(), old, ok }
[ "func", "(", "t", "*", "Tree", ")", "Insert", "(", "k", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "(", "*", "Tree", ",", "interface", "{", "}", ",", "bool", ")", "{", "txn", ":=", "t", ".", "Txn", "(", ")", "\n", "old", ",", "ok", ":=", "txn", ".", "Insert", "(", "k", ",", "v", ")", "\n", "return", "txn", ".", "Commit", "(", ")", ",", "old", ",", "ok", "\n", "}" ]
// Insert is used to add or update a given key. The return provides // the new tree, previous value and a bool indicating if any was set.
[ "Insert", "is", "used", "to", "add", "or", "update", "a", "given", "key", ".", "The", "return", "provides", "the", "new", "tree", "previous", "value", "and", "a", "bool", "indicating", "if", "any", "was", "set", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L606-L610
train
hashicorp/go-immutable-radix
iradix.go
Delete
func (t *Tree) Delete(k []byte) (*Tree, interface{}, bool) { txn := t.Txn() old, ok := txn.Delete(k) return txn.Commit(), old, ok }
go
func (t *Tree) Delete(k []byte) (*Tree, interface{}, bool) { txn := t.Txn() old, ok := txn.Delete(k) return txn.Commit(), old, ok }
[ "func", "(", "t", "*", "Tree", ")", "Delete", "(", "k", "[", "]", "byte", ")", "(", "*", "Tree", ",", "interface", "{", "}", ",", "bool", ")", "{", "txn", ":=", "t", ".", "Txn", "(", ")", "\n", "old", ",", "ok", ":=", "txn", ".", "Delete", "(", "k", ")", "\n", "return", "txn", ".", "Commit", "(", ")", ",", "old", ",", "ok", "\n", "}" ]
// Delete is used to delete a given key. Returns the new tree, // old value if any, and a bool indicating if the key was set.
[ "Delete", "is", "used", "to", "delete", "a", "given", "key", ".", "Returns", "the", "new", "tree", "old", "value", "if", "any", "and", "a", "bool", "indicating", "if", "the", "key", "was", "set", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L614-L618
train
hashicorp/go-immutable-radix
iradix.go
DeletePrefix
func (t *Tree) DeletePrefix(k []byte) (*Tree, bool) { txn := t.Txn() ok := txn.DeletePrefix(k) return txn.Commit(), ok }
go
func (t *Tree) DeletePrefix(k []byte) (*Tree, bool) { txn := t.Txn() ok := txn.DeletePrefix(k) return txn.Commit(), ok }
[ "func", "(", "t", "*", "Tree", ")", "DeletePrefix", "(", "k", "[", "]", "byte", ")", "(", "*", "Tree", ",", "bool", ")", "{", "txn", ":=", "t", ".", "Txn", "(", ")", "\n", "ok", ":=", "txn", ".", "DeletePrefix", "(", "k", ")", "\n", "return", "txn", ".", "Commit", "(", ")", ",", "ok", "\n", "}" ]
// DeletePrefix is used to delete all nodes starting with a given prefix. Returns the new tree, // and a bool indicating if the prefix matched any nodes
[ "DeletePrefix", "is", "used", "to", "delete", "all", "nodes", "starting", "with", "a", "given", "prefix", ".", "Returns", "the", "new", "tree", "and", "a", "bool", "indicating", "if", "the", "prefix", "matched", "any", "nodes" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L622-L626
train
hashicorp/go-immutable-radix
iradix.go
longestPrefix
func longestPrefix(k1, k2 []byte) int { max := len(k1) if l := len(k2); l < max { max = l } var i int for i = 0; i < max; i++ { if k1[i] != k2[i] { break } } return i }
go
func longestPrefix(k1, k2 []byte) int { max := len(k1) if l := len(k2); l < max { max = l } var i int for i = 0; i < max; i++ { if k1[i] != k2[i] { break } } return i }
[ "func", "longestPrefix", "(", "k1", ",", "k2", "[", "]", "byte", ")", "int", "{", "max", ":=", "len", "(", "k1", ")", "\n", "if", "l", ":=", "len", "(", "k2", ")", ";", "l", "<", "max", "{", "max", "=", "l", "\n", "}", "\n", "var", "i", "int", "\n", "for", "i", "=", "0", ";", "i", "<", "max", ";", "i", "++", "{", "if", "k1", "[", "i", "]", "!=", "k2", "[", "i", "]", "{", "break", "\n", "}", "\n", "}", "\n", "return", "i", "\n", "}" ]
// longestPrefix finds the length of the shared prefix // of two strings
[ "longestPrefix", "finds", "the", "length", "of", "the", "shared", "prefix", "of", "two", "strings" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L642-L654
train
hashicorp/go-immutable-radix
iradix.go
concat
func concat(a, b []byte) []byte { c := make([]byte, len(a)+len(b)) copy(c, a) copy(c[len(a):], b) return c }
go
func concat(a, b []byte) []byte { c := make([]byte, len(a)+len(b)) copy(c, a) copy(c[len(a):], b) return c }
[ "func", "concat", "(", "a", ",", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "c", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "a", ")", "+", "len", "(", "b", ")", ")", "\n", "copy", "(", "c", ",", "a", ")", "\n", "copy", "(", "c", "[", "len", "(", "a", ")", ":", "]", ",", "b", ")", "\n", "return", "c", "\n", "}" ]
// concat two byte slices, returning a third new copy
[ "concat", "two", "byte", "slices", "returning", "a", "third", "new", "copy" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iradix.go#L657-L662
train
hashicorp/go-immutable-radix
node.go
LongestPrefix
func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) { var last *leafNode search := k for { // Look for a leaf node if n.isLeaf() { last = n.leaf } // Check for key exhaution if len(search) == 0 { break } // Look for an edge _, n = n.getEdge(search[0]) if n == nil { break } // Consume the search prefix if bytes.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else { break } } if last != nil { return last.key, last.val, true } return nil, nil, false }
go
func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) { var last *leafNode search := k for { // Look for a leaf node if n.isLeaf() { last = n.leaf } // Check for key exhaution if len(search) == 0 { break } // Look for an edge _, n = n.getEdge(search[0]) if n == nil { break } // Consume the search prefix if bytes.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else { break } } if last != nil { return last.key, last.val, true } return nil, nil, false }
[ "func", "(", "n", "*", "Node", ")", "LongestPrefix", "(", "k", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "interface", "{", "}", ",", "bool", ")", "{", "var", "last", "*", "leafNode", "\n", "search", ":=", "k", "\n", "for", "{", "// Look for a leaf node", "if", "n", ".", "isLeaf", "(", ")", "{", "last", "=", "n", ".", "leaf", "\n", "}", "\n\n", "// Check for key exhaution", "if", "len", "(", "search", ")", "==", "0", "{", "break", "\n", "}", "\n\n", "// Look for an edge", "_", ",", "n", "=", "n", ".", "getEdge", "(", "search", "[", "0", "]", ")", "\n", "if", "n", "==", "nil", "{", "break", "\n", "}", "\n\n", "// Consume the search prefix", "if", "bytes", ".", "HasPrefix", "(", "search", ",", "n", ".", "prefix", ")", "{", "search", "=", "search", "[", "len", "(", "n", ".", "prefix", ")", ":", "]", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "if", "last", "!=", "nil", "{", "return", "last", ".", "key", ",", "last", ".", "val", ",", "true", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "false", "\n", "}" ]
// LongestPrefix is like Get, but instead of an // exact match, it will return the longest prefix match.
[ "LongestPrefix", "is", "like", "Get", "but", "instead", "of", "an", "exact", "match", "it", "will", "return", "the", "longest", "prefix", "match", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/node.go#L132-L163
train
hashicorp/go-immutable-radix
node.go
Minimum
func (n *Node) Minimum() ([]byte, interface{}, bool) { for { if n.isLeaf() { return n.leaf.key, n.leaf.val, true } if len(n.edges) > 0 { n = n.edges[0].node } else { break } } return nil, nil, false }
go
func (n *Node) Minimum() ([]byte, interface{}, bool) { for { if n.isLeaf() { return n.leaf.key, n.leaf.val, true } if len(n.edges) > 0 { n = n.edges[0].node } else { break } } return nil, nil, false }
[ "func", "(", "n", "*", "Node", ")", "Minimum", "(", ")", "(", "[", "]", "byte", ",", "interface", "{", "}", ",", "bool", ")", "{", "for", "{", "if", "n", ".", "isLeaf", "(", ")", "{", "return", "n", ".", "leaf", ".", "key", ",", "n", ".", "leaf", ".", "val", ",", "true", "\n", "}", "\n", "if", "len", "(", "n", ".", "edges", ")", ">", "0", "{", "n", "=", "n", ".", "edges", "[", "0", "]", ".", "node", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "false", "\n", "}" ]
// Minimum is used to return the minimum value in the tree
[ "Minimum", "is", "used", "to", "return", "the", "minimum", "value", "in", "the", "tree" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/node.go#L166-L178
train
hashicorp/go-immutable-radix
node.go
rawIterator
func (n *Node) rawIterator() *rawIterator { iter := &rawIterator{node: n} iter.Next() return iter }
go
func (n *Node) rawIterator() *rawIterator { iter := &rawIterator{node: n} iter.Next() return iter }
[ "func", "(", "n", "*", "Node", ")", "rawIterator", "(", ")", "*", "rawIterator", "{", "iter", ":=", "&", "rawIterator", "{", "node", ":", "n", "}", "\n", "iter", ".", "Next", "(", ")", "\n", "return", "iter", "\n", "}" ]
// rawIterator is used to return a raw iterator at the given node to walk the // tree.
[ "rawIterator", "is", "used", "to", "return", "a", "raw", "iterator", "at", "the", "given", "node", "to", "walk", "the", "tree", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/node.go#L204-L208
train
hashicorp/go-immutable-radix
node.go
WalkPrefix
func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) { search := prefix for { // Check for key exhaution if len(search) == 0 { recursiveWalk(n, fn) return } // Look for an edge _, n = n.getEdge(search[0]) if n == nil { break } // Consume the search prefix if bytes.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else if bytes.HasPrefix(n.prefix, search) { // Child may be under our search prefix recursiveWalk(n, fn) return } else { break } } }
go
func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) { search := prefix for { // Check for key exhaution if len(search) == 0 { recursiveWalk(n, fn) return } // Look for an edge _, n = n.getEdge(search[0]) if n == nil { break } // Consume the search prefix if bytes.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else if bytes.HasPrefix(n.prefix, search) { // Child may be under our search prefix recursiveWalk(n, fn) return } else { break } } }
[ "func", "(", "n", "*", "Node", ")", "WalkPrefix", "(", "prefix", "[", "]", "byte", ",", "fn", "WalkFn", ")", "{", "search", ":=", "prefix", "\n", "for", "{", "// Check for key exhaution", "if", "len", "(", "search", ")", "==", "0", "{", "recursiveWalk", "(", "n", ",", "fn", ")", "\n", "return", "\n", "}", "\n\n", "// Look for an edge", "_", ",", "n", "=", "n", ".", "getEdge", "(", "search", "[", "0", "]", ")", "\n", "if", "n", "==", "nil", "{", "break", "\n", "}", "\n\n", "// Consume the search prefix", "if", "bytes", ".", "HasPrefix", "(", "search", ",", "n", ".", "prefix", ")", "{", "search", "=", "search", "[", "len", "(", "n", ".", "prefix", ")", ":", "]", "\n\n", "}", "else", "if", "bytes", ".", "HasPrefix", "(", "n", ".", "prefix", ",", "search", ")", "{", "// Child may be under our search prefix", "recursiveWalk", "(", "n", ",", "fn", ")", "\n", "return", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// WalkPrefix is used to walk the tree under a prefix
[ "WalkPrefix", "is", "used", "to", "walk", "the", "tree", "under", "a", "prefix" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/node.go#L216-L243
train
hashicorp/go-immutable-radix
iter.go
SeekPrefixWatch
func (i *Iterator) SeekPrefixWatch(prefix []byte) (watch <-chan struct{}) { // Wipe the stack i.stack = nil n := i.node watch = n.mutateCh search := prefix for { // Check for key exhaution if len(search) == 0 { i.node = n return } // Look for an edge _, n = n.getEdge(search[0]) if n == nil { i.node = nil return } // Update to the finest granularity as the search makes progress watch = n.mutateCh // Consume the search prefix if bytes.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else if bytes.HasPrefix(n.prefix, search) { i.node = n return } else { i.node = nil return } } }
go
func (i *Iterator) SeekPrefixWatch(prefix []byte) (watch <-chan struct{}) { // Wipe the stack i.stack = nil n := i.node watch = n.mutateCh search := prefix for { // Check for key exhaution if len(search) == 0 { i.node = n return } // Look for an edge _, n = n.getEdge(search[0]) if n == nil { i.node = nil return } // Update to the finest granularity as the search makes progress watch = n.mutateCh // Consume the search prefix if bytes.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else if bytes.HasPrefix(n.prefix, search) { i.node = n return } else { i.node = nil return } } }
[ "func", "(", "i", "*", "Iterator", ")", "SeekPrefixWatch", "(", "prefix", "[", "]", "byte", ")", "(", "watch", "<-", "chan", "struct", "{", "}", ")", "{", "// Wipe the stack", "i", ".", "stack", "=", "nil", "\n", "n", ":=", "i", ".", "node", "\n", "watch", "=", "n", ".", "mutateCh", "\n", "search", ":=", "prefix", "\n", "for", "{", "// Check for key exhaution", "if", "len", "(", "search", ")", "==", "0", "{", "i", ".", "node", "=", "n", "\n", "return", "\n", "}", "\n\n", "// Look for an edge", "_", ",", "n", "=", "n", ".", "getEdge", "(", "search", "[", "0", "]", ")", "\n", "if", "n", "==", "nil", "{", "i", ".", "node", "=", "nil", "\n", "return", "\n", "}", "\n\n", "// Update to the finest granularity as the search makes progress", "watch", "=", "n", ".", "mutateCh", "\n\n", "// Consume the search prefix", "if", "bytes", ".", "HasPrefix", "(", "search", ",", "n", ".", "prefix", ")", "{", "search", "=", "search", "[", "len", "(", "n", ".", "prefix", ")", ":", "]", "\n\n", "}", "else", "if", "bytes", ".", "HasPrefix", "(", "n", ".", "prefix", ",", "search", ")", "{", "i", ".", "node", "=", "n", "\n", "return", "\n", "}", "else", "{", "i", ".", "node", "=", "nil", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// SeekPrefixWatch is used to seek the iterator to a given prefix // and returns the watch channel of the finest granularity
[ "SeekPrefixWatch", "is", "used", "to", "seek", "the", "iterator", "to", "a", "given", "prefix", "and", "returns", "the", "watch", "channel", "of", "the", "finest", "granularity" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iter.go#L14-L49
train
hashicorp/go-immutable-radix
iter.go
Next
func (i *Iterator) Next() ([]byte, interface{}, bool) { // Initialize our stack if needed if i.stack == nil && i.node != nil { i.stack = []edges{ edges{ edge{node: i.node}, }, } } for len(i.stack) > 0 { // Inspect the last element of the stack n := len(i.stack) last := i.stack[n-1] elem := last[0].node // Update the stack if len(last) > 1 { i.stack[n-1] = last[1:] } else { i.stack = i.stack[:n-1] } // Push the edges onto the frontier if len(elem.edges) > 0 { i.stack = append(i.stack, elem.edges) } // Return the leaf values if any if elem.leaf != nil { return elem.leaf.key, elem.leaf.val, true } } return nil, nil, false }
go
func (i *Iterator) Next() ([]byte, interface{}, bool) { // Initialize our stack if needed if i.stack == nil && i.node != nil { i.stack = []edges{ edges{ edge{node: i.node}, }, } } for len(i.stack) > 0 { // Inspect the last element of the stack n := len(i.stack) last := i.stack[n-1] elem := last[0].node // Update the stack if len(last) > 1 { i.stack[n-1] = last[1:] } else { i.stack = i.stack[:n-1] } // Push the edges onto the frontier if len(elem.edges) > 0 { i.stack = append(i.stack, elem.edges) } // Return the leaf values if any if elem.leaf != nil { return elem.leaf.key, elem.leaf.val, true } } return nil, nil, false }
[ "func", "(", "i", "*", "Iterator", ")", "Next", "(", ")", "(", "[", "]", "byte", ",", "interface", "{", "}", ",", "bool", ")", "{", "// Initialize our stack if needed", "if", "i", ".", "stack", "==", "nil", "&&", "i", ".", "node", "!=", "nil", "{", "i", ".", "stack", "=", "[", "]", "edges", "{", "edges", "{", "edge", "{", "node", ":", "i", ".", "node", "}", ",", "}", ",", "}", "\n", "}", "\n\n", "for", "len", "(", "i", ".", "stack", ")", ">", "0", "{", "// Inspect the last element of the stack", "n", ":=", "len", "(", "i", ".", "stack", ")", "\n", "last", ":=", "i", ".", "stack", "[", "n", "-", "1", "]", "\n", "elem", ":=", "last", "[", "0", "]", ".", "node", "\n\n", "// Update the stack", "if", "len", "(", "last", ")", ">", "1", "{", "i", ".", "stack", "[", "n", "-", "1", "]", "=", "last", "[", "1", ":", "]", "\n", "}", "else", "{", "i", ".", "stack", "=", "i", ".", "stack", "[", ":", "n", "-", "1", "]", "\n", "}", "\n\n", "// Push the edges onto the frontier", "if", "len", "(", "elem", ".", "edges", ")", ">", "0", "{", "i", ".", "stack", "=", "append", "(", "i", ".", "stack", ",", "elem", ".", "edges", ")", "\n", "}", "\n\n", "// Return the leaf values if any", "if", "elem", ".", "leaf", "!=", "nil", "{", "return", "elem", ".", "leaf", ".", "key", ",", "elem", ".", "leaf", ".", "val", ",", "true", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "false", "\n", "}" ]
// Next returns the next node in order
[ "Next", "returns", "the", "next", "node", "in", "order" ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/iter.go#L57-L91
train
hashicorp/go-immutable-radix
raw_iter.go
Next
func (i *rawIterator) Next() { // Initialize our stack if needed. if i.stack == nil && i.node != nil { i.stack = []rawStackEntry{ rawStackEntry{ edges: edges{ edge{node: i.node}, }, }, } } for len(i.stack) > 0 { // Inspect the last element of the stack. n := len(i.stack) last := i.stack[n-1] elem := last.edges[0].node // Update the stack. if len(last.edges) > 1 { i.stack[n-1].edges = last.edges[1:] } else { i.stack = i.stack[:n-1] } // Push the edges onto the frontier. if len(elem.edges) > 0 { path := last.path + string(elem.prefix) i.stack = append(i.stack, rawStackEntry{path, elem.edges}) } i.pos = elem i.path = last.path + string(elem.prefix) return } i.pos = nil i.path = "" }
go
func (i *rawIterator) Next() { // Initialize our stack if needed. if i.stack == nil && i.node != nil { i.stack = []rawStackEntry{ rawStackEntry{ edges: edges{ edge{node: i.node}, }, }, } } for len(i.stack) > 0 { // Inspect the last element of the stack. n := len(i.stack) last := i.stack[n-1] elem := last.edges[0].node // Update the stack. if len(last.edges) > 1 { i.stack[n-1].edges = last.edges[1:] } else { i.stack = i.stack[:n-1] } // Push the edges onto the frontier. if len(elem.edges) > 0 { path := last.path + string(elem.prefix) i.stack = append(i.stack, rawStackEntry{path, elem.edges}) } i.pos = elem i.path = last.path + string(elem.prefix) return } i.pos = nil i.path = "" }
[ "func", "(", "i", "*", "rawIterator", ")", "Next", "(", ")", "{", "// Initialize our stack if needed.", "if", "i", ".", "stack", "==", "nil", "&&", "i", ".", "node", "!=", "nil", "{", "i", ".", "stack", "=", "[", "]", "rawStackEntry", "{", "rawStackEntry", "{", "edges", ":", "edges", "{", "edge", "{", "node", ":", "i", ".", "node", "}", ",", "}", ",", "}", ",", "}", "\n", "}", "\n\n", "for", "len", "(", "i", ".", "stack", ")", ">", "0", "{", "// Inspect the last element of the stack.", "n", ":=", "len", "(", "i", ".", "stack", ")", "\n", "last", ":=", "i", ".", "stack", "[", "n", "-", "1", "]", "\n", "elem", ":=", "last", ".", "edges", "[", "0", "]", ".", "node", "\n\n", "// Update the stack.", "if", "len", "(", "last", ".", "edges", ")", ">", "1", "{", "i", ".", "stack", "[", "n", "-", "1", "]", ".", "edges", "=", "last", ".", "edges", "[", "1", ":", "]", "\n", "}", "else", "{", "i", ".", "stack", "=", "i", ".", "stack", "[", ":", "n", "-", "1", "]", "\n", "}", "\n\n", "// Push the edges onto the frontier.", "if", "len", "(", "elem", ".", "edges", ")", ">", "0", "{", "path", ":=", "last", ".", "path", "+", "string", "(", "elem", ".", "prefix", ")", "\n", "i", ".", "stack", "=", "append", "(", "i", ".", "stack", ",", "rawStackEntry", "{", "path", ",", "elem", ".", "edges", "}", ")", "\n", "}", "\n\n", "i", ".", "pos", "=", "elem", "\n", "i", ".", "path", "=", "last", ".", "path", "+", "string", "(", "elem", ".", "prefix", ")", "\n", "return", "\n", "}", "\n\n", "i", ".", "pos", "=", "nil", "\n", "i", ".", "path", "=", "\"", "\"", "\n", "}" ]
// Next advances the iterator to the next node.
[ "Next", "advances", "the", "iterator", "to", "the", "next", "node", "." ]
27df80928bb34bb1b0d6d0e01b9e679902e7a6b5
https://github.com/hashicorp/go-immutable-radix/blob/27df80928bb34bb1b0d6d0e01b9e679902e7a6b5/raw_iter.go#L40-L78
train
lestrrat-go/jwx
jwe/serializer.go
Serialize
func (s CompactSerialize) Serialize(m *Message) ([]byte, error) { if len(m.Recipients) != 1 { return nil, errors.New("wrong number of recipients for compact serialization") } recipient := m.Recipients[0] // The protected header must be a merge between the message-wide // protected header AND the recipient header hcopy := NewHeader() // There's something wrong if m.ProtectedHeader.Header is nil, but // it could happen if m.ProtectedHeader == nil || m.ProtectedHeader.Header == nil { return nil, errors.New("invalid protected header") } err := hcopy.Copy(m.ProtectedHeader.Header) if err != nil { return nil, errors.Wrap(err, "failed to copy protected header") } hcopy, err = hcopy.Merge(m.UnprotectedHeader) if err != nil { return nil, errors.Wrap(err, "failed to merge unprotected header") } hcopy, err = hcopy.Merge(recipient.Header) if err != nil { return nil, errors.Wrap(err, "failed to merge recipient header") } protected, err := EncodedHeader{Header: hcopy}.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode header") } encryptedKey, err := recipient.EncryptedKey.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode encryption key") } iv, err := m.InitializationVector.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode iv") } cipher, err := m.CipherText.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode cipher text") } tag, err := m.Tag.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode tag") } buf := append(append(append(append(append(append(append(append(protected, '.'), encryptedKey...), '.'), iv...), '.'), cipher...), '.'), tag...) return buf, nil }
go
func (s CompactSerialize) Serialize(m *Message) ([]byte, error) { if len(m.Recipients) != 1 { return nil, errors.New("wrong number of recipients for compact serialization") } recipient := m.Recipients[0] // The protected header must be a merge between the message-wide // protected header AND the recipient header hcopy := NewHeader() // There's something wrong if m.ProtectedHeader.Header is nil, but // it could happen if m.ProtectedHeader == nil || m.ProtectedHeader.Header == nil { return nil, errors.New("invalid protected header") } err := hcopy.Copy(m.ProtectedHeader.Header) if err != nil { return nil, errors.Wrap(err, "failed to copy protected header") } hcopy, err = hcopy.Merge(m.UnprotectedHeader) if err != nil { return nil, errors.Wrap(err, "failed to merge unprotected header") } hcopy, err = hcopy.Merge(recipient.Header) if err != nil { return nil, errors.Wrap(err, "failed to merge recipient header") } protected, err := EncodedHeader{Header: hcopy}.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode header") } encryptedKey, err := recipient.EncryptedKey.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode encryption key") } iv, err := m.InitializationVector.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode iv") } cipher, err := m.CipherText.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode cipher text") } tag, err := m.Tag.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode tag") } buf := append(append(append(append(append(append(append(append(protected, '.'), encryptedKey...), '.'), iv...), '.'), cipher...), '.'), tag...) return buf, nil }
[ "func", "(", "s", "CompactSerialize", ")", "Serialize", "(", "m", "*", "Message", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "m", ".", "Recipients", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "recipient", ":=", "m", ".", "Recipients", "[", "0", "]", "\n\n", "// The protected header must be a merge between the message-wide", "// protected header AND the recipient header", "hcopy", ":=", "NewHeader", "(", ")", "\n", "// There's something wrong if m.ProtectedHeader.Header is nil, but", "// it could happen", "if", "m", ".", "ProtectedHeader", "==", "nil", "||", "m", ".", "ProtectedHeader", ".", "Header", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "err", ":=", "hcopy", ".", "Copy", "(", "m", ".", "ProtectedHeader", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "hcopy", ",", "err", "=", "hcopy", ".", "Merge", "(", "m", ".", "UnprotectedHeader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "hcopy", ",", "err", "=", "hcopy", ".", "Merge", "(", "recipient", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "protected", ",", "err", ":=", "EncodedHeader", "{", "Header", ":", "hcopy", "}", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "encryptedKey", ",", "err", ":=", "recipient", ".", "EncryptedKey", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "iv", ",", "err", ":=", "m", ".", "InitializationVector", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "cipher", ",", "err", ":=", "m", ".", "CipherText", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "tag", ",", "err", ":=", "m", ".", "Tag", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "buf", ":=", "append", "(", "append", "(", "append", "(", "append", "(", "append", "(", "append", "(", "append", "(", "append", "(", "protected", ",", "'.'", ")", ",", "encryptedKey", "...", ")", ",", "'.'", ")", ",", "iv", "...", ")", ",", "'.'", ")", ",", "cipher", "...", ")", ",", "'.'", ")", ",", "tag", "...", ")", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// Serialize converts the message into a JWE compact serialize format byte buffer
[ "Serialize", "converts", "the", "message", "into", "a", "JWE", "compact", "serialize", "format", "byte", "buffer" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/serializer.go#L10-L65
train
lestrrat-go/jwx
jwe/serializer.go
Serialize
func (s JSONSerialize) Serialize(m *Message) ([]byte, error) { if s.Pretty { return json.MarshalIndent(m, "", " ") } return json.Marshal(m) }
go
func (s JSONSerialize) Serialize(m *Message) ([]byte, error) { if s.Pretty { return json.MarshalIndent(m, "", " ") } return json.Marshal(m) }
[ "func", "(", "s", "JSONSerialize", ")", "Serialize", "(", "m", "*", "Message", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "s", ".", "Pretty", "{", "return", "json", ".", "MarshalIndent", "(", "m", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "m", ")", "\n", "}" ]
// Serialize converts the message into a JWE JSON serialize format byte buffer
[ "Serialize", "converts", "the", "message", "into", "a", "JWE", "JSON", "serialize", "format", "byte", "buffer" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/serializer.go#L68-L73
train
lestrrat-go/jwx
jwe/aescbc/aescbc.go
Seal
func (c AesCbcHmac) Seal(dst, nonce, plaintext, data []byte) []byte { ctlen := len(plaintext) ciphertext := make([]byte, ctlen+c.Overhead())[:ctlen] copy(ciphertext, plaintext) ciphertext = padbuf.PadBuffer(ciphertext).Pad(c.blockCipher.BlockSize()) cbc := cipher.NewCBCEncrypter(c.blockCipher, nonce) cbc.CryptBlocks(ciphertext, ciphertext) authtag := c.ComputeAuthTag(data, nonce, ciphertext) retlen := len(dst) + len(ciphertext) + len(authtag) ret := ensureSize(dst, retlen) out := ret[len(dst):] n := copy(out, ciphertext) n += copy(out[n:], authtag) if debug.Enabled { debug.Printf("Seal: ciphertext = %x (%d)\n", ciphertext, len(ciphertext)) debug.Printf("Seal: authtag = %x (%d)\n", authtag, len(authtag)) debug.Printf("Seal: ret = %x (%d)\n", ret, len(ret)) } return ret }
go
func (c AesCbcHmac) Seal(dst, nonce, plaintext, data []byte) []byte { ctlen := len(plaintext) ciphertext := make([]byte, ctlen+c.Overhead())[:ctlen] copy(ciphertext, plaintext) ciphertext = padbuf.PadBuffer(ciphertext).Pad(c.blockCipher.BlockSize()) cbc := cipher.NewCBCEncrypter(c.blockCipher, nonce) cbc.CryptBlocks(ciphertext, ciphertext) authtag := c.ComputeAuthTag(data, nonce, ciphertext) retlen := len(dst) + len(ciphertext) + len(authtag) ret := ensureSize(dst, retlen) out := ret[len(dst):] n := copy(out, ciphertext) n += copy(out[n:], authtag) if debug.Enabled { debug.Printf("Seal: ciphertext = %x (%d)\n", ciphertext, len(ciphertext)) debug.Printf("Seal: authtag = %x (%d)\n", authtag, len(authtag)) debug.Printf("Seal: ret = %x (%d)\n", ret, len(ret)) } return ret }
[ "func", "(", "c", "AesCbcHmac", ")", "Seal", "(", "dst", ",", "nonce", ",", "plaintext", ",", "data", "[", "]", "byte", ")", "[", "]", "byte", "{", "ctlen", ":=", "len", "(", "plaintext", ")", "\n", "ciphertext", ":=", "make", "(", "[", "]", "byte", ",", "ctlen", "+", "c", ".", "Overhead", "(", ")", ")", "[", ":", "ctlen", "]", "\n", "copy", "(", "ciphertext", ",", "plaintext", ")", "\n", "ciphertext", "=", "padbuf", ".", "PadBuffer", "(", "ciphertext", ")", ".", "Pad", "(", "c", ".", "blockCipher", ".", "BlockSize", "(", ")", ")", "\n\n", "cbc", ":=", "cipher", ".", "NewCBCEncrypter", "(", "c", ".", "blockCipher", ",", "nonce", ")", "\n", "cbc", ".", "CryptBlocks", "(", "ciphertext", ",", "ciphertext", ")", "\n\n", "authtag", ":=", "c", ".", "ComputeAuthTag", "(", "data", ",", "nonce", ",", "ciphertext", ")", "\n\n", "retlen", ":=", "len", "(", "dst", ")", "+", "len", "(", "ciphertext", ")", "+", "len", "(", "authtag", ")", "\n\n", "ret", ":=", "ensureSize", "(", "dst", ",", "retlen", ")", "\n", "out", ":=", "ret", "[", "len", "(", "dst", ")", ":", "]", "\n", "n", ":=", "copy", "(", "out", ",", "ciphertext", ")", "\n", "n", "+=", "copy", "(", "out", "[", "n", ":", "]", ",", "authtag", ")", "\n\n", "if", "debug", ".", "Enabled", "{", "debug", ".", "Printf", "(", "\"", "\\n", "\"", ",", "ciphertext", ",", "len", "(", "ciphertext", ")", ")", "\n", "debug", ".", "Printf", "(", "\"", "\\n", "\"", ",", "authtag", ",", "len", "(", "authtag", ")", ")", "\n", "debug", ".", "Printf", "(", "\"", "\\n", "\"", ",", "ret", ",", "len", "(", "ret", ")", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Seal fulfills the crypto.AEAD interface
[ "Seal", "fulfills", "the", "crypto", ".", "AEAD", "interface" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/aescbc/aescbc.go#L119-L143
train
lestrrat-go/jwx
jwe/aescbc/aescbc.go
Open
func (c AesCbcHmac) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { if len(ciphertext) < c.keysize { return nil, errors.New("invalid ciphertext (too short)") } tagOffset := len(ciphertext) - c.tagsize if tagOffset%c.blockCipher.BlockSize() != 0 { return nil, fmt.Errorf( "invalid ciphertext (invalid length: %d %% %d != 0)", tagOffset, c.blockCipher.BlockSize(), ) } tag := ciphertext[tagOffset:] ciphertext = ciphertext[:tagOffset] expectedTag := c.ComputeAuthTag(data, nonce, ciphertext) if subtle.ConstantTimeCompare(expectedTag, tag) != 1 { if debug.Enabled { debug.Printf("provided tag = %x\n", tag) debug.Printf("expected tag = %x\n", expectedTag) } return nil, errors.New("invalid ciphertext (tag mismatch)") } cbc := cipher.NewCBCDecrypter(c.blockCipher, nonce) buf := make([]byte, tagOffset) cbc.CryptBlocks(buf, ciphertext) plaintext, err := padbuf.PadBuffer(buf).Unpad(c.blockCipher.BlockSize()) if err != nil { return nil, errors.Wrap(err, `failed to generate plaintext from decrypted blocks`) } ret := ensureSize(dst, len(plaintext)) out := ret[len(dst):] copy(out, plaintext) return ret, nil }
go
func (c AesCbcHmac) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { if len(ciphertext) < c.keysize { return nil, errors.New("invalid ciphertext (too short)") } tagOffset := len(ciphertext) - c.tagsize if tagOffset%c.blockCipher.BlockSize() != 0 { return nil, fmt.Errorf( "invalid ciphertext (invalid length: %d %% %d != 0)", tagOffset, c.blockCipher.BlockSize(), ) } tag := ciphertext[tagOffset:] ciphertext = ciphertext[:tagOffset] expectedTag := c.ComputeAuthTag(data, nonce, ciphertext) if subtle.ConstantTimeCompare(expectedTag, tag) != 1 { if debug.Enabled { debug.Printf("provided tag = %x\n", tag) debug.Printf("expected tag = %x\n", expectedTag) } return nil, errors.New("invalid ciphertext (tag mismatch)") } cbc := cipher.NewCBCDecrypter(c.blockCipher, nonce) buf := make([]byte, tagOffset) cbc.CryptBlocks(buf, ciphertext) plaintext, err := padbuf.PadBuffer(buf).Unpad(c.blockCipher.BlockSize()) if err != nil { return nil, errors.Wrap(err, `failed to generate plaintext from decrypted blocks`) } ret := ensureSize(dst, len(plaintext)) out := ret[len(dst):] copy(out, plaintext) return ret, nil }
[ "func", "(", "c", "AesCbcHmac", ")", "Open", "(", "dst", ",", "nonce", ",", "ciphertext", ",", "data", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "ciphertext", ")", "<", "c", ".", "keysize", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "tagOffset", ":=", "len", "(", "ciphertext", ")", "-", "c", ".", "tagsize", "\n", "if", "tagOffset", "%", "c", ".", "blockCipher", ".", "BlockSize", "(", ")", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tagOffset", ",", "c", ".", "blockCipher", ".", "BlockSize", "(", ")", ",", ")", "\n", "}", "\n", "tag", ":=", "ciphertext", "[", "tagOffset", ":", "]", "\n", "ciphertext", "=", "ciphertext", "[", ":", "tagOffset", "]", "\n\n", "expectedTag", ":=", "c", ".", "ComputeAuthTag", "(", "data", ",", "nonce", ",", "ciphertext", ")", "\n", "if", "subtle", ".", "ConstantTimeCompare", "(", "expectedTag", ",", "tag", ")", "!=", "1", "{", "if", "debug", ".", "Enabled", "{", "debug", ".", "Printf", "(", "\"", "\\n", "\"", ",", "tag", ")", "\n", "debug", ".", "Printf", "(", "\"", "\\n", "\"", ",", "expectedTag", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cbc", ":=", "cipher", ".", "NewCBCDecrypter", "(", "c", ".", "blockCipher", ",", "nonce", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "tagOffset", ")", "\n", "cbc", ".", "CryptBlocks", "(", "buf", ",", "ciphertext", ")", "\n\n", "plaintext", ",", "err", ":=", "padbuf", ".", "PadBuffer", "(", "buf", ")", ".", "Unpad", "(", "c", ".", "blockCipher", ".", "BlockSize", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to generate plaintext from decrypted blocks`", ")", "\n", "}", "\n", "ret", ":=", "ensureSize", "(", "dst", ",", "len", "(", "plaintext", ")", ")", "\n", "out", ":=", "ret", "[", "len", "(", "dst", ")", ":", "]", "\n", "copy", "(", "out", ",", "plaintext", ")", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// Open fulfills the crypto.AEAD interface
[ "Open", "fulfills", "the", "crypto", ".", "AEAD", "interface" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/aescbc/aescbc.go#L146-L183
train
lestrrat-go/jwx
jwk/headers_gen.go
PopulateMap
func (h StandardHeaders) PopulateMap(m map[string]interface{}) error { for k, v := range h.privateParams { m[k] = v } if v, ok := h.Get(AlgorithmKey); ok { m[AlgorithmKey] = v } if v, ok := h.Get(KeyIDKey); ok { m[KeyIDKey] = v } if v, ok := h.Get(KeyTypeKey); ok { m[KeyTypeKey] = v } if v, ok := h.Get(KeyUsageKey); ok { m[KeyUsageKey] = v } if v, ok := h.Get(KeyOpsKey); ok { m[KeyOpsKey] = v } if v, ok := h.Get(X509CertChainKey); ok { m[X509CertChainKey] = v } if v, ok := h.Get(X509CertThumbprintKey); ok { m[X509CertThumbprintKey] = v } if v, ok := h.Get(X509CertThumbprintS256Key); ok { m[X509CertThumbprintS256Key] = v } if v, ok := h.Get(X509URLKey); ok { m[X509URLKey] = v } return nil }
go
func (h StandardHeaders) PopulateMap(m map[string]interface{}) error { for k, v := range h.privateParams { m[k] = v } if v, ok := h.Get(AlgorithmKey); ok { m[AlgorithmKey] = v } if v, ok := h.Get(KeyIDKey); ok { m[KeyIDKey] = v } if v, ok := h.Get(KeyTypeKey); ok { m[KeyTypeKey] = v } if v, ok := h.Get(KeyUsageKey); ok { m[KeyUsageKey] = v } if v, ok := h.Get(KeyOpsKey); ok { m[KeyOpsKey] = v } if v, ok := h.Get(X509CertChainKey); ok { m[X509CertChainKey] = v } if v, ok := h.Get(X509CertThumbprintKey); ok { m[X509CertThumbprintKey] = v } if v, ok := h.Get(X509CertThumbprintS256Key); ok { m[X509CertThumbprintS256Key] = v } if v, ok := h.Get(X509URLKey); ok { m[X509URLKey] = v } return nil }
[ "func", "(", "h", "StandardHeaders", ")", "PopulateMap", "(", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "for", "k", ",", "v", ":=", "range", "h", ".", "privateParams", "{", "m", "[", "k", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "AlgorithmKey", ")", ";", "ok", "{", "m", "[", "AlgorithmKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "KeyIDKey", ")", ";", "ok", "{", "m", "[", "KeyIDKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "KeyTypeKey", ")", ";", "ok", "{", "m", "[", "KeyTypeKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "KeyUsageKey", ")", ";", "ok", "{", "m", "[", "KeyUsageKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "KeyOpsKey", ")", ";", "ok", "{", "m", "[", "KeyOpsKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "X509CertChainKey", ")", ";", "ok", "{", "m", "[", "X509CertChainKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "X509CertThumbprintKey", ")", ";", "ok", "{", "m", "[", "X509CertThumbprintKey", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "X509CertThumbprintS256Key", ")", ";", "ok", "{", "m", "[", "X509CertThumbprintS256Key", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "h", ".", "Get", "(", "X509URLKey", ")", ";", "ok", "{", "m", "[", "X509URLKey", "]", "=", "v", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PopulateMap populates a map with appropriate values that represent // the headers as a JSON object. This exists primarily because JWKs are // represented as flat objects instead of differentiating the different // parts of the message in separate sub objects.
[ "PopulateMap", "populates", "a", "map", "with", "appropriate", "values", "that", "represent", "the", "headers", "as", "a", "JSON", "object", ".", "This", "exists", "primarily", "because", "JWKs", "are", "represented", "as", "flat", "objects", "instead", "of", "differentiating", "the", "different", "parts", "of", "the", "message", "in", "separate", "sub", "objects", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwk/headers_gen.go#L254-L287
train
lestrrat-go/jwx
jwe/encrypt.go
NewMultiEncrypt
func NewMultiEncrypt(cc ContentEncrypter, kg KeyGenerator, ke ...KeyEncrypter) *MultiEncrypt { e := &MultiEncrypt{ ContentEncrypter: cc, KeyGenerator: kg, KeyEncrypters: ke, } return e }
go
func NewMultiEncrypt(cc ContentEncrypter, kg KeyGenerator, ke ...KeyEncrypter) *MultiEncrypt { e := &MultiEncrypt{ ContentEncrypter: cc, KeyGenerator: kg, KeyEncrypters: ke, } return e }
[ "func", "NewMultiEncrypt", "(", "cc", "ContentEncrypter", ",", "kg", "KeyGenerator", ",", "ke", "...", "KeyEncrypter", ")", "*", "MultiEncrypt", "{", "e", ":=", "&", "MultiEncrypt", "{", "ContentEncrypter", ":", "cc", ",", "KeyGenerator", ":", "kg", ",", "KeyEncrypters", ":", "ke", ",", "}", "\n", "return", "e", "\n", "}" ]
// NewMultiEncrypt creates a new Encrypt struct. The caller is responsible // for instantiating valid inputs for ContentEncrypter, KeyGenerator, // and KeyEncrypters.
[ "NewMultiEncrypt", "creates", "a", "new", "Encrypt", "struct", ".", "The", "caller", "is", "responsible", "for", "instantiating", "valid", "inputs", "for", "ContentEncrypter", "KeyGenerator", "and", "KeyEncrypters", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/encrypt.go#L11-L18
train
lestrrat-go/jwx
jwe/jwe.go
Decrypt
func Decrypt(buf []byte, alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) { msg, err := Parse(buf) if err != nil { return nil, errors.Wrap(err, "failed to parse buffer for Decrypt") } return msg.Decrypt(alg, key) }
go
func Decrypt(buf []byte, alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) { msg, err := Parse(buf) if err != nil { return nil, errors.Wrap(err, "failed to parse buffer for Decrypt") } return msg.Decrypt(alg, key) }
[ "func", "Decrypt", "(", "buf", "[", "]", "byte", ",", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "key", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "msg", ",", "err", ":=", "Parse", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "msg", ".", "Decrypt", "(", "alg", ",", "key", ")", "\n", "}" ]
// Decrypt takes the key encryption algorithm and the corresponding // key to decrypt the JWE message, and returns the decrypted payload. // The JWE message can be either compact or full JSON format.
[ "Decrypt", "takes", "the", "key", "encryption", "algorithm", "and", "the", "corresponding", "key", "to", "decrypt", "the", "JWE", "message", "and", "returns", "the", "decrypted", "payload", ".", "The", "JWE", "message", "can", "be", "either", "compact", "or", "full", "JSON", "format", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/jwe.go#L103-L110
train
lestrrat-go/jwx
jwe/jwe.go
Parse
func Parse(buf []byte) (*Message, error) { buf = bytes.TrimSpace(buf) if len(buf) == 0 { return nil, errors.New("empty buffer") } if buf[0] == '{' { return parseJSON(buf) } return parseCompact(buf) }
go
func Parse(buf []byte) (*Message, error) { buf = bytes.TrimSpace(buf) if len(buf) == 0 { return nil, errors.New("empty buffer") } if buf[0] == '{' { return parseJSON(buf) } return parseCompact(buf) }
[ "func", "Parse", "(", "buf", "[", "]", "byte", ")", "(", "*", "Message", ",", "error", ")", "{", "buf", "=", "bytes", ".", "TrimSpace", "(", "buf", ")", "\n", "if", "len", "(", "buf", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "buf", "[", "0", "]", "==", "'{'", "{", "return", "parseJSON", "(", "buf", ")", "\n", "}", "\n", "return", "parseCompact", "(", "buf", ")", "\n", "}" ]
// Parse parses the JWE message into a Message object. The JWE message // can be either compact or full JSON format.
[ "Parse", "parses", "the", "JWE", "message", "into", "a", "Message", "object", ".", "The", "JWE", "message", "can", "be", "either", "compact", "or", "full", "JSON", "format", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/jwe.go#L114-L124
train
lestrrat-go/jwx
jwk/jwk.go
New
func New(key interface{}) (Key, error) { if key == nil { return nil, errors.New(`jwk.New requires a non-nil key`) } switch v := key.(type) { case *rsa.PrivateKey: return newRSAPrivateKey(v) case *rsa.PublicKey: return newRSAPublicKey(v) case *ecdsa.PrivateKey: return newECDSAPrivateKey(v) case *ecdsa.PublicKey: return newECDSAPublicKey(v) case []byte: return newSymmetricKey(v) default: return nil, errors.Errorf(`invalid key type %T`, key) } }
go
func New(key interface{}) (Key, error) { if key == nil { return nil, errors.New(`jwk.New requires a non-nil key`) } switch v := key.(type) { case *rsa.PrivateKey: return newRSAPrivateKey(v) case *rsa.PublicKey: return newRSAPublicKey(v) case *ecdsa.PrivateKey: return newECDSAPrivateKey(v) case *ecdsa.PublicKey: return newECDSAPublicKey(v) case []byte: return newSymmetricKey(v) default: return nil, errors.Errorf(`invalid key type %T`, key) } }
[ "func", "New", "(", "key", "interface", "{", "}", ")", "(", "Key", ",", "error", ")", "{", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "`jwk.New requires a non-nil key`", ")", "\n", "}", "\n\n", "switch", "v", ":=", "key", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PrivateKey", ":", "return", "newRSAPrivateKey", "(", "v", ")", "\n", "case", "*", "rsa", ".", "PublicKey", ":", "return", "newRSAPublicKey", "(", "v", ")", "\n", "case", "*", "ecdsa", ".", "PrivateKey", ":", "return", "newECDSAPrivateKey", "(", "v", ")", "\n", "case", "*", "ecdsa", ".", "PublicKey", ":", "return", "newECDSAPublicKey", "(", "v", ")", "\n", "case", "[", "]", "byte", ":", "return", "newSymmetricKey", "(", "v", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "`invalid key type %T`", ",", "key", ")", "\n", "}", "\n", "}" ]
// New creates a jwk.Key from the given key.
[ "New", "creates", "a", "jwk", ".", "Key", "from", "the", "given", "key", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwk/jwk.go#L49-L68
train
lestrrat-go/jwx
jwk/jwk.go
Fetch
func Fetch(urlstring string, options ...Option) (*Set, error) { u, err := url.Parse(urlstring) if err != nil { return nil, errors.Wrap(err, `failed to parse url`) } switch u.Scheme { case "http", "https": return FetchHTTP(urlstring, options...) case "file": f, err := os.Open(u.Path) if err != nil { return nil, errors.Wrap(err, `failed to open jwk file`) } defer f.Close() buf, err := ioutil.ReadAll(f) if err != nil { return nil, errors.Wrap(err, `failed read content from jwk file`) } return ParseBytes(buf) } return nil, errors.Errorf(`invalid url scheme %s`, u.Scheme) }
go
func Fetch(urlstring string, options ...Option) (*Set, error) { u, err := url.Parse(urlstring) if err != nil { return nil, errors.Wrap(err, `failed to parse url`) } switch u.Scheme { case "http", "https": return FetchHTTP(urlstring, options...) case "file": f, err := os.Open(u.Path) if err != nil { return nil, errors.Wrap(err, `failed to open jwk file`) } defer f.Close() buf, err := ioutil.ReadAll(f) if err != nil { return nil, errors.Wrap(err, `failed read content from jwk file`) } return ParseBytes(buf) } return nil, errors.Errorf(`invalid url scheme %s`, u.Scheme) }
[ "func", "Fetch", "(", "urlstring", "string", ",", "options", "...", "Option", ")", "(", "*", "Set", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "urlstring", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to parse url`", ")", "\n", "}", "\n\n", "switch", "u", ".", "Scheme", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "FetchHTTP", "(", "urlstring", ",", "options", "...", ")", "\n", "case", "\"", "\"", ":", "f", ",", "err", ":=", "os", ".", "Open", "(", "u", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to open jwk file`", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed read content from jwk file`", ")", "\n", "}", "\n", "return", "ParseBytes", "(", "buf", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Errorf", "(", "`invalid url scheme %s`", ",", "u", ".", "Scheme", ")", "\n", "}" ]
// Fetch fetches a JWK resource specified by a URL
[ "Fetch", "fetches", "a", "JWK", "resource", "specified", "by", "a", "URL" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwk/jwk.go#L71-L94
train
lestrrat-go/jwx
jwk/jwk.go
FetchHTTP
func FetchHTTP(jwkurl string, options ...Option) (*Set, error) { var httpcl HTTPClient = http.DefaultClient for _, option := range options { switch option.Name() { case optkeyHTTPClient: httpcl = option.Value().(HTTPClient) } } res, err := httpcl.Get(jwkurl) if err != nil { return nil, errors.Wrap(err, "failed to fetch remote JWK") } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, errors.New("failed to fetch remote JWK (status != 200)") } buf, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrap(err, "failed to read JWK HTTP response body") } return ParseBytes(buf) }
go
func FetchHTTP(jwkurl string, options ...Option) (*Set, error) { var httpcl HTTPClient = http.DefaultClient for _, option := range options { switch option.Name() { case optkeyHTTPClient: httpcl = option.Value().(HTTPClient) } } res, err := httpcl.Get(jwkurl) if err != nil { return nil, errors.Wrap(err, "failed to fetch remote JWK") } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, errors.New("failed to fetch remote JWK (status != 200)") } buf, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrap(err, "failed to read JWK HTTP response body") } return ParseBytes(buf) }
[ "func", "FetchHTTP", "(", "jwkurl", "string", ",", "options", "...", "Option", ")", "(", "*", "Set", ",", "error", ")", "{", "var", "httpcl", "HTTPClient", "=", "http", ".", "DefaultClient", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "switch", "option", ".", "Name", "(", ")", "{", "case", "optkeyHTTPClient", ":", "httpcl", "=", "option", ".", "Value", "(", ")", ".", "(", "HTTPClient", ")", "\n", "}", "\n", "}", "\n\n", "res", ",", "err", ":=", "httpcl", ".", "Get", "(", "jwkurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "ParseBytes", "(", "buf", ")", "\n", "}" ]
// FetchHTTP fetches the remote JWK and parses its contents
[ "FetchHTTP", "fetches", "the", "remote", "JWK", "and", "parses", "its", "contents" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwk/jwk.go#L97-L122
train
lestrrat-go/jwx
jwk/jwk.go
Parse
func Parse(in io.Reader) (*Set, error) { m := make(map[string]interface{}) if err := json.NewDecoder(in).Decode(&m); err != nil { return nil, errors.Wrap(err, "failed to unmarshal JWK") } // We must change what the underlying structure that gets decoded // out of this JSON is based on parameters within the already parsed // JSON (m). In order to do this, we have to go through the tedious // task of parsing the contents of this map :/ if _, ok := m["keys"]; ok { var set Set if err := set.ExtractMap(m); err != nil { return nil, errors.Wrap(err, `failed to extract from map`) } return &set, nil } k, err := constructKey(m) if err != nil { return nil, errors.Wrap(err, `failed to construct key from keys`) } return &Set{Keys: []Key{k}}, nil }
go
func Parse(in io.Reader) (*Set, error) { m := make(map[string]interface{}) if err := json.NewDecoder(in).Decode(&m); err != nil { return nil, errors.Wrap(err, "failed to unmarshal JWK") } // We must change what the underlying structure that gets decoded // out of this JSON is based on parameters within the already parsed // JSON (m). In order to do this, we have to go through the tedious // task of parsing the contents of this map :/ if _, ok := m["keys"]; ok { var set Set if err := set.ExtractMap(m); err != nil { return nil, errors.Wrap(err, `failed to extract from map`) } return &set, nil } k, err := constructKey(m) if err != nil { return nil, errors.Wrap(err, `failed to construct key from keys`) } return &Set{Keys: []Key{k}}, nil }
[ "func", "Parse", "(", "in", "io", ".", "Reader", ")", "(", "*", "Set", ",", "error", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "in", ")", ".", "Decode", "(", "&", "m", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// We must change what the underlying structure that gets decoded", "// out of this JSON is based on parameters within the already parsed", "// JSON (m). In order to do this, we have to go through the tedious", "// task of parsing the contents of this map :/", "if", "_", ",", "ok", ":=", "m", "[", "\"", "\"", "]", ";", "ok", "{", "var", "set", "Set", "\n", "if", "err", ":=", "set", ".", "ExtractMap", "(", "m", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to extract from map`", ")", "\n", "}", "\n", "return", "&", "set", ",", "nil", "\n", "}", "\n\n", "k", ",", "err", ":=", "constructKey", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to construct key from keys`", ")", "\n", "}", "\n", "return", "&", "Set", "{", "Keys", ":", "[", "]", "Key", "{", "k", "}", "}", ",", "nil", "\n", "}" ]
// Parse parses JWK from the incoming io.Reader.
[ "Parse", "parses", "JWK", "from", "the", "incoming", "io", ".", "Reader", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwk/jwk.go#L134-L157
train
lestrrat-go/jwx
jws/message.go
LookupSignature
func (m Message) LookupSignature(kid string) []*Signature { var sigs []*Signature for _, sig := range m.signatures { if hdr := sig.PublicHeaders(); hdr != nil { hdrKeyId, ok := hdr.Get(KeyIDKey) if ok && hdrKeyId == kid { sigs = append(sigs, sig) continue } } if hdr := sig.ProtectedHeaders(); hdr != nil { hdrKeyId, ok := hdr.Get(KeyIDKey) if ok && hdrKeyId == kid { sigs = append(sigs, sig) continue } } } return sigs }
go
func (m Message) LookupSignature(kid string) []*Signature { var sigs []*Signature for _, sig := range m.signatures { if hdr := sig.PublicHeaders(); hdr != nil { hdrKeyId, ok := hdr.Get(KeyIDKey) if ok && hdrKeyId == kid { sigs = append(sigs, sig) continue } } if hdr := sig.ProtectedHeaders(); hdr != nil { hdrKeyId, ok := hdr.Get(KeyIDKey) if ok && hdrKeyId == kid { sigs = append(sigs, sig) continue } } } return sigs }
[ "func", "(", "m", "Message", ")", "LookupSignature", "(", "kid", "string", ")", "[", "]", "*", "Signature", "{", "var", "sigs", "[", "]", "*", "Signature", "\n", "for", "_", ",", "sig", ":=", "range", "m", ".", "signatures", "{", "if", "hdr", ":=", "sig", ".", "PublicHeaders", "(", ")", ";", "hdr", "!=", "nil", "{", "hdrKeyId", ",", "ok", ":=", "hdr", ".", "Get", "(", "KeyIDKey", ")", "\n", "if", "ok", "&&", "hdrKeyId", "==", "kid", "{", "sigs", "=", "append", "(", "sigs", ",", "sig", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "if", "hdr", ":=", "sig", ".", "ProtectedHeaders", "(", ")", ";", "hdr", "!=", "nil", "{", "hdrKeyId", ",", "ok", ":=", "hdr", ".", "Get", "(", "KeyIDKey", ")", "\n", "if", "ok", "&&", "hdrKeyId", "==", "kid", "{", "sigs", "=", "append", "(", "sigs", ",", "sig", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "sigs", "\n", "}" ]
// LookupSignature looks up a particular signature entry using // the `kid` value
[ "LookupSignature", "looks", "up", "a", "particular", "signature", "entry", "using", "the", "kid", "value" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/message.go#L25-L45
train
lestrrat-go/jwx
jwe/interface.go
NewErrUnsupportedAlgorithm
func NewErrUnsupportedAlgorithm(alg, purpose string) errUnsupportedAlgorithm { return errUnsupportedAlgorithm{alg: alg, purpose: purpose} }
go
func NewErrUnsupportedAlgorithm(alg, purpose string) errUnsupportedAlgorithm { return errUnsupportedAlgorithm{alg: alg, purpose: purpose} }
[ "func", "NewErrUnsupportedAlgorithm", "(", "alg", ",", "purpose", "string", ")", "errUnsupportedAlgorithm", "{", "return", "errUnsupportedAlgorithm", "{", "alg", ":", "alg", ",", "purpose", ":", "purpose", "}", "\n", "}" ]
// NewErrUnsupportedAlgorithm creates a new UnsupportedAlgorithm error
[ "NewErrUnsupportedAlgorithm", "creates", "a", "new", "UnsupportedAlgorithm", "error" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/interface.go#L31-L33
train
lestrrat-go/jwx
jwe/interface.go
Error
func (e errUnsupportedAlgorithm) Error() string { return fmt.Sprintf("unsupported algorithm '%s' for %s", e.alg, e.purpose) }
go
func (e errUnsupportedAlgorithm) Error() string { return fmt.Sprintf("unsupported algorithm '%s' for %s", e.alg, e.purpose) }
[ "func", "(", "e", "errUnsupportedAlgorithm", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "alg", ",", "e", ".", "purpose", ")", "\n", "}" ]
// Error returns the string representation of the error
[ "Error", "returns", "the", "string", "representation", "of", "the", "error" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/interface.go#L36-L38
train
lestrrat-go/jwx
jws/jws.go
Sign
func Sign(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, options ...Option) ([]byte, error) { var hdrs Headers = &StandardHeaders{} for _, o := range options { switch o.Name() { case optkeyHeaders: hdrs = o.Value().(Headers) } } signer, err := sign.New(alg) if err != nil { return nil, errors.Wrap(err, `failed to create signer`) } hdrs.Set(AlgorithmKey, signer.Algorithm()) hdrbuf, err := json.Marshal(hdrs) if err != nil { return nil, errors.Wrap(err, `failed to marshal headers`) } var buf bytes.Buffer enc := base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(hdrbuf); err != nil { return nil, errors.Wrap(err, `failed to write headers as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing headers as base64`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(payload); err != nil { return nil, errors.Wrap(err, `failed to write payload as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing payload as base64`) } signature, err := signer.Sign(buf.Bytes(), key) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(signature); err != nil { return nil, errors.Wrap(err, `failed to write signature as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing signature as base64`) } return buf.Bytes(), nil }
go
func Sign(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, options ...Option) ([]byte, error) { var hdrs Headers = &StandardHeaders{} for _, o := range options { switch o.Name() { case optkeyHeaders: hdrs = o.Value().(Headers) } } signer, err := sign.New(alg) if err != nil { return nil, errors.Wrap(err, `failed to create signer`) } hdrs.Set(AlgorithmKey, signer.Algorithm()) hdrbuf, err := json.Marshal(hdrs) if err != nil { return nil, errors.Wrap(err, `failed to marshal headers`) } var buf bytes.Buffer enc := base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(hdrbuf); err != nil { return nil, errors.Wrap(err, `failed to write headers as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing headers as base64`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(payload); err != nil { return nil, errors.Wrap(err, `failed to write payload as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing payload as base64`) } signature, err := signer.Sign(buf.Bytes(), key) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(signature); err != nil { return nil, errors.Wrap(err, `failed to write signature as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing signature as base64`) } return buf.Bytes(), nil }
[ "func", "Sign", "(", "payload", "[", "]", "byte", ",", "alg", "jwa", ".", "SignatureAlgorithm", ",", "key", "interface", "{", "}", ",", "options", "...", "Option", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "hdrs", "Headers", "=", "&", "StandardHeaders", "{", "}", "\n", "for", "_", ",", "o", ":=", "range", "options", "{", "switch", "o", ".", "Name", "(", ")", "{", "case", "optkeyHeaders", ":", "hdrs", "=", "o", ".", "Value", "(", ")", ".", "(", "Headers", ")", "\n", "}", "\n", "}", "\n\n", "signer", ",", "err", ":=", "sign", ".", "New", "(", "alg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to create signer`", ")", "\n", "}", "\n\n", "hdrs", ".", "Set", "(", "AlgorithmKey", ",", "signer", ".", "Algorithm", "(", ")", ")", "\n\n", "hdrbuf", ",", "err", ":=", "json", ".", "Marshal", "(", "hdrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to marshal headers`", ")", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "enc", ":=", "base64", ".", "NewEncoder", "(", "base64", ".", "RawURLEncoding", ",", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "enc", ".", "Write", "(", "hdrbuf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to write headers as base64`", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to finalize writing headers as base64`", ")", "\n", "}", "\n\n", "buf", ".", "WriteByte", "(", "'.'", ")", "\n", "enc", "=", "base64", ".", "NewEncoder", "(", "base64", ".", "RawURLEncoding", ",", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "enc", ".", "Write", "(", "payload", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to write payload as base64`", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to finalize writing payload as base64`", ")", "\n", "}", "\n\n", "signature", ",", "err", ":=", "signer", ".", "Sign", "(", "buf", ".", "Bytes", "(", ")", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to sign payload`", ")", "\n", "}", "\n\n", "buf", ".", "WriteByte", "(", "'.'", ")", "\n", "enc", "=", "base64", ".", "NewEncoder", "(", "base64", ".", "RawURLEncoding", ",", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "enc", ".", "Write", "(", "signature", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to write signature as base64`", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to finalize writing signature as base64`", ")", "\n", "}", "\n\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Sign generates a signature for the given payload, and serializes // it in compact serialization format. In this format you may NOT use // multiple signers. // // If you would like to pass custom headers, use the WithHeaders option.
[ "Sign", "generates", "a", "signature", "for", "the", "given", "payload", "and", "serializes", "it", "in", "compact", "serialization", "format", ".", "In", "this", "format", "you", "may", "NOT", "use", "multiple", "signers", ".", "If", "you", "would", "like", "to", "pass", "custom", "headers", "use", "the", "WithHeaders", "option", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L87-L141
train
lestrrat-go/jwx
jws/jws.go
SignLiteral
func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, headers []byte) ([]byte, error) { signer, err := sign.New(alg) if err != nil { return nil, errors.Wrap(err, `failed to create signer`) } var buf bytes.Buffer enc := base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(headers); err != nil { return nil, errors.Wrap(err, `failed to write headers as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing headers as base64`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(payload); err != nil { return nil, errors.Wrap(err, `failed to write payload as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing payload as base64`) } signature, err := signer.Sign(buf.Bytes(), key) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(signature); err != nil { return nil, errors.Wrap(err, `failed to write signature as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing signature as base64`) } return buf.Bytes(), nil }
go
func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, headers []byte) ([]byte, error) { signer, err := sign.New(alg) if err != nil { return nil, errors.Wrap(err, `failed to create signer`) } var buf bytes.Buffer enc := base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(headers); err != nil { return nil, errors.Wrap(err, `failed to write headers as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing headers as base64`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(payload); err != nil { return nil, errors.Wrap(err, `failed to write payload as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing payload as base64`) } signature, err := signer.Sign(buf.Bytes(), key) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } buf.WriteByte('.') enc = base64.NewEncoder(base64.RawURLEncoding, &buf) if _, err := enc.Write(signature); err != nil { return nil, errors.Wrap(err, `failed to write signature as base64`) } if err := enc.Close(); err != nil { return nil, errors.Wrap(err, `failed to finalize writing signature as base64`) } return buf.Bytes(), nil }
[ "func", "SignLiteral", "(", "payload", "[", "]", "byte", ",", "alg", "jwa", ".", "SignatureAlgorithm", ",", "key", "interface", "{", "}", ",", "headers", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "signer", ",", "err", ":=", "sign", ".", "New", "(", "alg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to create signer`", ")", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "enc", ":=", "base64", ".", "NewEncoder", "(", "base64", ".", "RawURLEncoding", ",", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "enc", ".", "Write", "(", "headers", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to write headers as base64`", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to finalize writing headers as base64`", ")", "\n", "}", "\n\n", "buf", ".", "WriteByte", "(", "'.'", ")", "\n", "enc", "=", "base64", ".", "NewEncoder", "(", "base64", ".", "RawURLEncoding", ",", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "enc", ".", "Write", "(", "payload", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to write payload as base64`", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to finalize writing payload as base64`", ")", "\n", "}", "\n\n", "signature", ",", "err", ":=", "signer", ".", "Sign", "(", "buf", ".", "Bytes", "(", ")", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to sign payload`", ")", "\n", "}", "\n\n", "buf", ".", "WriteByte", "(", "'.'", ")", "\n", "enc", "=", "base64", ".", "NewEncoder", "(", "base64", ".", "RawURLEncoding", ",", "&", "buf", ")", "\n", "if", "_", ",", "err", ":=", "enc", ".", "Write", "(", "signature", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to write signature as base64`", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to finalize writing signature as base64`", ")", "\n", "}", "\n\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// SignLiteral generates a signature for the given payload and headers, and serializes // it in compact serialization format. In this format you may NOT use // multiple signers. //
[ "SignLiteral", "generates", "a", "signature", "for", "the", "given", "payload", "and", "headers", "and", "serializes", "it", "in", "compact", "serialization", "format", ".", "In", "this", "format", "you", "may", "NOT", "use", "multiple", "signers", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L147-L187
train
lestrrat-go/jwx
jws/jws.go
SignMulti
func SignMulti(payload []byte, options ...Option) ([]byte, error) { var signers []PayloadSigner for _, o := range options { switch o.Name() { case optkeyPayloadSigner: signers = append(signers, o.Value().(PayloadSigner)) } } if len(signers) == 0 { return nil, errors.New(`no signers provided`) } var result EncodedMessage result.Payload = base64.RawURLEncoding.EncodeToString(payload) for _, signer := range signers { protected := signer.ProtectedHeader() if protected == nil { protected = &StandardHeaders{} } protected.Set(AlgorithmKey, signer.Algorithm()) hdrbuf, err := json.Marshal(protected) if err != nil { return nil, errors.Wrap(err, `failed to marshal headers`) } encodedHeader := base64.RawURLEncoding.EncodeToString(hdrbuf) var buf bytes.Buffer buf.WriteString(encodedHeader) buf.WriteByte('.') buf.WriteString(result.Payload) signature, err := signer.Sign(buf.Bytes()) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } result.Signatures = append(result.Signatures, &EncodedSignature{ Headers: signer.PublicHeader(), Protected: encodedHeader, Signature: base64.RawURLEncoding.EncodeToString(signature), }) } return json.Marshal(result) }
go
func SignMulti(payload []byte, options ...Option) ([]byte, error) { var signers []PayloadSigner for _, o := range options { switch o.Name() { case optkeyPayloadSigner: signers = append(signers, o.Value().(PayloadSigner)) } } if len(signers) == 0 { return nil, errors.New(`no signers provided`) } var result EncodedMessage result.Payload = base64.RawURLEncoding.EncodeToString(payload) for _, signer := range signers { protected := signer.ProtectedHeader() if protected == nil { protected = &StandardHeaders{} } protected.Set(AlgorithmKey, signer.Algorithm()) hdrbuf, err := json.Marshal(protected) if err != nil { return nil, errors.Wrap(err, `failed to marshal headers`) } encodedHeader := base64.RawURLEncoding.EncodeToString(hdrbuf) var buf bytes.Buffer buf.WriteString(encodedHeader) buf.WriteByte('.') buf.WriteString(result.Payload) signature, err := signer.Sign(buf.Bytes()) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } result.Signatures = append(result.Signatures, &EncodedSignature{ Headers: signer.PublicHeader(), Protected: encodedHeader, Signature: base64.RawURLEncoding.EncodeToString(signature), }) } return json.Marshal(result) }
[ "func", "SignMulti", "(", "payload", "[", "]", "byte", ",", "options", "...", "Option", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "signers", "[", "]", "PayloadSigner", "\n", "for", "_", ",", "o", ":=", "range", "options", "{", "switch", "o", ".", "Name", "(", ")", "{", "case", "optkeyPayloadSigner", ":", "signers", "=", "append", "(", "signers", ",", "o", ".", "Value", "(", ")", ".", "(", "PayloadSigner", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "signers", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "`no signers provided`", ")", "\n", "}", "\n\n", "var", "result", "EncodedMessage", "\n\n", "result", ".", "Payload", "=", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "payload", ")", "\n\n", "for", "_", ",", "signer", ":=", "range", "signers", "{", "protected", ":=", "signer", ".", "ProtectedHeader", "(", ")", "\n", "if", "protected", "==", "nil", "{", "protected", "=", "&", "StandardHeaders", "{", "}", "\n", "}", "\n\n", "protected", ".", "Set", "(", "AlgorithmKey", ",", "signer", ".", "Algorithm", "(", ")", ")", "\n\n", "hdrbuf", ",", "err", ":=", "json", ".", "Marshal", "(", "protected", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to marshal headers`", ")", "\n", "}", "\n", "encodedHeader", ":=", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "hdrbuf", ")", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "WriteString", "(", "encodedHeader", ")", "\n", "buf", ".", "WriteByte", "(", "'.'", ")", "\n", "buf", ".", "WriteString", "(", "result", ".", "Payload", ")", "\n", "signature", ",", "err", ":=", "signer", ".", "Sign", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to sign payload`", ")", "\n", "}", "\n\n", "result", ".", "Signatures", "=", "append", "(", "result", ".", "Signatures", ",", "&", "EncodedSignature", "{", "Headers", ":", "signer", ".", "PublicHeader", "(", ")", ",", "Protected", ":", "encodedHeader", ",", "Signature", ":", "base64", ".", "RawURLEncoding", ".", "EncodeToString", "(", "signature", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "json", ".", "Marshal", "(", "result", ")", "\n", "}" ]
// SignMulti accepts multiple signers via the options parameter, // and creates a JWS in JSON serialization format that contains // signatures from applying aforementioned signers.
[ "SignMulti", "accepts", "multiple", "signers", "via", "the", "options", "parameter", "and", "creates", "a", "JWS", "in", "JSON", "serialization", "format", "that", "contains", "signatures", "from", "applying", "aforementioned", "signers", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L192-L239
train
lestrrat-go/jwx
jws/jws.go
VerifyWithJKU
func VerifyWithJKU(buf []byte, jwkurl string) ([]byte, error) { key, err := jwk.FetchHTTP(jwkurl) if err != nil { return nil, errors.Wrap(err, `failed to fetch jwk via HTTP`) } return VerifyWithJWKSet(buf, key, nil) }
go
func VerifyWithJKU(buf []byte, jwkurl string) ([]byte, error) { key, err := jwk.FetchHTTP(jwkurl) if err != nil { return nil, errors.Wrap(err, `failed to fetch jwk via HTTP`) } return VerifyWithJWKSet(buf, key, nil) }
[ "func", "VerifyWithJKU", "(", "buf", "[", "]", "byte", ",", "jwkurl", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "key", ",", "err", ":=", "jwk", ".", "FetchHTTP", "(", "jwkurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to fetch jwk via HTTP`", ")", "\n", "}", "\n\n", "return", "VerifyWithJWKSet", "(", "buf", ",", "key", ",", "nil", ")", "\n", "}" ]
// VerifyWithJKU verifies the JWS message using a remote JWK // file represented in the url.
[ "VerifyWithJKU", "verifies", "the", "JWS", "message", "using", "a", "remote", "JWK", "file", "represented", "in", "the", "url", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L327-L334
train
lestrrat-go/jwx
jws/jws.go
VerifyWithJWK
func VerifyWithJWK(buf []byte, key jwk.Key) (payload []byte, err error) { keyval, err := key.Materialize() if err != nil { return nil, errors.Wrap(err, `failed to materialize jwk.Key`) } payload, err = Verify(buf, jwa.SignatureAlgorithm(key.Algorithm()), keyval) if err != nil { return nil, errors.Wrap(err, "failed to verify message") } return payload, nil }
go
func VerifyWithJWK(buf []byte, key jwk.Key) (payload []byte, err error) { keyval, err := key.Materialize() if err != nil { return nil, errors.Wrap(err, `failed to materialize jwk.Key`) } payload, err = Verify(buf, jwa.SignatureAlgorithm(key.Algorithm()), keyval) if err != nil { return nil, errors.Wrap(err, "failed to verify message") } return payload, nil }
[ "func", "VerifyWithJWK", "(", "buf", "[", "]", "byte", ",", "key", "jwk", ".", "Key", ")", "(", "payload", "[", "]", "byte", ",", "err", "error", ")", "{", "keyval", ",", "err", ":=", "key", ".", "Materialize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to materialize jwk.Key`", ")", "\n", "}", "\n\n", "payload", ",", "err", "=", "Verify", "(", "buf", ",", "jwa", ".", "SignatureAlgorithm", "(", "key", ".", "Algorithm", "(", ")", ")", ",", "keyval", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "payload", ",", "nil", "\n", "}" ]
// VerifyWithJWK verifies the JWS message using the specified JWK
[ "VerifyWithJWK", "verifies", "the", "JWS", "message", "using", "the", "specified", "JWK" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L337-L349
train
lestrrat-go/jwx
jws/jws.go
VerifyWithJWKSet
func VerifyWithJWKSet(buf []byte, keyset *jwk.Set, keyaccept JWKAcceptFunc) (payload []byte, err error) { if keyaccept == nil { keyaccept = DefaultJWKAcceptor } for _, key := range keyset.Keys { if !keyaccept(key) { continue } payload, err := VerifyWithJWK(buf, key) if err == nil { return payload, nil } } return nil, errors.New("failed to verify with any of the keys") }
go
func VerifyWithJWKSet(buf []byte, keyset *jwk.Set, keyaccept JWKAcceptFunc) (payload []byte, err error) { if keyaccept == nil { keyaccept = DefaultJWKAcceptor } for _, key := range keyset.Keys { if !keyaccept(key) { continue } payload, err := VerifyWithJWK(buf, key) if err == nil { return payload, nil } } return nil, errors.New("failed to verify with any of the keys") }
[ "func", "VerifyWithJWKSet", "(", "buf", "[", "]", "byte", ",", "keyset", "*", "jwk", ".", "Set", ",", "keyaccept", "JWKAcceptFunc", ")", "(", "payload", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "keyaccept", "==", "nil", "{", "keyaccept", "=", "DefaultJWKAcceptor", "\n", "}", "\n\n", "for", "_", ",", "key", ":=", "range", "keyset", ".", "Keys", "{", "if", "!", "keyaccept", "(", "key", ")", "{", "continue", "\n", "}", "\n\n", "payload", ",", "err", ":=", "VerifyWithJWK", "(", "buf", ",", "key", ")", "\n", "if", "err", "==", "nil", "{", "return", "payload", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// VerifyWithJWKSet verifies the JWS message using JWK key set. // By default it will only pick up keys that have the "use" key // set to either "sig" or "enc", but you can override it by // providing a keyaccept function.
[ "VerifyWithJWKSet", "verifies", "the", "JWS", "message", "using", "JWK", "key", "set", ".", "By", "default", "it", "will", "only", "pick", "up", "keys", "that", "have", "the", "use", "key", "set", "to", "either", "sig", "or", "enc", "but", "you", "can", "override", "it", "by", "providing", "a", "keyaccept", "function", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L355-L373
train
lestrrat-go/jwx
jws/jws.go
Parse
func Parse(src io.Reader) (m *Message, err error) { rdr := bufio.NewReader(src) var first rune for { r, _, err := rdr.ReadRune() if err != nil { return nil, errors.Wrap(err, `failed to read rune`) } if !unicode.IsSpace(r) { first = r rdr.UnreadRune() break } } var parser func(io.Reader) (*Message, error) if first == '{' { parser = parseJSON } else { parser = parseCompact } m, err = parser(rdr) if err != nil { return nil, errors.Wrap(err, `failed to parse jws message`) } return m, nil }
go
func Parse(src io.Reader) (m *Message, err error) { rdr := bufio.NewReader(src) var first rune for { r, _, err := rdr.ReadRune() if err != nil { return nil, errors.Wrap(err, `failed to read rune`) } if !unicode.IsSpace(r) { first = r rdr.UnreadRune() break } } var parser func(io.Reader) (*Message, error) if first == '{' { parser = parseJSON } else { parser = parseCompact } m, err = parser(rdr) if err != nil { return nil, errors.Wrap(err, `failed to parse jws message`) } return m, nil }
[ "func", "Parse", "(", "src", "io", ".", "Reader", ")", "(", "m", "*", "Message", ",", "err", "error", ")", "{", "rdr", ":=", "bufio", ".", "NewReader", "(", "src", ")", "\n", "var", "first", "rune", "\n", "for", "{", "r", ",", "_", ",", "err", ":=", "rdr", ".", "ReadRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to read rune`", ")", "\n", "}", "\n", "if", "!", "unicode", ".", "IsSpace", "(", "r", ")", "{", "first", "=", "r", "\n", "rdr", ".", "UnreadRune", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "var", "parser", "func", "(", "io", ".", "Reader", ")", "(", "*", "Message", ",", "error", ")", "\n", "if", "first", "==", "'{'", "{", "parser", "=", "parseJSON", "\n", "}", "else", "{", "parser", "=", "parseCompact", "\n", "}", "\n\n", "m", ",", "err", "=", "parser", "(", "rdr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to parse jws message`", ")", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// Parse parses contents from the given source and creates a jws.Message // struct. The input can be in either compact or full JSON serialization.
[ "Parse", "parses", "contents", "from", "the", "given", "source", "and", "creates", "a", "jws", ".", "Message", "struct", ".", "The", "input", "can", "be", "in", "either", "compact", "or", "full", "JSON", "serialization", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L377-L406
train
lestrrat-go/jwx
jws/jws.go
parseCompact
func parseCompact(rdr io.Reader) (m *Message, err error) { protected, payload, signature, err := SplitCompact(rdr) if err != nil { return nil, errors.Wrap(err, `invalid compact serialization format`) } decodedHeader := make([]byte, base64.RawURLEncoding.DecodedLen(len(protected))) if _, err := base64.RawURLEncoding.Decode(decodedHeader, protected); err != nil { return nil, errors.Wrap(err, `failed to decode headers`) } var hdr StandardHeaders if err := json.Unmarshal(decodedHeader, &hdr); err != nil { return nil, errors.Wrap(err, `failed to parse JOSE headers`) } decodedPayload := make([]byte, base64.RawURLEncoding.DecodedLen(len(payload))) if _, err = base64.RawURLEncoding.Decode(decodedPayload, payload); err != nil { return nil, errors.Wrap(err, `failed to decode payload`) } decodedSignature := make([]byte, base64.RawURLEncoding.DecodedLen(len(signature))) if _, err := base64.RawURLEncoding.Decode(decodedSignature, signature); err != nil { return nil, errors.Wrap(err, `failed to decode signature`) } var msg Message msg.payload = decodedPayload msg.signatures = append(msg.signatures, &Signature{ protected: &hdr, signature: decodedSignature, }) return &msg, nil }
go
func parseCompact(rdr io.Reader) (m *Message, err error) { protected, payload, signature, err := SplitCompact(rdr) if err != nil { return nil, errors.Wrap(err, `invalid compact serialization format`) } decodedHeader := make([]byte, base64.RawURLEncoding.DecodedLen(len(protected))) if _, err := base64.RawURLEncoding.Decode(decodedHeader, protected); err != nil { return nil, errors.Wrap(err, `failed to decode headers`) } var hdr StandardHeaders if err := json.Unmarshal(decodedHeader, &hdr); err != nil { return nil, errors.Wrap(err, `failed to parse JOSE headers`) } decodedPayload := make([]byte, base64.RawURLEncoding.DecodedLen(len(payload))) if _, err = base64.RawURLEncoding.Decode(decodedPayload, payload); err != nil { return nil, errors.Wrap(err, `failed to decode payload`) } decodedSignature := make([]byte, base64.RawURLEncoding.DecodedLen(len(signature))) if _, err := base64.RawURLEncoding.Decode(decodedSignature, signature); err != nil { return nil, errors.Wrap(err, `failed to decode signature`) } var msg Message msg.payload = decodedPayload msg.signatures = append(msg.signatures, &Signature{ protected: &hdr, signature: decodedSignature, }) return &msg, nil }
[ "func", "parseCompact", "(", "rdr", "io", ".", "Reader", ")", "(", "m", "*", "Message", ",", "err", "error", ")", "{", "protected", ",", "payload", ",", "signature", ",", "err", ":=", "SplitCompact", "(", "rdr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`invalid compact serialization format`", ")", "\n", "}", "\n\n", "decodedHeader", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "RawURLEncoding", ".", "DecodedLen", "(", "len", "(", "protected", ")", ")", ")", "\n", "if", "_", ",", "err", ":=", "base64", ".", "RawURLEncoding", ".", "Decode", "(", "decodedHeader", ",", "protected", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to decode headers`", ")", "\n", "}", "\n", "var", "hdr", "StandardHeaders", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "decodedHeader", ",", "&", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to parse JOSE headers`", ")", "\n", "}", "\n\n", "decodedPayload", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "RawURLEncoding", ".", "DecodedLen", "(", "len", "(", "payload", ")", ")", ")", "\n", "if", "_", ",", "err", "=", "base64", ".", "RawURLEncoding", ".", "Decode", "(", "decodedPayload", ",", "payload", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to decode payload`", ")", "\n", "}", "\n\n", "decodedSignature", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "RawURLEncoding", ".", "DecodedLen", "(", "len", "(", "signature", ")", ")", ")", "\n", "if", "_", ",", "err", ":=", "base64", ".", "RawURLEncoding", ".", "Decode", "(", "decodedSignature", ",", "signature", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to decode signature`", ")", "\n", "}", "\n\n", "var", "msg", "Message", "\n", "msg", ".", "payload", "=", "decodedPayload", "\n", "msg", ".", "signatures", "=", "append", "(", "msg", ".", "signatures", ",", "&", "Signature", "{", "protected", ":", "&", "hdr", ",", "signature", ":", "decodedSignature", ",", "}", ")", "\n", "return", "&", "msg", ",", "nil", "\n", "}" ]
// parseCompact parses a JWS value serialized via compact serialization.
[ "parseCompact", "parses", "a", "JWS", "value", "serialized", "via", "compact", "serialization", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/jws.go#L525-L558
train
lestrrat-go/jwx
jws/verify/verify.go
New
func New(alg jwa.SignatureAlgorithm) (Verifier, error) { switch alg { case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512: return newRSA(alg) case jwa.ES256, jwa.ES384, jwa.ES512: return newECDSA(alg) case jwa.HS256, jwa.HS384, jwa.HS512: return newHMAC(alg) default: return nil, errors.Errorf(`unsupported signature algorithm: %s`, alg) } }
go
func New(alg jwa.SignatureAlgorithm) (Verifier, error) { switch alg { case jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512: return newRSA(alg) case jwa.ES256, jwa.ES384, jwa.ES512: return newECDSA(alg) case jwa.HS256, jwa.HS384, jwa.HS512: return newHMAC(alg) default: return nil, errors.Errorf(`unsupported signature algorithm: %s`, alg) } }
[ "func", "New", "(", "alg", "jwa", ".", "SignatureAlgorithm", ")", "(", "Verifier", ",", "error", ")", "{", "switch", "alg", "{", "case", "jwa", ".", "RS256", ",", "jwa", ".", "RS384", ",", "jwa", ".", "RS512", ",", "jwa", ".", "PS256", ",", "jwa", ".", "PS384", ",", "jwa", ".", "PS512", ":", "return", "newRSA", "(", "alg", ")", "\n", "case", "jwa", ".", "ES256", ",", "jwa", ".", "ES384", ",", "jwa", ".", "ES512", ":", "return", "newECDSA", "(", "alg", ")", "\n", "case", "jwa", ".", "HS256", ",", "jwa", ".", "HS384", ",", "jwa", ".", "HS512", ":", "return", "newHMAC", "(", "alg", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "`unsupported signature algorithm: %s`", ",", "alg", ")", "\n", "}", "\n", "}" ]
// New creates a new JWS verifier using the specified algorithm // and the public key
[ "New", "creates", "a", "new", "JWS", "verifier", "using", "the", "specified", "algorithm", "and", "the", "public", "key" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jws/verify/verify.go#L10-L21
train
lestrrat-go/jwx
jwt/jwt.go
ParseString
func ParseString(s string, options ...Option) (*Token, error) { return Parse(strings.NewReader(s), options...) }
go
func ParseString(s string, options ...Option) (*Token, error) { return Parse(strings.NewReader(s), options...) }
[ "func", "ParseString", "(", "s", "string", ",", "options", "...", "Option", ")", "(", "*", "Token", ",", "error", ")", "{", "return", "Parse", "(", "strings", ".", "NewReader", "(", "s", ")", ",", "options", "...", ")", "\n", "}" ]
// ParseString calls Parse with the given string
[ "ParseString", "calls", "Parse", "with", "the", "given", "string" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwt/jwt.go#L19-L21
train