id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
12,600 | FDio/govpp | extras/libmemif/packethandle.go | WritePacketData | func (handle *MemifPacketHandle) WritePacketData(data []byte) (err error) {
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
if handle.stop {
err = io.EOF
return
}
count, err := handle.memif.TxBurst(handle.queueId, []RawPacketData{data})
if err != nil {
return
}
if count == 0 {
err = io.EOF
}
return
} | go | func (handle *MemifPacketHandle) WritePacketData(data []byte) (err error) {
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
if handle.stop {
err = io.EOF
return
}
count, err := handle.memif.TxBurst(handle.queueId, []RawPacketData{data})
if err != nil {
return
}
if count == 0 {
err = io.EOF
}
return
} | [
"func",
"(",
"handle",
"*",
"MemifPacketHandle",
")",
"WritePacketData",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"handle",
".",
"writeMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"handle",
".",
"writeMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"handle",
".",
"stop",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"return",
"\n",
"}",
"\n\n",
"count",
",",
"err",
":=",
"handle",
".",
"memif",
".",
"TxBurst",
"(",
"handle",
".",
"queueId",
",",
"[",
"]",
"RawPacketData",
"{",
"data",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"count",
"==",
"0",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Writes packet data to memif in burst of 1 packet. In case no packet is sent, this method throws io.EOF error and
// called should stop trying to write packets. | [
"Writes",
"packet",
"data",
"to",
"memif",
"in",
"burst",
"of",
"1",
"packet",
".",
"In",
"case",
"no",
"packet",
"is",
"sent",
"this",
"method",
"throws",
"io",
".",
"EOF",
"error",
"and",
"called",
"should",
"stop",
"trying",
"to",
"write",
"packets",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/packethandle.go#L112-L132 |
12,601 | FDio/govpp | extras/libmemif/packethandle.go | Close | func (handle *MemifPacketHandle) Close() {
handle.closeMu.Lock()
defer handle.closeMu.Unlock()
// wait for packet reader to stop
handle.readMu.Lock()
defer handle.readMu.Unlock()
// wait for packet writer to stop
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
// stop reading and writing
handle.stop = true
} | go | func (handle *MemifPacketHandle) Close() {
handle.closeMu.Lock()
defer handle.closeMu.Unlock()
// wait for packet reader to stop
handle.readMu.Lock()
defer handle.readMu.Unlock()
// wait for packet writer to stop
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
// stop reading and writing
handle.stop = true
} | [
"func",
"(",
"handle",
"*",
"MemifPacketHandle",
")",
"Close",
"(",
")",
"{",
"handle",
".",
"closeMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"handle",
".",
"closeMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// wait for packet reader to stop",
"handle",
".",
"readMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"handle",
".",
"readMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// wait for packet writer to stop",
"handle",
".",
"writeMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"handle",
".",
"writeMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// stop reading and writing",
"handle",
".",
"stop",
"=",
"true",
"\n",
"}"
] | // Waits for all read and write operations to finish and then prevents more from occurring. Handle can be closed only
// once and then can never be opened again. | [
"Waits",
"for",
"all",
"read",
"and",
"write",
"operations",
"to",
"finish",
"and",
"then",
"prevents",
"more",
"from",
"occurring",
".",
"Handle",
"can",
"be",
"closed",
"only",
"once",
"and",
"then",
"can",
"never",
"be",
"opened",
"again",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/packethandle.go#L136-L150 |
12,602 | FDio/govpp | api/binapi.go | RegisterMessage | func RegisterMessage(x Message, name string) {
name = x.GetMessageName() + "_" + x.GetCrcString()
/*if _, ok := registeredMessages[name]; ok {
panic(fmt.Errorf("govpp: duplicate message registered: %s (%s)", name, x.GetCrcString()))
}*/
registeredMessages[name] = x
} | go | func RegisterMessage(x Message, name string) {
name = x.GetMessageName() + "_" + x.GetCrcString()
/*if _, ok := registeredMessages[name]; ok {
panic(fmt.Errorf("govpp: duplicate message registered: %s (%s)", name, x.GetCrcString()))
}*/
registeredMessages[name] = x
} | [
"func",
"RegisterMessage",
"(",
"x",
"Message",
",",
"name",
"string",
")",
"{",
"name",
"=",
"x",
".",
"GetMessageName",
"(",
")",
"+",
"\"",
"\"",
"+",
"x",
".",
"GetCrcString",
"(",
")",
"\n",
"/*if _, ok := registeredMessages[name]; ok {\n\t\tpanic(fmt.Errorf(\"govpp: duplicate message registered: %s (%s)\", name, x.GetCrcString()))\n\t}*/",
"registeredMessages",
"[",
"name",
"]",
"=",
"x",
"\n",
"}"
] | // RegisterMessage is called from generated code to register message. | [
"RegisterMessage",
"is",
"called",
"from",
"generated",
"code",
"to",
"register",
"message",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/api/binapi.go#L124-L130 |
12,603 | FDio/govpp | core/stats.go | ConnectStats | func ConnectStats(stats adapter.StatsAPI) (*StatsConnection, error) {
c := newStatsConnection(stats)
if err := c.connectClient(); err != nil {
return nil, err
}
return c, nil
} | go | func ConnectStats(stats adapter.StatsAPI) (*StatsConnection, error) {
c := newStatsConnection(stats)
if err := c.connectClient(); err != nil {
return nil, err
}
return c, nil
} | [
"func",
"ConnectStats",
"(",
"stats",
"adapter",
".",
"StatsAPI",
")",
"(",
"*",
"StatsConnection",
",",
"error",
")",
"{",
"c",
":=",
"newStatsConnection",
"(",
"stats",
")",
"\n\n",
"if",
"err",
":=",
"c",
".",
"connectClient",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // Connect connects to Stats API using specified adapter and returns a connection handle.
// This call blocks until it is either connected, or an error occurs.
// Only one connection attempt will be performed. | [
"Connect",
"connects",
"to",
"Stats",
"API",
"using",
"specified",
"adapter",
"and",
"returns",
"a",
"connection",
"handle",
".",
"This",
"call",
"blocks",
"until",
"it",
"is",
"either",
"connected",
"or",
"an",
"error",
"occurs",
".",
"Only",
"one",
"connection",
"attempt",
"will",
"be",
"performed",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L78-L86 |
12,604 | FDio/govpp | core/stats.go | Disconnect | func (c *StatsConnection) Disconnect() {
if c == nil {
return
}
if c.statsClient != nil {
c.disconnectClient()
}
} | go | func (c *StatsConnection) Disconnect() {
if c == nil {
return
}
if c.statsClient != nil {
c.disconnectClient()
}
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"Disconnect",
"(",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"statsClient",
"!=",
"nil",
"{",
"c",
".",
"disconnectClient",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Disconnect disconnects from Stats API and releases all connection-related resources. | [
"Disconnect",
"disconnects",
"from",
"Stats",
"API",
"and",
"releases",
"all",
"connection",
"-",
"related",
"resources",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L104-L112 |
12,605 | FDio/govpp | core/stats.go | GetSystemStats | func (c *StatsConnection) GetSystemStats() (*api.SystemStats, error) {
stats, err := c.statsClient.DumpStats(SystemStatsPrefix)
if err != nil {
return nil, err
}
sysStats := &api.SystemStats{}
for _, stat := range stats {
switch stat.Name {
case SystemStats_VectorRate:
sysStats.VectorRate = scalarStatToFloat64(stat.Data)
case SystemStats_InputRate:
sysStats.InputRate = scalarStatToFloat64(stat.Data)
case SystemStats_LastUpdate:
sysStats.LastUpdate = scalarStatToFloat64(stat.Data)
case SystemStats_LastStatsClear:
sysStats.LastStatsClear = scalarStatToFloat64(stat.Data)
case SystemStats_Heartbeat:
sysStats.Heartbeat = scalarStatToFloat64(stat.Data)
}
}
return sysStats, nil
} | go | func (c *StatsConnection) GetSystemStats() (*api.SystemStats, error) {
stats, err := c.statsClient.DumpStats(SystemStatsPrefix)
if err != nil {
return nil, err
}
sysStats := &api.SystemStats{}
for _, stat := range stats {
switch stat.Name {
case SystemStats_VectorRate:
sysStats.VectorRate = scalarStatToFloat64(stat.Data)
case SystemStats_InputRate:
sysStats.InputRate = scalarStatToFloat64(stat.Data)
case SystemStats_LastUpdate:
sysStats.LastUpdate = scalarStatToFloat64(stat.Data)
case SystemStats_LastStatsClear:
sysStats.LastStatsClear = scalarStatToFloat64(stat.Data)
case SystemStats_Heartbeat:
sysStats.Heartbeat = scalarStatToFloat64(stat.Data)
}
}
return sysStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetSystemStats",
"(",
")",
"(",
"*",
"api",
".",
"SystemStats",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"SystemStatsPrefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"sysStats",
":=",
"&",
"api",
".",
"SystemStats",
"{",
"}",
"\n\n",
"for",
"_",
",",
"stat",
":=",
"range",
"stats",
"{",
"switch",
"stat",
".",
"Name",
"{",
"case",
"SystemStats_VectorRate",
":",
"sysStats",
".",
"VectorRate",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"case",
"SystemStats_InputRate",
":",
"sysStats",
".",
"InputRate",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"case",
"SystemStats_LastUpdate",
":",
"sysStats",
".",
"LastUpdate",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"case",
"SystemStats_LastStatsClear",
":",
"sysStats",
".",
"LastStatsClear",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"case",
"SystemStats_Heartbeat",
":",
"sysStats",
".",
"Heartbeat",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"sysStats",
",",
"nil",
"\n",
"}"
] | // GetSystemStats retrieves VPP system stats. | [
"GetSystemStats",
"retrieves",
"VPP",
"system",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L121-L145 |
12,606 | FDio/govpp | core/stats.go | GetErrorStats | func (c *StatsConnection) GetErrorStats(names ...string) (*api.ErrorStats, error) {
var patterns []string
if len(names) > 0 {
patterns = make([]string, len(names))
for i, name := range names {
patterns[i] = CounterStatsPrefix + name
}
} else {
// retrieve all error counters by default
patterns = []string{CounterStatsPrefix}
}
stats, err := c.statsClient.DumpStats(patterns...)
if err != nil {
return nil, err
}
var errorStats = &api.ErrorStats{}
for _, stat := range stats {
statName := strings.TrimPrefix(stat.Name, CounterStatsPrefix)
/* TODO: deal with stats that contain '/' in node/counter name
parts := strings.Split(statName, "/")
var nodeName, counterName string
switch len(parts) {
case 2:
nodeName = parts[0]
counterName = parts[1]
case 3:
nodeName = parts[0] + parts[1]
counterName = parts[2]
}*/
errorStats.Errors = append(errorStats.Errors, api.ErrorCounter{
CounterName: statName,
Value: errorStatToUint64(stat.Data),
})
}
return errorStats, nil
} | go | func (c *StatsConnection) GetErrorStats(names ...string) (*api.ErrorStats, error) {
var patterns []string
if len(names) > 0 {
patterns = make([]string, len(names))
for i, name := range names {
patterns[i] = CounterStatsPrefix + name
}
} else {
// retrieve all error counters by default
patterns = []string{CounterStatsPrefix}
}
stats, err := c.statsClient.DumpStats(patterns...)
if err != nil {
return nil, err
}
var errorStats = &api.ErrorStats{}
for _, stat := range stats {
statName := strings.TrimPrefix(stat.Name, CounterStatsPrefix)
/* TODO: deal with stats that contain '/' in node/counter name
parts := strings.Split(statName, "/")
var nodeName, counterName string
switch len(parts) {
case 2:
nodeName = parts[0]
counterName = parts[1]
case 3:
nodeName = parts[0] + parts[1]
counterName = parts[2]
}*/
errorStats.Errors = append(errorStats.Errors, api.ErrorCounter{
CounterName: statName,
Value: errorStatToUint64(stat.Data),
})
}
return errorStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetErrorStats",
"(",
"names",
"...",
"string",
")",
"(",
"*",
"api",
".",
"ErrorStats",
",",
"error",
")",
"{",
"var",
"patterns",
"[",
"]",
"string",
"\n",
"if",
"len",
"(",
"names",
")",
">",
"0",
"{",
"patterns",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
"i",
",",
"name",
":=",
"range",
"names",
"{",
"patterns",
"[",
"i",
"]",
"=",
"CounterStatsPrefix",
"+",
"name",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// retrieve all error counters by default",
"patterns",
"=",
"[",
"]",
"string",
"{",
"CounterStatsPrefix",
"}",
"\n",
"}",
"\n",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"patterns",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"errorStats",
"=",
"&",
"api",
".",
"ErrorStats",
"{",
"}",
"\n\n",
"for",
"_",
",",
"stat",
":=",
"range",
"stats",
"{",
"statName",
":=",
"strings",
".",
"TrimPrefix",
"(",
"stat",
".",
"Name",
",",
"CounterStatsPrefix",
")",
"\n\n",
"/* TODO: deal with stats that contain '/' in node/counter name\n\t\tparts := strings.Split(statName, \"/\")\n\t\tvar nodeName, counterName string\n\t\tswitch len(parts) {\n\t\tcase 2:\n\t\t\tnodeName = parts[0]\n\t\t\tcounterName = parts[1]\n\t\tcase 3:\n\t\t\tnodeName = parts[0] + parts[1]\n\t\t\tcounterName = parts[2]\n\t\t}*/",
"errorStats",
".",
"Errors",
"=",
"append",
"(",
"errorStats",
".",
"Errors",
",",
"api",
".",
"ErrorCounter",
"{",
"CounterName",
":",
"statName",
",",
"Value",
":",
"errorStatToUint64",
"(",
"stat",
".",
"Data",
")",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"errorStats",
",",
"nil",
"\n",
"}"
] | // GetErrorStats retrieves VPP error stats. | [
"GetErrorStats",
"retrieves",
"VPP",
"error",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L148-L188 |
12,607 | FDio/govpp | core/stats.go | GetNodeStats | func (c *StatsConnection) GetNodeStats() (*api.NodeStats, error) {
stats, err := c.statsClient.DumpStats(NodeStatsPrefix)
if err != nil {
return nil, err
}
nodeStats := &api.NodeStats{}
var setPerNode = func(perNode []uint64, fn func(c *api.NodeCounters, v uint64)) {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(perNode))
for i := range perNode {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, v := range perNode {
if len(nodeStats.Nodes) <= i {
break
}
nodeCounters := nodeStats.Nodes[i]
fn(&nodeCounters, v)
nodeStats.Nodes[i] = nodeCounters
}
}
for _, stat := range stats {
switch stat.Name {
case NodeStats_Names:
if names, ok := stat.Data.(adapter.NameStat); !ok {
return nil, fmt.Errorf("invalid stat type for %s", stat.Name)
} else {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(names))
for i := range names {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, name := range names {
nodeStats.Nodes[i].NodeName = string(name)
}
}
case NodeStats_Clocks:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Clocks = v
})
case NodeStats_Vectors:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Vectors = v
})
case NodeStats_Calls:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Calls = v
})
case NodeStats_Suspends:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Suspends = v
})
}
}
return nodeStats, nil
} | go | func (c *StatsConnection) GetNodeStats() (*api.NodeStats, error) {
stats, err := c.statsClient.DumpStats(NodeStatsPrefix)
if err != nil {
return nil, err
}
nodeStats := &api.NodeStats{}
var setPerNode = func(perNode []uint64, fn func(c *api.NodeCounters, v uint64)) {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(perNode))
for i := range perNode {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, v := range perNode {
if len(nodeStats.Nodes) <= i {
break
}
nodeCounters := nodeStats.Nodes[i]
fn(&nodeCounters, v)
nodeStats.Nodes[i] = nodeCounters
}
}
for _, stat := range stats {
switch stat.Name {
case NodeStats_Names:
if names, ok := stat.Data.(adapter.NameStat); !ok {
return nil, fmt.Errorf("invalid stat type for %s", stat.Name)
} else {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(names))
for i := range names {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, name := range names {
nodeStats.Nodes[i].NodeName = string(name)
}
}
case NodeStats_Clocks:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Clocks = v
})
case NodeStats_Vectors:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Vectors = v
})
case NodeStats_Calls:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Calls = v
})
case NodeStats_Suspends:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Suspends = v
})
}
}
return nodeStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetNodeStats",
"(",
")",
"(",
"*",
"api",
".",
"NodeStats",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"NodeStatsPrefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"nodeStats",
":=",
"&",
"api",
".",
"NodeStats",
"{",
"}",
"\n\n",
"var",
"setPerNode",
"=",
"func",
"(",
"perNode",
"[",
"]",
"uint64",
",",
"fn",
"func",
"(",
"c",
"*",
"api",
".",
"NodeCounters",
",",
"v",
"uint64",
")",
")",
"{",
"if",
"nodeStats",
".",
"Nodes",
"==",
"nil",
"{",
"nodeStats",
".",
"Nodes",
"=",
"make",
"(",
"[",
"]",
"api",
".",
"NodeCounters",
",",
"len",
"(",
"perNode",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"perNode",
"{",
"nodeStats",
".",
"Nodes",
"[",
"i",
"]",
".",
"NodeIndex",
"=",
"uint32",
"(",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"perNode",
"{",
"if",
"len",
"(",
"nodeStats",
".",
"Nodes",
")",
"<=",
"i",
"{",
"break",
"\n",
"}",
"\n",
"nodeCounters",
":=",
"nodeStats",
".",
"Nodes",
"[",
"i",
"]",
"\n",
"fn",
"(",
"&",
"nodeCounters",
",",
"v",
")",
"\n",
"nodeStats",
".",
"Nodes",
"[",
"i",
"]",
"=",
"nodeCounters",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"stat",
":=",
"range",
"stats",
"{",
"switch",
"stat",
".",
"Name",
"{",
"case",
"NodeStats_Names",
":",
"if",
"names",
",",
"ok",
":=",
"stat",
".",
"Data",
".",
"(",
"adapter",
".",
"NameStat",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"stat",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"if",
"nodeStats",
".",
"Nodes",
"==",
"nil",
"{",
"nodeStats",
".",
"Nodes",
"=",
"make",
"(",
"[",
"]",
"api",
".",
"NodeCounters",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"names",
"{",
"nodeStats",
".",
"Nodes",
"[",
"i",
"]",
".",
"NodeIndex",
"=",
"uint32",
"(",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
",",
"name",
":=",
"range",
"names",
"{",
"nodeStats",
".",
"Nodes",
"[",
"i",
"]",
".",
"NodeName",
"=",
"string",
"(",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"NodeStats_Clocks",
":",
"setPerNode",
"(",
"reduceSimpleCounterStat",
"(",
"stat",
".",
"Data",
")",
",",
"func",
"(",
"c",
"*",
"api",
".",
"NodeCounters",
",",
"v",
"uint64",
")",
"{",
"c",
".",
"Clocks",
"=",
"v",
"\n",
"}",
")",
"\n",
"case",
"NodeStats_Vectors",
":",
"setPerNode",
"(",
"reduceSimpleCounterStat",
"(",
"stat",
".",
"Data",
")",
",",
"func",
"(",
"c",
"*",
"api",
".",
"NodeCounters",
",",
"v",
"uint64",
")",
"{",
"c",
".",
"Vectors",
"=",
"v",
"\n",
"}",
")",
"\n",
"case",
"NodeStats_Calls",
":",
"setPerNode",
"(",
"reduceSimpleCounterStat",
"(",
"stat",
".",
"Data",
")",
",",
"func",
"(",
"c",
"*",
"api",
".",
"NodeCounters",
",",
"v",
"uint64",
")",
"{",
"c",
".",
"Calls",
"=",
"v",
"\n",
"}",
")",
"\n",
"case",
"NodeStats_Suspends",
":",
"setPerNode",
"(",
"reduceSimpleCounterStat",
"(",
"stat",
".",
"Data",
")",
",",
"func",
"(",
"c",
"*",
"api",
".",
"NodeCounters",
",",
"v",
"uint64",
")",
"{",
"c",
".",
"Suspends",
"=",
"v",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nodeStats",
",",
"nil",
"\n",
"}"
] | // GetNodeStats retrieves VPP per node stats. | [
"GetNodeStats",
"retrieves",
"VPP",
"per",
"node",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L191-L252 |
12,608 | FDio/govpp | core/stats.go | GetBufferStats | func (c *StatsConnection) GetBufferStats() (*api.BufferStats, error) {
stats, err := c.statsClient.DumpStats(BufferStatsPrefix)
if err != nil {
return nil, err
}
bufStats := &api.BufferStats{
Buffer: map[string]api.BufferPool{},
}
for _, stat := range stats {
d, f := path.Split(stat.Name)
d = strings.TrimSuffix(d, "/")
name := strings.TrimPrefix(d, BufferStatsPrefix)
b, ok := bufStats.Buffer[name]
if !ok {
b.PoolName = name
}
switch f {
case BufferStats_Cached:
b.Cached = scalarStatToFloat64(stat.Data)
case BufferStats_Used:
b.Used = scalarStatToFloat64(stat.Data)
case BufferStats_Available:
b.Available = scalarStatToFloat64(stat.Data)
}
bufStats.Buffer[name] = b
}
return bufStats, nil
} | go | func (c *StatsConnection) GetBufferStats() (*api.BufferStats, error) {
stats, err := c.statsClient.DumpStats(BufferStatsPrefix)
if err != nil {
return nil, err
}
bufStats := &api.BufferStats{
Buffer: map[string]api.BufferPool{},
}
for _, stat := range stats {
d, f := path.Split(stat.Name)
d = strings.TrimSuffix(d, "/")
name := strings.TrimPrefix(d, BufferStatsPrefix)
b, ok := bufStats.Buffer[name]
if !ok {
b.PoolName = name
}
switch f {
case BufferStats_Cached:
b.Cached = scalarStatToFloat64(stat.Data)
case BufferStats_Used:
b.Used = scalarStatToFloat64(stat.Data)
case BufferStats_Available:
b.Available = scalarStatToFloat64(stat.Data)
}
bufStats.Buffer[name] = b
}
return bufStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetBufferStats",
"(",
")",
"(",
"*",
"api",
".",
"BufferStats",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"BufferStatsPrefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"bufStats",
":=",
"&",
"api",
".",
"BufferStats",
"{",
"Buffer",
":",
"map",
"[",
"string",
"]",
"api",
".",
"BufferPool",
"{",
"}",
",",
"}",
"\n\n",
"for",
"_",
",",
"stat",
":=",
"range",
"stats",
"{",
"d",
",",
"f",
":=",
"path",
".",
"Split",
"(",
"stat",
".",
"Name",
")",
"\n",
"d",
"=",
"strings",
".",
"TrimSuffix",
"(",
"d",
",",
"\"",
"\"",
")",
"\n\n",
"name",
":=",
"strings",
".",
"TrimPrefix",
"(",
"d",
",",
"BufferStatsPrefix",
")",
"\n",
"b",
",",
"ok",
":=",
"bufStats",
".",
"Buffer",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"b",
".",
"PoolName",
"=",
"name",
"\n",
"}",
"\n\n",
"switch",
"f",
"{",
"case",
"BufferStats_Cached",
":",
"b",
".",
"Cached",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"case",
"BufferStats_Used",
":",
"b",
".",
"Used",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"case",
"BufferStats_Available",
":",
"b",
".",
"Available",
"=",
"scalarStatToFloat64",
"(",
"stat",
".",
"Data",
")",
"\n",
"}",
"\n\n",
"bufStats",
".",
"Buffer",
"[",
"name",
"]",
"=",
"b",
"\n",
"}",
"\n\n",
"return",
"bufStats",
",",
"nil",
"\n",
"}"
] | // GetBufferStats retrieves VPP buffer pools stats. | [
"GetBufferStats",
"retrieves",
"VPP",
"buffer",
"pools",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L399-L432 |
12,609 | FDio/govpp | codec/msg_codec.go | EncodeMsg | func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
if msg == nil {
return nil, errors.New("nil message passed in")
}
// try to recover panic which might possibly occur in struc.Pack call
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
err = fmt.Errorf("%v", r)
}
err = fmt.Errorf("panic occurred: %v", err)
}
}()
var header interface{}
// encode message header
switch msg.GetMessageType() {
case api.RequestMessage:
header = &VppRequestHeader{VlMsgID: msgID}
case api.ReplyMessage:
header = &VppReplyHeader{VlMsgID: msgID}
case api.EventMessage:
header = &VppEventHeader{VlMsgID: msgID}
default:
header = &VppOtherHeader{VlMsgID: msgID}
}
buf := new(bytes.Buffer)
// encode message header
if err := struc.Pack(buf, header); err != nil {
return nil, fmt.Errorf("failed to encode message header: %+v, error: %v", header, err)
}
// encode message content
if reflect.TypeOf(msg).Elem().NumField() > 0 {
if err := struc.Pack(buf, msg); err != nil {
return nil, fmt.Errorf("failed to encode message data: %+v, error: %v", data, err)
}
}
return buf.Bytes(), nil
} | go | func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
if msg == nil {
return nil, errors.New("nil message passed in")
}
// try to recover panic which might possibly occur in struc.Pack call
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
err = fmt.Errorf("%v", r)
}
err = fmt.Errorf("panic occurred: %v", err)
}
}()
var header interface{}
// encode message header
switch msg.GetMessageType() {
case api.RequestMessage:
header = &VppRequestHeader{VlMsgID: msgID}
case api.ReplyMessage:
header = &VppReplyHeader{VlMsgID: msgID}
case api.EventMessage:
header = &VppEventHeader{VlMsgID: msgID}
default:
header = &VppOtherHeader{VlMsgID: msgID}
}
buf := new(bytes.Buffer)
// encode message header
if err := struc.Pack(buf, header); err != nil {
return nil, fmt.Errorf("failed to encode message header: %+v, error: %v", header, err)
}
// encode message content
if reflect.TypeOf(msg).Elem().NumField() > 0 {
if err := struc.Pack(buf, msg); err != nil {
return nil, fmt.Errorf("failed to encode message data: %+v, error: %v", data, err)
}
}
return buf.Bytes(), nil
} | [
"func",
"(",
"*",
"MsgCodec",
")",
"EncodeMsg",
"(",
"msg",
"api",
".",
"Message",
",",
"msgID",
"uint16",
")",
"(",
"data",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"if",
"msg",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// try to recover panic which might possibly occur in struc.Pack call",
"defer",
"func",
"(",
")",
"{",
"if",
"r",
":=",
"recover",
"(",
")",
";",
"r",
"!=",
"nil",
"{",
"var",
"ok",
"bool",
"\n",
"if",
"err",
",",
"ok",
"=",
"r",
".",
"(",
"error",
")",
";",
"!",
"ok",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"r",
")",
"\n",
"}",
"\n",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"header",
"interface",
"{",
"}",
"\n\n",
"// encode message header",
"switch",
"msg",
".",
"GetMessageType",
"(",
")",
"{",
"case",
"api",
".",
"RequestMessage",
":",
"header",
"=",
"&",
"VppRequestHeader",
"{",
"VlMsgID",
":",
"msgID",
"}",
"\n",
"case",
"api",
".",
"ReplyMessage",
":",
"header",
"=",
"&",
"VppReplyHeader",
"{",
"VlMsgID",
":",
"msgID",
"}",
"\n",
"case",
"api",
".",
"EventMessage",
":",
"header",
"=",
"&",
"VppEventHeader",
"{",
"VlMsgID",
":",
"msgID",
"}",
"\n",
"default",
":",
"header",
"=",
"&",
"VppOtherHeader",
"{",
"VlMsgID",
":",
"msgID",
"}",
"\n",
"}",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n\n",
"// encode message header",
"if",
"err",
":=",
"struc",
".",
"Pack",
"(",
"buf",
",",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"header",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// encode message content",
"if",
"reflect",
".",
"TypeOf",
"(",
"msg",
")",
".",
"Elem",
"(",
")",
".",
"NumField",
"(",
")",
">",
"0",
"{",
"if",
"err",
":=",
"struc",
".",
"Pack",
"(",
"buf",
",",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"data",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // EncodeMsg encodes provided `Message` structure into its binary-encoded data representation. | [
"EncodeMsg",
"encodes",
"provided",
"Message",
"structure",
"into",
"its",
"binary",
"-",
"encoded",
"data",
"representation",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/codec/msg_codec.go#L56-L101 |
12,610 | FDio/govpp | codec/msg_codec.go | DecodeMsg | func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) error {
if msg == nil {
return errors.New("nil message passed in")
}
var header interface{}
// check which header is expected
switch msg.GetMessageType() {
case api.RequestMessage:
header = new(VppRequestHeader)
case api.ReplyMessage:
header = new(VppReplyHeader)
case api.EventMessage:
header = new(VppEventHeader)
default:
header = new(VppOtherHeader)
}
buf := bytes.NewReader(data)
// decode message header
if err := struc.Unpack(buf, header); err != nil {
return fmt.Errorf("failed to decode message header: %+v, error: %v", header, err)
}
// decode message content
if err := struc.Unpack(buf, msg); err != nil {
return fmt.Errorf("failed to decode message data: %+v, error: %v", data, err)
}
return nil
} | go | func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) error {
if msg == nil {
return errors.New("nil message passed in")
}
var header interface{}
// check which header is expected
switch msg.GetMessageType() {
case api.RequestMessage:
header = new(VppRequestHeader)
case api.ReplyMessage:
header = new(VppReplyHeader)
case api.EventMessage:
header = new(VppEventHeader)
default:
header = new(VppOtherHeader)
}
buf := bytes.NewReader(data)
// decode message header
if err := struc.Unpack(buf, header); err != nil {
return fmt.Errorf("failed to decode message header: %+v, error: %v", header, err)
}
// decode message content
if err := struc.Unpack(buf, msg); err != nil {
return fmt.Errorf("failed to decode message data: %+v, error: %v", data, err)
}
return nil
} | [
"func",
"(",
"*",
"MsgCodec",
")",
"DecodeMsg",
"(",
"data",
"[",
"]",
"byte",
",",
"msg",
"api",
".",
"Message",
")",
"error",
"{",
"if",
"msg",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"header",
"interface",
"{",
"}",
"\n\n",
"// check which header is expected",
"switch",
"msg",
".",
"GetMessageType",
"(",
")",
"{",
"case",
"api",
".",
"RequestMessage",
":",
"header",
"=",
"new",
"(",
"VppRequestHeader",
")",
"\n",
"case",
"api",
".",
"ReplyMessage",
":",
"header",
"=",
"new",
"(",
"VppReplyHeader",
")",
"\n",
"case",
"api",
".",
"EventMessage",
":",
"header",
"=",
"new",
"(",
"VppEventHeader",
")",
"\n",
"default",
":",
"header",
"=",
"new",
"(",
"VppOtherHeader",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"bytes",
".",
"NewReader",
"(",
"data",
")",
"\n\n",
"// decode message header",
"if",
"err",
":=",
"struc",
".",
"Unpack",
"(",
"buf",
",",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"header",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// decode message content",
"if",
"err",
":=",
"struc",
".",
"Unpack",
"(",
"buf",
",",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"data",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DecodeMsg decodes binary-encoded data of a message into provided `Message` structure. | [
"DecodeMsg",
"decodes",
"binary",
"-",
"encoded",
"data",
"of",
"a",
"message",
"into",
"provided",
"Message",
"structure",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/codec/msg_codec.go#L104-L136 |
12,611 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | findFieldOfType | func findFieldOfType(reply reflect.Type, fieldName string) (reflect.StructField, bool) {
for reply.Kind() == reflect.Ptr {
reply = reply.Elem()
}
if reply.Kind() == reflect.Struct {
field, found := reply.FieldByName(fieldName)
return field, found
}
return reflect.StructField{}, false
} | go | func findFieldOfType(reply reflect.Type, fieldName string) (reflect.StructField, bool) {
for reply.Kind() == reflect.Ptr {
reply = reply.Elem()
}
if reply.Kind() == reflect.Struct {
field, found := reply.FieldByName(fieldName)
return field, found
}
return reflect.StructField{}, false
} | [
"func",
"findFieldOfType",
"(",
"reply",
"reflect",
".",
"Type",
",",
"fieldName",
"string",
")",
"(",
"reflect",
".",
"StructField",
",",
"bool",
")",
"{",
"for",
"reply",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"reply",
"=",
"reply",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"reply",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"field",
",",
"found",
":=",
"reply",
".",
"FieldByName",
"(",
"fieldName",
")",
"\n",
"return",
"field",
",",
"found",
"\n",
"}",
"\n",
"return",
"reflect",
".",
"StructField",
"{",
"}",
",",
"false",
"\n",
"}"
] | // findFieldOfType finds the field specified by its name in provided message defined as reflect.Type data type. | [
"findFieldOfType",
"finds",
"the",
"field",
"specified",
"by",
"its",
"name",
"in",
"provided",
"message",
"defined",
"as",
"reflect",
".",
"Type",
"data",
"type",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L28-L37 |
12,612 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | findFieldOfValue | func findFieldOfValue(reply reflect.Value, fieldName string) (reflect.Value, bool) {
if reply.Kind() == reflect.Struct {
field := reply.FieldByName(fieldName)
return field, field.IsValid()
} else if reply.Kind() == reflect.Ptr && reply.Elem().Kind() == reflect.Struct {
field := reply.Elem().FieldByName(fieldName)
return field, field.IsValid()
}
return reflect.Value{}, false
} | go | func findFieldOfValue(reply reflect.Value, fieldName string) (reflect.Value, bool) {
if reply.Kind() == reflect.Struct {
field := reply.FieldByName(fieldName)
return field, field.IsValid()
} else if reply.Kind() == reflect.Ptr && reply.Elem().Kind() == reflect.Struct {
field := reply.Elem().FieldByName(fieldName)
return field, field.IsValid()
}
return reflect.Value{}, false
} | [
"func",
"findFieldOfValue",
"(",
"reply",
"reflect",
".",
"Value",
",",
"fieldName",
"string",
")",
"(",
"reflect",
".",
"Value",
",",
"bool",
")",
"{",
"if",
"reply",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"field",
":=",
"reply",
".",
"FieldByName",
"(",
"fieldName",
")",
"\n",
"return",
"field",
",",
"field",
".",
"IsValid",
"(",
")",
"\n",
"}",
"else",
"if",
"reply",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"&&",
"reply",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"field",
":=",
"reply",
".",
"Elem",
"(",
")",
".",
"FieldByName",
"(",
"fieldName",
")",
"\n",
"return",
"field",
",",
"field",
".",
"IsValid",
"(",
")",
"\n",
"}",
"\n",
"return",
"reflect",
".",
"Value",
"{",
"}",
",",
"false",
"\n",
"}"
] | // findFieldOfValue finds the field specified by its name in provided message defined as reflect.Value data type. | [
"findFieldOfValue",
"finds",
"the",
"field",
"specified",
"by",
"its",
"name",
"in",
"provided",
"message",
"defined",
"as",
"reflect",
".",
"Value",
"data",
"type",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L40-L49 |
12,613 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | HasSwIfIdx | func HasSwIfIdx(msg reflect.Type) bool {
_, found := findFieldOfType(msg, swIfIndexName)
return found
} | go | func HasSwIfIdx(msg reflect.Type) bool {
_, found := findFieldOfType(msg, swIfIndexName)
return found
} | [
"func",
"HasSwIfIdx",
"(",
"msg",
"reflect",
".",
"Type",
")",
"bool",
"{",
"_",
",",
"found",
":=",
"findFieldOfType",
"(",
"msg",
",",
"swIfIndexName",
")",
"\n",
"return",
"found",
"\n",
"}"
] | // HasSwIfIdx checks whether provided message has the swIfIndex field. | [
"HasSwIfIdx",
"checks",
"whether",
"provided",
"message",
"has",
"the",
"swIfIndex",
"field",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L52-L55 |
12,614 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | SetSwIfIdx | func SetSwIfIdx(msg reflect.Value, swIfIndex uint32) {
if field, found := findFieldOfValue(msg, swIfIndexName); found {
field.Set(reflect.ValueOf(swIfIndex))
}
} | go | func SetSwIfIdx(msg reflect.Value, swIfIndex uint32) {
if field, found := findFieldOfValue(msg, swIfIndexName); found {
field.Set(reflect.ValueOf(swIfIndex))
}
} | [
"func",
"SetSwIfIdx",
"(",
"msg",
"reflect",
".",
"Value",
",",
"swIfIndex",
"uint32",
")",
"{",
"if",
"field",
",",
"found",
":=",
"findFieldOfValue",
"(",
"msg",
",",
"swIfIndexName",
")",
";",
"found",
"{",
"field",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"swIfIndex",
")",
")",
"\n",
"}",
"\n",
"}"
] | // SetSwIfIdx sets the swIfIndex field of provided message to provided value. | [
"SetSwIfIdx",
"sets",
"the",
"swIfIndex",
"field",
"of",
"provided",
"message",
"to",
"provided",
"value",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L58-L62 |
12,615 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | SetRetval | func SetRetval(msg reflect.Value, retVal int32) {
if field, found := findFieldOfValue(msg, retvalName); found {
field.Set(reflect.ValueOf(retVal))
}
} | go | func SetRetval(msg reflect.Value, retVal int32) {
if field, found := findFieldOfValue(msg, retvalName); found {
field.Set(reflect.ValueOf(retVal))
}
} | [
"func",
"SetRetval",
"(",
"msg",
"reflect",
".",
"Value",
",",
"retVal",
"int32",
")",
"{",
"if",
"field",
",",
"found",
":=",
"findFieldOfValue",
"(",
"msg",
",",
"retvalName",
")",
";",
"found",
"{",
"field",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"retVal",
")",
")",
"\n",
"}",
"\n",
"}"
] | // SetRetval sets the retval field of provided message to provided value. | [
"SetRetval",
"sets",
"the",
"retval",
"field",
"of",
"provided",
"message",
"to",
"provided",
"value",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L65-L69 |
12,616 | FDio/govpp | cmd/binapi-generator/generate.go | getContext | func getContext(inputFile, outputDir string) (*context, error) {
if !strings.HasSuffix(inputFile, inputFileExt) {
return nil, fmt.Errorf("invalid input file name: %q", inputFile)
}
ctx := &context{
inputFile: inputFile,
}
// package name
inputFileName := filepath.Base(inputFile)
ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
// alter package names for modules that are reserved keywords in Go
switch ctx.moduleName {
case "interface":
ctx.packageName = "interfaces"
case "map":
ctx.packageName = "maps"
default:
ctx.packageName = ctx.moduleName
}
// output file
packageDir := filepath.Join(outputDir, ctx.packageName)
outputFileName := ctx.packageName + outputFileExt
ctx.outputFile = filepath.Join(packageDir, outputFileName)
return ctx, nil
} | go | func getContext(inputFile, outputDir string) (*context, error) {
if !strings.HasSuffix(inputFile, inputFileExt) {
return nil, fmt.Errorf("invalid input file name: %q", inputFile)
}
ctx := &context{
inputFile: inputFile,
}
// package name
inputFileName := filepath.Base(inputFile)
ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
// alter package names for modules that are reserved keywords in Go
switch ctx.moduleName {
case "interface":
ctx.packageName = "interfaces"
case "map":
ctx.packageName = "maps"
default:
ctx.packageName = ctx.moduleName
}
// output file
packageDir := filepath.Join(outputDir, ctx.packageName)
outputFileName := ctx.packageName + outputFileExt
ctx.outputFile = filepath.Join(packageDir, outputFileName)
return ctx, nil
} | [
"func",
"getContext",
"(",
"inputFile",
",",
"outputDir",
"string",
")",
"(",
"*",
"context",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"inputFile",
",",
"inputFileExt",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"inputFile",
")",
"\n",
"}",
"\n\n",
"ctx",
":=",
"&",
"context",
"{",
"inputFile",
":",
"inputFile",
",",
"}",
"\n\n",
"// package name",
"inputFileName",
":=",
"filepath",
".",
"Base",
"(",
"inputFile",
")",
"\n",
"ctx",
".",
"moduleName",
"=",
"inputFileName",
"[",
":",
"strings",
".",
"Index",
"(",
"inputFileName",
",",
"\"",
"\"",
")",
"]",
"\n\n",
"// alter package names for modules that are reserved keywords in Go",
"switch",
"ctx",
".",
"moduleName",
"{",
"case",
"\"",
"\"",
":",
"ctx",
".",
"packageName",
"=",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
":",
"ctx",
".",
"packageName",
"=",
"\"",
"\"",
"\n",
"default",
":",
"ctx",
".",
"packageName",
"=",
"ctx",
".",
"moduleName",
"\n",
"}",
"\n\n",
"// output file",
"packageDir",
":=",
"filepath",
".",
"Join",
"(",
"outputDir",
",",
"ctx",
".",
"packageName",
")",
"\n",
"outputFileName",
":=",
"ctx",
".",
"packageName",
"+",
"outputFileExt",
"\n",
"ctx",
".",
"outputFile",
"=",
"filepath",
".",
"Join",
"(",
"packageDir",
",",
"outputFileName",
")",
"\n\n",
"return",
"ctx",
",",
"nil",
"\n",
"}"
] | // getContext returns context details of the code generation task | [
"getContext",
"returns",
"context",
"details",
"of",
"the",
"code",
"generation",
"task"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L52-L81 |
12,617 | FDio/govpp | cmd/binapi-generator/generate.go | generatePackage | func generatePackage(ctx *context, w *bufio.Writer) error {
logf("generating package %q", ctx.packageName)
// generate file header
generateHeader(ctx, w)
generateImports(ctx, w)
if ctx.includeAPIVersionCrc {
fmt.Fprintf(w, "// %s defines API version CRC of the VPP binary API module.\n", constAPIVersionCrc)
fmt.Fprintf(w, "const %s = %v\n", constAPIVersionCrc, ctx.packageData.APIVersion)
fmt.Fprintln(w)
}
// generate services
if len(ctx.packageData.Services) > 0 {
generateServices(ctx, w, ctx.packageData.Services)
// TODO: generate implementation for Services interface
}
// generate enums
if len(ctx.packageData.Enums) > 0 {
fmt.Fprintf(w, "/* Enums */\n\n")
for _, enum := range ctx.packageData.Enums {
generateEnum(ctx, w, &enum)
}
}
// generate aliases
if len(ctx.packageData.Aliases) > 0 {
fmt.Fprintf(w, "/* Aliases */\n\n")
for _, alias := range ctx.packageData.Aliases {
generateAlias(ctx, w, &alias)
}
}
// generate types
if len(ctx.packageData.Types) > 0 {
fmt.Fprintf(w, "/* Types */\n\n")
for _, typ := range ctx.packageData.Types {
generateType(ctx, w, &typ)
}
}
// generate unions
if len(ctx.packageData.Unions) > 0 {
fmt.Fprintf(w, "/* Unions */\n\n")
for _, union := range ctx.packageData.Unions {
generateUnion(ctx, w, &union)
}
}
// generate messages
if len(ctx.packageData.Messages) > 0 {
fmt.Fprintf(w, "/* Messages */\n\n")
for _, msg := range ctx.packageData.Messages {
generateMessage(ctx, w, &msg)
}
// generate message registrations
fmt.Fprintln(w, "func init() {")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
fmt.Fprintln(w, "var Messages = []api.Message{")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\t(*%s)(nil),\n", name)
}
fmt.Fprintln(w, "}")
}
// flush the data:
if err := w.Flush(); err != nil {
return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
}
return nil
} | go | func generatePackage(ctx *context, w *bufio.Writer) error {
logf("generating package %q", ctx.packageName)
// generate file header
generateHeader(ctx, w)
generateImports(ctx, w)
if ctx.includeAPIVersionCrc {
fmt.Fprintf(w, "// %s defines API version CRC of the VPP binary API module.\n", constAPIVersionCrc)
fmt.Fprintf(w, "const %s = %v\n", constAPIVersionCrc, ctx.packageData.APIVersion)
fmt.Fprintln(w)
}
// generate services
if len(ctx.packageData.Services) > 0 {
generateServices(ctx, w, ctx.packageData.Services)
// TODO: generate implementation for Services interface
}
// generate enums
if len(ctx.packageData.Enums) > 0 {
fmt.Fprintf(w, "/* Enums */\n\n")
for _, enum := range ctx.packageData.Enums {
generateEnum(ctx, w, &enum)
}
}
// generate aliases
if len(ctx.packageData.Aliases) > 0 {
fmt.Fprintf(w, "/* Aliases */\n\n")
for _, alias := range ctx.packageData.Aliases {
generateAlias(ctx, w, &alias)
}
}
// generate types
if len(ctx.packageData.Types) > 0 {
fmt.Fprintf(w, "/* Types */\n\n")
for _, typ := range ctx.packageData.Types {
generateType(ctx, w, &typ)
}
}
// generate unions
if len(ctx.packageData.Unions) > 0 {
fmt.Fprintf(w, "/* Unions */\n\n")
for _, union := range ctx.packageData.Unions {
generateUnion(ctx, w, &union)
}
}
// generate messages
if len(ctx.packageData.Messages) > 0 {
fmt.Fprintf(w, "/* Messages */\n\n")
for _, msg := range ctx.packageData.Messages {
generateMessage(ctx, w, &msg)
}
// generate message registrations
fmt.Fprintln(w, "func init() {")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
fmt.Fprintln(w, "var Messages = []api.Message{")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\t(*%s)(nil),\n", name)
}
fmt.Fprintln(w, "}")
}
// flush the data:
if err := w.Flush(); err != nil {
return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
}
return nil
} | [
"func",
"generatePackage",
"(",
"ctx",
"*",
"context",
",",
"w",
"*",
"bufio",
".",
"Writer",
")",
"error",
"{",
"logf",
"(",
"\"",
"\"",
",",
"ctx",
".",
"packageName",
")",
"\n\n",
"// generate file header",
"generateHeader",
"(",
"ctx",
",",
"w",
")",
"\n",
"generateImports",
"(",
"ctx",
",",
"w",
")",
"\n\n",
"if",
"ctx",
".",
"includeAPIVersionCrc",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"constAPIVersionCrc",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"constAPIVersionCrc",
",",
"ctx",
".",
"packageData",
".",
"APIVersion",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}",
"\n\n",
"// generate services",
"if",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Services",
")",
">",
"0",
"{",
"generateServices",
"(",
"ctx",
",",
"w",
",",
"ctx",
".",
"packageData",
".",
"Services",
")",
"\n\n",
"// TODO: generate implementation for Services interface",
"}",
"\n\n",
"// generate enums",
"if",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Enums",
")",
">",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"for",
"_",
",",
"enum",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Enums",
"{",
"generateEnum",
"(",
"ctx",
",",
"w",
",",
"&",
"enum",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// generate aliases",
"if",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Aliases",
")",
">",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"for",
"_",
",",
"alias",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Aliases",
"{",
"generateAlias",
"(",
"ctx",
",",
"w",
",",
"&",
"alias",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// generate types",
"if",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Types",
")",
">",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"for",
"_",
",",
"typ",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Types",
"{",
"generateType",
"(",
"ctx",
",",
"w",
",",
"&",
"typ",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// generate unions",
"if",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Unions",
")",
">",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"for",
"_",
",",
"union",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Unions",
"{",
"generateUnion",
"(",
"ctx",
",",
"w",
",",
"&",
"union",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// generate messages",
"if",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Messages",
")",
">",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"for",
"_",
",",
"msg",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Messages",
"{",
"generateMessage",
"(",
"ctx",
",",
"w",
",",
"&",
"msg",
")",
"\n",
"}",
"\n\n",
"// generate message registrations",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Messages",
"{",
"name",
":=",
"camelCaseName",
"(",
"msg",
".",
"Name",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"name",
",",
"ctx",
".",
"moduleName",
"+",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"ctx",
".",
"packageData",
".",
"Messages",
"{",
"name",
":=",
"camelCaseName",
"(",
"msg",
".",
"Name",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\n",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// flush the data:",
"if",
"err",
":=",
"w",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ctx",
".",
"outputFile",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // generatePackage generates code for the parsed package data and writes it into w | [
"generatePackage",
"generates",
"code",
"for",
"the",
"parsed",
"package",
"data",
"and",
"writes",
"it",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L84-L171 |
12,618 | FDio/govpp | cmd/binapi-generator/generate.go | generateHeader | func generateHeader(ctx *context, w io.Writer) {
fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
fmt.Fprintln(w)
fmt.Fprintln(w, "/*")
fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
fmt.Fprintln(w)
fmt.Fprintln(w, " It contains following objects:")
var printObjNum = func(obj string, num int) {
if num > 0 {
if num > 1 {
if strings.HasSuffix(obj, "s") {
obj += "es"
} else {
obj += "s"
}
}
fmt.Fprintf(w, "\t%3d %s\n", num, obj)
}
}
printObjNum("service", len(ctx.packageData.Services))
printObjNum("enum", len(ctx.packageData.Enums))
printObjNum("alias", len(ctx.packageData.Aliases))
printObjNum("type", len(ctx.packageData.Types))
printObjNum("union", len(ctx.packageData.Unions))
printObjNum("message", len(ctx.packageData.Messages))
fmt.Fprintln(w, "*/")
fmt.Fprintf(w, "package %s\n", ctx.packageName)
fmt.Fprintln(w)
} | go | func generateHeader(ctx *context, w io.Writer) {
fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
fmt.Fprintln(w)
fmt.Fprintln(w, "/*")
fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
fmt.Fprintln(w)
fmt.Fprintln(w, " It contains following objects:")
var printObjNum = func(obj string, num int) {
if num > 0 {
if num > 1 {
if strings.HasSuffix(obj, "s") {
obj += "es"
} else {
obj += "s"
}
}
fmt.Fprintf(w, "\t%3d %s\n", num, obj)
}
}
printObjNum("service", len(ctx.packageData.Services))
printObjNum("enum", len(ctx.packageData.Enums))
printObjNum("alias", len(ctx.packageData.Aliases))
printObjNum("type", len(ctx.packageData.Types))
printObjNum("union", len(ctx.packageData.Unions))
printObjNum("message", len(ctx.packageData.Messages))
fmt.Fprintln(w, "*/")
fmt.Fprintf(w, "package %s\n", ctx.packageName)
fmt.Fprintln(w)
} | [
"func",
"generateHeader",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"ctx",
".",
"inputFile",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"ctx",
".",
"packageName",
",",
"ctx",
".",
"moduleName",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"var",
"printObjNum",
"=",
"func",
"(",
"obj",
"string",
",",
"num",
"int",
")",
"{",
"if",
"num",
">",
"0",
"{",
"if",
"num",
">",
"1",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"obj",
",",
"\"",
"\"",
")",
"{",
"obj",
"+=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"obj",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\n",
"\"",
",",
"num",
",",
"obj",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"printObjNum",
"(",
"\"",
"\"",
",",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Services",
")",
")",
"\n",
"printObjNum",
"(",
"\"",
"\"",
",",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Enums",
")",
")",
"\n",
"printObjNum",
"(",
"\"",
"\"",
",",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Aliases",
")",
")",
"\n",
"printObjNum",
"(",
"\"",
"\"",
",",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Types",
")",
")",
"\n",
"printObjNum",
"(",
"\"",
"\"",
",",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Unions",
")",
")",
"\n",
"printObjNum",
"(",
"\"",
"\"",
",",
"len",
"(",
"ctx",
".",
"packageData",
".",
"Messages",
")",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"ctx",
".",
"packageName",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateHeader writes generated package header into w | [
"generateHeader",
"writes",
"generated",
"package",
"header",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L174-L205 |
12,619 | FDio/govpp | cmd/binapi-generator/generate.go | generateImports | func generateImports(ctx *context, w io.Writer) {
fmt.Fprintf(w, "import api \"%s\"\n", govppApiImportPath)
fmt.Fprintf(w, "import struc \"%s\"\n", "github.com/lunixbochs/struc")
fmt.Fprintf(w, "import bytes \"%s\"\n", "bytes")
fmt.Fprintln(w)
fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
fmt.Fprintf(w, "var _ = struc.Pack\n")
fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
fmt.Fprintln(w)
/*fmt.Fprintln(w, "// This is a compile-time assertion to ensure that this generated file")
fmt.Fprintln(w, "// is compatible with the GoVPP api package it is being compiled against.")
fmt.Fprintln(w, "// A compilation error at this line likely means your copy of the")
fmt.Fprintln(w, "// GoVPP api package needs to be updated.")
fmt.Fprintln(w, "const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package")
fmt.Fprintln(w)*/
} | go | func generateImports(ctx *context, w io.Writer) {
fmt.Fprintf(w, "import api \"%s\"\n", govppApiImportPath)
fmt.Fprintf(w, "import struc \"%s\"\n", "github.com/lunixbochs/struc")
fmt.Fprintf(w, "import bytes \"%s\"\n", "bytes")
fmt.Fprintln(w)
fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
fmt.Fprintf(w, "var _ = struc.Pack\n")
fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
fmt.Fprintln(w)
/*fmt.Fprintln(w, "// This is a compile-time assertion to ensure that this generated file")
fmt.Fprintln(w, "// is compatible with the GoVPP api package it is being compiled against.")
fmt.Fprintln(w, "// A compilation error at this line likely means your copy of the")
fmt.Fprintln(w, "// GoVPP api package needs to be updated.")
fmt.Fprintln(w, "const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package")
fmt.Fprintln(w)*/
} | [
"func",
"generateImports",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"govppApiImportPath",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n\n",
"/*fmt.Fprintln(w, \"// This is a compile-time assertion to ensure that this generated file\")\n\tfmt.Fprintln(w, \"// is compatible with the GoVPP api package it is being compiled against.\")\n\tfmt.Fprintln(w, \"// A compilation error at this line likely means your copy of the\")\n\tfmt.Fprintln(w, \"// GoVPP api package needs to be updated.\")\n\tfmt.Fprintln(w, \"const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package\")\n\tfmt.Fprintln(w)*/",
"}"
] | // generateImports writes generated package imports into w | [
"generateImports",
"writes",
"generated",
"package",
"imports",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L208-L226 |
12,620 | FDio/govpp | cmd/binapi-generator/generate.go | generateComment | func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
if objKind == "service" {
fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
} else {
fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
}
if !ctx.includeComments {
return
}
var isNotSpace = func(r rune) bool {
return !unicode.IsSpace(r)
}
// print out the source of the generated object
mapType := false
objFound := false
objTitle := fmt.Sprintf(`"%s",`, vppName)
switch objKind {
case "alias", "service":
objTitle = fmt.Sprintf(`"%s": {`, vppName)
mapType = true
}
inputBuff := bytes.NewBuffer(ctx.inputData)
inputLine := 0
var trimIndent string
var indent int
for {
line, err := inputBuff.ReadString('\n')
if err != nil {
break
}
inputLine++
noSpaceAt := strings.IndexFunc(line, isNotSpace)
if !objFound {
indent = strings.Index(line, objTitle)
if indent == -1 {
continue
}
trimIndent = line[:indent]
// If no other non-whitespace character then we are at the message header.
if trimmed := strings.TrimSpace(line); trimmed == objTitle {
objFound = true
fmt.Fprintln(w, "//")
}
} else if noSpaceAt < indent {
break // end of the definition in JSON for array types
} else if objFound && mapType && noSpaceAt <= indent {
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
break // end of the definition in JSON for map types (aliases, services)
}
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
}
fmt.Fprintln(w, "//")
} | go | func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
if objKind == "service" {
fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
} else {
fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
}
if !ctx.includeComments {
return
}
var isNotSpace = func(r rune) bool {
return !unicode.IsSpace(r)
}
// print out the source of the generated object
mapType := false
objFound := false
objTitle := fmt.Sprintf(`"%s",`, vppName)
switch objKind {
case "alias", "service":
objTitle = fmt.Sprintf(`"%s": {`, vppName)
mapType = true
}
inputBuff := bytes.NewBuffer(ctx.inputData)
inputLine := 0
var trimIndent string
var indent int
for {
line, err := inputBuff.ReadString('\n')
if err != nil {
break
}
inputLine++
noSpaceAt := strings.IndexFunc(line, isNotSpace)
if !objFound {
indent = strings.Index(line, objTitle)
if indent == -1 {
continue
}
trimIndent = line[:indent]
// If no other non-whitespace character then we are at the message header.
if trimmed := strings.TrimSpace(line); trimmed == objTitle {
objFound = true
fmt.Fprintln(w, "//")
}
} else if noSpaceAt < indent {
break // end of the definition in JSON for array types
} else if objFound && mapType && noSpaceAt <= indent {
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
break // end of the definition in JSON for map types (aliases, services)
}
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
}
fmt.Fprintln(w, "//")
} | [
"func",
"generateComment",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"goName",
"string",
",",
"vppName",
"string",
",",
"objKind",
"string",
")",
"{",
"if",
"objKind",
"==",
"\"",
"\"",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"goName",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"goName",
",",
"objKind",
",",
"vppName",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"ctx",
".",
"includeComments",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"isNotSpace",
"=",
"func",
"(",
"r",
"rune",
")",
"bool",
"{",
"return",
"!",
"unicode",
".",
"IsSpace",
"(",
"r",
")",
"\n",
"}",
"\n\n",
"// print out the source of the generated object",
"mapType",
":=",
"false",
"\n",
"objFound",
":=",
"false",
"\n",
"objTitle",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\"%s\",`",
",",
"vppName",
")",
"\n",
"switch",
"objKind",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"objTitle",
"=",
"fmt",
".",
"Sprintf",
"(",
"`\"%s\": {`",
",",
"vppName",
")",
"\n",
"mapType",
"=",
"true",
"\n",
"}",
"\n\n",
"inputBuff",
":=",
"bytes",
".",
"NewBuffer",
"(",
"ctx",
".",
"inputData",
")",
"\n",
"inputLine",
":=",
"0",
"\n\n",
"var",
"trimIndent",
"string",
"\n",
"var",
"indent",
"int",
"\n",
"for",
"{",
"line",
",",
"err",
":=",
"inputBuff",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"inputLine",
"++",
"\n\n",
"noSpaceAt",
":=",
"strings",
".",
"IndexFunc",
"(",
"line",
",",
"isNotSpace",
")",
"\n",
"if",
"!",
"objFound",
"{",
"indent",
"=",
"strings",
".",
"Index",
"(",
"line",
",",
"objTitle",
")",
"\n",
"if",
"indent",
"==",
"-",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"trimIndent",
"=",
"line",
"[",
":",
"indent",
"]",
"\n",
"// If no other non-whitespace character then we are at the message header.",
"if",
"trimmed",
":=",
"strings",
".",
"TrimSpace",
"(",
"line",
")",
";",
"trimmed",
"==",
"objTitle",
"{",
"objFound",
"=",
"true",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"noSpaceAt",
"<",
"indent",
"{",
"break",
"// end of the definition in JSON for array types",
"\n",
"}",
"else",
"if",
"objFound",
"&&",
"mapType",
"&&",
"noSpaceAt",
"<=",
"indent",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\"",
",",
"strings",
".",
"TrimPrefix",
"(",
"line",
",",
"trimIndent",
")",
")",
"\n",
"break",
"// end of the definition in JSON for map types (aliases, services)",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\"",
",",
"strings",
".",
"TrimPrefix",
"(",
"line",
",",
"trimIndent",
")",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // generateComment writes generated comment for the object into w | [
"generateComment",
"writes",
"generated",
"comment",
"for",
"the",
"object",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L229-L288 |
12,621 | FDio/govpp | cmd/binapi-generator/generate.go | generateServices | func generateServices(ctx *context, w *bufio.Writer, services []Service) {
// generate services comment
generateComment(ctx, w, "Services", "services", "service")
// generate interface
fmt.Fprintf(w, "type %s interface {\n", "Services")
for _, svc := range services {
generateService(ctx, w, &svc)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
} | go | func generateServices(ctx *context, w *bufio.Writer, services []Service) {
// generate services comment
generateComment(ctx, w, "Services", "services", "service")
// generate interface
fmt.Fprintf(w, "type %s interface {\n", "Services")
for _, svc := range services {
generateService(ctx, w, &svc)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
} | [
"func",
"generateServices",
"(",
"ctx",
"*",
"context",
",",
"w",
"*",
"bufio",
".",
"Writer",
",",
"services",
"[",
"]",
"Service",
")",
"{",
"// generate services comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// generate interface",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"svc",
":=",
"range",
"services",
"{",
"generateService",
"(",
"ctx",
",",
"w",
",",
"&",
"svc",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateServices writes generated code for the Services interface into w | [
"generateServices",
"writes",
"generated",
"code",
"for",
"the",
"Services",
"interface",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L291-L303 |
12,622 | FDio/govpp | cmd/binapi-generator/generate.go | generateService | func generateService(ctx *context, w io.Writer, svc *Service) {
reqTyp := camelCaseName(svc.RequestType)
// method name is same as parameter type name by default
method := reqTyp
if svc.Stream {
// use Dump as prefix instead of suffix for stream services
if m := strings.TrimSuffix(method, "Dump"); method != m {
method = "Dump" + m
}
}
params := fmt.Sprintf("*%s", reqTyp)
returns := "error"
if replyType := camelCaseName(svc.ReplyType); replyType != "" {
repTyp := fmt.Sprintf("*%s", replyType)
if svc.Stream {
repTyp = fmt.Sprintf("[]%s", repTyp)
}
returns = fmt.Sprintf("(%s, error)", repTyp)
}
fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
} | go | func generateService(ctx *context, w io.Writer, svc *Service) {
reqTyp := camelCaseName(svc.RequestType)
// method name is same as parameter type name by default
method := reqTyp
if svc.Stream {
// use Dump as prefix instead of suffix for stream services
if m := strings.TrimSuffix(method, "Dump"); method != m {
method = "Dump" + m
}
}
params := fmt.Sprintf("*%s", reqTyp)
returns := "error"
if replyType := camelCaseName(svc.ReplyType); replyType != "" {
repTyp := fmt.Sprintf("*%s", replyType)
if svc.Stream {
repTyp = fmt.Sprintf("[]%s", repTyp)
}
returns = fmt.Sprintf("(%s, error)", repTyp)
}
fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
} | [
"func",
"generateService",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"svc",
"*",
"Service",
")",
"{",
"reqTyp",
":=",
"camelCaseName",
"(",
"svc",
".",
"RequestType",
")",
"\n\n",
"// method name is same as parameter type name by default",
"method",
":=",
"reqTyp",
"\n",
"if",
"svc",
".",
"Stream",
"{",
"// use Dump as prefix instead of suffix for stream services",
"if",
"m",
":=",
"strings",
".",
"TrimSuffix",
"(",
"method",
",",
"\"",
"\"",
")",
";",
"method",
"!=",
"m",
"{",
"method",
"=",
"\"",
"\"",
"+",
"m",
"\n",
"}",
"\n",
"}",
"\n\n",
"params",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"reqTyp",
")",
"\n",
"returns",
":=",
"\"",
"\"",
"\n",
"if",
"replyType",
":=",
"camelCaseName",
"(",
"svc",
".",
"ReplyType",
")",
";",
"replyType",
"!=",
"\"",
"\"",
"{",
"repTyp",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"replyType",
")",
"\n",
"if",
"svc",
".",
"Stream",
"{",
"repTyp",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"repTyp",
")",
"\n",
"}",
"\n",
"returns",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"repTyp",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\n",
"\"",
",",
"method",
",",
"params",
",",
"returns",
")",
"\n",
"}"
] | // generateService writes generated code for the service into w | [
"generateService",
"writes",
"generated",
"code",
"for",
"the",
"service",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L306-L329 |
12,623 | FDio/govpp | cmd/binapi-generator/generate.go | generateEnum | func generateEnum(ctx *context, w io.Writer, enum *Enum) {
name := camelCaseName(enum.Name)
typ := binapiTypes[enum.Type]
logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
// generate enum comment
generateComment(ctx, w, name, enum.Name, "enum")
// generate enum definition
fmt.Fprintf(w, "type %s %s\n", name, typ)
fmt.Fprintln(w)
fmt.Fprintln(w, "const (")
// generate enum entries
for _, entry := range enum.Entries {
fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
}
fmt.Fprintln(w, ")")
fmt.Fprintln(w)
} | go | func generateEnum(ctx *context, w io.Writer, enum *Enum) {
name := camelCaseName(enum.Name)
typ := binapiTypes[enum.Type]
logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
// generate enum comment
generateComment(ctx, w, name, enum.Name, "enum")
// generate enum definition
fmt.Fprintf(w, "type %s %s\n", name, typ)
fmt.Fprintln(w)
fmt.Fprintln(w, "const (")
// generate enum entries
for _, entry := range enum.Entries {
fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
}
fmt.Fprintln(w, ")")
fmt.Fprintln(w)
} | [
"func",
"generateEnum",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"enum",
"*",
"Enum",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"enum",
".",
"Name",
")",
"\n",
"typ",
":=",
"binapiTypes",
"[",
"enum",
".",
"Type",
"]",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"enum",
".",
"Name",
",",
"name",
",",
"len",
"(",
"enum",
".",
"Entries",
")",
")",
"\n\n",
"// generate enum comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"name",
",",
"enum",
".",
"Name",
",",
"\"",
"\"",
")",
"\n\n",
"// generate enum definition",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"name",
",",
"typ",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n\n",
"// generate enum entries",
"for",
"_",
",",
"entry",
":=",
"range",
"enum",
".",
"Entries",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\n",
"\"",
",",
"entry",
".",
"Name",
",",
"name",
",",
"entry",
".",
"Value",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateEnum writes generated code for the enum into w | [
"generateEnum",
"writes",
"generated",
"code",
"for",
"the",
"enum",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L332-L355 |
12,624 | FDio/govpp | cmd/binapi-generator/generate.go | generateAlias | func generateAlias(ctx *context, w io.Writer, alias *Alias) {
name := camelCaseName(alias.Name)
logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
// generate struct comment
generateComment(ctx, w, name, alias.Name, "alias")
// generate struct definition
fmt.Fprintf(w, "type %s ", name)
if alias.Length > 0 {
fmt.Fprintf(w, "[%d]", alias.Length)
}
dataType := convertToGoType(ctx, alias.Type)
fmt.Fprintf(w, "%s\n", dataType)
fmt.Fprintln(w)
} | go | func generateAlias(ctx *context, w io.Writer, alias *Alias) {
name := camelCaseName(alias.Name)
logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
// generate struct comment
generateComment(ctx, w, name, alias.Name, "alias")
// generate struct definition
fmt.Fprintf(w, "type %s ", name)
if alias.Length > 0 {
fmt.Fprintf(w, "[%d]", alias.Length)
}
dataType := convertToGoType(ctx, alias.Type)
fmt.Fprintf(w, "%s\n", dataType)
fmt.Fprintln(w)
} | [
"func",
"generateAlias",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"alias",
"*",
"Alias",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"alias",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"alias",
".",
"Name",
",",
"name",
",",
"alias",
".",
"Length",
")",
"\n\n",
"// generate struct comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"name",
",",
"alias",
".",
"Name",
",",
"\"",
"\"",
")",
"\n\n",
"// generate struct definition",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
",",
"name",
")",
"\n\n",
"if",
"alias",
".",
"Length",
">",
"0",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
",",
"alias",
".",
"Length",
")",
"\n",
"}",
"\n\n",
"dataType",
":=",
"convertToGoType",
"(",
"ctx",
",",
"alias",
".",
"Type",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"dataType",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateAlias writes generated code for the alias into w | [
"generateAlias",
"writes",
"generated",
"code",
"for",
"the",
"alias",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L358-L377 |
12,625 | FDio/govpp | cmd/binapi-generator/generate.go | generateUnion | func generateUnion(ctx *context, w io.Writer, union *Union) {
name := camelCaseName(union.Name)
logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
// generate struct comment
generateComment(ctx, w, name, union.Name, "union")
// generate struct definition
fmt.Fprintln(w, "type", name, "struct {")
// maximum size for union
maxSize := getUnionSize(ctx, union)
// generate data field
fieldName := "Union_data"
fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, union.Name)
// generate CRC getter
generateCrcGetter(w, name, union.CRC)
// generate getters for fields
for _, field := range union.Fields {
fieldName := camelCaseName(field.Name)
fieldType := convertToGoType(ctx, field.Type)
generateUnionGetterSetter(w, name, fieldName, fieldType)
}
// generate union methods
//generateUnionMethods(w, name)
fmt.Fprintln(w)
} | go | func generateUnion(ctx *context, w io.Writer, union *Union) {
name := camelCaseName(union.Name)
logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
// generate struct comment
generateComment(ctx, w, name, union.Name, "union")
// generate struct definition
fmt.Fprintln(w, "type", name, "struct {")
// maximum size for union
maxSize := getUnionSize(ctx, union)
// generate data field
fieldName := "Union_data"
fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, union.Name)
// generate CRC getter
generateCrcGetter(w, name, union.CRC)
// generate getters for fields
for _, field := range union.Fields {
fieldName := camelCaseName(field.Name)
fieldType := convertToGoType(ctx, field.Type)
generateUnionGetterSetter(w, name, fieldName, fieldType)
}
// generate union methods
//generateUnionMethods(w, name)
fmt.Fprintln(w)
} | [
"func",
"generateUnion",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"union",
"*",
"Union",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"union",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"union",
".",
"Name",
",",
"name",
",",
"len",
"(",
"union",
".",
"Fields",
")",
")",
"\n\n",
"// generate struct comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"name",
",",
"union",
".",
"Name",
",",
"\"",
"\"",
")",
"\n\n",
"// generate struct definition",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
")",
"\n\n",
"// maximum size for union",
"maxSize",
":=",
"getUnionSize",
"(",
"ctx",
",",
"union",
")",
"\n\n",
"// generate data field",
"fieldName",
":=",
"\"",
"\"",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\n",
"\"",
",",
"fieldName",
",",
"maxSize",
")",
"\n\n",
"// generate end of the struct",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n\n",
"// generate name getter",
"generateTypeNameGetter",
"(",
"w",
",",
"name",
",",
"union",
".",
"Name",
")",
"\n\n",
"// generate CRC getter",
"generateCrcGetter",
"(",
"w",
",",
"name",
",",
"union",
".",
"CRC",
")",
"\n\n",
"// generate getters for fields",
"for",
"_",
",",
"field",
":=",
"range",
"union",
".",
"Fields",
"{",
"fieldName",
":=",
"camelCaseName",
"(",
"field",
".",
"Name",
")",
"\n",
"fieldType",
":=",
"convertToGoType",
"(",
"ctx",
",",
"field",
".",
"Type",
")",
"\n",
"generateUnionGetterSetter",
"(",
"w",
",",
"name",
",",
"fieldName",
",",
"fieldType",
")",
"\n",
"}",
"\n\n",
"// generate union methods",
"//generateUnionMethods(w, name)",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateUnion writes generated code for the union into w | [
"generateUnion",
"writes",
"generated",
"code",
"for",
"the",
"union",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L380-L418 |
12,626 | FDio/govpp | cmd/binapi-generator/generate.go | generateType | func generateType(ctx *context, w io.Writer, typ *Type) {
name := camelCaseName(typ.Name)
logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
// generate struct comment
generateComment(ctx, w, name, typ.Name, "type")
// generate struct definition
fmt.Fprintf(w, "type %s struct {\n", name)
// generate struct fields
for i, field := range typ.Fields {
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
}
generateField(ctx, w, typ.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, typ.Name)
// generate CRC getter
generateCrcGetter(w, name, typ.CRC)
fmt.Fprintln(w)
} | go | func generateType(ctx *context, w io.Writer, typ *Type) {
name := camelCaseName(typ.Name)
logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
// generate struct comment
generateComment(ctx, w, name, typ.Name, "type")
// generate struct definition
fmt.Fprintf(w, "type %s struct {\n", name)
// generate struct fields
for i, field := range typ.Fields {
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
}
generateField(ctx, w, typ.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, typ.Name)
// generate CRC getter
generateCrcGetter(w, name, typ.CRC)
fmt.Fprintln(w)
} | [
"func",
"generateType",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"typ",
"*",
"Type",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"typ",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"typ",
".",
"Name",
",",
"name",
",",
"len",
"(",
"typ",
".",
"Fields",
")",
")",
"\n\n",
"// generate struct comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"name",
",",
"typ",
".",
"Name",
",",
"\"",
"\"",
")",
"\n\n",
"// generate struct definition",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n\n",
"// generate struct fields",
"for",
"i",
",",
"field",
":=",
"range",
"typ",
".",
"Fields",
"{",
"// skip internal fields",
"switch",
"strings",
".",
"ToLower",
"(",
"field",
".",
"Name",
")",
"{",
"case",
"crcField",
",",
"msgIdField",
":",
"continue",
"\n",
"}",
"\n\n",
"generateField",
"(",
"ctx",
",",
"w",
",",
"typ",
".",
"Fields",
",",
"i",
")",
"\n",
"}",
"\n\n",
"// generate end of the struct",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n\n",
"// generate name getter",
"generateTypeNameGetter",
"(",
"w",
",",
"name",
",",
"typ",
".",
"Name",
")",
"\n\n",
"// generate CRC getter",
"generateCrcGetter",
"(",
"w",
",",
"name",
",",
"typ",
".",
"CRC",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateType writes generated code for the type into w | [
"generateType",
"writes",
"generated",
"code",
"for",
"the",
"type",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L468-L500 |
12,627 | FDio/govpp | cmd/binapi-generator/generate.go | generateMessage | func generateMessage(ctx *context, w io.Writer, msg *Message) {
name := camelCaseName(msg.Name)
logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
// generate struct comment
generateComment(ctx, w, name, msg.Name, "message")
// generate struct definition
fmt.Fprintf(w, "type %s struct {", name)
msgType := otherMessage
wasClientIndex := false
// generate struct fields
n := 0
for i, field := range msg.Fields {
if i == 1 {
if field.Name == clientIndexField {
// "client_index" as the second member,
// this might be an event message or a request
msgType = eventMessage
wasClientIndex = true
} else if field.Name == contextField {
// reply needs "context" as the second member
msgType = replyMessage
}
} else if i == 2 {
if wasClientIndex && field.Name == contextField {
// request needs "client_index" as the second member
// and "context" as the third member
msgType = requestMessage
}
}
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
case clientIndexField, contextField:
if n == 0 {
continue
}
}
n++
if n == 1 {
fmt.Fprintln(w)
}
generateField(ctx, w, msg.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateMessageNameGetter(w, name, msg.Name)
// generate CRC getter
generateCrcGetter(w, name, msg.CRC)
// generate message type getter method
generateMessageTypeGetter(w, name, msgType)
fmt.Fprintln(w)
} | go | func generateMessage(ctx *context, w io.Writer, msg *Message) {
name := camelCaseName(msg.Name)
logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
// generate struct comment
generateComment(ctx, w, name, msg.Name, "message")
// generate struct definition
fmt.Fprintf(w, "type %s struct {", name)
msgType := otherMessage
wasClientIndex := false
// generate struct fields
n := 0
for i, field := range msg.Fields {
if i == 1 {
if field.Name == clientIndexField {
// "client_index" as the second member,
// this might be an event message or a request
msgType = eventMessage
wasClientIndex = true
} else if field.Name == contextField {
// reply needs "context" as the second member
msgType = replyMessage
}
} else if i == 2 {
if wasClientIndex && field.Name == contextField {
// request needs "client_index" as the second member
// and "context" as the third member
msgType = requestMessage
}
}
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
case clientIndexField, contextField:
if n == 0 {
continue
}
}
n++
if n == 1 {
fmt.Fprintln(w)
}
generateField(ctx, w, msg.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateMessageNameGetter(w, name, msg.Name)
// generate CRC getter
generateCrcGetter(w, name, msg.CRC)
// generate message type getter method
generateMessageTypeGetter(w, name, msgType)
fmt.Fprintln(w)
} | [
"func",
"generateMessage",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"msg",
"*",
"Message",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"msg",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Name",
",",
"name",
",",
"len",
"(",
"msg",
".",
"Fields",
")",
")",
"\n\n",
"// generate struct comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"name",
",",
"msg",
".",
"Name",
",",
"\"",
"\"",
")",
"\n\n",
"// generate struct definition",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
",",
"name",
")",
"\n\n",
"msgType",
":=",
"otherMessage",
"\n",
"wasClientIndex",
":=",
"false",
"\n\n",
"// generate struct fields",
"n",
":=",
"0",
"\n",
"for",
"i",
",",
"field",
":=",
"range",
"msg",
".",
"Fields",
"{",
"if",
"i",
"==",
"1",
"{",
"if",
"field",
".",
"Name",
"==",
"clientIndexField",
"{",
"// \"client_index\" as the second member,",
"// this might be an event message or a request",
"msgType",
"=",
"eventMessage",
"\n",
"wasClientIndex",
"=",
"true",
"\n",
"}",
"else",
"if",
"field",
".",
"Name",
"==",
"contextField",
"{",
"// reply needs \"context\" as the second member",
"msgType",
"=",
"replyMessage",
"\n",
"}",
"\n",
"}",
"else",
"if",
"i",
"==",
"2",
"{",
"if",
"wasClientIndex",
"&&",
"field",
".",
"Name",
"==",
"contextField",
"{",
"// request needs \"client_index\" as the second member",
"// and \"context\" as the third member",
"msgType",
"=",
"requestMessage",
"\n",
"}",
"\n",
"}",
"\n\n",
"// skip internal fields",
"switch",
"strings",
".",
"ToLower",
"(",
"field",
".",
"Name",
")",
"{",
"case",
"crcField",
",",
"msgIdField",
":",
"continue",
"\n",
"case",
"clientIndexField",
",",
"contextField",
":",
"if",
"n",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"n",
"++",
"\n",
"if",
"n",
"==",
"1",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}",
"\n\n",
"generateField",
"(",
"ctx",
",",
"w",
",",
"msg",
".",
"Fields",
",",
"i",
")",
"\n",
"}",
"\n\n",
"// generate end of the struct",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n\n",
"// generate name getter",
"generateMessageNameGetter",
"(",
"w",
",",
"name",
",",
"msg",
".",
"Name",
")",
"\n\n",
"// generate CRC getter",
"generateCrcGetter",
"(",
"w",
",",
"name",
",",
"msg",
".",
"CRC",
")",
"\n\n",
"// generate message type getter method",
"generateMessageTypeGetter",
"(",
"w",
",",
"name",
",",
"msgType",
")",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateMessage writes generated code for the message into w | [
"generateMessage",
"writes",
"generated",
"code",
"for",
"the",
"message",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L503-L568 |
12,628 | FDio/govpp | cmd/binapi-generator/generate.go | generateField | func generateField(ctx *context, w io.Writer, fields []Field, i int) {
field := fields[i]
fieldName := strings.TrimPrefix(field.Name, "_")
fieldName = camelCaseName(fieldName)
// generate length field for strings
if field.Type == "string" {
fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
}
dataType := convertToGoType(ctx, field.Type)
fieldType := dataType
// check if it is array
if field.Length > 0 || field.SizeFrom != "" {
if dataType == "uint8" {
dataType = "byte"
}
fieldType = "[]" + dataType
}
fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
if field.Length > 0 {
// fixed size array
fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
} else {
for _, f := range fields {
if f.SizeFrom == field.Name {
// variable sized array
sizeOfName := camelCaseName(f.Name)
fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
}
}
}
fmt.Fprintln(w)
} | go | func generateField(ctx *context, w io.Writer, fields []Field, i int) {
field := fields[i]
fieldName := strings.TrimPrefix(field.Name, "_")
fieldName = camelCaseName(fieldName)
// generate length field for strings
if field.Type == "string" {
fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
}
dataType := convertToGoType(ctx, field.Type)
fieldType := dataType
// check if it is array
if field.Length > 0 || field.SizeFrom != "" {
if dataType == "uint8" {
dataType = "byte"
}
fieldType = "[]" + dataType
}
fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
if field.Length > 0 {
// fixed size array
fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
} else {
for _, f := range fields {
if f.SizeFrom == field.Name {
// variable sized array
sizeOfName := camelCaseName(f.Name)
fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
}
}
}
fmt.Fprintln(w)
} | [
"func",
"generateField",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"fields",
"[",
"]",
"Field",
",",
"i",
"int",
")",
"{",
"field",
":=",
"fields",
"[",
"i",
"]",
"\n\n",
"fieldName",
":=",
"strings",
".",
"TrimPrefix",
"(",
"field",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"fieldName",
"=",
"camelCaseName",
"(",
"fieldName",
")",
"\n\n",
"// generate length field for strings",
"if",
"field",
".",
"Type",
"==",
"\"",
"\"",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"fieldName",
",",
"fieldName",
")",
"\n",
"}",
"\n\n",
"dataType",
":=",
"convertToGoType",
"(",
"ctx",
",",
"field",
".",
"Type",
")",
"\n",
"fieldType",
":=",
"dataType",
"\n\n",
"// check if it is array",
"if",
"field",
".",
"Length",
">",
"0",
"||",
"field",
".",
"SizeFrom",
"!=",
"\"",
"\"",
"{",
"if",
"dataType",
"==",
"\"",
"\"",
"{",
"dataType",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"fieldType",
"=",
"\"",
"\"",
"+",
"dataType",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\"",
",",
"fieldName",
",",
"fieldType",
")",
"\n\n",
"if",
"field",
".",
"Length",
">",
"0",
"{",
"// fixed size array",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\"",
",",
"field",
".",
"Length",
",",
"dataType",
")",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"fields",
"{",
"if",
"f",
".",
"SizeFrom",
"==",
"field",
".",
"Name",
"{",
"// variable sized array",
"sizeOfName",
":=",
"camelCaseName",
"(",
"f",
".",
"Name",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\"",
",",
"sizeOfName",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
")",
"\n",
"}"
] | // generateField writes generated code for the field into w | [
"generateField",
"writes",
"generated",
"code",
"for",
"the",
"field",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L571-L608 |
12,629 | FDio/govpp | cmd/binapi-generator/generate.go | generateTypeNameGetter | func generateTypeNameGetter(w io.Writer, structName, msgName string) {
fmt.Fprintf(w, `func (*%s) GetTypeName() string {
return %q
}
`, structName, msgName)
} | go | func generateTypeNameGetter(w io.Writer, structName, msgName string) {
fmt.Fprintf(w, `func (*%s) GetTypeName() string {
return %q
}
`, structName, msgName)
} | [
"func",
"generateTypeNameGetter",
"(",
"w",
"io",
".",
"Writer",
",",
"structName",
",",
"msgName",
"string",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"`func (*%s) GetTypeName() string {\n\treturn %q\n}\n`",
",",
"structName",
",",
"msgName",
")",
"\n",
"}"
] | // generateTypeNameGetter generates getter for original VPP type name into the provider writer | [
"generateTypeNameGetter",
"generates",
"getter",
"for",
"original",
"VPP",
"type",
"name",
"into",
"the",
"provider",
"writer"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L619-L624 |
12,630 | FDio/govpp | cmd/binapi-generator/generate.go | generateCrcGetter | func generateCrcGetter(w io.Writer, structName, crc string) {
crc = strings.TrimPrefix(crc, "0x")
fmt.Fprintf(w, `func (*%s) GetCrcString() string {
return %q
}
`, structName, crc)
} | go | func generateCrcGetter(w io.Writer, structName, crc string) {
crc = strings.TrimPrefix(crc, "0x")
fmt.Fprintf(w, `func (*%s) GetCrcString() string {
return %q
}
`, structName, crc)
} | [
"func",
"generateCrcGetter",
"(",
"w",
"io",
".",
"Writer",
",",
"structName",
",",
"crc",
"string",
")",
"{",
"crc",
"=",
"strings",
".",
"TrimPrefix",
"(",
"crc",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"`func (*%s) GetCrcString() string {\n\treturn %q\n}\n`",
",",
"structName",
",",
"crc",
")",
"\n",
"}"
] | // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer | [
"generateCrcGetter",
"generates",
"getter",
"for",
"CRC",
"checksum",
"of",
"the",
"message",
"definition",
"into",
"the",
"provider",
"writer"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L627-L633 |
12,631 | FDio/govpp | cmd/binapi-generator/generate.go | generateMessageTypeGetter | func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
if msgType == requestMessage {
fmt.Fprintln(w, "\treturn api.RequestMessage")
} else if msgType == replyMessage {
fmt.Fprintln(w, "\treturn api.ReplyMessage")
} else if msgType == eventMessage {
fmt.Fprintln(w, "\treturn api.EventMessage")
} else {
fmt.Fprintln(w, "\treturn api.OtherMessage")
}
fmt.Fprintln(w, "}")
} | go | func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
if msgType == requestMessage {
fmt.Fprintln(w, "\treturn api.RequestMessage")
} else if msgType == replyMessage {
fmt.Fprintln(w, "\treturn api.ReplyMessage")
} else if msgType == eventMessage {
fmt.Fprintln(w, "\treturn api.EventMessage")
} else {
fmt.Fprintln(w, "\treturn api.OtherMessage")
}
fmt.Fprintln(w, "}")
} | [
"func",
"generateMessageTypeGetter",
"(",
"w",
"io",
".",
"Writer",
",",
"structName",
"string",
",",
"msgType",
"MessageType",
")",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
"+",
"structName",
"+",
"\"",
"\"",
")",
"\n",
"if",
"msgType",
"==",
"requestMessage",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}",
"else",
"if",
"msgType",
"==",
"replyMessage",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}",
"else",
"if",
"msgType",
"==",
"eventMessage",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // generateMessageTypeGetter generates message factory for the generated message into the provider writer | [
"generateMessageTypeGetter",
"generates",
"message",
"factory",
"for",
"the",
"generated",
"message",
"into",
"the",
"provider",
"writer"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L636-L648 |
12,632 | FDio/govpp | extras/libmemif/examples/raw-data/raw-data.go | SendPackets | func SendPackets(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
counter := 0
for {
select {
case <-time.After(3 * time.Second):
counter++
// Prepare fake packets.
packets := []libmemif.RawPacketData{
libmemif.RawPacketData("Packet #1 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #2 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #3 in burst number " + strconv.Itoa(counter)),
}
// Send the packets. We may not be able to do it in one burst if the ring
// is (almost) full or the internal buffer cannot contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, packets[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(packets) {
break
}
}
}
case <-stopCh:
return
}
}
} | go | func SendPackets(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
counter := 0
for {
select {
case <-time.After(3 * time.Second):
counter++
// Prepare fake packets.
packets := []libmemif.RawPacketData{
libmemif.RawPacketData("Packet #1 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #2 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #3 in burst number " + strconv.Itoa(counter)),
}
// Send the packets. We may not be able to do it in one burst if the ring
// is (almost) full or the internal buffer cannot contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, packets[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(packets) {
break
}
}
}
case <-stopCh:
return
}
}
} | [
"func",
"SendPackets",
"(",
"memif",
"*",
"libmemif",
".",
"Memif",
",",
"queueID",
"uint8",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"counter",
":=",
"0",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"3",
"*",
"time",
".",
"Second",
")",
":",
"counter",
"++",
"\n",
"// Prepare fake packets.",
"packets",
":=",
"[",
"]",
"libmemif",
".",
"RawPacketData",
"{",
"libmemif",
".",
"RawPacketData",
"(",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"counter",
")",
")",
",",
"libmemif",
".",
"RawPacketData",
"(",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"counter",
")",
")",
",",
"libmemif",
".",
"RawPacketData",
"(",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"counter",
")",
")",
",",
"}",
"\n",
"// Send the packets. We may not be able to do it in one burst if the ring",
"// is (almost) full or the internal buffer cannot contain it.",
"sent",
":=",
"0",
"\n",
"for",
"{",
"count",
",",
"err",
":=",
"memif",
".",
"TxBurst",
"(",
"queueID",
",",
"packets",
"[",
"sent",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"break",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"count",
")",
"\n",
"sent",
"+=",
"int",
"(",
"count",
")",
"\n",
"if",
"sent",
"==",
"len",
"(",
"packets",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"<-",
"stopCh",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // SendPackets keeps sending bursts of 3 raw-data packets every 3 seconds into
// the selected queue. | [
"SendPackets",
"keeps",
"sending",
"bursts",
"of",
"3",
"raw",
"-",
"data",
"packets",
"every",
"3",
"seconds",
"into",
"the",
"selected",
"queue",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/raw-data/raw-data.go#L139-L173 |
12,633 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | NewVppClientWithInputQueueSize | func NewVppClientWithInputQueueSize(shmPrefix string, inputQueueSize uint16) adapter.VppAPI {
return &vppClient{
shmPrefix: shmPrefix,
inputQueueSize: inputQueueSize,
}
} | go | func NewVppClientWithInputQueueSize(shmPrefix string, inputQueueSize uint16) adapter.VppAPI {
return &vppClient{
shmPrefix: shmPrefix,
inputQueueSize: inputQueueSize,
}
} | [
"func",
"NewVppClientWithInputQueueSize",
"(",
"shmPrefix",
"string",
",",
"inputQueueSize",
"uint16",
")",
"adapter",
".",
"VppAPI",
"{",
"return",
"&",
"vppClient",
"{",
"shmPrefix",
":",
"shmPrefix",
",",
"inputQueueSize",
":",
"inputQueueSize",
",",
"}",
"\n",
"}"
] | // NewVppClientWithInputQueueSize returns a new VPP binary API client with a custom input queue size. | [
"NewVppClientWithInputQueueSize",
"returns",
"a",
"new",
"VPP",
"binary",
"API",
"client",
"with",
"a",
"custom",
"input",
"queue",
"size",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L118-L123 |
12,634 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | Connect | func (a *vppClient) Connect() error {
if globalVppClient != nil {
return fmt.Errorf("already connected to binary API, disconnect first")
}
rxQlen := C.int(a.inputQueueSize)
var rc C.int
if a.shmPrefix == "" {
rc = C.govpp_connect(nil, rxQlen)
} else {
shm := C.CString(a.shmPrefix)
rc = C.govpp_connect(shm, rxQlen)
}
if rc != 0 {
return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
}
globalVppClient = a
return nil
} | go | func (a *vppClient) Connect() error {
if globalVppClient != nil {
return fmt.Errorf("already connected to binary API, disconnect first")
}
rxQlen := C.int(a.inputQueueSize)
var rc C.int
if a.shmPrefix == "" {
rc = C.govpp_connect(nil, rxQlen)
} else {
shm := C.CString(a.shmPrefix)
rc = C.govpp_connect(shm, rxQlen)
}
if rc != 0 {
return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
}
globalVppClient = a
return nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"Connect",
"(",
")",
"error",
"{",
"if",
"globalVppClient",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"rxQlen",
":=",
"C",
".",
"int",
"(",
"a",
".",
"inputQueueSize",
")",
"\n",
"var",
"rc",
"C",
".",
"int",
"\n",
"if",
"a",
".",
"shmPrefix",
"==",
"\"",
"\"",
"{",
"rc",
"=",
"C",
".",
"govpp_connect",
"(",
"nil",
",",
"rxQlen",
")",
"\n",
"}",
"else",
"{",
"shm",
":=",
"C",
".",
"CString",
"(",
"a",
".",
"shmPrefix",
")",
"\n",
"rc",
"=",
"C",
".",
"govpp_connect",
"(",
"shm",
",",
"rxQlen",
")",
"\n",
"}",
"\n",
"if",
"rc",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rc",
")",
"\n",
"}",
"\n\n",
"globalVppClient",
"=",
"a",
"\n",
"return",
"nil",
"\n",
"}"
] | // Connect connects the process to VPP. | [
"Connect",
"connects",
"the",
"process",
"to",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L126-L145 |
12,635 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | Disconnect | func (a *vppClient) Disconnect() error {
globalVppClient = nil
rc := C.govpp_disconnect()
if rc != 0 {
return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
}
return nil
} | go | func (a *vppClient) Disconnect() error {
globalVppClient = nil
rc := C.govpp_disconnect()
if rc != 0 {
return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
}
return nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"Disconnect",
"(",
")",
"error",
"{",
"globalVppClient",
"=",
"nil",
"\n\n",
"rc",
":=",
"C",
".",
"govpp_disconnect",
"(",
")",
"\n",
"if",
"rc",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rc",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Disconnect disconnects the process from VPP. | [
"Disconnect",
"disconnects",
"the",
"process",
"from",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L148-L157 |
12,636 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | GetMsgID | func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
nameAndCrc := C.CString(msgName + "_" + msgCrc)
defer C.free(unsafe.Pointer(nameAndCrc))
msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
if msgID == ^uint16(0) {
// VPP does not know this message
return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
}
return msgID, nil
} | go | func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
nameAndCrc := C.CString(msgName + "_" + msgCrc)
defer C.free(unsafe.Pointer(nameAndCrc))
msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
if msgID == ^uint16(0) {
// VPP does not know this message
return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
}
return msgID, nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"GetMsgID",
"(",
"msgName",
"string",
",",
"msgCrc",
"string",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"nameAndCrc",
":=",
"C",
".",
"CString",
"(",
"msgName",
"+",
"\"",
"\"",
"+",
"msgCrc",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"nameAndCrc",
")",
")",
"\n\n",
"msgID",
":=",
"uint16",
"(",
"C",
".",
"govpp_get_msg_index",
"(",
"nameAndCrc",
")",
")",
"\n",
"if",
"msgID",
"==",
"^",
"uint16",
"(",
"0",
")",
"{",
"// VPP does not know this message",
"return",
"msgID",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msgName",
",",
"msgCrc",
")",
"\n",
"}",
"\n\n",
"return",
"msgID",
",",
"nil",
"\n",
"}"
] | // GetMsgID returns a runtime message ID for the given message name and CRC. | [
"GetMsgID",
"returns",
"a",
"runtime",
"message",
"ID",
"for",
"the",
"given",
"message",
"name",
"and",
"CRC",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L160-L171 |
12,637 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | SendMsg | func (a *vppClient) SendMsg(context uint32, data []byte) error {
rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
if rc != 0 {
return fmt.Errorf("unable to send the message (rc=%v)", rc)
}
return nil
} | go | func (a *vppClient) SendMsg(context uint32, data []byte) error {
rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
if rc != 0 {
return fmt.Errorf("unable to send the message (rc=%v)", rc)
}
return nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"SendMsg",
"(",
"context",
"uint32",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"rc",
":=",
"C",
".",
"govpp_send",
"(",
"C",
".",
"uint32_t",
"(",
"context",
")",
",",
"unsafe",
".",
"Pointer",
"(",
"&",
"data",
"[",
"0",
"]",
")",
",",
"C",
".",
"size_t",
"(",
"len",
"(",
"data",
")",
")",
")",
"\n",
"if",
"rc",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rc",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SendMsg sends a binary-encoded message to VPP. | [
"SendMsg",
"sends",
"a",
"binary",
"-",
"encoded",
"message",
"to",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L174-L180 |
12,638 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | WaitReady | func (a *vppClient) WaitReady() error {
// join the path to the shared memory segment
var path string
if a.shmPrefix == "" {
path = filepath.Join(shmDir, vppShmFile)
} else {
path = filepath.Join(shmDir, a.shmPrefix+"-"+vppShmFile)
}
// check if file at the path already exists
if _, err := os.Stat(path); err == nil {
// file exists, we are ready
return nil
} else if !os.IsNotExist(err) {
return err
}
// file does not exist, start watching folder
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// start watching directory
if err := watcher.Add(shmDir); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for shared memory segment timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
if ev.Name == path {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// file was created, we are ready
return nil
}
}
}
}
} | go | func (a *vppClient) WaitReady() error {
// join the path to the shared memory segment
var path string
if a.shmPrefix == "" {
path = filepath.Join(shmDir, vppShmFile)
} else {
path = filepath.Join(shmDir, a.shmPrefix+"-"+vppShmFile)
}
// check if file at the path already exists
if _, err := os.Stat(path); err == nil {
// file exists, we are ready
return nil
} else if !os.IsNotExist(err) {
return err
}
// file does not exist, start watching folder
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// start watching directory
if err := watcher.Add(shmDir); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for shared memory segment timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
if ev.Name == path {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// file was created, we are ready
return nil
}
}
}
}
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"WaitReady",
"(",
")",
"error",
"{",
"// join the path to the shared memory segment",
"var",
"path",
"string",
"\n",
"if",
"a",
".",
"shmPrefix",
"==",
"\"",
"\"",
"{",
"path",
"=",
"filepath",
".",
"Join",
"(",
"shmDir",
",",
"vppShmFile",
")",
"\n",
"}",
"else",
"{",
"path",
"=",
"filepath",
".",
"Join",
"(",
"shmDir",
",",
"a",
".",
"shmPrefix",
"+",
"\"",
"\"",
"+",
"vppShmFile",
")",
"\n",
"}",
"\n\n",
"// check if file at the path already exists",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"err",
"==",
"nil",
"{",
"// file exists, we are ready",
"return",
"nil",
"\n",
"}",
"else",
"if",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// file does not exist, start watching folder",
"watcher",
",",
"err",
":=",
"fsnotify",
".",
"NewWatcher",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"watcher",
".",
"Close",
"(",
")",
"\n\n",
"// start watching directory",
"if",
"err",
":=",
"watcher",
".",
"Add",
"(",
"shmDir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"MaxWaitReady",
")",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"MaxWaitReady",
")",
"\n",
"case",
"e",
":=",
"<-",
"watcher",
".",
"Errors",
":",
"return",
"e",
"\n",
"case",
"ev",
":=",
"<-",
"watcher",
".",
"Events",
":",
"if",
"ev",
".",
"Name",
"==",
"path",
"{",
"if",
"(",
"ev",
".",
"Op",
"&",
"fsnotify",
".",
"Create",
")",
"==",
"fsnotify",
".",
"Create",
"{",
"// file was created, we are ready",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WaitReady blocks until shared memory for sending
// binary api calls is present on the file system. | [
"WaitReady",
"blocks",
"until",
"shared",
"memory",
"for",
"sending",
"binary",
"api",
"calls",
"is",
"present",
"on",
"the",
"file",
"system",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L190-L234 |
12,639 | FDio/govpp | extras/libmemif/error.go | newMemifError | func newMemifError(code int, desc ...string) *MemifError {
var err *MemifError
if len(desc) > 0 {
err = &MemifError{code: code, description: "libmemif: " + desc[0]}
} else {
err = &MemifError{code: code, description: "libmemif: " + C.GoString(C.memif_strerror(C.int(code)))}
}
errorRegistry[code] = err
return err
} | go | func newMemifError(code int, desc ...string) *MemifError {
var err *MemifError
if len(desc) > 0 {
err = &MemifError{code: code, description: "libmemif: " + desc[0]}
} else {
err = &MemifError{code: code, description: "libmemif: " + C.GoString(C.memif_strerror(C.int(code)))}
}
errorRegistry[code] = err
return err
} | [
"func",
"newMemifError",
"(",
"code",
"int",
",",
"desc",
"...",
"string",
")",
"*",
"MemifError",
"{",
"var",
"err",
"*",
"MemifError",
"\n",
"if",
"len",
"(",
"desc",
")",
">",
"0",
"{",
"err",
"=",
"&",
"MemifError",
"{",
"code",
":",
"code",
",",
"description",
":",
"\"",
"\"",
"+",
"desc",
"[",
"0",
"]",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"&",
"MemifError",
"{",
"code",
":",
"code",
",",
"description",
":",
"\"",
"\"",
"+",
"C",
".",
"GoString",
"(",
"C",
".",
"memif_strerror",
"(",
"C",
".",
"int",
"(",
"code",
")",
")",
")",
"}",
"\n",
"}",
"\n",
"errorRegistry",
"[",
"code",
"]",
"=",
"err",
"\n",
"return",
"err",
"\n",
"}"
] | // newMemifError builds and registers a new MemifError. | [
"newMemifError",
"builds",
"and",
"registers",
"a",
"new",
"MemifError",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/error.go#L102-L111 |
12,640 | FDio/govpp | extras/libmemif/error.go | getMemifError | func getMemifError(code int) error {
if code == 0 {
return nil /* success */
}
err, known := errorRegistry[code]
if !known {
return ErrUnknown
}
return err
} | go | func getMemifError(code int) error {
if code == 0 {
return nil /* success */
}
err, known := errorRegistry[code]
if !known {
return ErrUnknown
}
return err
} | [
"func",
"getMemifError",
"(",
"code",
"int",
")",
"error",
"{",
"if",
"code",
"==",
"0",
"{",
"return",
"nil",
"/* success */",
"\n",
"}",
"\n",
"err",
",",
"known",
":=",
"errorRegistry",
"[",
"code",
"]",
"\n",
"if",
"!",
"known",
"{",
"return",
"ErrUnknown",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // getMemifError returns the MemifError associated with the given C-libmemif
// error code. | [
"getMemifError",
"returns",
"the",
"MemifError",
"associated",
"with",
"the",
"given",
"C",
"-",
"libmemif",
"error",
"code",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/error.go#L115-L124 |
12,641 | FDio/govpp | extras/libmemif/adapter.go | Cleanup | func Cleanup() error {
context.lock.Lock()
defer context.lock.Unlock()
if !context.initialized {
return ErrNotInit
}
log.Debug("Closing libmemif library")
// Delete all active interfaces.
for _, memif := range context.memifs {
memif.Close()
}
// Stop the event loop (if supported by C-libmemif).
errCode := C.memif_cancel_poll_event()
err := getMemifError(int(errCode))
if err == nil {
log.Debug("Waiting for pollEvents() to stop...")
context.wg.Wait()
log.Debug("pollEvents() has stopped...")
} else {
log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
}
// Run cleanup for C-libmemif.
err = getMemifError(int(C.memif_cleanup()))
if err == nil {
context.initialized = false
log.Debug("libmemif library was closed")
}
return err
} | go | func Cleanup() error {
context.lock.Lock()
defer context.lock.Unlock()
if !context.initialized {
return ErrNotInit
}
log.Debug("Closing libmemif library")
// Delete all active interfaces.
for _, memif := range context.memifs {
memif.Close()
}
// Stop the event loop (if supported by C-libmemif).
errCode := C.memif_cancel_poll_event()
err := getMemifError(int(errCode))
if err == nil {
log.Debug("Waiting for pollEvents() to stop...")
context.wg.Wait()
log.Debug("pollEvents() has stopped...")
} else {
log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
}
// Run cleanup for C-libmemif.
err = getMemifError(int(C.memif_cleanup()))
if err == nil {
context.initialized = false
log.Debug("libmemif library was closed")
}
return err
} | [
"func",
"Cleanup",
"(",
")",
"error",
"{",
"context",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"context",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"context",
".",
"initialized",
"{",
"return",
"ErrNotInit",
"\n",
"}",
"\n\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// Delete all active interfaces.",
"for",
"_",
",",
"memif",
":=",
"range",
"context",
".",
"memifs",
"{",
"memif",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"// Stop the event loop (if supported by C-libmemif).",
"errCode",
":=",
"C",
".",
"memif_cancel_poll_event",
"(",
")",
"\n",
"err",
":=",
"getMemifError",
"(",
"int",
"(",
"errCode",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"context",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Run cleanup for C-libmemif.",
"err",
"=",
"getMemifError",
"(",
"int",
"(",
"C",
".",
"memif_cleanup",
"(",
")",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"context",
".",
"initialized",
"=",
"false",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Cleanup cleans up all the resources allocated by libmemif. | [
"Cleanup",
"cleans",
"up",
"all",
"the",
"resources",
"allocated",
"by",
"libmemif",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L505-L538 |
12,642 | FDio/govpp | extras/libmemif/adapter.go | SetRxMode | func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
var cRxMode C.memif_rx_mode_t
switch rxMode {
case RxModeInterrupt:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
case RxModePolling:
cRxMode = C.MEMIF_RX_MODE_POLLING
default:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
}
errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
return getMemifError(int(errCode))
} | go | func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
var cRxMode C.memif_rx_mode_t
switch rxMode {
case RxModeInterrupt:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
case RxModePolling:
cRxMode = C.MEMIF_RX_MODE_POLLING
default:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
}
errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
return getMemifError(int(errCode))
} | [
"func",
"(",
"memif",
"*",
"Memif",
")",
"SetRxMode",
"(",
"queueID",
"uint8",
",",
"rxMode",
"RxMode",
")",
"(",
"err",
"error",
")",
"{",
"var",
"cRxMode",
"C",
".",
"memif_rx_mode_t",
"\n",
"switch",
"rxMode",
"{",
"case",
"RxModeInterrupt",
":",
"cRxMode",
"=",
"C",
".",
"MEMIF_RX_MODE_INTERRUPT",
"\n",
"case",
"RxModePolling",
":",
"cRxMode",
"=",
"C",
".",
"MEMIF_RX_MODE_POLLING",
"\n",
"default",
":",
"cRxMode",
"=",
"C",
".",
"MEMIF_RX_MODE_INTERRUPT",
"\n",
"}",
"\n",
"errCode",
":=",
"C",
".",
"memif_set_rx_mode",
"(",
"memif",
".",
"cHandle",
",",
"cRxMode",
",",
"C",
".",
"uint16_t",
"(",
"queueID",
")",
")",
"\n",
"return",
"getMemifError",
"(",
"int",
"(",
"errCode",
")",
")",
"\n",
"}"
] | // SetRxMode allows to switch between the interrupt and the polling mode for Rx.
// The method is thread-safe. | [
"SetRxMode",
"allows",
"to",
"switch",
"between",
"the",
"interrupt",
"and",
"the",
"polling",
"mode",
"for",
"Rx",
".",
"The",
"method",
"is",
"thread",
"-",
"safe",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L680-L692 |
12,643 | FDio/govpp | extras/libmemif/adapter.go | GetDetails | func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
cDetails := C.govpp_memif_details_t{}
var buf *C.char
// Get memif details from C-libmemif.
errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
err = getMemifError(int(errCode))
if err != nil {
return nil, err
}
defer C.free(unsafe.Pointer(buf))
// Convert details from C to Go.
details = &MemifDetails{}
// - metadata:
details.IfName = C.GoString(cDetails.if_name)
details.InstanceName = C.GoString(cDetails.inst_name)
details.ConnID = uint32(cDetails.id)
details.SocketFilename = C.GoString(cDetails.socket_filename)
if cDetails.secret != nil {
details.Secret = C.GoString(cDetails.secret)
}
details.IsMaster = cDetails.role == C.uint8_t(0)
switch cDetails.mode {
case C.MEMIF_INTERFACE_MODE_ETHERNET:
details.Mode = IfModeEthernet
case C.MEMIF_INTERFACE_MODE_IP:
details.Mode = IfModeIP
case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
details.Mode = IfModePuntInject
default:
details.Mode = IfModeEthernet
}
// - connection details:
details.RemoteIfName = C.GoString(cDetails.remote_if_name)
details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
details.HasLink = cDetails.link_up_down == C.uint8_t(1)
// - RX queues:
var i uint8
for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cRxQueue.qid),
RingSize: uint32(cRxQueue.ring_size),
BufferSize: uint16(cRxQueue.buffer_size),
}
details.RxQueues = append(details.RxQueues, queueDetails)
}
// - TX queues:
for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cTxQueue.qid),
RingSize: uint32(cTxQueue.ring_size),
BufferSize: uint16(cTxQueue.buffer_size),
}
details.TxQueues = append(details.TxQueues, queueDetails)
}
return details, nil
} | go | func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
cDetails := C.govpp_memif_details_t{}
var buf *C.char
// Get memif details from C-libmemif.
errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
err = getMemifError(int(errCode))
if err != nil {
return nil, err
}
defer C.free(unsafe.Pointer(buf))
// Convert details from C to Go.
details = &MemifDetails{}
// - metadata:
details.IfName = C.GoString(cDetails.if_name)
details.InstanceName = C.GoString(cDetails.inst_name)
details.ConnID = uint32(cDetails.id)
details.SocketFilename = C.GoString(cDetails.socket_filename)
if cDetails.secret != nil {
details.Secret = C.GoString(cDetails.secret)
}
details.IsMaster = cDetails.role == C.uint8_t(0)
switch cDetails.mode {
case C.MEMIF_INTERFACE_MODE_ETHERNET:
details.Mode = IfModeEthernet
case C.MEMIF_INTERFACE_MODE_IP:
details.Mode = IfModeIP
case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
details.Mode = IfModePuntInject
default:
details.Mode = IfModeEthernet
}
// - connection details:
details.RemoteIfName = C.GoString(cDetails.remote_if_name)
details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
details.HasLink = cDetails.link_up_down == C.uint8_t(1)
// - RX queues:
var i uint8
for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cRxQueue.qid),
RingSize: uint32(cRxQueue.ring_size),
BufferSize: uint16(cRxQueue.buffer_size),
}
details.RxQueues = append(details.RxQueues, queueDetails)
}
// - TX queues:
for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cTxQueue.qid),
RingSize: uint32(cTxQueue.ring_size),
BufferSize: uint16(cTxQueue.buffer_size),
}
details.TxQueues = append(details.TxQueues, queueDetails)
}
return details, nil
} | [
"func",
"(",
"memif",
"*",
"Memif",
")",
"GetDetails",
"(",
")",
"(",
"details",
"*",
"MemifDetails",
",",
"err",
"error",
")",
"{",
"cDetails",
":=",
"C",
".",
"govpp_memif_details_t",
"{",
"}",
"\n",
"var",
"buf",
"*",
"C",
".",
"char",
"\n\n",
"// Get memif details from C-libmemif.",
"errCode",
":=",
"C",
".",
"govpp_memif_get_details",
"(",
"memif",
".",
"cHandle",
",",
"&",
"cDetails",
",",
"&",
"buf",
")",
"\n",
"err",
"=",
"getMemifError",
"(",
"int",
"(",
"errCode",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"buf",
")",
")",
"\n\n",
"// Convert details from C to Go.",
"details",
"=",
"&",
"MemifDetails",
"{",
"}",
"\n",
"// - metadata:",
"details",
".",
"IfName",
"=",
"C",
".",
"GoString",
"(",
"cDetails",
".",
"if_name",
")",
"\n",
"details",
".",
"InstanceName",
"=",
"C",
".",
"GoString",
"(",
"cDetails",
".",
"inst_name",
")",
"\n",
"details",
".",
"ConnID",
"=",
"uint32",
"(",
"cDetails",
".",
"id",
")",
"\n",
"details",
".",
"SocketFilename",
"=",
"C",
".",
"GoString",
"(",
"cDetails",
".",
"socket_filename",
")",
"\n",
"if",
"cDetails",
".",
"secret",
"!=",
"nil",
"{",
"details",
".",
"Secret",
"=",
"C",
".",
"GoString",
"(",
"cDetails",
".",
"secret",
")",
"\n",
"}",
"\n",
"details",
".",
"IsMaster",
"=",
"cDetails",
".",
"role",
"==",
"C",
".",
"uint8_t",
"(",
"0",
")",
"\n",
"switch",
"cDetails",
".",
"mode",
"{",
"case",
"C",
".",
"MEMIF_INTERFACE_MODE_ETHERNET",
":",
"details",
".",
"Mode",
"=",
"IfModeEthernet",
"\n",
"case",
"C",
".",
"MEMIF_INTERFACE_MODE_IP",
":",
"details",
".",
"Mode",
"=",
"IfModeIP",
"\n",
"case",
"C",
".",
"MEMIF_INTERFACE_MODE_PUNT_INJECT",
":",
"details",
".",
"Mode",
"=",
"IfModePuntInject",
"\n",
"default",
":",
"details",
".",
"Mode",
"=",
"IfModeEthernet",
"\n",
"}",
"\n",
"// - connection details:",
"details",
".",
"RemoteIfName",
"=",
"C",
".",
"GoString",
"(",
"cDetails",
".",
"remote_if_name",
")",
"\n",
"details",
".",
"RemoteInstanceName",
"=",
"C",
".",
"GoString",
"(",
"cDetails",
".",
"remote_inst_name",
")",
"\n",
"details",
".",
"HasLink",
"=",
"cDetails",
".",
"link_up_down",
"==",
"C",
".",
"uint8_t",
"(",
"1",
")",
"\n",
"// - RX queues:",
"var",
"i",
"uint8",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"uint8",
"(",
"cDetails",
".",
"rx_queues_num",
")",
";",
"i",
"++",
"{",
"cRxQueue",
":=",
"C",
".",
"govpp_get_rx_queue_details",
"(",
"&",
"cDetails",
",",
"C",
".",
"int",
"(",
"i",
")",
")",
"\n",
"queueDetails",
":=",
"MemifQueueDetails",
"{",
"QueueID",
":",
"uint8",
"(",
"cRxQueue",
".",
"qid",
")",
",",
"RingSize",
":",
"uint32",
"(",
"cRxQueue",
".",
"ring_size",
")",
",",
"BufferSize",
":",
"uint16",
"(",
"cRxQueue",
".",
"buffer_size",
")",
",",
"}",
"\n",
"details",
".",
"RxQueues",
"=",
"append",
"(",
"details",
".",
"RxQueues",
",",
"queueDetails",
")",
"\n",
"}",
"\n",
"// - TX queues:",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"uint8",
"(",
"cDetails",
".",
"tx_queues_num",
")",
";",
"i",
"++",
"{",
"cTxQueue",
":=",
"C",
".",
"govpp_get_tx_queue_details",
"(",
"&",
"cDetails",
",",
"C",
".",
"int",
"(",
"i",
")",
")",
"\n",
"queueDetails",
":=",
"MemifQueueDetails",
"{",
"QueueID",
":",
"uint8",
"(",
"cTxQueue",
".",
"qid",
")",
",",
"RingSize",
":",
"uint32",
"(",
"cTxQueue",
".",
"ring_size",
")",
",",
"BufferSize",
":",
"uint16",
"(",
"cTxQueue",
".",
"buffer_size",
")",
",",
"}",
"\n",
"details",
".",
"TxQueues",
"=",
"append",
"(",
"details",
".",
"TxQueues",
",",
"queueDetails",
")",
"\n",
"}",
"\n\n",
"return",
"details",
",",
"nil",
"\n",
"}"
] | // GetDetails returns a detailed runtime information about this memif.
// The method is thread-safe. | [
"GetDetails",
"returns",
"a",
"detailed",
"runtime",
"information",
"about",
"this",
"memif",
".",
"The",
"method",
"is",
"thread",
"-",
"safe",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L696-L756 |
12,644 | FDio/govpp | extras/libmemif/adapter.go | Close | func (memif *Memif) Close() error {
log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")
// Delete memif from C-libmemif.
err := getMemifError(int(C.memif_delete(&memif.cHandle)))
if err != nil {
// Close memif-global interrupt channel.
close(memif.intCh)
// Close file descriptor stopQPollFd.
C.close(C.int(memif.stopQPollFd))
}
context.lock.Lock()
defer context.lock.Unlock()
// Unregister the interface from the context.
delete(context.memifs, memif.ifIndex)
log.WithField("ifName", memif.IfName).Debug("memif interface was closed")
return err
} | go | func (memif *Memif) Close() error {
log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")
// Delete memif from C-libmemif.
err := getMemifError(int(C.memif_delete(&memif.cHandle)))
if err != nil {
// Close memif-global interrupt channel.
close(memif.intCh)
// Close file descriptor stopQPollFd.
C.close(C.int(memif.stopQPollFd))
}
context.lock.Lock()
defer context.lock.Unlock()
// Unregister the interface from the context.
delete(context.memifs, memif.ifIndex)
log.WithField("ifName", memif.IfName).Debug("memif interface was closed")
return err
} | [
"func",
"(",
"memif",
"*",
"Memif",
")",
"Close",
"(",
")",
"error",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"memif",
".",
"IfName",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// Delete memif from C-libmemif.",
"err",
":=",
"getMemifError",
"(",
"int",
"(",
"C",
".",
"memif_delete",
"(",
"&",
"memif",
".",
"cHandle",
")",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// Close memif-global interrupt channel.",
"close",
"(",
"memif",
".",
"intCh",
")",
"\n",
"// Close file descriptor stopQPollFd.",
"C",
".",
"close",
"(",
"C",
".",
"int",
"(",
"memif",
".",
"stopQPollFd",
")",
")",
"\n",
"}",
"\n\n",
"context",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"context",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"// Unregister the interface from the context.",
"delete",
"(",
"context",
".",
"memifs",
",",
"memif",
".",
"ifIndex",
")",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"memif",
".",
"IfName",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Close removes the memif interface. If the memif is in the connected state,
// the connection is first properly closed.
// Do not access memif after it is closed, let garbage collector to remove it. | [
"Close",
"removes",
"the",
"memif",
"interface",
".",
"If",
"the",
"memif",
"is",
"in",
"the",
"connected",
"state",
"the",
"connection",
"is",
"first",
"properly",
"closed",
".",
"Do",
"not",
"access",
"memif",
"after",
"it",
"is",
"closed",
"let",
"garbage",
"collector",
"to",
"remove",
"it",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L1005-L1025 |
12,645 | FDio/govpp | extras/libmemif/adapter.go | pollEvents | func pollEvents() {
defer context.wg.Done()
for {
errCode := C.memif_poll_event(C.int(-1))
err := getMemifError(int(errCode))
if err == ErrPollCanceled {
return
}
}
} | go | func pollEvents() {
defer context.wg.Done()
for {
errCode := C.memif_poll_event(C.int(-1))
err := getMemifError(int(errCode))
if err == ErrPollCanceled {
return
}
}
} | [
"func",
"pollEvents",
"(",
")",
"{",
"defer",
"context",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"for",
"{",
"errCode",
":=",
"C",
".",
"memif_poll_event",
"(",
"C",
".",
"int",
"(",
"-",
"1",
")",
")",
"\n",
"err",
":=",
"getMemifError",
"(",
"int",
"(",
"errCode",
")",
")",
"\n",
"if",
"err",
"==",
"ErrPollCanceled",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // pollEvents repeatedly polls for a libmemif event. | [
"pollEvents",
"repeatedly",
"polls",
"for",
"a",
"libmemif",
"event",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L1092-L1101 |
12,646 | FDio/govpp | extras/libmemif/adapter.go | pollRxQueue | func pollRxQueue(memif *Memif, queueID uint8) {
defer memif.wg.Done()
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Started queue interrupt polling.")
var qfd C.int
errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
err := getMemifError(int(errCode))
if err != nil {
log.WithField("err", err).Error("memif_get_queue_efd() failed")
return
}
// Create epoll file descriptor.
var event [1]syscall.EpollEvent
epFd, err := syscall.EpollCreate1(0)
if err != nil {
log.WithField("err", err).Error("epoll_create1() failed")
return
}
defer syscall.Close(epFd)
// Add Rx queue interrupt file descriptor.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(qfd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Add file descriptor used to stop this go routine.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(memif.stopQPollFd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Poll for interrupts.
for {
_, err := syscall.EpollWait(epFd, event[:], -1)
if err != nil {
log.WithField("err", err).Error("epoll_wait() failed")
return
}
// Handle Rx Interrupt.
if event[0].Fd == int32(qfd) {
// Consume the interrupt event.
buf := make([]byte, 8)
_, err = syscall.Read(int(qfd), buf[:])
if err != nil {
log.WithField("err", err).Warn("read() failed")
}
// Send signal to memif-global interrupt channel.
select {
case memif.intCh <- queueID:
break
default:
break
}
// Send signal to queue-specific interrupt channel.
select {
case memif.queueIntCh[queueID] <- struct{}{}:
break
default:
break
}
}
// Stop the go routine if requested.
if event[0].Fd == int32(memif.stopQPollFd) {
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Stopped queue interrupt polling.")
return
}
}
} | go | func pollRxQueue(memif *Memif, queueID uint8) {
defer memif.wg.Done()
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Started queue interrupt polling.")
var qfd C.int
errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
err := getMemifError(int(errCode))
if err != nil {
log.WithField("err", err).Error("memif_get_queue_efd() failed")
return
}
// Create epoll file descriptor.
var event [1]syscall.EpollEvent
epFd, err := syscall.EpollCreate1(0)
if err != nil {
log.WithField("err", err).Error("epoll_create1() failed")
return
}
defer syscall.Close(epFd)
// Add Rx queue interrupt file descriptor.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(qfd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Add file descriptor used to stop this go routine.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(memif.stopQPollFd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Poll for interrupts.
for {
_, err := syscall.EpollWait(epFd, event[:], -1)
if err != nil {
log.WithField("err", err).Error("epoll_wait() failed")
return
}
// Handle Rx Interrupt.
if event[0].Fd == int32(qfd) {
// Consume the interrupt event.
buf := make([]byte, 8)
_, err = syscall.Read(int(qfd), buf[:])
if err != nil {
log.WithField("err", err).Warn("read() failed")
}
// Send signal to memif-global interrupt channel.
select {
case memif.intCh <- queueID:
break
default:
break
}
// Send signal to queue-specific interrupt channel.
select {
case memif.queueIntCh[queueID] <- struct{}{}:
break
default:
break
}
}
// Stop the go routine if requested.
if event[0].Fd == int32(memif.stopQPollFd) {
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Stopped queue interrupt polling.")
return
}
}
} | [
"func",
"pollRxQueue",
"(",
"memif",
"*",
"Memif",
",",
"queueID",
"uint8",
")",
"{",
"defer",
"memif",
".",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"log",
".",
"WithFields",
"(",
"logger",
".",
"Fields",
"{",
"\"",
"\"",
":",
"memif",
".",
"IfName",
",",
"\"",
"\"",
":",
"queueID",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"var",
"qfd",
"C",
".",
"int",
"\n",
"errCode",
":=",
"C",
".",
"memif_get_queue_efd",
"(",
"memif",
".",
"cHandle",
",",
"C",
".",
"uint16_t",
"(",
"queueID",
")",
",",
"&",
"qfd",
")",
"\n",
"err",
":=",
"getMemifError",
"(",
"int",
"(",
"errCode",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Create epoll file descriptor.",
"var",
"event",
"[",
"1",
"]",
"syscall",
".",
"EpollEvent",
"\n",
"epFd",
",",
"err",
":=",
"syscall",
".",
"EpollCreate1",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"syscall",
".",
"Close",
"(",
"epFd",
")",
"\n\n",
"// Add Rx queue interrupt file descriptor.",
"event",
"[",
"0",
"]",
".",
"Events",
"=",
"syscall",
".",
"EPOLLIN",
"\n",
"event",
"[",
"0",
"]",
".",
"Fd",
"=",
"int32",
"(",
"qfd",
")",
"\n",
"if",
"err",
"=",
"syscall",
".",
"EpollCtl",
"(",
"epFd",
",",
"syscall",
".",
"EPOLL_CTL_ADD",
",",
"int",
"(",
"qfd",
")",
",",
"&",
"event",
"[",
"0",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Add file descriptor used to stop this go routine.",
"event",
"[",
"0",
"]",
".",
"Events",
"=",
"syscall",
".",
"EPOLLIN",
"\n",
"event",
"[",
"0",
"]",
".",
"Fd",
"=",
"int32",
"(",
"memif",
".",
"stopQPollFd",
")",
"\n",
"if",
"err",
"=",
"syscall",
".",
"EpollCtl",
"(",
"epFd",
",",
"syscall",
".",
"EPOLL_CTL_ADD",
",",
"memif",
".",
"stopQPollFd",
",",
"&",
"event",
"[",
"0",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Poll for interrupts.",
"for",
"{",
"_",
",",
"err",
":=",
"syscall",
".",
"EpollWait",
"(",
"epFd",
",",
"event",
"[",
":",
"]",
",",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Handle Rx Interrupt.",
"if",
"event",
"[",
"0",
"]",
".",
"Fd",
"==",
"int32",
"(",
"qfd",
")",
"{",
"// Consume the interrupt event.",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8",
")",
"\n",
"_",
",",
"err",
"=",
"syscall",
".",
"Read",
"(",
"int",
"(",
"qfd",
")",
",",
"buf",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Send signal to memif-global interrupt channel.",
"select",
"{",
"case",
"memif",
".",
"intCh",
"<-",
"queueID",
":",
"break",
"\n",
"default",
":",
"break",
"\n",
"}",
"\n\n",
"// Send signal to queue-specific interrupt channel.",
"select",
"{",
"case",
"memif",
".",
"queueIntCh",
"[",
"queueID",
"]",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"break",
"\n",
"default",
":",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Stop the go routine if requested.",
"if",
"event",
"[",
"0",
"]",
".",
"Fd",
"==",
"int32",
"(",
"memif",
".",
"stopQPollFd",
")",
"{",
"log",
".",
"WithFields",
"(",
"logger",
".",
"Fields",
"{",
"\"",
"\"",
":",
"memif",
".",
"IfName",
",",
"\"",
"\"",
":",
"queueID",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // pollRxQueue repeatedly polls an Rx queue for interrupts. | [
"pollRxQueue",
"repeatedly",
"polls",
"an",
"Rx",
"queue",
"for",
"interrupts",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L1104-L1188 |
12,647 | FDio/govpp | extras/libmemif/examples/icmp-responder/icmp-responder.go | IcmpResponder | func IcmpResponder(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
// Get channel which fires every time there are packets to read on the queue.
interruptCh, err := memif.GetQueueInterruptChan(queueID)
if err != nil {
// Example of libmemif error handling code:
switch err {
case libmemif.ErrQueueID:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() complains about invalid queue id!?")
// Here you would put all the errors that need to be handled individually...
default:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() error: %v\n", err)
}
return
}
for {
select {
case <-interruptCh:
// Read all packets from the queue but at most 10 at once.
// Since there is only one interrupt signal sent for an entire burst
// of packets, an interrupt handling routine should repeatedly call
// RxBurst() until the function returns an empty slice of packets.
// This way it is ensured that there are no packets left
// on the queue unread when the interrupt signal is cleared.
for {
packets, err := memif.RxBurst(queueID, 10)
if err != nil {
fmt.Printf("libmemif.Memif.RxBurst() error: %v\n", err)
// Skip this burst, continue with the next one 3secs later...
break
}
if len(packets) == 0 {
// No more packets to read until the next interrupt.
break
}
// Generate response for each supported request.
responses := []libmemif.RawPacketData{}
for _, packet := range packets {
fmt.Println("Received new packet:")
DumpPacket(packet)
response, err := GeneratePacketResponse(packet)
if err == nil {
fmt.Println("Sending response:")
DumpPacket(response)
responses = append(responses, response)
} else {
fmt.Printf("Failed to generate response: %v\n", err)
}
}
// Send pongs / ARP responses. We may not be able to do it in one
// burst if the ring is (almost) full or the internal buffer cannot
// contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, responses[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(responses) {
break
}
}
}
}
case <-stopCh:
return
}
}
} | go | func IcmpResponder(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
// Get channel which fires every time there are packets to read on the queue.
interruptCh, err := memif.GetQueueInterruptChan(queueID)
if err != nil {
// Example of libmemif error handling code:
switch err {
case libmemif.ErrQueueID:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() complains about invalid queue id!?")
// Here you would put all the errors that need to be handled individually...
default:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() error: %v\n", err)
}
return
}
for {
select {
case <-interruptCh:
// Read all packets from the queue but at most 10 at once.
// Since there is only one interrupt signal sent for an entire burst
// of packets, an interrupt handling routine should repeatedly call
// RxBurst() until the function returns an empty slice of packets.
// This way it is ensured that there are no packets left
// on the queue unread when the interrupt signal is cleared.
for {
packets, err := memif.RxBurst(queueID, 10)
if err != nil {
fmt.Printf("libmemif.Memif.RxBurst() error: %v\n", err)
// Skip this burst, continue with the next one 3secs later...
break
}
if len(packets) == 0 {
// No more packets to read until the next interrupt.
break
}
// Generate response for each supported request.
responses := []libmemif.RawPacketData{}
for _, packet := range packets {
fmt.Println("Received new packet:")
DumpPacket(packet)
response, err := GeneratePacketResponse(packet)
if err == nil {
fmt.Println("Sending response:")
DumpPacket(response)
responses = append(responses, response)
} else {
fmt.Printf("Failed to generate response: %v\n", err)
}
}
// Send pongs / ARP responses. We may not be able to do it in one
// burst if the ring is (almost) full or the internal buffer cannot
// contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, responses[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(responses) {
break
}
}
}
}
case <-stopCh:
return
}
}
} | [
"func",
"IcmpResponder",
"(",
"memif",
"*",
"libmemif",
".",
"Memif",
",",
"queueID",
"uint8",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"// Get channel which fires every time there are packets to read on the queue.",
"interruptCh",
",",
"err",
":=",
"memif",
".",
"GetQueueInterruptChan",
"(",
"queueID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Example of libmemif error handling code:",
"switch",
"err",
"{",
"case",
"libmemif",
".",
"ErrQueueID",
":",
"fmt",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"// Here you would put all the errors that need to be handled individually...",
"default",
":",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"interruptCh",
":",
"// Read all packets from the queue but at most 10 at once.",
"// Since there is only one interrupt signal sent for an entire burst",
"// of packets, an interrupt handling routine should repeatedly call",
"// RxBurst() until the function returns an empty slice of packets.",
"// This way it is ensured that there are no packets left",
"// on the queue unread when the interrupt signal is cleared.",
"for",
"{",
"packets",
",",
"err",
":=",
"memif",
".",
"RxBurst",
"(",
"queueID",
",",
"10",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"// Skip this burst, continue with the next one 3secs later...",
"break",
"\n",
"}",
"\n",
"if",
"len",
"(",
"packets",
")",
"==",
"0",
"{",
"// No more packets to read until the next interrupt.",
"break",
"\n",
"}",
"\n",
"// Generate response for each supported request.",
"responses",
":=",
"[",
"]",
"libmemif",
".",
"RawPacketData",
"{",
"}",
"\n",
"for",
"_",
",",
"packet",
":=",
"range",
"packets",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"DumpPacket",
"(",
"packet",
")",
"\n",
"response",
",",
"err",
":=",
"GeneratePacketResponse",
"(",
"packet",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"DumpPacket",
"(",
"response",
")",
"\n",
"responses",
"=",
"append",
"(",
"responses",
",",
"response",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Send pongs / ARP responses. We may not be able to do it in one",
"// burst if the ring is (almost) full or the internal buffer cannot",
"// contain it.",
"sent",
":=",
"0",
"\n",
"for",
"{",
"count",
",",
"err",
":=",
"memif",
".",
"TxBurst",
"(",
"queueID",
",",
"responses",
"[",
"sent",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"break",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"count",
")",
"\n",
"sent",
"+=",
"int",
"(",
"count",
")",
"\n",
"if",
"sent",
"==",
"len",
"(",
"responses",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"<-",
"stopCh",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // IcmpResponder answers to ICMP pings with ICMP pongs. | [
"IcmpResponder",
"answers",
"to",
"ICMP",
"pings",
"with",
"ICMP",
"pongs",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/icmp-responder/icmp-responder.go#L120-L193 |
12,648 | FDio/govpp | extras/libmemif/examples/icmp-responder/icmp-responder.go | DumpPacket | func DumpPacket(packetData libmemif.RawPacketData) {
packet := gopacket.NewPacket(packetData, layers.LayerTypeEthernet, gopacket.Default)
fmt.Println(packet.Dump())
} | go | func DumpPacket(packetData libmemif.RawPacketData) {
packet := gopacket.NewPacket(packetData, layers.LayerTypeEthernet, gopacket.Default)
fmt.Println(packet.Dump())
} | [
"func",
"DumpPacket",
"(",
"packetData",
"libmemif",
".",
"RawPacketData",
")",
"{",
"packet",
":=",
"gopacket",
".",
"NewPacket",
"(",
"packetData",
",",
"layers",
".",
"LayerTypeEthernet",
",",
"gopacket",
".",
"Default",
")",
"\n",
"fmt",
".",
"Println",
"(",
"packet",
".",
"Dump",
"(",
")",
")",
"\n",
"}"
] | // DumpPacket prints a human-readable description of the packet. | [
"DumpPacket",
"prints",
"a",
"human",
"-",
"readable",
"description",
"of",
"the",
"packet",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/icmp-responder/icmp-responder.go#L196-L199 |
12,649 | FDio/govpp | core/channel.go | receiveReplyInternal | func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
if msg == nil {
return false, errors.New("nil message passed in")
}
var ignore bool
if vppReply := ch.delayedReply; vppReply != nil {
// try the delayed reply
ch.delayedReply = nil
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if !ignore {
return lastReplyReceived, err
}
}
timer := time.NewTimer(ch.replyTimeout)
for {
select {
// blocks until a reply comes to ReplyChan or until timeout expires
case vppReply := <-ch.replyChan:
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if ignore {
logrus.Warnf("ignoring reply: %+v", vppReply)
continue
}
return lastReplyReceived, err
case <-timer.C:
err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
return false, err
}
}
return
} | go | func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
if msg == nil {
return false, errors.New("nil message passed in")
}
var ignore bool
if vppReply := ch.delayedReply; vppReply != nil {
// try the delayed reply
ch.delayedReply = nil
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if !ignore {
return lastReplyReceived, err
}
}
timer := time.NewTimer(ch.replyTimeout)
for {
select {
// blocks until a reply comes to ReplyChan or until timeout expires
case vppReply := <-ch.replyChan:
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if ignore {
logrus.Warnf("ignoring reply: %+v", vppReply)
continue
}
return lastReplyReceived, err
case <-timer.C:
err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
return false, err
}
}
return
} | [
"func",
"(",
"ch",
"*",
"Channel",
")",
"receiveReplyInternal",
"(",
"msg",
"api",
".",
"Message",
",",
"expSeqNum",
"uint16",
")",
"(",
"lastReplyReceived",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"msg",
"==",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"ignore",
"bool",
"\n\n",
"if",
"vppReply",
":=",
"ch",
".",
"delayedReply",
";",
"vppReply",
"!=",
"nil",
"{",
"// try the delayed reply",
"ch",
".",
"delayedReply",
"=",
"nil",
"\n",
"ignore",
",",
"lastReplyReceived",
",",
"err",
"=",
"ch",
".",
"processReply",
"(",
"vppReply",
",",
"expSeqNum",
",",
"msg",
")",
"\n",
"if",
"!",
"ignore",
"{",
"return",
"lastReplyReceived",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"timer",
":=",
"time",
".",
"NewTimer",
"(",
"ch",
".",
"replyTimeout",
")",
"\n",
"for",
"{",
"select",
"{",
"// blocks until a reply comes to ReplyChan or until timeout expires",
"case",
"vppReply",
":=",
"<-",
"ch",
".",
"replyChan",
":",
"ignore",
",",
"lastReplyReceived",
",",
"err",
"=",
"ch",
".",
"processReply",
"(",
"vppReply",
",",
"expSeqNum",
",",
"msg",
")",
"\n",
"if",
"ignore",
"{",
"logrus",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"vppReply",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"lastReplyReceived",
",",
"err",
"\n\n",
"case",
"<-",
"timer",
".",
"C",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ch",
".",
"replyTimeout",
")",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // receiveReplyInternal receives a reply from the reply channel into the provided msg structure. | [
"receiveReplyInternal",
"receives",
"a",
"reply",
"from",
"the",
"reply",
"channel",
"into",
"the",
"provided",
"msg",
"structure",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/channel.go#L235-L269 |
12,650 | FDio/govpp | adapter/mock/mock_stats_adapter.go | ListStats | func (a *StatsAdapter) ListStats(patterns ...string) ([]string, error) {
var statNames []string
for _, stat := range a.entries {
statNames = append(statNames, stat.Name)
}
return statNames, nil
} | go | func (a *StatsAdapter) ListStats(patterns ...string) ([]string, error) {
var statNames []string
for _, stat := range a.entries {
statNames = append(statNames, stat.Name)
}
return statNames, nil
} | [
"func",
"(",
"a",
"*",
"StatsAdapter",
")",
"ListStats",
"(",
"patterns",
"...",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"statNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"stat",
":=",
"range",
"a",
".",
"entries",
"{",
"statNames",
"=",
"append",
"(",
"statNames",
",",
"stat",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"statNames",
",",
"nil",
"\n",
"}"
] | // ListStats mocks name listing for all stats. | [
"ListStats",
"mocks",
"name",
"listing",
"for",
"all",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_stats_adapter.go#L45-L51 |
12,651 | FDio/govpp | adapter/mock/mock_stats_adapter.go | DumpStats | func (a *StatsAdapter) DumpStats(patterns ...string) ([]*adapter.StatEntry, error) {
return a.entries, nil
} | go | func (a *StatsAdapter) DumpStats(patterns ...string) ([]*adapter.StatEntry, error) {
return a.entries, nil
} | [
"func",
"(",
"a",
"*",
"StatsAdapter",
")",
"DumpStats",
"(",
"patterns",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"adapter",
".",
"StatEntry",
",",
"error",
")",
"{",
"return",
"a",
".",
"entries",
",",
"nil",
"\n",
"}"
] | // DumpStats mocks all stat entries dump. | [
"DumpStats",
"mocks",
"all",
"stat",
"entries",
"dump",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_stats_adapter.go#L54-L56 |
12,652 | FDio/govpp | cmd/binapi-generator/types.go | convertToGoType | func convertToGoType(ctx *context, binapiType string) (typ string) {
if t, ok := binapiTypes[binapiType]; ok {
// basic types
typ = t
} else if r, ok := ctx.packageData.RefMap[binapiType]; ok {
// specific types (enums/types/unions)
typ = camelCaseName(r)
} else {
switch binapiType {
case "bool", "string":
typ = binapiType
default:
// fallback type
log.Warnf("found unknown VPP binary API type %q, using byte", binapiType)
typ = "byte"
}
}
return typ
} | go | func convertToGoType(ctx *context, binapiType string) (typ string) {
if t, ok := binapiTypes[binapiType]; ok {
// basic types
typ = t
} else if r, ok := ctx.packageData.RefMap[binapiType]; ok {
// specific types (enums/types/unions)
typ = camelCaseName(r)
} else {
switch binapiType {
case "bool", "string":
typ = binapiType
default:
// fallback type
log.Warnf("found unknown VPP binary API type %q, using byte", binapiType)
typ = "byte"
}
}
return typ
} | [
"func",
"convertToGoType",
"(",
"ctx",
"*",
"context",
",",
"binapiType",
"string",
")",
"(",
"typ",
"string",
")",
"{",
"if",
"t",
",",
"ok",
":=",
"binapiTypes",
"[",
"binapiType",
"]",
";",
"ok",
"{",
"// basic types",
"typ",
"=",
"t",
"\n",
"}",
"else",
"if",
"r",
",",
"ok",
":=",
"ctx",
".",
"packageData",
".",
"RefMap",
"[",
"binapiType",
"]",
";",
"ok",
"{",
"// specific types (enums/types/unions)",
"typ",
"=",
"camelCaseName",
"(",
"r",
")",
"\n",
"}",
"else",
"{",
"switch",
"binapiType",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"typ",
"=",
"binapiType",
"\n",
"default",
":",
"// fallback type",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"binapiType",
")",
"\n",
"typ",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"typ",
"\n",
"}"
] | // convertToGoType translates the VPP binary API type into Go type | [
"convertToGoType",
"translates",
"the",
"VPP",
"binary",
"API",
"type",
"into",
"Go",
"type"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/types.go#L52-L70 |
12,653 | FDio/govpp | cmd/binapi-generator/parse.go | printPackage | func printPackage(pkg *Package) {
if len(pkg.Enums) > 0 {
logf("loaded %d enums:", len(pkg.Enums))
for k, enum := range pkg.Enums {
logf(" - enum #%d\t%+v", k, enum)
}
}
if len(pkg.Unions) > 0 {
logf("loaded %d unions:", len(pkg.Unions))
for k, union := range pkg.Unions {
logf(" - union #%d\t%+v", k, union)
}
}
if len(pkg.Types) > 0 {
logf("loaded %d types:", len(pkg.Types))
for _, typ := range pkg.Types {
logf(" - type: %q (%d fields)", typ.Name, len(typ.Fields))
}
}
if len(pkg.Messages) > 0 {
logf("loaded %d messages:", len(pkg.Messages))
for _, msg := range pkg.Messages {
logf(" - message: %q (%d fields)", msg.Name, len(msg.Fields))
}
}
if len(pkg.Services) > 0 {
logf("loaded %d services:", len(pkg.Services))
for _, svc := range pkg.Services {
var info string
if svc.Stream {
info = "(STREAM)"
} else if len(svc.Events) > 0 {
info = fmt.Sprintf("(EVENTS: %v)", svc.Events)
}
logf(" - service: %q -> %q %s", svc.RequestType, svc.ReplyType, info)
}
}
} | go | func printPackage(pkg *Package) {
if len(pkg.Enums) > 0 {
logf("loaded %d enums:", len(pkg.Enums))
for k, enum := range pkg.Enums {
logf(" - enum #%d\t%+v", k, enum)
}
}
if len(pkg.Unions) > 0 {
logf("loaded %d unions:", len(pkg.Unions))
for k, union := range pkg.Unions {
logf(" - union #%d\t%+v", k, union)
}
}
if len(pkg.Types) > 0 {
logf("loaded %d types:", len(pkg.Types))
for _, typ := range pkg.Types {
logf(" - type: %q (%d fields)", typ.Name, len(typ.Fields))
}
}
if len(pkg.Messages) > 0 {
logf("loaded %d messages:", len(pkg.Messages))
for _, msg := range pkg.Messages {
logf(" - message: %q (%d fields)", msg.Name, len(msg.Fields))
}
}
if len(pkg.Services) > 0 {
logf("loaded %d services:", len(pkg.Services))
for _, svc := range pkg.Services {
var info string
if svc.Stream {
info = "(STREAM)"
} else if len(svc.Events) > 0 {
info = fmt.Sprintf("(EVENTS: %v)", svc.Events)
}
logf(" - service: %q -> %q %s", svc.RequestType, svc.ReplyType, info)
}
}
} | [
"func",
"printPackage",
"(",
"pkg",
"*",
"Package",
")",
"{",
"if",
"len",
"(",
"pkg",
".",
"Enums",
")",
">",
"0",
"{",
"logf",
"(",
"\"",
"\"",
",",
"len",
"(",
"pkg",
".",
"Enums",
")",
")",
"\n",
"for",
"k",
",",
"enum",
":=",
"range",
"pkg",
".",
"Enums",
"{",
"logf",
"(",
"\"",
"\\t",
"\"",
",",
"k",
",",
"enum",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pkg",
".",
"Unions",
")",
">",
"0",
"{",
"logf",
"(",
"\"",
"\"",
",",
"len",
"(",
"pkg",
".",
"Unions",
")",
")",
"\n",
"for",
"k",
",",
"union",
":=",
"range",
"pkg",
".",
"Unions",
"{",
"logf",
"(",
"\"",
"\\t",
"\"",
",",
"k",
",",
"union",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pkg",
".",
"Types",
")",
">",
"0",
"{",
"logf",
"(",
"\"",
"\"",
",",
"len",
"(",
"pkg",
".",
"Types",
")",
")",
"\n",
"for",
"_",
",",
"typ",
":=",
"range",
"pkg",
".",
"Types",
"{",
"logf",
"(",
"\"",
"\"",
",",
"typ",
".",
"Name",
",",
"len",
"(",
"typ",
".",
"Fields",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pkg",
".",
"Messages",
")",
">",
"0",
"{",
"logf",
"(",
"\"",
"\"",
",",
"len",
"(",
"pkg",
".",
"Messages",
")",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"pkg",
".",
"Messages",
"{",
"logf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Name",
",",
"len",
"(",
"msg",
".",
"Fields",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pkg",
".",
"Services",
")",
">",
"0",
"{",
"logf",
"(",
"\"",
"\"",
",",
"len",
"(",
"pkg",
".",
"Services",
")",
")",
"\n",
"for",
"_",
",",
"svc",
":=",
"range",
"pkg",
".",
"Services",
"{",
"var",
"info",
"string",
"\n",
"if",
"svc",
".",
"Stream",
"{",
"info",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"len",
"(",
"svc",
".",
"Events",
")",
">",
"0",
"{",
"info",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"svc",
".",
"Events",
")",
"\n",
"}",
"\n",
"logf",
"(",
"\"",
"\"",
",",
"svc",
".",
"RequestType",
",",
"svc",
".",
"ReplyType",
",",
"info",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printPackage prints all loaded objects for package | [
"printPackage",
"prints",
"all",
"loaded",
"objects",
"for",
"package"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L200-L237 |
12,654 | FDio/govpp | cmd/binapi-generator/parse.go | parseEnum | func parseEnum(ctx *context, enumNode *jsongo.JSONNode) (*Enum, error) {
if enumNode.Len() == 0 || enumNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum specified")
}
enumName, ok := enumNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum name is %T, not a string", enumNode.At(0).Get())
}
enumType, ok := enumNode.At(enumNode.Len() - 1).At("enumtype").Get().(string)
if !ok {
return nil, fmt.Errorf("enum type invalid or missing")
}
enum := Enum{
Name: enumName,
Type: enumType,
}
// loop through enum entries, skip first (name) and last (enumtype)
for j := 1; j < enumNode.Len()-1; j++ {
if enumNode.At(j).GetType() == jsongo.TypeArray {
entry := enumNode.At(j)
if entry.Len() < 2 || entry.At(0).GetType() != jsongo.TypeValue || entry.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum entry specified")
}
entryName, ok := entry.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum entry name is %T, not a string", entry.At(0).Get())
}
entryVal := entry.At(1).Get()
enum.Entries = append(enum.Entries, EnumEntry{
Name: entryName,
Value: entryVal,
})
}
}
return &enum, nil
} | go | func parseEnum(ctx *context, enumNode *jsongo.JSONNode) (*Enum, error) {
if enumNode.Len() == 0 || enumNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum specified")
}
enumName, ok := enumNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum name is %T, not a string", enumNode.At(0).Get())
}
enumType, ok := enumNode.At(enumNode.Len() - 1).At("enumtype").Get().(string)
if !ok {
return nil, fmt.Errorf("enum type invalid or missing")
}
enum := Enum{
Name: enumName,
Type: enumType,
}
// loop through enum entries, skip first (name) and last (enumtype)
for j := 1; j < enumNode.Len()-1; j++ {
if enumNode.At(j).GetType() == jsongo.TypeArray {
entry := enumNode.At(j)
if entry.Len() < 2 || entry.At(0).GetType() != jsongo.TypeValue || entry.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum entry specified")
}
entryName, ok := entry.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum entry name is %T, not a string", entry.At(0).Get())
}
entryVal := entry.At(1).Get()
enum.Entries = append(enum.Entries, EnumEntry{
Name: entryName,
Value: entryVal,
})
}
}
return &enum, nil
} | [
"func",
"parseEnum",
"(",
"ctx",
"*",
"context",
",",
"enumNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Enum",
",",
"error",
")",
"{",
"if",
"enumNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"enumNode",
".",
"At",
"(",
"0",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"enumName",
",",
"ok",
":=",
"enumNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"enumNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"enumType",
",",
"ok",
":=",
"enumNode",
".",
"At",
"(",
"enumNode",
".",
"Len",
"(",
")",
"-",
"1",
")",
".",
"At",
"(",
"\"",
"\"",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"enum",
":=",
"Enum",
"{",
"Name",
":",
"enumName",
",",
"Type",
":",
"enumType",
",",
"}",
"\n\n",
"// loop through enum entries, skip first (name) and last (enumtype)",
"for",
"j",
":=",
"1",
";",
"j",
"<",
"enumNode",
".",
"Len",
"(",
")",
"-",
"1",
";",
"j",
"++",
"{",
"if",
"enumNode",
".",
"At",
"(",
"j",
")",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeArray",
"{",
"entry",
":=",
"enumNode",
".",
"At",
"(",
"j",
")",
"\n\n",
"if",
"entry",
".",
"Len",
"(",
")",
"<",
"2",
"||",
"entry",
".",
"At",
"(",
"0",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"||",
"entry",
".",
"At",
"(",
"1",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"entryName",
",",
"ok",
":=",
"entry",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"entry",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"entryVal",
":=",
"entry",
".",
"At",
"(",
"1",
")",
".",
"Get",
"(",
")",
"\n\n",
"enum",
".",
"Entries",
"=",
"append",
"(",
"enum",
".",
"Entries",
",",
"EnumEntry",
"{",
"Name",
":",
"entryName",
",",
"Value",
":",
"entryVal",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"enum",
",",
"nil",
"\n",
"}"
] | // parseEnum parses VPP binary API enum object from JSON node | [
"parseEnum",
"parses",
"VPP",
"binary",
"API",
"enum",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L240-L282 |
12,655 | FDio/govpp | cmd/binapi-generator/parse.go | parseUnion | func parseUnion(ctx *context, unionNode *jsongo.JSONNode) (*Union, error) {
if unionNode.Len() == 0 || unionNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for union specified")
}
unionName, ok := unionNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("union name is %T, not a string", unionNode.At(0).Get())
}
unionCRC, ok := unionNode.At(unionNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("union crc invalid or missing")
}
union := Union{
Name: unionName,
CRC: unionCRC,
}
// loop through union fields, skip first (name) and last (crc)
for j := 1; j < unionNode.Len()-1; j++ {
if unionNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := unionNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
union.Fields = append(union.Fields, *field)
}
}
return &union, nil
} | go | func parseUnion(ctx *context, unionNode *jsongo.JSONNode) (*Union, error) {
if unionNode.Len() == 0 || unionNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for union specified")
}
unionName, ok := unionNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("union name is %T, not a string", unionNode.At(0).Get())
}
unionCRC, ok := unionNode.At(unionNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("union crc invalid or missing")
}
union := Union{
Name: unionName,
CRC: unionCRC,
}
// loop through union fields, skip first (name) and last (crc)
for j := 1; j < unionNode.Len()-1; j++ {
if unionNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := unionNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
union.Fields = append(union.Fields, *field)
}
}
return &union, nil
} | [
"func",
"parseUnion",
"(",
"ctx",
"*",
"context",
",",
"unionNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Union",
",",
"error",
")",
"{",
"if",
"unionNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"unionNode",
".",
"At",
"(",
"0",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"unionName",
",",
"ok",
":=",
"unionNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"unionNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"unionCRC",
",",
"ok",
":=",
"unionNode",
".",
"At",
"(",
"unionNode",
".",
"Len",
"(",
")",
"-",
"1",
")",
".",
"At",
"(",
"crcField",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"union",
":=",
"Union",
"{",
"Name",
":",
"unionName",
",",
"CRC",
":",
"unionCRC",
",",
"}",
"\n\n",
"// loop through union fields, skip first (name) and last (crc)",
"for",
"j",
":=",
"1",
";",
"j",
"<",
"unionNode",
".",
"Len",
"(",
")",
"-",
"1",
";",
"j",
"++",
"{",
"if",
"unionNode",
".",
"At",
"(",
"j",
")",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeArray",
"{",
"fieldNode",
":=",
"unionNode",
".",
"At",
"(",
"j",
")",
"\n\n",
"field",
",",
"err",
":=",
"parseField",
"(",
"ctx",
",",
"fieldNode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"union",
".",
"Fields",
"=",
"append",
"(",
"union",
".",
"Fields",
",",
"*",
"field",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"union",
",",
"nil",
"\n",
"}"
] | // parseUnion parses VPP binary API union object from JSON node | [
"parseUnion",
"parses",
"VPP",
"binary",
"API",
"union",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L285-L319 |
12,656 | FDio/govpp | cmd/binapi-generator/parse.go | parseType | func parseType(ctx *context, typeNode *jsongo.JSONNode) (*Type, error) {
if typeNode.Len() == 0 || typeNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for type specified")
}
typeName, ok := typeNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("type name is %T, not a string", typeNode.At(0).Get())
}
typeCRC, ok := typeNode.At(typeNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("type crc invalid or missing")
}
typ := Type{
Name: typeName,
CRC: typeCRC,
}
// loop through type fields, skip first (name) and last (crc)
for j := 1; j < typeNode.Len()-1; j++ {
if typeNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := typeNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
typ.Fields = append(typ.Fields, *field)
}
}
return &typ, nil
} | go | func parseType(ctx *context, typeNode *jsongo.JSONNode) (*Type, error) {
if typeNode.Len() == 0 || typeNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for type specified")
}
typeName, ok := typeNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("type name is %T, not a string", typeNode.At(0).Get())
}
typeCRC, ok := typeNode.At(typeNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("type crc invalid or missing")
}
typ := Type{
Name: typeName,
CRC: typeCRC,
}
// loop through type fields, skip first (name) and last (crc)
for j := 1; j < typeNode.Len()-1; j++ {
if typeNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := typeNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
typ.Fields = append(typ.Fields, *field)
}
}
return &typ, nil
} | [
"func",
"parseType",
"(",
"ctx",
"*",
"context",
",",
"typeNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Type",
",",
"error",
")",
"{",
"if",
"typeNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"typeNode",
".",
"At",
"(",
"0",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"typeName",
",",
"ok",
":=",
"typeNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"typeNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"typeCRC",
",",
"ok",
":=",
"typeNode",
".",
"At",
"(",
"typeNode",
".",
"Len",
"(",
")",
"-",
"1",
")",
".",
"At",
"(",
"crcField",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"typ",
":=",
"Type",
"{",
"Name",
":",
"typeName",
",",
"CRC",
":",
"typeCRC",
",",
"}",
"\n\n",
"// loop through type fields, skip first (name) and last (crc)",
"for",
"j",
":=",
"1",
";",
"j",
"<",
"typeNode",
".",
"Len",
"(",
")",
"-",
"1",
";",
"j",
"++",
"{",
"if",
"typeNode",
".",
"At",
"(",
"j",
")",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeArray",
"{",
"fieldNode",
":=",
"typeNode",
".",
"At",
"(",
"j",
")",
"\n\n",
"field",
",",
"err",
":=",
"parseField",
"(",
"ctx",
",",
"fieldNode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"typ",
".",
"Fields",
"=",
"append",
"(",
"typ",
".",
"Fields",
",",
"*",
"field",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"typ",
",",
"nil",
"\n",
"}"
] | // parseType parses VPP binary API type object from JSON node | [
"parseType",
"parses",
"VPP",
"binary",
"API",
"type",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L322-L356 |
12,657 | FDio/govpp | cmd/binapi-generator/parse.go | parseAlias | func parseAlias(ctx *context, aliasName string, aliasNode *jsongo.JSONNode) (*Alias, error) {
if aliasNode.Len() == 0 || aliasNode.At(aliasTypeField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for alias specified")
}
alias := Alias{
Name: aliasName,
}
if typeNode := aliasNode.At(aliasTypeField); typeNode.GetType() == jsongo.TypeValue {
typ, ok := typeNode.Get().(string)
if !ok {
return nil, fmt.Errorf("alias type is %T, not a string", typeNode.Get())
}
if typ != "null" {
alias.Type = typ
}
}
if lengthNode := aliasNode.At(aliasLengthField); lengthNode.GetType() == jsongo.TypeValue {
length, ok := lengthNode.Get().(float64)
if !ok {
return nil, fmt.Errorf("alias length is %T, not a float64", lengthNode.Get())
}
alias.Length = int(length)
}
return &alias, nil
} | go | func parseAlias(ctx *context, aliasName string, aliasNode *jsongo.JSONNode) (*Alias, error) {
if aliasNode.Len() == 0 || aliasNode.At(aliasTypeField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for alias specified")
}
alias := Alias{
Name: aliasName,
}
if typeNode := aliasNode.At(aliasTypeField); typeNode.GetType() == jsongo.TypeValue {
typ, ok := typeNode.Get().(string)
if !ok {
return nil, fmt.Errorf("alias type is %T, not a string", typeNode.Get())
}
if typ != "null" {
alias.Type = typ
}
}
if lengthNode := aliasNode.At(aliasLengthField); lengthNode.GetType() == jsongo.TypeValue {
length, ok := lengthNode.Get().(float64)
if !ok {
return nil, fmt.Errorf("alias length is %T, not a float64", lengthNode.Get())
}
alias.Length = int(length)
}
return &alias, nil
} | [
"func",
"parseAlias",
"(",
"ctx",
"*",
"context",
",",
"aliasName",
"string",
",",
"aliasNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Alias",
",",
"error",
")",
"{",
"if",
"aliasNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"aliasNode",
".",
"At",
"(",
"aliasTypeField",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"alias",
":=",
"Alias",
"{",
"Name",
":",
"aliasName",
",",
"}",
"\n\n",
"if",
"typeNode",
":=",
"aliasNode",
".",
"At",
"(",
"aliasTypeField",
")",
";",
"typeNode",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeValue",
"{",
"typ",
",",
"ok",
":=",
"typeNode",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"typeNode",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"typ",
"!=",
"\"",
"\"",
"{",
"alias",
".",
"Type",
"=",
"typ",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"lengthNode",
":=",
"aliasNode",
".",
"At",
"(",
"aliasLengthField",
")",
";",
"lengthNode",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeValue",
"{",
"length",
",",
"ok",
":=",
"lengthNode",
".",
"Get",
"(",
")",
".",
"(",
"float64",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"lengthNode",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"alias",
".",
"Length",
"=",
"int",
"(",
"length",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"alias",
",",
"nil",
"\n",
"}"
] | // parseAlias parses VPP binary API alias object from JSON node | [
"parseAlias",
"parses",
"VPP",
"binary",
"API",
"alias",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L359-L387 |
12,658 | FDio/govpp | cmd/binapi-generator/parse.go | parseMessage | func parseMessage(ctx *context, msgNode *jsongo.JSONNode) (*Message, error) {
if msgNode.Len() == 0 || msgNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for message specified")
}
msgName, ok := msgNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("message name is %T, not a string", msgNode.At(0).Get())
}
msgCRC, ok := msgNode.At(msgNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("message crc invalid or missing")
}
msg := Message{
Name: msgName,
CRC: msgCRC,
}
// loop through message fields, skip first (name) and last (crc)
for j := 1; j < msgNode.Len()-1; j++ {
if msgNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := msgNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
msg.Fields = append(msg.Fields, *field)
}
}
return &msg, nil
} | go | func parseMessage(ctx *context, msgNode *jsongo.JSONNode) (*Message, error) {
if msgNode.Len() == 0 || msgNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for message specified")
}
msgName, ok := msgNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("message name is %T, not a string", msgNode.At(0).Get())
}
msgCRC, ok := msgNode.At(msgNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("message crc invalid or missing")
}
msg := Message{
Name: msgName,
CRC: msgCRC,
}
// loop through message fields, skip first (name) and last (crc)
for j := 1; j < msgNode.Len()-1; j++ {
if msgNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := msgNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
msg.Fields = append(msg.Fields, *field)
}
}
return &msg, nil
} | [
"func",
"parseMessage",
"(",
"ctx",
"*",
"context",
",",
"msgNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Message",
",",
"error",
")",
"{",
"if",
"msgNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"msgNode",
".",
"At",
"(",
"0",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"msgName",
",",
"ok",
":=",
"msgNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msgNode",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"msgCRC",
",",
"ok",
":=",
"msgNode",
".",
"At",
"(",
"msgNode",
".",
"Len",
"(",
")",
"-",
"1",
")",
".",
"At",
"(",
"crcField",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"msg",
":=",
"Message",
"{",
"Name",
":",
"msgName",
",",
"CRC",
":",
"msgCRC",
",",
"}",
"\n\n",
"// loop through message fields, skip first (name) and last (crc)",
"for",
"j",
":=",
"1",
";",
"j",
"<",
"msgNode",
".",
"Len",
"(",
")",
"-",
"1",
";",
"j",
"++",
"{",
"if",
"msgNode",
".",
"At",
"(",
"j",
")",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeArray",
"{",
"fieldNode",
":=",
"msgNode",
".",
"At",
"(",
"j",
")",
"\n\n",
"field",
",",
"err",
":=",
"parseField",
"(",
"ctx",
",",
"fieldNode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"msg",
".",
"Fields",
"=",
"append",
"(",
"msg",
".",
"Fields",
",",
"*",
"field",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"msg",
",",
"nil",
"\n",
"}"
] | // parseMessage parses VPP binary API message object from JSON node | [
"parseMessage",
"parses",
"VPP",
"binary",
"API",
"message",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L390-L425 |
12,659 | FDio/govpp | cmd/binapi-generator/parse.go | parseField | func parseField(ctx *context, field *jsongo.JSONNode) (*Field, error) {
if field.Len() < 2 || field.At(0).GetType() != jsongo.TypeValue || field.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for field specified")
}
fieldType, ok := field.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("field type is %T, not a string", field.At(0).Get())
}
fieldName, ok := field.At(1).Get().(string)
if !ok {
return nil, fmt.Errorf("field name is %T, not a string", field.At(1).Get())
}
var fieldLength float64
if field.Len() >= 3 {
fieldLength, ok = field.At(2).Get().(float64)
if !ok {
return nil, fmt.Errorf("field length is %T, not float64", field.At(2).Get())
}
}
var fieldLengthFrom string
if field.Len() >= 4 {
fieldLengthFrom, ok = field.At(3).Get().(string)
if !ok {
return nil, fmt.Errorf("field length from is %T, not a string", field.At(3).Get())
}
}
return &Field{
Name: fieldName,
Type: fieldType,
Length: int(fieldLength),
SizeFrom: fieldLengthFrom,
}, nil
} | go | func parseField(ctx *context, field *jsongo.JSONNode) (*Field, error) {
if field.Len() < 2 || field.At(0).GetType() != jsongo.TypeValue || field.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for field specified")
}
fieldType, ok := field.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("field type is %T, not a string", field.At(0).Get())
}
fieldName, ok := field.At(1).Get().(string)
if !ok {
return nil, fmt.Errorf("field name is %T, not a string", field.At(1).Get())
}
var fieldLength float64
if field.Len() >= 3 {
fieldLength, ok = field.At(2).Get().(float64)
if !ok {
return nil, fmt.Errorf("field length is %T, not float64", field.At(2).Get())
}
}
var fieldLengthFrom string
if field.Len() >= 4 {
fieldLengthFrom, ok = field.At(3).Get().(string)
if !ok {
return nil, fmt.Errorf("field length from is %T, not a string", field.At(3).Get())
}
}
return &Field{
Name: fieldName,
Type: fieldType,
Length: int(fieldLength),
SizeFrom: fieldLengthFrom,
}, nil
} | [
"func",
"parseField",
"(",
"ctx",
"*",
"context",
",",
"field",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Field",
",",
"error",
")",
"{",
"if",
"field",
".",
"Len",
"(",
")",
"<",
"2",
"||",
"field",
".",
"At",
"(",
"0",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"||",
"field",
".",
"At",
"(",
"1",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"fieldType",
",",
"ok",
":=",
"field",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
".",
"At",
"(",
"0",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"fieldName",
",",
"ok",
":=",
"field",
".",
"At",
"(",
"1",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
".",
"At",
"(",
"1",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"var",
"fieldLength",
"float64",
"\n",
"if",
"field",
".",
"Len",
"(",
")",
">=",
"3",
"{",
"fieldLength",
",",
"ok",
"=",
"field",
".",
"At",
"(",
"2",
")",
".",
"Get",
"(",
")",
".",
"(",
"float64",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
".",
"At",
"(",
"2",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"fieldLengthFrom",
"string",
"\n",
"if",
"field",
".",
"Len",
"(",
")",
">=",
"4",
"{",
"fieldLengthFrom",
",",
"ok",
"=",
"field",
".",
"At",
"(",
"3",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
".",
"At",
"(",
"3",
")",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"Field",
"{",
"Name",
":",
"fieldName",
",",
"Type",
":",
"fieldType",
",",
"Length",
":",
"int",
"(",
"fieldLength",
")",
",",
"SizeFrom",
":",
"fieldLengthFrom",
",",
"}",
",",
"nil",
"\n",
"}"
] | // parseField parses VPP binary API object field from JSON node | [
"parseField",
"parses",
"VPP",
"binary",
"API",
"object",
"field",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L428-L462 |
12,660 | FDio/govpp | cmd/binapi-generator/parse.go | parseService | func parseService(ctx *context, svcName string, svcNode *jsongo.JSONNode) (*Service, error) {
if svcNode.Len() == 0 || svcNode.At(replyField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for service specified")
}
svc := Service{
Name: ctx.moduleName + "." + svcName,
RequestType: svcName,
}
if replyNode := svcNode.At(replyField); replyNode.GetType() == jsongo.TypeValue {
reply, ok := replyNode.Get().(string)
if !ok {
return nil, fmt.Errorf("service reply is %T, not a string", replyNode.Get())
}
if reply != serviceNoReply {
svc.ReplyType = reply
}
}
// stream service (dumps)
if streamNode := svcNode.At(streamField); streamNode.GetType() == jsongo.TypeValue {
var ok bool
svc.Stream, ok = streamNode.Get().(bool)
if !ok {
return nil, fmt.Errorf("service stream is %T, not a string", streamNode.Get())
}
}
// events service (event subscription)
if eventsNode := svcNode.At(eventsField); eventsNode.GetType() == jsongo.TypeArray {
for j := 0; j < eventsNode.Len(); j++ {
event := eventsNode.At(j).Get().(string)
svc.Events = append(svc.Events, event)
}
}
// validate service
if len(svc.Events) > 0 {
// EVENT service
if !strings.HasPrefix(svc.RequestType, serviceEventPrefix) {
log.Debugf("unusual EVENTS service: %+v\n"+
"- events service %q does not have %q prefix in request.",
svc, svc.Name, serviceEventPrefix)
}
} else if svc.Stream {
// STREAM service
if !strings.HasSuffix(svc.RequestType, serviceDumpSuffix) ||
!strings.HasSuffix(svc.ReplyType, serviceDetailsSuffix) {
log.Debugf("unusual STREAM service: %+v\n"+
"- stream service %q does not have %q suffix in request or reply does not have %q suffix.",
svc, svc.Name, serviceDumpSuffix, serviceDetailsSuffix)
}
} else if svc.ReplyType != "" && svc.ReplyType != serviceNoReply {
// REQUEST service
// some messages might have `null` reply (for example: memclnt)
if !strings.HasSuffix(svc.ReplyType, serviceReplySuffix) {
log.Debugf("unusual REQUEST service: %+v\n"+
"- service %q does not have %q suffix in reply.",
svc, svc.Name, serviceReplySuffix)
}
}
return &svc, nil
} | go | func parseService(ctx *context, svcName string, svcNode *jsongo.JSONNode) (*Service, error) {
if svcNode.Len() == 0 || svcNode.At(replyField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for service specified")
}
svc := Service{
Name: ctx.moduleName + "." + svcName,
RequestType: svcName,
}
if replyNode := svcNode.At(replyField); replyNode.GetType() == jsongo.TypeValue {
reply, ok := replyNode.Get().(string)
if !ok {
return nil, fmt.Errorf("service reply is %T, not a string", replyNode.Get())
}
if reply != serviceNoReply {
svc.ReplyType = reply
}
}
// stream service (dumps)
if streamNode := svcNode.At(streamField); streamNode.GetType() == jsongo.TypeValue {
var ok bool
svc.Stream, ok = streamNode.Get().(bool)
if !ok {
return nil, fmt.Errorf("service stream is %T, not a string", streamNode.Get())
}
}
// events service (event subscription)
if eventsNode := svcNode.At(eventsField); eventsNode.GetType() == jsongo.TypeArray {
for j := 0; j < eventsNode.Len(); j++ {
event := eventsNode.At(j).Get().(string)
svc.Events = append(svc.Events, event)
}
}
// validate service
if len(svc.Events) > 0 {
// EVENT service
if !strings.HasPrefix(svc.RequestType, serviceEventPrefix) {
log.Debugf("unusual EVENTS service: %+v\n"+
"- events service %q does not have %q prefix in request.",
svc, svc.Name, serviceEventPrefix)
}
} else if svc.Stream {
// STREAM service
if !strings.HasSuffix(svc.RequestType, serviceDumpSuffix) ||
!strings.HasSuffix(svc.ReplyType, serviceDetailsSuffix) {
log.Debugf("unusual STREAM service: %+v\n"+
"- stream service %q does not have %q suffix in request or reply does not have %q suffix.",
svc, svc.Name, serviceDumpSuffix, serviceDetailsSuffix)
}
} else if svc.ReplyType != "" && svc.ReplyType != serviceNoReply {
// REQUEST service
// some messages might have `null` reply (for example: memclnt)
if !strings.HasSuffix(svc.ReplyType, serviceReplySuffix) {
log.Debugf("unusual REQUEST service: %+v\n"+
"- service %q does not have %q suffix in reply.",
svc, svc.Name, serviceReplySuffix)
}
}
return &svc, nil
} | [
"func",
"parseService",
"(",
"ctx",
"*",
"context",
",",
"svcName",
"string",
",",
"svcNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Service",
",",
"error",
")",
"{",
"if",
"svcNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"svcNode",
".",
"At",
"(",
"replyField",
")",
".",
"GetType",
"(",
")",
"!=",
"jsongo",
".",
"TypeValue",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"svc",
":=",
"Service",
"{",
"Name",
":",
"ctx",
".",
"moduleName",
"+",
"\"",
"\"",
"+",
"svcName",
",",
"RequestType",
":",
"svcName",
",",
"}",
"\n\n",
"if",
"replyNode",
":=",
"svcNode",
".",
"At",
"(",
"replyField",
")",
";",
"replyNode",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeValue",
"{",
"reply",
",",
"ok",
":=",
"replyNode",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"replyNode",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"reply",
"!=",
"serviceNoReply",
"{",
"svc",
".",
"ReplyType",
"=",
"reply",
"\n",
"}",
"\n",
"}",
"\n\n",
"// stream service (dumps)",
"if",
"streamNode",
":=",
"svcNode",
".",
"At",
"(",
"streamField",
")",
";",
"streamNode",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeValue",
"{",
"var",
"ok",
"bool",
"\n",
"svc",
".",
"Stream",
",",
"ok",
"=",
"streamNode",
".",
"Get",
"(",
")",
".",
"(",
"bool",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"streamNode",
".",
"Get",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// events service (event subscription)",
"if",
"eventsNode",
":=",
"svcNode",
".",
"At",
"(",
"eventsField",
")",
";",
"eventsNode",
".",
"GetType",
"(",
")",
"==",
"jsongo",
".",
"TypeArray",
"{",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"eventsNode",
".",
"Len",
"(",
")",
";",
"j",
"++",
"{",
"event",
":=",
"eventsNode",
".",
"At",
"(",
"j",
")",
".",
"Get",
"(",
")",
".",
"(",
"string",
")",
"\n",
"svc",
".",
"Events",
"=",
"append",
"(",
"svc",
".",
"Events",
",",
"event",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// validate service",
"if",
"len",
"(",
"svc",
".",
"Events",
")",
">",
"0",
"{",
"// EVENT service",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"svc",
".",
"RequestType",
",",
"serviceEventPrefix",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
",",
"svc",
",",
"svc",
".",
"Name",
",",
"serviceEventPrefix",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"svc",
".",
"Stream",
"{",
"// STREAM service",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"svc",
".",
"RequestType",
",",
"serviceDumpSuffix",
")",
"||",
"!",
"strings",
".",
"HasSuffix",
"(",
"svc",
".",
"ReplyType",
",",
"serviceDetailsSuffix",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
",",
"svc",
",",
"svc",
".",
"Name",
",",
"serviceDumpSuffix",
",",
"serviceDetailsSuffix",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"svc",
".",
"ReplyType",
"!=",
"\"",
"\"",
"&&",
"svc",
".",
"ReplyType",
"!=",
"serviceNoReply",
"{",
"// REQUEST service",
"// some messages might have `null` reply (for example: memclnt)",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"svc",
".",
"ReplyType",
",",
"serviceReplySuffix",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
",",
"svc",
",",
"svc",
".",
"Name",
",",
"serviceReplySuffix",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"svc",
",",
"nil",
"\n",
"}"
] | // parseService parses VPP binary API service object from JSON node | [
"parseService",
"parses",
"VPP",
"binary",
"API",
"service",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L465-L529 |
12,661 | FDio/govpp | adapter/socketclient/socketclient.go | WaitReady | func (c *vppClient) WaitReady() error {
// check if file at the path already exists
if _, err := os.Stat(c.sockAddr); err == nil {
return nil
} else if os.IsExist(err) {
return err
}
// if not, watch for it
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer func() {
if err := watcher.Close(); err != nil {
Log.Errorf("failed to close file watcher: %v", err)
}
}()
// start watching directory
if err := watcher.Add(filepath.Dir(c.sockAddr)); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for socket file timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
Log.Debugf("watcher event: %+v", ev)
if ev.Name == c.sockAddr {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// socket was created, we are ready
return nil
}
}
}
}
} | go | func (c *vppClient) WaitReady() error {
// check if file at the path already exists
if _, err := os.Stat(c.sockAddr); err == nil {
return nil
} else if os.IsExist(err) {
return err
}
// if not, watch for it
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer func() {
if err := watcher.Close(); err != nil {
Log.Errorf("failed to close file watcher: %v", err)
}
}()
// start watching directory
if err := watcher.Add(filepath.Dir(c.sockAddr)); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for socket file timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
Log.Debugf("watcher event: %+v", ev)
if ev.Name == c.sockAddr {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// socket was created, we are ready
return nil
}
}
}
}
} | [
"func",
"(",
"c",
"*",
"vppClient",
")",
"WaitReady",
"(",
")",
"error",
"{",
"// check if file at the path already exists",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"c",
".",
"sockAddr",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// if not, watch for it",
"watcher",
",",
"err",
":=",
"fsnotify",
".",
"NewWatcher",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"watcher",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// start watching directory",
"if",
"err",
":=",
"watcher",
".",
"Add",
"(",
"filepath",
".",
"Dir",
"(",
"c",
".",
"sockAddr",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"MaxWaitReady",
")",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"MaxWaitReady",
")",
"\n",
"case",
"e",
":=",
"<-",
"watcher",
".",
"Errors",
":",
"return",
"e",
"\n",
"case",
"ev",
":=",
"<-",
"watcher",
".",
"Events",
":",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"ev",
")",
"\n",
"if",
"ev",
".",
"Name",
"==",
"c",
".",
"sockAddr",
"{",
"if",
"(",
"ev",
".",
"Op",
"&",
"fsnotify",
".",
"Create",
")",
"==",
"fsnotify",
".",
"Create",
"{",
"// socket was created, we are ready",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WaitReady checks socket file existence and waits for it if necessary | [
"WaitReady",
"checks",
"socket",
"file",
"existence",
"and",
"waits",
"for",
"it",
"if",
"necessary"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/socketclient/socketclient.go#L102-L142 |
12,662 | FDio/govpp | examples/simple-client/simple_client.go | aclVersion | func aclVersion(ch api.Channel) {
fmt.Println("ACL getting version")
req := &acl.ACLPluginGetVersion{}
reply := &acl.ACLPluginGetVersionReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
} else {
fmt.Printf("ACL version reply: %+v\n", reply)
}
} | go | func aclVersion(ch api.Channel) {
fmt.Println("ACL getting version")
req := &acl.ACLPluginGetVersion{}
reply := &acl.ACLPluginGetVersionReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
} else {
fmt.Printf("ACL version reply: %+v\n", reply)
}
} | [
"func",
"aclVersion",
"(",
"ch",
"api",
".",
"Channel",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"req",
":=",
"&",
"acl",
".",
"ACLPluginGetVersion",
"{",
"}",
"\n",
"reply",
":=",
"&",
"acl",
".",
"ACLPluginGetVersionReply",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"ch",
".",
"SendRequest",
"(",
"req",
")",
".",
"ReceiveReply",
"(",
"reply",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"reply",
")",
"\n",
"}",
"\n",
"}"
] | // aclVersion is the simplest API example - one empty request message and one reply message. | [
"aclVersion",
"is",
"the",
"simplest",
"API",
"example",
"-",
"one",
"empty",
"request",
"message",
"and",
"one",
"reply",
"message",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/examples/simple-client/simple_client.go#L73-L84 |
12,663 | FDio/govpp | examples/simple-client/simple_client.go | aclConfig | func aclConfig(ch api.Channel) {
fmt.Println("ACL adding replace")
req := &acl.ACLAddReplace{
ACLIndex: ^uint32(0),
Tag: []byte("access list 1"),
R: []acl.ACLRule{
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("10.0.0.0").To4(),
SrcIPPrefixLen: 8,
DstIPAddr: net.ParseIP("192.168.1.0").To4(),
DstIPPrefixLen: 24,
Proto: 6,
},
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("8.8.8.8").To4(),
SrcIPPrefixLen: 32,
DstIPAddr: net.ParseIP("172.16.0.0").To4(),
DstIPPrefixLen: 16,
Proto: 6,
},
},
}
reply := &acl.ACLAddReplaceReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
return
}
if reply.Retval != 0 {
fmt.Println("Retval:", reply.Retval)
return
}
fmt.Printf("ACL add replace reply: %+v\n", reply)
} | go | func aclConfig(ch api.Channel) {
fmt.Println("ACL adding replace")
req := &acl.ACLAddReplace{
ACLIndex: ^uint32(0),
Tag: []byte("access list 1"),
R: []acl.ACLRule{
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("10.0.0.0").To4(),
SrcIPPrefixLen: 8,
DstIPAddr: net.ParseIP("192.168.1.0").To4(),
DstIPPrefixLen: 24,
Proto: 6,
},
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("8.8.8.8").To4(),
SrcIPPrefixLen: 32,
DstIPAddr: net.ParseIP("172.16.0.0").To4(),
DstIPPrefixLen: 16,
Proto: 6,
},
},
}
reply := &acl.ACLAddReplaceReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
return
}
if reply.Retval != 0 {
fmt.Println("Retval:", reply.Retval)
return
}
fmt.Printf("ACL add replace reply: %+v\n", reply)
} | [
"func",
"aclConfig",
"(",
"ch",
"api",
".",
"Channel",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"req",
":=",
"&",
"acl",
".",
"ACLAddReplace",
"{",
"ACLIndex",
":",
"^",
"uint32",
"(",
"0",
")",
",",
"Tag",
":",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"R",
":",
"[",
"]",
"acl",
".",
"ACLRule",
"{",
"{",
"IsPermit",
":",
"1",
",",
"SrcIPAddr",
":",
"net",
".",
"ParseIP",
"(",
"\"",
"\"",
")",
".",
"To4",
"(",
")",
",",
"SrcIPPrefixLen",
":",
"8",
",",
"DstIPAddr",
":",
"net",
".",
"ParseIP",
"(",
"\"",
"\"",
")",
".",
"To4",
"(",
")",
",",
"DstIPPrefixLen",
":",
"24",
",",
"Proto",
":",
"6",
",",
"}",
",",
"{",
"IsPermit",
":",
"1",
",",
"SrcIPAddr",
":",
"net",
".",
"ParseIP",
"(",
"\"",
"\"",
")",
".",
"To4",
"(",
")",
",",
"SrcIPPrefixLen",
":",
"32",
",",
"DstIPAddr",
":",
"net",
".",
"ParseIP",
"(",
"\"",
"\"",
")",
".",
"To4",
"(",
")",
",",
"DstIPPrefixLen",
":",
"16",
",",
"Proto",
":",
"6",
",",
"}",
",",
"}",
",",
"}",
"\n",
"reply",
":=",
"&",
"acl",
".",
"ACLAddReplaceReply",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"ch",
".",
"SendRequest",
"(",
"req",
")",
".",
"ReceiveReply",
"(",
"reply",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"reply",
".",
"Retval",
"!=",
"0",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"reply",
".",
"Retval",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"reply",
")",
"\n\n",
"}"
] | // aclConfig is another simple API example - in this case, the request contains structured data. | [
"aclConfig",
"is",
"another",
"simple",
"API",
"example",
"-",
"in",
"this",
"case",
"the",
"request",
"contains",
"structured",
"data",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/examples/simple-client/simple_client.go#L87-L125 |
12,664 | FDio/govpp | examples/simple-client/simple_client.go | interfaceNotifications | func interfaceNotifications(ch api.Channel) {
fmt.Println("Subscribing to notificaiton events")
notifChan := make(chan api.Message, 100)
// subscribe for specific notification message
sub, err := ch.SubscribeNotification(notifChan, &interfaces.SwInterfaceEvent{})
if err != nil {
panic(err)
}
// enable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 1,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// generate some events in VPP
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 0,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 1,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
// receive one notification
notif := (<-notifChan).(*interfaces.SwInterfaceEvent)
fmt.Printf("incoming event: %+v\n", notif)
// disable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 0,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// unsubscribe from delivery of the notifications
err = sub.Unsubscribe()
if err != nil {
panic(err)
}
} | go | func interfaceNotifications(ch api.Channel) {
fmt.Println("Subscribing to notificaiton events")
notifChan := make(chan api.Message, 100)
// subscribe for specific notification message
sub, err := ch.SubscribeNotification(notifChan, &interfaces.SwInterfaceEvent{})
if err != nil {
panic(err)
}
// enable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 1,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// generate some events in VPP
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 0,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 1,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
// receive one notification
notif := (<-notifChan).(*interfaces.SwInterfaceEvent)
fmt.Printf("incoming event: %+v\n", notif)
// disable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 0,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// unsubscribe from delivery of the notifications
err = sub.Unsubscribe()
if err != nil {
panic(err)
}
} | [
"func",
"interfaceNotifications",
"(",
"ch",
"api",
".",
"Channel",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"notifChan",
":=",
"make",
"(",
"chan",
"api",
".",
"Message",
",",
"100",
")",
"\n\n",
"// subscribe for specific notification message",
"sub",
",",
"err",
":=",
"ch",
".",
"SubscribeNotification",
"(",
"notifChan",
",",
"&",
"interfaces",
".",
"SwInterfaceEvent",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// enable interface events in VPP",
"err",
"=",
"ch",
".",
"SendRequest",
"(",
"&",
"interfaces",
".",
"WantInterfaceEvents",
"{",
"PID",
":",
"uint32",
"(",
"os",
".",
"Getpid",
"(",
")",
")",
",",
"EnableDisable",
":",
"1",
",",
"}",
")",
".",
"ReceiveReply",
"(",
"&",
"interfaces",
".",
"WantInterfaceEventsReply",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// generate some events in VPP",
"err",
"=",
"ch",
".",
"SendRequest",
"(",
"&",
"interfaces",
".",
"SwInterfaceSetFlags",
"{",
"SwIfIndex",
":",
"0",
",",
"AdminUpDown",
":",
"0",
",",
"}",
")",
".",
"ReceiveReply",
"(",
"&",
"interfaces",
".",
"SwInterfaceSetFlagsReply",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"ch",
".",
"SendRequest",
"(",
"&",
"interfaces",
".",
"SwInterfaceSetFlags",
"{",
"SwIfIndex",
":",
"0",
",",
"AdminUpDown",
":",
"1",
",",
"}",
")",
".",
"ReceiveReply",
"(",
"&",
"interfaces",
".",
"SwInterfaceSetFlagsReply",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// receive one notification",
"notif",
":=",
"(",
"<-",
"notifChan",
")",
".",
"(",
"*",
"interfaces",
".",
"SwInterfaceEvent",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"notif",
")",
"\n\n",
"// disable interface events in VPP",
"err",
"=",
"ch",
".",
"SendRequest",
"(",
"&",
"interfaces",
".",
"WantInterfaceEvents",
"{",
"PID",
":",
"uint32",
"(",
"os",
".",
"Getpid",
"(",
")",
")",
",",
"EnableDisable",
":",
"0",
",",
"}",
")",
".",
"ReceiveReply",
"(",
"&",
"interfaces",
".",
"WantInterfaceEventsReply",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// unsubscribe from delivery of the notifications",
"err",
"=",
"sub",
".",
"Unsubscribe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // interfaceNotifications shows the usage of notification API. Note that for notifications,
// you are supposed to create your own Go channel with your preferred buffer size. If the channel's
// buffer is full, the notifications will not be delivered into it. | [
"interfaceNotifications",
"shows",
"the",
"usage",
"of",
"notification",
"API",
".",
"Note",
"that",
"for",
"notifications",
"you",
"are",
"supposed",
"to",
"create",
"your",
"own",
"Go",
"channel",
"with",
"your",
"preferred",
"buffer",
"size",
".",
"If",
"the",
"channel",
"s",
"buffer",
"is",
"full",
"the",
"notifications",
"will",
"not",
"be",
"delivered",
"into",
"it",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/examples/simple-client/simple_client.go#L225-L279 |
12,665 | FDio/govpp | cmd/binapi-generator/main.go | getInputFiles | func getInputFiles(inputDir string) (res []string, err error) {
files, err := ioutil.ReadDir(inputDir)
if err != nil {
return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
}
for _, f := range files {
if strings.HasSuffix(f.Name(), inputFileExt) {
res = append(res, filepath.Join(inputDir, f.Name()))
}
}
return res, nil
} | go | func getInputFiles(inputDir string) (res []string, err error) {
files, err := ioutil.ReadDir(inputDir)
if err != nil {
return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
}
for _, f := range files {
if strings.HasSuffix(f.Name(), inputFileExt) {
res = append(res, filepath.Join(inputDir, f.Name()))
}
}
return res, nil
} | [
"func",
"getInputFiles",
"(",
"inputDir",
"string",
")",
"(",
"res",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"inputDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"inputDir",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"f",
".",
"Name",
"(",
")",
",",
"inputFileExt",
")",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"filepath",
".",
"Join",
"(",
"inputDir",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // getInputFiles returns all input files located in specified directory | [
"getInputFiles",
"returns",
"all",
"input",
"files",
"located",
"in",
"specified",
"directory"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L85-L96 |
12,666 | FDio/govpp | cmd/binapi-generator/main.go | generateFromFile | func generateFromFile(inputFile, outputDir string) error {
logf("generating from file: %q", inputFile)
defer logf("--------------------------------------")
ctx, err := getContext(inputFile, outputDir)
if err != nil {
return err
}
ctx.includeAPIVersionCrc = *includeAPIVer
ctx.includeComments = *includeComments
// read input file contents
ctx.inputData, err = readFile(inputFile)
if err != nil {
return err
}
// parse JSON data into objects
jsonRoot, err := parseJSON(ctx.inputData)
if err != nil {
return err
}
ctx.packageData, err = parsePackage(ctx, jsonRoot)
if err != nil {
return err
}
// create output directory
packageDir := filepath.Dir(ctx.outputFile)
if err := os.MkdirAll(packageDir, 0777); err != nil {
return fmt.Errorf("creating output directory %q failed: %v", packageDir, err)
}
// open output file
f, err := os.Create(ctx.outputFile)
if err != nil {
return fmt.Errorf("creating output file %q failed: %v", ctx.outputFile, err)
}
defer f.Close()
// generate Go package code
w := bufio.NewWriter(f)
if err := generatePackage(ctx, w); err != nil {
return err
}
// go format the output file (fail probably means the output is not compilable)
cmd := exec.Command("gofmt", "-w", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("gofmt failed: %v\n%s", err, string(output))
}
// count number of lines in generated output file
cmd = exec.Command("wc", "-l", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
log.Warnf("wc command failed: %v\n%s", err, string(output))
} else {
logf("generated lines: %s", output)
}
return nil
} | go | func generateFromFile(inputFile, outputDir string) error {
logf("generating from file: %q", inputFile)
defer logf("--------------------------------------")
ctx, err := getContext(inputFile, outputDir)
if err != nil {
return err
}
ctx.includeAPIVersionCrc = *includeAPIVer
ctx.includeComments = *includeComments
// read input file contents
ctx.inputData, err = readFile(inputFile)
if err != nil {
return err
}
// parse JSON data into objects
jsonRoot, err := parseJSON(ctx.inputData)
if err != nil {
return err
}
ctx.packageData, err = parsePackage(ctx, jsonRoot)
if err != nil {
return err
}
// create output directory
packageDir := filepath.Dir(ctx.outputFile)
if err := os.MkdirAll(packageDir, 0777); err != nil {
return fmt.Errorf("creating output directory %q failed: %v", packageDir, err)
}
// open output file
f, err := os.Create(ctx.outputFile)
if err != nil {
return fmt.Errorf("creating output file %q failed: %v", ctx.outputFile, err)
}
defer f.Close()
// generate Go package code
w := bufio.NewWriter(f)
if err := generatePackage(ctx, w); err != nil {
return err
}
// go format the output file (fail probably means the output is not compilable)
cmd := exec.Command("gofmt", "-w", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("gofmt failed: %v\n%s", err, string(output))
}
// count number of lines in generated output file
cmd = exec.Command("wc", "-l", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
log.Warnf("wc command failed: %v\n%s", err, string(output))
} else {
logf("generated lines: %s", output)
}
return nil
} | [
"func",
"generateFromFile",
"(",
"inputFile",
",",
"outputDir",
"string",
")",
"error",
"{",
"logf",
"(",
"\"",
"\"",
",",
"inputFile",
")",
"\n",
"defer",
"logf",
"(",
"\"",
"\"",
")",
"\n\n",
"ctx",
",",
"err",
":=",
"getContext",
"(",
"inputFile",
",",
"outputDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"ctx",
".",
"includeAPIVersionCrc",
"=",
"*",
"includeAPIVer",
"\n",
"ctx",
".",
"includeComments",
"=",
"*",
"includeComments",
"\n\n",
"// read input file contents",
"ctx",
".",
"inputData",
",",
"err",
"=",
"readFile",
"(",
"inputFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// parse JSON data into objects",
"jsonRoot",
",",
"err",
":=",
"parseJSON",
"(",
"ctx",
".",
"inputData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ctx",
".",
"packageData",
",",
"err",
"=",
"parsePackage",
"(",
"ctx",
",",
"jsonRoot",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// create output directory",
"packageDir",
":=",
"filepath",
".",
"Dir",
"(",
"ctx",
".",
"outputFile",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"packageDir",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"packageDir",
",",
"err",
")",
"\n",
"}",
"\n",
"// open output file",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"ctx",
".",
"outputFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ctx",
".",
"outputFile",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"// generate Go package code",
"w",
":=",
"bufio",
".",
"NewWriter",
"(",
"f",
")",
"\n",
"if",
"err",
":=",
"generatePackage",
"(",
"ctx",
",",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// go format the output file (fail probably means the output is not compilable)",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ctx",
".",
"outputFile",
")",
"\n",
"if",
"output",
",",
"err",
":=",
"cmd",
".",
"CombinedOutput",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
",",
"string",
"(",
"output",
")",
")",
"\n",
"}",
"\n\n",
"// count number of lines in generated output file",
"cmd",
"=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ctx",
".",
"outputFile",
")",
"\n",
"if",
"output",
",",
"err",
":=",
"cmd",
".",
"CombinedOutput",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
",",
"string",
"(",
"output",
")",
")",
"\n",
"}",
"else",
"{",
"logf",
"(",
"\"",
"\"",
",",
"output",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // generateFromFile generates Go package from one input JSON file | [
"generateFromFile",
"generates",
"Go",
"package",
"from",
"one",
"input",
"JSON",
"file"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L99-L159 |
12,667 | FDio/govpp | cmd/binapi-generator/main.go | readFile | func readFile(inputFile string) ([]byte, error) {
inputData, err := ioutil.ReadFile(inputFile)
if err != nil {
return nil, fmt.Errorf("reading data from file failed: %v", err)
}
return inputData, nil
} | go | func readFile(inputFile string) ([]byte, error) {
inputData, err := ioutil.ReadFile(inputFile)
if err != nil {
return nil, fmt.Errorf("reading data from file failed: %v", err)
}
return inputData, nil
} | [
"func",
"readFile",
"(",
"inputFile",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"inputData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"inputFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"inputData",
",",
"nil",
"\n",
"}"
] | // readFile reads content of a file into memory | [
"readFile",
"reads",
"content",
"of",
"a",
"file",
"into",
"memory"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L162-L169 |
12,668 | FDio/govpp | cmd/binapi-generator/main.go | parseJSON | func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
root := jsongo.JSONNode{}
if err := json.Unmarshal(inputData, &root); err != nil {
return nil, fmt.Errorf("unmarshalling JSON failed: %v", err)
}
return &root, nil
} | go | func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
root := jsongo.JSONNode{}
if err := json.Unmarshal(inputData, &root); err != nil {
return nil, fmt.Errorf("unmarshalling JSON failed: %v", err)
}
return &root, nil
} | [
"func",
"parseJSON",
"(",
"inputData",
"[",
"]",
"byte",
")",
"(",
"*",
"jsongo",
".",
"JSONNode",
",",
"error",
")",
"{",
"root",
":=",
"jsongo",
".",
"JSONNode",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"inputData",
",",
"&",
"root",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"root",
",",
"nil",
"\n",
"}"
] | // parseJSON parses a JSON data into an in-memory tree | [
"parseJSON",
"parses",
"a",
"JSON",
"data",
"into",
"an",
"in",
"-",
"memory",
"tree"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L172-L180 |
12,669 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | NewVppAdapter | func NewVppAdapter() *VppAdapter {
a := &VppAdapter{
msgIDSeq: 1000,
msgIDsToName: make(map[uint16]string),
msgNameToIds: make(map[string]uint16),
binAPITypes: make(map[string]reflect.Type),
}
a.registerBinAPITypes()
return a
} | go | func NewVppAdapter() *VppAdapter {
a := &VppAdapter{
msgIDSeq: 1000,
msgIDsToName: make(map[uint16]string),
msgNameToIds: make(map[string]uint16),
binAPITypes: make(map[string]reflect.Type),
}
a.registerBinAPITypes()
return a
} | [
"func",
"NewVppAdapter",
"(",
")",
"*",
"VppAdapter",
"{",
"a",
":=",
"&",
"VppAdapter",
"{",
"msgIDSeq",
":",
"1000",
",",
"msgIDsToName",
":",
"make",
"(",
"map",
"[",
"uint16",
"]",
"string",
")",
",",
"msgNameToIds",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"uint16",
")",
",",
"binAPITypes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"reflect",
".",
"Type",
")",
",",
"}",
"\n",
"a",
".",
"registerBinAPITypes",
"(",
")",
"\n",
"return",
"a",
"\n",
"}"
] | // NewVppAdapter returns a new mock adapter. | [
"NewVppAdapter",
"returns",
"a",
"new",
"mock",
"adapter",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L93-L102 |
12,670 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | GetMsgNameByID | func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
switch msgID {
case 100:
return "control_ping", true
case 101:
return "control_ping_reply", true
case 200:
return "sw_interface_dump", true
case 201:
return "sw_interface_details", true
}
a.access.Lock()
defer a.access.Unlock()
msgName, found := a.msgIDsToName[msgID]
return msgName, found
} | go | func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
switch msgID {
case 100:
return "control_ping", true
case 101:
return "control_ping_reply", true
case 200:
return "sw_interface_dump", true
case 201:
return "sw_interface_details", true
}
a.access.Lock()
defer a.access.Unlock()
msgName, found := a.msgIDsToName[msgID]
return msgName, found
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"GetMsgNameByID",
"(",
"msgID",
"uint16",
")",
"(",
"string",
",",
"bool",
")",
"{",
"switch",
"msgID",
"{",
"case",
"100",
":",
"return",
"\"",
"\"",
",",
"true",
"\n",
"case",
"101",
":",
"return",
"\"",
"\"",
",",
"true",
"\n",
"case",
"200",
":",
"return",
"\"",
"\"",
",",
"true",
"\n",
"case",
"201",
":",
"return",
"\"",
"\"",
",",
"true",
"\n",
"}",
"\n\n",
"a",
".",
"access",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"access",
".",
"Unlock",
"(",
")",
"\n",
"msgName",
",",
"found",
":=",
"a",
".",
"msgIDsToName",
"[",
"msgID",
"]",
"\n\n",
"return",
"msgName",
",",
"found",
"\n",
"}"
] | // GetMsgNameByID returns message name for specified message ID. | [
"GetMsgNameByID",
"returns",
"message",
"name",
"for",
"specified",
"message",
"ID",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L115-L132 |
12,671 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | ReplyTypeFor | func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
replyName, foundName := binapi.ReplyNameFor(requestMsgName)
if foundName {
if reply, found := a.binAPITypes[replyName]; found {
msgID, err := a.GetMsgID(replyName, "")
if err == nil {
return reply, msgID, found
}
}
}
return nil, 0, false
} | go | func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
replyName, foundName := binapi.ReplyNameFor(requestMsgName)
if foundName {
if reply, found := a.binAPITypes[replyName]; found {
msgID, err := a.GetMsgID(replyName, "")
if err == nil {
return reply, msgID, found
}
}
}
return nil, 0, false
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"ReplyTypeFor",
"(",
"requestMsgName",
"string",
")",
"(",
"reflect",
".",
"Type",
",",
"uint16",
",",
"bool",
")",
"{",
"replyName",
",",
"foundName",
":=",
"binapi",
".",
"ReplyNameFor",
"(",
"requestMsgName",
")",
"\n",
"if",
"foundName",
"{",
"if",
"reply",
",",
"found",
":=",
"a",
".",
"binAPITypes",
"[",
"replyName",
"]",
";",
"found",
"{",
"msgID",
",",
"err",
":=",
"a",
".",
"GetMsgID",
"(",
"replyName",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"reply",
",",
"msgID",
",",
"found",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"0",
",",
"false",
"\n",
"}"
] | // ReplyTypeFor returns reply message type for given request message name. | [
"ReplyTypeFor",
"returns",
"reply",
"message",
"type",
"for",
"given",
"request",
"message",
"name",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L143-L155 |
12,672 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | ReplyFor | func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
if foundReplType {
msgVal := reflect.New(replType)
if msg, ok := msgVal.Interface().(api.Message); ok {
log.Println("FFF ", replType, msgID, foundReplType)
return msg, msgID, true
}
}
return nil, 0, false
} | go | func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
if foundReplType {
msgVal := reflect.New(replType)
if msg, ok := msgVal.Interface().(api.Message); ok {
log.Println("FFF ", replType, msgID, foundReplType)
return msg, msgID, true
}
}
return nil, 0, false
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"ReplyFor",
"(",
"requestMsgName",
"string",
")",
"(",
"api",
".",
"Message",
",",
"uint16",
",",
"bool",
")",
"{",
"replType",
",",
"msgID",
",",
"foundReplType",
":=",
"a",
".",
"ReplyTypeFor",
"(",
"requestMsgName",
")",
"\n",
"if",
"foundReplType",
"{",
"msgVal",
":=",
"reflect",
".",
"New",
"(",
"replType",
")",
"\n",
"if",
"msg",
",",
"ok",
":=",
"msgVal",
".",
"Interface",
"(",
")",
".",
"(",
"api",
".",
"Message",
")",
";",
"ok",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"replType",
",",
"msgID",
",",
"foundReplType",
")",
"\n",
"return",
"msg",
",",
"msgID",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"0",
",",
"false",
"\n",
"}"
] | // ReplyFor returns reply message for given request message name. | [
"ReplyFor",
"returns",
"reply",
"message",
"for",
"given",
"request",
"message",
"name",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L158-L169 |
12,673 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | ReplyBytes | func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
if err != nil {
log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
" ", err)
return nil, err
}
log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
buf := new(bytes.Buffer)
err = struc.Pack(buf, &codec.VppReplyHeader{
VlMsgID: replyMsgID,
Context: request.ClientID,
})
if err != nil {
return nil, err
}
if err = struc.Pack(buf, reply); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
if err != nil {
log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
" ", err)
return nil, err
}
log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
buf := new(bytes.Buffer)
err = struc.Pack(buf, &codec.VppReplyHeader{
VlMsgID: replyMsgID,
Context: request.ClientID,
})
if err != nil {
return nil, err
}
if err = struc.Pack(buf, reply); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"ReplyBytes",
"(",
"request",
"MessageDTO",
",",
"reply",
"api",
".",
"Message",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"replyMsgID",
",",
"err",
":=",
"a",
".",
"GetMsgID",
"(",
"reply",
".",
"GetMessageName",
"(",
")",
",",
"reply",
".",
"GetCrcString",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"replyMsgID",
",",
"\"",
"\"",
",",
"reply",
".",
"GetMessageName",
"(",
")",
",",
"\"",
"\"",
",",
"request",
".",
"ClientID",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"replyMsgID",
",",
"\"",
"\"",
",",
"reply",
".",
"GetMessageName",
"(",
")",
",",
"\"",
"\"",
",",
"request",
".",
"ClientID",
")",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"err",
"=",
"struc",
".",
"Pack",
"(",
"buf",
",",
"&",
"codec",
".",
"VppReplyHeader",
"{",
"VlMsgID",
":",
"replyMsgID",
",",
"Context",
":",
"request",
".",
"ClientID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"struc",
".",
"Pack",
"(",
"buf",
",",
"reply",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // ReplyBytes encodes the mocked reply into binary format. | [
"ReplyBytes",
"encodes",
"the",
"mocked",
"reply",
"into",
"binary",
"format",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L172-L194 |
12,674 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | GetMsgID | func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
switch msgName {
case "control_ping":
return 100, nil
case "control_ping_reply":
return 101, nil
case "sw_interface_dump":
return 200, nil
case "sw_interface_details":
return 201, nil
}
a.access.Lock()
defer a.access.Unlock()
msgID, found := a.msgNameToIds[msgName]
if found {
return msgID, nil
}
a.msgIDSeq++
msgID = a.msgIDSeq
a.msgNameToIds[msgName] = msgID
a.msgIDsToName[msgID] = msgName
return msgID, nil
} | go | func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
switch msgName {
case "control_ping":
return 100, nil
case "control_ping_reply":
return 101, nil
case "sw_interface_dump":
return 200, nil
case "sw_interface_details":
return 201, nil
}
a.access.Lock()
defer a.access.Unlock()
msgID, found := a.msgNameToIds[msgName]
if found {
return msgID, nil
}
a.msgIDSeq++
msgID = a.msgIDSeq
a.msgNameToIds[msgName] = msgID
a.msgIDsToName[msgID] = msgName
return msgID, nil
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"GetMsgID",
"(",
"msgName",
"string",
",",
"msgCrc",
"string",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"switch",
"msgName",
"{",
"case",
"\"",
"\"",
":",
"return",
"100",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"101",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"200",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"201",
",",
"nil",
"\n",
"}",
"\n\n",
"a",
".",
"access",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"access",
".",
"Unlock",
"(",
")",
"\n\n",
"msgID",
",",
"found",
":=",
"a",
".",
"msgNameToIds",
"[",
"msgName",
"]",
"\n",
"if",
"found",
"{",
"return",
"msgID",
",",
"nil",
"\n",
"}",
"\n\n",
"a",
".",
"msgIDSeq",
"++",
"\n",
"msgID",
"=",
"a",
".",
"msgIDSeq",
"\n",
"a",
".",
"msgNameToIds",
"[",
"msgName",
"]",
"=",
"msgID",
"\n",
"a",
".",
"msgIDsToName",
"[",
"msgID",
"]",
"=",
"msgName",
"\n\n",
"return",
"msgID",
",",
"nil",
"\n",
"}"
] | // GetMsgID returns mocked message ID for the given message name and CRC. | [
"GetMsgID",
"returns",
"mocked",
"message",
"ID",
"for",
"the",
"given",
"message",
"name",
"and",
"CRC",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L197-L223 |
12,675 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | MockReplyHandler | func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
a.repliesLock.Lock()
defer a.repliesLock.Unlock()
a.replyHandlers = append(a.replyHandlers, replyHandler)
a.mode = useReplyHandlers
} | go | func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
a.repliesLock.Lock()
defer a.repliesLock.Unlock()
a.replyHandlers = append(a.replyHandlers, replyHandler)
a.mode = useReplyHandlers
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"MockReplyHandler",
"(",
"replyHandler",
"ReplyHandler",
")",
"{",
"a",
".",
"repliesLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"repliesLock",
".",
"Unlock",
"(",
")",
"\n\n",
"a",
".",
"replyHandlers",
"=",
"append",
"(",
"a",
".",
"replyHandlers",
",",
"replyHandler",
")",
"\n",
"a",
".",
"mode",
"=",
"useReplyHandlers",
"\n",
"}"
] | // MockReplyHandler registers a handler function that is supposed to generate mock responses to incoming requests.
// Using of this method automatically switches the mock into th useReplyHandlers mode. | [
"MockReplyHandler",
"registers",
"a",
"handler",
"function",
"that",
"is",
"supposed",
"to",
"generate",
"mock",
"responses",
"to",
"incoming",
"requests",
".",
"Using",
"of",
"this",
"method",
"automatically",
"switches",
"the",
"mock",
"into",
"th",
"useReplyHandlers",
"mode",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L367-L373 |
12,676 | FDio/govpp | extras/libmemif/examples/gopacket/gopacket.go | OnInterrupt | func OnInterrupt(handle *libmemif.MemifPacketHandle) {
source := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
var responses []gopacket.Packet
// Process ICMP pings
for packet := range source.Packets() {
fmt.Println("Received new packet:")
fmt.Println(packet.Dump())
response, err := GeneratePacketResponse(packet)
if err != nil {
fmt.Printf("Failed to generate response: %v\n", err)
continue
}
fmt.Println("Sending response:")
fmt.Println(response.Dump())
responses = append(responses, response)
}
// Answer with ICMP pongs
for i, response := range responses {
err := handle.WritePacketData(response.Data())
switch err {
case io.EOF:
return
case nil:
fmt.Printf("Succesfully sent packet #%v %v\n", i, len(response.Data()))
default:
fmt.Printf("Got error while sending packet #%v %v\n", i, err)
}
}
} | go | func OnInterrupt(handle *libmemif.MemifPacketHandle) {
source := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
var responses []gopacket.Packet
// Process ICMP pings
for packet := range source.Packets() {
fmt.Println("Received new packet:")
fmt.Println(packet.Dump())
response, err := GeneratePacketResponse(packet)
if err != nil {
fmt.Printf("Failed to generate response: %v\n", err)
continue
}
fmt.Println("Sending response:")
fmt.Println(response.Dump())
responses = append(responses, response)
}
// Answer with ICMP pongs
for i, response := range responses {
err := handle.WritePacketData(response.Data())
switch err {
case io.EOF:
return
case nil:
fmt.Printf("Succesfully sent packet #%v %v\n", i, len(response.Data()))
default:
fmt.Printf("Got error while sending packet #%v %v\n", i, err)
}
}
} | [
"func",
"OnInterrupt",
"(",
"handle",
"*",
"libmemif",
".",
"MemifPacketHandle",
")",
"{",
"source",
":=",
"gopacket",
".",
"NewPacketSource",
"(",
"handle",
",",
"layers",
".",
"LayerTypeEthernet",
")",
"\n",
"var",
"responses",
"[",
"]",
"gopacket",
".",
"Packet",
"\n\n",
"// Process ICMP pings",
"for",
"packet",
":=",
"range",
"source",
".",
"Packets",
"(",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Println",
"(",
"packet",
".",
"Dump",
"(",
")",
")",
"\n\n",
"response",
",",
"err",
":=",
"GeneratePacketResponse",
"(",
"packet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Println",
"(",
"response",
".",
"Dump",
"(",
")",
")",
"\n",
"responses",
"=",
"append",
"(",
"responses",
",",
"response",
")",
"\n",
"}",
"\n\n",
"// Answer with ICMP pongs",
"for",
"i",
",",
"response",
":=",
"range",
"responses",
"{",
"err",
":=",
"handle",
".",
"WritePacketData",
"(",
"response",
".",
"Data",
"(",
")",
")",
"\n\n",
"switch",
"err",
"{",
"case",
"io",
".",
"EOF",
":",
"return",
"\n",
"case",
"nil",
":",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
",",
"len",
"(",
"response",
".",
"Data",
"(",
")",
")",
")",
"\n",
"default",
":",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // OnInterrupt is called when interrupted | [
"OnInterrupt",
"is",
"called",
"when",
"interrupted"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/gopacket/gopacket.go#L107-L140 |
12,677 | FDio/govpp | extras/libmemif/examples/gopacket/gopacket.go | CreateInterruptCallback | func CreateInterruptCallback(handle *libmemif.MemifPacketHandle, interruptCh <-chan struct{}, callback func(handle *libmemif.MemifPacketHandle)) {
for {
select {
case <-interruptCh:
callback(handle)
case <-stopCh:
handle.Close()
return
}
}
} | go | func CreateInterruptCallback(handle *libmemif.MemifPacketHandle, interruptCh <-chan struct{}, callback func(handle *libmemif.MemifPacketHandle)) {
for {
select {
case <-interruptCh:
callback(handle)
case <-stopCh:
handle.Close()
return
}
}
} | [
"func",
"CreateInterruptCallback",
"(",
"handle",
"*",
"libmemif",
".",
"MemifPacketHandle",
",",
"interruptCh",
"<-",
"chan",
"struct",
"{",
"}",
",",
"callback",
"func",
"(",
"handle",
"*",
"libmemif",
".",
"MemifPacketHandle",
")",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"interruptCh",
":",
"callback",
"(",
"handle",
")",
"\n",
"case",
"<-",
"stopCh",
":",
"handle",
".",
"Close",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Creates user-friendly memif interrupt callback | [
"Creates",
"user",
"-",
"friendly",
"memif",
"interrupt",
"callback"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/gopacket/gopacket.go#L143-L153 |
12,678 | FDio/govpp | core/connection.go | Connect | func Connect(binapi adapter.VppAPI) (*Connection, error) {
// create new connection handle
c := newConnection(binapi, DefaultMaxReconnectAttempts, DefaultReconnectInterval)
// blocking attempt to connect to VPP
if err := c.connectVPP(); err != nil {
return nil, err
}
return c, nil
} | go | func Connect(binapi adapter.VppAPI) (*Connection, error) {
// create new connection handle
c := newConnection(binapi, DefaultMaxReconnectAttempts, DefaultReconnectInterval)
// blocking attempt to connect to VPP
if err := c.connectVPP(); err != nil {
return nil, err
}
return c, nil
} | [
"func",
"Connect",
"(",
"binapi",
"adapter",
".",
"VppAPI",
")",
"(",
"*",
"Connection",
",",
"error",
")",
"{",
"// create new connection handle",
"c",
":=",
"newConnection",
"(",
"binapi",
",",
"DefaultMaxReconnectAttempts",
",",
"DefaultReconnectInterval",
")",
"\n\n",
"// blocking attempt to connect to VPP",
"if",
"err",
":=",
"c",
".",
"connectVPP",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // Connect connects to VPP API using specified adapter and returns a connection handle.
// This call blocks until it is either connected, or an error occurs.
// Only one connection attempt will be performed. | [
"Connect",
"connects",
"to",
"VPP",
"API",
"using",
"specified",
"adapter",
"and",
"returns",
"a",
"connection",
"handle",
".",
"This",
"call",
"blocks",
"until",
"it",
"is",
"either",
"connected",
"or",
"an",
"error",
"occurs",
".",
"Only",
"one",
"connection",
"attempt",
"will",
"be",
"performed",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L142-L152 |
12,679 | FDio/govpp | core/connection.go | connectVPP | func (c *Connection) connectVPP() error {
log.Debug("Connecting to VPP..")
// blocking connect
if err := c.vppClient.Connect(); err != nil {
return err
}
log.Debugf("Connected to VPP.")
if err := c.retrieveMessageIDs(); err != nil {
c.vppClient.Disconnect()
return fmt.Errorf("VPP is incompatible: %v", err)
}
// store connected state
atomic.StoreUint32(&c.vppConnected, 1)
return nil
} | go | func (c *Connection) connectVPP() error {
log.Debug("Connecting to VPP..")
// blocking connect
if err := c.vppClient.Connect(); err != nil {
return err
}
log.Debugf("Connected to VPP.")
if err := c.retrieveMessageIDs(); err != nil {
c.vppClient.Disconnect()
return fmt.Errorf("VPP is incompatible: %v", err)
}
// store connected state
atomic.StoreUint32(&c.vppConnected, 1)
return nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"connectVPP",
"(",
")",
"error",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// blocking connect",
"if",
"err",
":=",
"c",
".",
"vppClient",
".",
"Connect",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
":=",
"c",
".",
"retrieveMessageIDs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"c",
".",
"vppClient",
".",
"Disconnect",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// store connected state",
"atomic",
".",
"StoreUint32",
"(",
"&",
"c",
".",
"vppConnected",
",",
"1",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // connectVPP performs blocking attempt to connect to VPP. | [
"connectVPP",
"performs",
"blocking",
"attempt",
"to",
"connect",
"to",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L170-L189 |
12,680 | FDio/govpp | core/connection.go | Disconnect | func (c *Connection) Disconnect() {
if c == nil {
return
}
if c.vppClient != nil {
c.disconnectVPP()
}
} | go | func (c *Connection) Disconnect() {
if c == nil {
return
}
if c.vppClient != nil {
c.disconnectVPP()
}
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"Disconnect",
"(",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"vppClient",
"!=",
"nil",
"{",
"c",
".",
"disconnectVPP",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Disconnect disconnects from VPP API and releases all connection-related resources. | [
"Disconnect",
"disconnects",
"from",
"VPP",
"API",
"and",
"releases",
"all",
"connection",
"-",
"related",
"resources",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L192-L200 |
12,681 | FDio/govpp | core/connection.go | disconnectVPP | func (c *Connection) disconnectVPP() {
if atomic.CompareAndSwapUint32(&c.vppConnected, 1, 0) {
c.vppClient.Disconnect()
}
} | go | func (c *Connection) disconnectVPP() {
if atomic.CompareAndSwapUint32(&c.vppConnected, 1, 0) {
c.vppClient.Disconnect()
}
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"disconnectVPP",
"(",
")",
"{",
"if",
"atomic",
".",
"CompareAndSwapUint32",
"(",
"&",
"c",
".",
"vppConnected",
",",
"1",
",",
"0",
")",
"{",
"c",
".",
"vppClient",
".",
"Disconnect",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // disconnectVPP disconnects from VPP in case it is connected. | [
"disconnectVPP",
"disconnects",
"from",
"VPP",
"in",
"case",
"it",
"is",
"connected",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L203-L207 |
12,682 | FDio/govpp | core/connection.go | newAPIChannel | func (c *Connection) newAPIChannel(reqChanBufSize, replyChanBufSize int) (*Channel, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
// create new channel
chID := uint16(atomic.AddUint32(&c.maxChannelID, 1) & 0x7fff)
channel := newChannel(chID, c, c.codec, c, reqChanBufSize, replyChanBufSize)
// store API channel within the client
c.channelsLock.Lock()
c.channels[chID] = channel
c.channelsLock.Unlock()
// start watching on the request channel
go c.watchRequests(channel)
return channel, nil
} | go | func (c *Connection) newAPIChannel(reqChanBufSize, replyChanBufSize int) (*Channel, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
// create new channel
chID := uint16(atomic.AddUint32(&c.maxChannelID, 1) & 0x7fff)
channel := newChannel(chID, c, c.codec, c, reqChanBufSize, replyChanBufSize)
// store API channel within the client
c.channelsLock.Lock()
c.channels[chID] = channel
c.channelsLock.Unlock()
// start watching on the request channel
go c.watchRequests(channel)
return channel, nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"newAPIChannel",
"(",
"reqChanBufSize",
",",
"replyChanBufSize",
"int",
")",
"(",
"*",
"Channel",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// create new channel",
"chID",
":=",
"uint16",
"(",
"atomic",
".",
"AddUint32",
"(",
"&",
"c",
".",
"maxChannelID",
",",
"1",
")",
"&",
"0x7fff",
")",
"\n",
"channel",
":=",
"newChannel",
"(",
"chID",
",",
"c",
",",
"c",
".",
"codec",
",",
"c",
",",
"reqChanBufSize",
",",
"replyChanBufSize",
")",
"\n\n",
"// store API channel within the client",
"c",
".",
"channelsLock",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"channels",
"[",
"chID",
"]",
"=",
"channel",
"\n",
"c",
".",
"channelsLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// start watching on the request channel",
"go",
"c",
".",
"watchRequests",
"(",
"channel",
")",
"\n\n",
"return",
"channel",
",",
"nil",
"\n",
"}"
] | // NewAPIChannelBuffered returns a new API channel for communication with VPP via govpp core.
// It allows to specify custom buffer sizes for the request and reply Go channels. | [
"NewAPIChannelBuffered",
"returns",
"a",
"new",
"API",
"channel",
"for",
"communication",
"with",
"VPP",
"via",
"govpp",
"core",
".",
"It",
"allows",
"to",
"specify",
"custom",
"buffer",
"sizes",
"for",
"the",
"request",
"and",
"reply",
"Go",
"channels",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L219-L237 |
12,683 | FDio/govpp | core/connection.go | releaseAPIChannel | func (c *Connection) releaseAPIChannel(ch *Channel) {
log.WithFields(logger.Fields{
"channel": ch.id,
}).Debug("API channel released")
// delete the channel from channels map
c.channelsLock.Lock()
delete(c.channels, ch.id)
c.channelsLock.Unlock()
} | go | func (c *Connection) releaseAPIChannel(ch *Channel) {
log.WithFields(logger.Fields{
"channel": ch.id,
}).Debug("API channel released")
// delete the channel from channels map
c.channelsLock.Lock()
delete(c.channels, ch.id)
c.channelsLock.Unlock()
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"releaseAPIChannel",
"(",
"ch",
"*",
"Channel",
")",
"{",
"log",
".",
"WithFields",
"(",
"logger",
".",
"Fields",
"{",
"\"",
"\"",
":",
"ch",
".",
"id",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// delete the channel from channels map",
"c",
".",
"channelsLock",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"c",
".",
"channels",
",",
"ch",
".",
"id",
")",
"\n",
"c",
".",
"channelsLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // releaseAPIChannel releases API channel that needs to be closed. | [
"releaseAPIChannel",
"releases",
"API",
"channel",
"that",
"needs",
"to",
"be",
"closed",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L240-L249 |
12,684 | FDio/govpp | core/connection.go | connectLoop | func (c *Connection) connectLoop(connChan chan ConnectionEvent) {
reconnectAttempts := 0
// loop until connected
for {
if err := c.vppClient.WaitReady(); err != nil {
log.Warnf("wait ready failed: %v", err)
}
if err := c.connectVPP(); err == nil {
// signal connected event
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Connected}
break
} else if reconnectAttempts < c.maxAttempts {
reconnectAttempts++
log.Errorf("connecting failed (attempt %d/%d): %v", reconnectAttempts, c.maxAttempts, err)
time.Sleep(c.recInterval)
} else {
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Failed, Error: err}
return
}
}
// we are now connected, continue with health check loop
c.healthCheckLoop(connChan)
} | go | func (c *Connection) connectLoop(connChan chan ConnectionEvent) {
reconnectAttempts := 0
// loop until connected
for {
if err := c.vppClient.WaitReady(); err != nil {
log.Warnf("wait ready failed: %v", err)
}
if err := c.connectVPP(); err == nil {
// signal connected event
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Connected}
break
} else if reconnectAttempts < c.maxAttempts {
reconnectAttempts++
log.Errorf("connecting failed (attempt %d/%d): %v", reconnectAttempts, c.maxAttempts, err)
time.Sleep(c.recInterval)
} else {
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Failed, Error: err}
return
}
}
// we are now connected, continue with health check loop
c.healthCheckLoop(connChan)
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"connectLoop",
"(",
"connChan",
"chan",
"ConnectionEvent",
")",
"{",
"reconnectAttempts",
":=",
"0",
"\n\n",
"// loop until connected",
"for",
"{",
"if",
"err",
":=",
"c",
".",
"vppClient",
".",
"WaitReady",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"connectVPP",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"// signal connected event",
"connChan",
"<-",
"ConnectionEvent",
"{",
"Timestamp",
":",
"time",
".",
"Now",
"(",
")",
",",
"State",
":",
"Connected",
"}",
"\n",
"break",
"\n",
"}",
"else",
"if",
"reconnectAttempts",
"<",
"c",
".",
"maxAttempts",
"{",
"reconnectAttempts",
"++",
"\n",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"reconnectAttempts",
",",
"c",
".",
"maxAttempts",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"c",
".",
"recInterval",
")",
"\n",
"}",
"else",
"{",
"connChan",
"<-",
"ConnectionEvent",
"{",
"Timestamp",
":",
"time",
".",
"Now",
"(",
")",
",",
"State",
":",
"Failed",
",",
"Error",
":",
"err",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// we are now connected, continue with health check loop",
"c",
".",
"healthCheckLoop",
"(",
"connChan",
")",
"\n",
"}"
] | // connectLoop attempts to connect to VPP until it succeeds.
// Then it continues with healthCheckLoop. | [
"connectLoop",
"attempts",
"to",
"connect",
"to",
"VPP",
"until",
"it",
"succeeds",
".",
"Then",
"it",
"continues",
"with",
"healthCheckLoop",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L253-L277 |
12,685 | FDio/govpp | core/connection.go | healthCheckLoop | func (c *Connection) healthCheckLoop(connChan chan ConnectionEvent) {
// create a separate API channel for health check probes
ch, err := c.newAPIChannel(1, 1)
if err != nil {
log.Error("Failed to create health check API channel, health check will be disabled:", err)
return
}
var (
sinceLastReply time.Duration
failedChecks int
)
// send health check probes until an error or timeout occurs
for {
// sleep until next health check probe period
time.Sleep(HealthCheckProbeInterval)
if atomic.LoadUint32(&c.vppConnected) == 0 {
// Disconnect has been called in the meantime, return the healthcheck - reconnect loop
log.Debug("Disconnected on request, exiting health check loop.")
return
}
// try draining probe replies from previous request before sending next one
select {
case <-ch.replyChan:
log.Debug("drained old probe reply from reply channel")
default:
}
// send the control ping request
ch.reqChan <- &vppRequest{msg: msgControlPing}
for {
// expect response within timeout period
select {
case vppReply := <-ch.replyChan:
err = vppReply.err
case <-time.After(HealthCheckReplyTimeout):
err = ErrProbeTimeout
// check if time since last reply from any other
// channel is less than health check reply timeout
c.lastReplyLock.Lock()
sinceLastReply = time.Since(c.lastReply)
c.lastReplyLock.Unlock()
if sinceLastReply < HealthCheckReplyTimeout {
log.Warnf("VPP health check probe timing out, but some request on other channel was received %v ago, continue waiting!", sinceLastReply)
continue
}
}
break
}
if err == ErrProbeTimeout {
failedChecks++
log.Warnf("VPP health check probe timed out after %v (%d. timeout)", HealthCheckReplyTimeout, failedChecks)
if failedChecks > HealthCheckThreshold {
// in case of exceeded failed check treshold, assume VPP disconnected
log.Errorf("VPP health check exceeded treshold for timeouts (>%d), assuming disconnect", HealthCheckThreshold)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected}
break
}
} else if err != nil {
// in case of error, assume VPP disconnected
log.Errorf("VPP health check probe failed: %v", err)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected, Error: err}
break
} else if failedChecks > 0 {
// in case of success after failed checks, clear failed check counter
failedChecks = 0
log.Infof("VPP health check probe OK")
}
}
// cleanup
ch.Close()
c.disconnectVPP()
// we are now disconnected, start connect loop
c.connectLoop(connChan)
} | go | func (c *Connection) healthCheckLoop(connChan chan ConnectionEvent) {
// create a separate API channel for health check probes
ch, err := c.newAPIChannel(1, 1)
if err != nil {
log.Error("Failed to create health check API channel, health check will be disabled:", err)
return
}
var (
sinceLastReply time.Duration
failedChecks int
)
// send health check probes until an error or timeout occurs
for {
// sleep until next health check probe period
time.Sleep(HealthCheckProbeInterval)
if atomic.LoadUint32(&c.vppConnected) == 0 {
// Disconnect has been called in the meantime, return the healthcheck - reconnect loop
log.Debug("Disconnected on request, exiting health check loop.")
return
}
// try draining probe replies from previous request before sending next one
select {
case <-ch.replyChan:
log.Debug("drained old probe reply from reply channel")
default:
}
// send the control ping request
ch.reqChan <- &vppRequest{msg: msgControlPing}
for {
// expect response within timeout period
select {
case vppReply := <-ch.replyChan:
err = vppReply.err
case <-time.After(HealthCheckReplyTimeout):
err = ErrProbeTimeout
// check if time since last reply from any other
// channel is less than health check reply timeout
c.lastReplyLock.Lock()
sinceLastReply = time.Since(c.lastReply)
c.lastReplyLock.Unlock()
if sinceLastReply < HealthCheckReplyTimeout {
log.Warnf("VPP health check probe timing out, but some request on other channel was received %v ago, continue waiting!", sinceLastReply)
continue
}
}
break
}
if err == ErrProbeTimeout {
failedChecks++
log.Warnf("VPP health check probe timed out after %v (%d. timeout)", HealthCheckReplyTimeout, failedChecks)
if failedChecks > HealthCheckThreshold {
// in case of exceeded failed check treshold, assume VPP disconnected
log.Errorf("VPP health check exceeded treshold for timeouts (>%d), assuming disconnect", HealthCheckThreshold)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected}
break
}
} else if err != nil {
// in case of error, assume VPP disconnected
log.Errorf("VPP health check probe failed: %v", err)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected, Error: err}
break
} else if failedChecks > 0 {
// in case of success after failed checks, clear failed check counter
failedChecks = 0
log.Infof("VPP health check probe OK")
}
}
// cleanup
ch.Close()
c.disconnectVPP()
// we are now disconnected, start connect loop
c.connectLoop(connChan)
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"healthCheckLoop",
"(",
"connChan",
"chan",
"ConnectionEvent",
")",
"{",
"// create a separate API channel for health check probes",
"ch",
",",
"err",
":=",
"c",
".",
"newAPIChannel",
"(",
"1",
",",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"(",
"sinceLastReply",
"time",
".",
"Duration",
"\n",
"failedChecks",
"int",
"\n",
")",
"\n\n",
"// send health check probes until an error or timeout occurs",
"for",
"{",
"// sleep until next health check probe period",
"time",
".",
"Sleep",
"(",
"HealthCheckProbeInterval",
")",
"\n\n",
"if",
"atomic",
".",
"LoadUint32",
"(",
"&",
"c",
".",
"vppConnected",
")",
"==",
"0",
"{",
"// Disconnect has been called in the meantime, return the healthcheck - reconnect loop",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// try draining probe replies from previous request before sending next one",
"select",
"{",
"case",
"<-",
"ch",
".",
"replyChan",
":",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"default",
":",
"}",
"\n\n",
"// send the control ping request",
"ch",
".",
"reqChan",
"<-",
"&",
"vppRequest",
"{",
"msg",
":",
"msgControlPing",
"}",
"\n\n",
"for",
"{",
"// expect response within timeout period",
"select",
"{",
"case",
"vppReply",
":=",
"<-",
"ch",
".",
"replyChan",
":",
"err",
"=",
"vppReply",
".",
"err",
"\n\n",
"case",
"<-",
"time",
".",
"After",
"(",
"HealthCheckReplyTimeout",
")",
":",
"err",
"=",
"ErrProbeTimeout",
"\n\n",
"// check if time since last reply from any other",
"// channel is less than health check reply timeout",
"c",
".",
"lastReplyLock",
".",
"Lock",
"(",
")",
"\n",
"sinceLastReply",
"=",
"time",
".",
"Since",
"(",
"c",
".",
"lastReply",
")",
"\n",
"c",
".",
"lastReplyLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"sinceLastReply",
"<",
"HealthCheckReplyTimeout",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"sinceLastReply",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"ErrProbeTimeout",
"{",
"failedChecks",
"++",
"\n",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"HealthCheckReplyTimeout",
",",
"failedChecks",
")",
"\n",
"if",
"failedChecks",
">",
"HealthCheckThreshold",
"{",
"// in case of exceeded failed check treshold, assume VPP disconnected",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"HealthCheckThreshold",
")",
"\n",
"connChan",
"<-",
"ConnectionEvent",
"{",
"Timestamp",
":",
"time",
".",
"Now",
"(",
")",
",",
"State",
":",
"Disconnected",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"// in case of error, assume VPP disconnected",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"connChan",
"<-",
"ConnectionEvent",
"{",
"Timestamp",
":",
"time",
".",
"Now",
"(",
")",
",",
"State",
":",
"Disconnected",
",",
"Error",
":",
"err",
"}",
"\n",
"break",
"\n",
"}",
"else",
"if",
"failedChecks",
">",
"0",
"{",
"// in case of success after failed checks, clear failed check counter",
"failedChecks",
"=",
"0",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// cleanup",
"ch",
".",
"Close",
"(",
")",
"\n",
"c",
".",
"disconnectVPP",
"(",
")",
"\n\n",
"// we are now disconnected, start connect loop",
"c",
".",
"connectLoop",
"(",
"connChan",
")",
"\n",
"}"
] | // healthCheckLoop checks whether connection to VPP is alive. In case of disconnect,
// it continues with connectLoop and tries to reconnect. | [
"healthCheckLoop",
"checks",
"whether",
"connection",
"to",
"VPP",
"is",
"alive",
".",
"In",
"case",
"of",
"disconnect",
"it",
"continues",
"with",
"connectLoop",
"and",
"tries",
"to",
"reconnect",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L281-L365 |
12,686 | FDio/govpp | core/connection.go | GetMessageID | func (c *Connection) GetMessageID(msg api.Message) (uint16, error) {
if c == nil {
return 0, errors.New("nil connection passed in")
}
if msgID, ok := c.msgIDs[getMsgNameWithCrc(msg)]; ok {
return msgID, nil
}
msgID, err := c.vppClient.GetMsgID(msg.GetMessageName(), msg.GetCrcString())
if err != nil {
return 0, err
}
c.msgIDs[getMsgNameWithCrc(msg)] = msgID
c.msgMap[msgID] = msg
return msgID, nil
} | go | func (c *Connection) GetMessageID(msg api.Message) (uint16, error) {
if c == nil {
return 0, errors.New("nil connection passed in")
}
if msgID, ok := c.msgIDs[getMsgNameWithCrc(msg)]; ok {
return msgID, nil
}
msgID, err := c.vppClient.GetMsgID(msg.GetMessageName(), msg.GetCrcString())
if err != nil {
return 0, err
}
c.msgIDs[getMsgNameWithCrc(msg)] = msgID
c.msgMap[msgID] = msg
return msgID, nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"GetMessageID",
"(",
"msg",
"api",
".",
"Message",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"msgID",
",",
"ok",
":=",
"c",
".",
"msgIDs",
"[",
"getMsgNameWithCrc",
"(",
"msg",
")",
"]",
";",
"ok",
"{",
"return",
"msgID",
",",
"nil",
"\n",
"}",
"\n\n",
"msgID",
",",
"err",
":=",
"c",
".",
"vppClient",
".",
"GetMsgID",
"(",
"msg",
".",
"GetMessageName",
"(",
")",
",",
"msg",
".",
"GetCrcString",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"msgIDs",
"[",
"getMsgNameWithCrc",
"(",
"msg",
")",
"]",
"=",
"msgID",
"\n",
"c",
".",
"msgMap",
"[",
"msgID",
"]",
"=",
"msg",
"\n\n",
"return",
"msgID",
",",
"nil",
"\n",
"}"
] | // GetMessageID returns message identifier of given API message. | [
"GetMessageID",
"returns",
"message",
"identifier",
"of",
"given",
"API",
"message",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L378-L396 |
12,687 | FDio/govpp | core/connection.go | LookupByID | func (c *Connection) LookupByID(msgID uint16) (api.Message, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
if msg, ok := c.msgMap[msgID]; ok {
return msg, nil
}
return nil, fmt.Errorf("unknown message ID: %d", msgID)
} | go | func (c *Connection) LookupByID(msgID uint16) (api.Message, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
if msg, ok := c.msgMap[msgID]; ok {
return msg, nil
}
return nil, fmt.Errorf("unknown message ID: %d", msgID)
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"LookupByID",
"(",
"msgID",
"uint16",
")",
"(",
"api",
".",
"Message",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"msg",
",",
"ok",
":=",
"c",
".",
"msgMap",
"[",
"msgID",
"]",
";",
"ok",
"{",
"return",
"msg",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msgID",
")",
"\n",
"}"
] | // LookupByID looks up message name and crc by ID. | [
"LookupByID",
"looks",
"up",
"message",
"name",
"and",
"crc",
"by",
"ID",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L399-L409 |
12,688 | FDio/govpp | core/connection.go | retrieveMessageIDs | func (c *Connection) retrieveMessageIDs() (err error) {
t := time.Now()
msgs := api.GetRegisteredMessages()
var n int
for name, msg := range msgs {
msgID, err := c.GetMessageID(msg)
if err != nil {
log.Debugf("retrieving msgID for %s failed: %v", name, err)
continue
}
n++
if c.pingReqID == 0 && msg.GetMessageName() == msgControlPing.GetMessageName() {
c.pingReqID = msgID
msgControlPing = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
} else if c.pingReplyID == 0 && msg.GetMessageName() == msgControlPingReply.GetMessageName() {
c.pingReplyID = msgID
msgControlPingReply = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
}
if debugMsgIDs {
log.Debugf("message %q (%s) has ID: %d", name, getMsgNameWithCrc(msg), msgID)
}
}
log.Debugf("retrieved %d/%d msgIDs (took %s)", n, len(msgs), time.Since(t))
return nil
} | go | func (c *Connection) retrieveMessageIDs() (err error) {
t := time.Now()
msgs := api.GetRegisteredMessages()
var n int
for name, msg := range msgs {
msgID, err := c.GetMessageID(msg)
if err != nil {
log.Debugf("retrieving msgID for %s failed: %v", name, err)
continue
}
n++
if c.pingReqID == 0 && msg.GetMessageName() == msgControlPing.GetMessageName() {
c.pingReqID = msgID
msgControlPing = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
} else if c.pingReplyID == 0 && msg.GetMessageName() == msgControlPingReply.GetMessageName() {
c.pingReplyID = msgID
msgControlPingReply = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
}
if debugMsgIDs {
log.Debugf("message %q (%s) has ID: %d", name, getMsgNameWithCrc(msg), msgID)
}
}
log.Debugf("retrieved %d/%d msgIDs (took %s)", n, len(msgs), time.Since(t))
return nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"retrieveMessageIDs",
"(",
")",
"(",
"err",
"error",
")",
"{",
"t",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"msgs",
":=",
"api",
".",
"GetRegisteredMessages",
"(",
")",
"\n\n",
"var",
"n",
"int",
"\n",
"for",
"name",
",",
"msg",
":=",
"range",
"msgs",
"{",
"msgID",
",",
"err",
":=",
"c",
".",
"GetMessageID",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"n",
"++",
"\n\n",
"if",
"c",
".",
"pingReqID",
"==",
"0",
"&&",
"msg",
".",
"GetMessageName",
"(",
")",
"==",
"msgControlPing",
".",
"GetMessageName",
"(",
")",
"{",
"c",
".",
"pingReqID",
"=",
"msgID",
"\n",
"msgControlPing",
"=",
"reflect",
".",
"New",
"(",
"reflect",
".",
"TypeOf",
"(",
"msg",
")",
".",
"Elem",
"(",
")",
")",
".",
"Interface",
"(",
")",
".",
"(",
"api",
".",
"Message",
")",
"\n",
"}",
"else",
"if",
"c",
".",
"pingReplyID",
"==",
"0",
"&&",
"msg",
".",
"GetMessageName",
"(",
")",
"==",
"msgControlPingReply",
".",
"GetMessageName",
"(",
")",
"{",
"c",
".",
"pingReplyID",
"=",
"msgID",
"\n",
"msgControlPingReply",
"=",
"reflect",
".",
"New",
"(",
"reflect",
".",
"TypeOf",
"(",
"msg",
")",
".",
"Elem",
"(",
")",
")",
".",
"Interface",
"(",
")",
".",
"(",
"api",
".",
"Message",
")",
"\n",
"}",
"\n\n",
"if",
"debugMsgIDs",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"getMsgNameWithCrc",
"(",
"msg",
")",
",",
"msgID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"n",
",",
"len",
"(",
"msgs",
")",
",",
"time",
".",
"Since",
"(",
"t",
")",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // retrieveMessageIDs retrieves IDs for all registered messages and stores them in map | [
"retrieveMessageIDs",
"retrieves",
"IDs",
"for",
"all",
"registered",
"messages",
"and",
"stores",
"them",
"in",
"map"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L412-L441 |
12,689 | mailgun/lemma | httpsign/nonce.go | NewNonceCache | func NewNonceCache(capacity int, cacheTTL int, timeProvider timetools.TimeProvider) (*NonceCache, error) {
c, err := ttlmap.NewMapWithProvider(capacity, timeProvider)
if err != nil {
return nil, err
}
return &NonceCache{
cache: c,
cacheTTL: cacheTTL,
timeProvider: timeProvider,
}, nil
} | go | func NewNonceCache(capacity int, cacheTTL int, timeProvider timetools.TimeProvider) (*NonceCache, error) {
c, err := ttlmap.NewMapWithProvider(capacity, timeProvider)
if err != nil {
return nil, err
}
return &NonceCache{
cache: c,
cacheTTL: cacheTTL,
timeProvider: timeProvider,
}, nil
} | [
"func",
"NewNonceCache",
"(",
"capacity",
"int",
",",
"cacheTTL",
"int",
",",
"timeProvider",
"timetools",
".",
"TimeProvider",
")",
"(",
"*",
"NonceCache",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"ttlmap",
".",
"NewMapWithProvider",
"(",
"capacity",
",",
"timeProvider",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"NonceCache",
"{",
"cache",
":",
"c",
",",
"cacheTTL",
":",
"cacheTTL",
",",
"timeProvider",
":",
"timeProvider",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Return a new NonceCache. Allows you to control cache capacity, ttl, as well as the TimeProvider. | [
"Return",
"a",
"new",
"NonceCache",
".",
"Allows",
"you",
"to",
"control",
"cache",
"capacity",
"ttl",
"as",
"well",
"as",
"the",
"TimeProvider",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/httpsign/nonce.go#L18-L29 |
12,690 | mailgun/lemma | httpsign/auth.go | NewWithProviders | func NewWithProviders(config *Config, timeProvider timetools.TimeProvider,
randomProvider random.RandomProvider) (*Service, error) {
// config is required!
if config == nil {
return nil, fmt.Errorf("config is required.")
}
// set defaults if not set
if config.NonceCacheCapacity < 1 {
config.NonceCacheCapacity = CacheCapacity
}
if config.NonceCacheTimeout < 1 {
config.NonceCacheTimeout = CacheTimeout
}
if config.NonceHeaderName == "" {
config.NonceHeaderName = XMailgunNonce
}
if config.TimestampHeaderName == "" {
config.TimestampHeaderName = XMailgunTimestamp
}
if config.SignatureHeaderName == "" {
config.SignatureHeaderName = XMailgunSignature
}
if config.SignatureVersionHeaderName == "" {
config.SignatureVersionHeaderName = XMailgunSignatureVersion
}
// setup metrics service
metricsClient := metrics.NewNop()
if config.EmitStats {
// get hostname of box
hostname, err := os.Hostname()
if err != nil {
return nil, fmt.Errorf("failed to obtain hostname: %v", err)
}
// build lemma prefix
prefix := "lemma." + strings.Replace(hostname, ".", "_", -1)
if config.StatsdPrefix != "" {
prefix += "." + config.StatsdPrefix
}
// build metrics client
hostport := fmt.Sprintf("%v:%v", config.StatsdHost, config.StatsdPort)
metricsClient, err = metrics.NewWithOptions(hostport, prefix, metrics.Options{UseBuffering: true})
if err != nil {
return nil, err
}
}
// Read in key from KeyPath or if not given, try getting them from KeyBytes.
var keyBytes []byte
var err error
if config.KeyPath != "" {
if keyBytes, err = readKeyFromDisk(config.KeyPath); err != nil {
return nil, err
}
} else {
if config.KeyBytes == nil {
return nil, errors.New("no key bytes provided")
}
keyBytes = config.KeyBytes
}
// setup nonce cache
ncache, err := NewNonceCache(config.NonceCacheCapacity, config.NonceCacheTimeout, timeProvider)
if err != nil {
return nil, err
}
// return service
return &Service{
config: config,
nonceCache: ncache,
secretKey: keyBytes,
timeProvider: timeProvider,
randomProvider: randomProvider,
metricsClient: metricsClient,
}, nil
} | go | func NewWithProviders(config *Config, timeProvider timetools.TimeProvider,
randomProvider random.RandomProvider) (*Service, error) {
// config is required!
if config == nil {
return nil, fmt.Errorf("config is required.")
}
// set defaults if not set
if config.NonceCacheCapacity < 1 {
config.NonceCacheCapacity = CacheCapacity
}
if config.NonceCacheTimeout < 1 {
config.NonceCacheTimeout = CacheTimeout
}
if config.NonceHeaderName == "" {
config.NonceHeaderName = XMailgunNonce
}
if config.TimestampHeaderName == "" {
config.TimestampHeaderName = XMailgunTimestamp
}
if config.SignatureHeaderName == "" {
config.SignatureHeaderName = XMailgunSignature
}
if config.SignatureVersionHeaderName == "" {
config.SignatureVersionHeaderName = XMailgunSignatureVersion
}
// setup metrics service
metricsClient := metrics.NewNop()
if config.EmitStats {
// get hostname of box
hostname, err := os.Hostname()
if err != nil {
return nil, fmt.Errorf("failed to obtain hostname: %v", err)
}
// build lemma prefix
prefix := "lemma." + strings.Replace(hostname, ".", "_", -1)
if config.StatsdPrefix != "" {
prefix += "." + config.StatsdPrefix
}
// build metrics client
hostport := fmt.Sprintf("%v:%v", config.StatsdHost, config.StatsdPort)
metricsClient, err = metrics.NewWithOptions(hostport, prefix, metrics.Options{UseBuffering: true})
if err != nil {
return nil, err
}
}
// Read in key from KeyPath or if not given, try getting them from KeyBytes.
var keyBytes []byte
var err error
if config.KeyPath != "" {
if keyBytes, err = readKeyFromDisk(config.KeyPath); err != nil {
return nil, err
}
} else {
if config.KeyBytes == nil {
return nil, errors.New("no key bytes provided")
}
keyBytes = config.KeyBytes
}
// setup nonce cache
ncache, err := NewNonceCache(config.NonceCacheCapacity, config.NonceCacheTimeout, timeProvider)
if err != nil {
return nil, err
}
// return service
return &Service{
config: config,
nonceCache: ncache,
secretKey: keyBytes,
timeProvider: timeProvider,
randomProvider: randomProvider,
metricsClient: metricsClient,
}, nil
} | [
"func",
"NewWithProviders",
"(",
"config",
"*",
"Config",
",",
"timeProvider",
"timetools",
".",
"TimeProvider",
",",
"randomProvider",
"random",
".",
"RandomProvider",
")",
"(",
"*",
"Service",
",",
"error",
")",
"{",
"// config is required!",
"if",
"config",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// set defaults if not set",
"if",
"config",
".",
"NonceCacheCapacity",
"<",
"1",
"{",
"config",
".",
"NonceCacheCapacity",
"=",
"CacheCapacity",
"\n",
"}",
"\n",
"if",
"config",
".",
"NonceCacheTimeout",
"<",
"1",
"{",
"config",
".",
"NonceCacheTimeout",
"=",
"CacheTimeout",
"\n",
"}",
"\n",
"if",
"config",
".",
"NonceHeaderName",
"==",
"\"",
"\"",
"{",
"config",
".",
"NonceHeaderName",
"=",
"XMailgunNonce",
"\n",
"}",
"\n",
"if",
"config",
".",
"TimestampHeaderName",
"==",
"\"",
"\"",
"{",
"config",
".",
"TimestampHeaderName",
"=",
"XMailgunTimestamp",
"\n",
"}",
"\n",
"if",
"config",
".",
"SignatureHeaderName",
"==",
"\"",
"\"",
"{",
"config",
".",
"SignatureHeaderName",
"=",
"XMailgunSignature",
"\n",
"}",
"\n",
"if",
"config",
".",
"SignatureVersionHeaderName",
"==",
"\"",
"\"",
"{",
"config",
".",
"SignatureVersionHeaderName",
"=",
"XMailgunSignatureVersion",
"\n",
"}",
"\n\n",
"// setup metrics service",
"metricsClient",
":=",
"metrics",
".",
"NewNop",
"(",
")",
"\n",
"if",
"config",
".",
"EmitStats",
"{",
"// get hostname of box",
"hostname",
",",
"err",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// build lemma prefix",
"prefix",
":=",
"\"",
"\"",
"+",
"strings",
".",
"Replace",
"(",
"hostname",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"if",
"config",
".",
"StatsdPrefix",
"!=",
"\"",
"\"",
"{",
"prefix",
"+=",
"\"",
"\"",
"+",
"config",
".",
"StatsdPrefix",
"\n",
"}",
"\n\n",
"// build metrics client",
"hostport",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"config",
".",
"StatsdHost",
",",
"config",
".",
"StatsdPort",
")",
"\n",
"metricsClient",
",",
"err",
"=",
"metrics",
".",
"NewWithOptions",
"(",
"hostport",
",",
"prefix",
",",
"metrics",
".",
"Options",
"{",
"UseBuffering",
":",
"true",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Read in key from KeyPath or if not given, try getting them from KeyBytes.",
"var",
"keyBytes",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"if",
"config",
".",
"KeyPath",
"!=",
"\"",
"\"",
"{",
"if",
"keyBytes",
",",
"err",
"=",
"readKeyFromDisk",
"(",
"config",
".",
"KeyPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"config",
".",
"KeyBytes",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"keyBytes",
"=",
"config",
".",
"KeyBytes",
"\n",
"}",
"\n\n",
"// setup nonce cache",
"ncache",
",",
"err",
":=",
"NewNonceCache",
"(",
"config",
".",
"NonceCacheCapacity",
",",
"config",
".",
"NonceCacheTimeout",
",",
"timeProvider",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// return service",
"return",
"&",
"Service",
"{",
"config",
":",
"config",
",",
"nonceCache",
":",
"ncache",
",",
"secretKey",
":",
"keyBytes",
",",
"timeProvider",
":",
"timeProvider",
",",
"randomProvider",
":",
"randomProvider",
",",
"metricsClient",
":",
"metricsClient",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Returns a new Service. Provides control over time and random providers. | [
"Returns",
"a",
"new",
"Service",
".",
"Provides",
"control",
"over",
"time",
"and",
"random",
"providers",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/httpsign/auth.go#L77-L157 |
12,691 | mailgun/lemma | httpsign/auth.go | SignRequestWithKey | func (s *Service) SignRequestWithKey(r *http.Request, secretKey []byte) error {
// extract request body bytes
bodyBytes, err := readBody(r)
if err != nil {
return err
}
// extract any headers if requested
headerValues, err := extractHeaderValues(r, s.config.HeadersToSign)
if err != nil {
return err
}
// get 128-bit random number from /dev/urandom and base16 encode it
nonce, err := s.randomProvider.HexDigest(16)
if err != nil {
return fmt.Errorf("unable to get random : %v", err)
}
// get current timestamp
timestamp := strconv.FormatInt(s.timeProvider.UtcNow().Unix(), 10)
// compute the hmac and base16 encode it
computedMAC := computeMAC(secretKey, s.config.SignVerbAndURI, r.Method, r.URL.RequestURI(),
timestamp, nonce, bodyBytes, headerValues)
signature := hex.EncodeToString(computedMAC)
// set headers
r.Header.Set(s.config.NonceHeaderName, nonce)
r.Header.Set(s.config.TimestampHeaderName, timestamp)
r.Header.Set(s.config.SignatureHeaderName, signature)
r.Header.Set(s.config.SignatureVersionHeaderName, "2")
// set the body bytes we read in to nil to hint to the gc to pick it up
bodyBytes = nil
return nil
} | go | func (s *Service) SignRequestWithKey(r *http.Request, secretKey []byte) error {
// extract request body bytes
bodyBytes, err := readBody(r)
if err != nil {
return err
}
// extract any headers if requested
headerValues, err := extractHeaderValues(r, s.config.HeadersToSign)
if err != nil {
return err
}
// get 128-bit random number from /dev/urandom and base16 encode it
nonce, err := s.randomProvider.HexDigest(16)
if err != nil {
return fmt.Errorf("unable to get random : %v", err)
}
// get current timestamp
timestamp := strconv.FormatInt(s.timeProvider.UtcNow().Unix(), 10)
// compute the hmac and base16 encode it
computedMAC := computeMAC(secretKey, s.config.SignVerbAndURI, r.Method, r.URL.RequestURI(),
timestamp, nonce, bodyBytes, headerValues)
signature := hex.EncodeToString(computedMAC)
// set headers
r.Header.Set(s.config.NonceHeaderName, nonce)
r.Header.Set(s.config.TimestampHeaderName, timestamp)
r.Header.Set(s.config.SignatureHeaderName, signature)
r.Header.Set(s.config.SignatureVersionHeaderName, "2")
// set the body bytes we read in to nil to hint to the gc to pick it up
bodyBytes = nil
return nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"SignRequestWithKey",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"secretKey",
"[",
"]",
"byte",
")",
"error",
"{",
"// extract request body bytes",
"bodyBytes",
",",
"err",
":=",
"readBody",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// extract any headers if requested",
"headerValues",
",",
"err",
":=",
"extractHeaderValues",
"(",
"r",
",",
"s",
".",
"config",
".",
"HeadersToSign",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// get 128-bit random number from /dev/urandom and base16 encode it",
"nonce",
",",
"err",
":=",
"s",
".",
"randomProvider",
".",
"HexDigest",
"(",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// get current timestamp",
"timestamp",
":=",
"strconv",
".",
"FormatInt",
"(",
"s",
".",
"timeProvider",
".",
"UtcNow",
"(",
")",
".",
"Unix",
"(",
")",
",",
"10",
")",
"\n\n",
"// compute the hmac and base16 encode it",
"computedMAC",
":=",
"computeMAC",
"(",
"secretKey",
",",
"s",
".",
"config",
".",
"SignVerbAndURI",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
".",
"RequestURI",
"(",
")",
",",
"timestamp",
",",
"nonce",
",",
"bodyBytes",
",",
"headerValues",
")",
"\n",
"signature",
":=",
"hex",
".",
"EncodeToString",
"(",
"computedMAC",
")",
"\n\n",
"// set headers",
"r",
".",
"Header",
".",
"Set",
"(",
"s",
".",
"config",
".",
"NonceHeaderName",
",",
"nonce",
")",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"s",
".",
"config",
".",
"TimestampHeaderName",
",",
"timestamp",
")",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"s",
".",
"config",
".",
"SignatureHeaderName",
",",
"signature",
")",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"s",
".",
"config",
".",
"SignatureVersionHeaderName",
",",
"\"",
"\"",
")",
"\n\n",
"// set the body bytes we read in to nil to hint to the gc to pick it up",
"bodyBytes",
"=",
"nil",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Signs a given HTTP request with signature, nonce, and timestamp. Signs the
// message with the passed in key not the one initialized with. | [
"Signs",
"a",
"given",
"HTTP",
"request",
"with",
"signature",
"nonce",
"and",
"timestamp",
".",
"Signs",
"the",
"message",
"with",
"the",
"passed",
"in",
"key",
"not",
"the",
"one",
"initialized",
"with",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/httpsign/auth.go#L169-L206 |
12,692 | mailgun/lemma | secret/key.go | NewKey | func NewKey() (*[SecretKeyLength]byte, error) {
// get 32-bytes of random from /dev/urandom
bytes, err := randomProvider.Bytes(SecretKeyLength)
if err != nil {
return nil, fmt.Errorf("unable to generate random: %v", err)
}
return KeySliceToArray(bytes)
} | go | func NewKey() (*[SecretKeyLength]byte, error) {
// get 32-bytes of random from /dev/urandom
bytes, err := randomProvider.Bytes(SecretKeyLength)
if err != nil {
return nil, fmt.Errorf("unable to generate random: %v", err)
}
return KeySliceToArray(bytes)
} | [
"func",
"NewKey",
"(",
")",
"(",
"*",
"[",
"SecretKeyLength",
"]",
"byte",
",",
"error",
")",
"{",
"// get 32-bytes of random from /dev/urandom",
"bytes",
",",
"err",
":=",
"randomProvider",
".",
"Bytes",
"(",
"SecretKeyLength",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"KeySliceToArray",
"(",
"bytes",
")",
"\n",
"}"
] | // NewKey returns a new key that can be used to encrypt and decrypt messages. | [
"NewKey",
"returns",
"a",
"new",
"key",
"that",
"can",
"be",
"used",
"to",
"encrypt",
"and",
"decrypt",
"messages",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/secret/key.go#L10-L18 |
12,693 | xiam/exif | exif.go | Read | func Read(file string) (*Data, error) {
data := New()
if err := data.Open(file); err != nil {
return nil, err
}
return data, nil
} | go | func Read(file string) (*Data, error) {
data := New()
if err := data.Open(file); err != nil {
return nil, err
}
return data, nil
} | [
"func",
"Read",
"(",
"file",
"string",
")",
"(",
"*",
"Data",
",",
"error",
")",
"{",
"data",
":=",
"New",
"(",
")",
"\n",
"if",
"err",
":=",
"data",
".",
"Open",
"(",
"file",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // Read attempts to read EXIF data from a file. | [
"Read",
"attempts",
"to",
"read",
"EXIF",
"data",
"from",
"a",
"file",
"."
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L66-L72 |
12,694 | xiam/exif | exif.go | Open | func (d *Data) Open(file string) error {
cfile := C.CString(file)
defer C.free(unsafe.Pointer(cfile))
exifData := C.exif_data_new_from_file(cfile)
if exifData == nil {
return ErrNoExifData
}
defer C.exif_data_unref(exifData)
return d.parseExifData(exifData)
} | go | func (d *Data) Open(file string) error {
cfile := C.CString(file)
defer C.free(unsafe.Pointer(cfile))
exifData := C.exif_data_new_from_file(cfile)
if exifData == nil {
return ErrNoExifData
}
defer C.exif_data_unref(exifData)
return d.parseExifData(exifData)
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Open",
"(",
"file",
"string",
")",
"error",
"{",
"cfile",
":=",
"C",
".",
"CString",
"(",
"file",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cfile",
")",
")",
"\n\n",
"exifData",
":=",
"C",
".",
"exif_data_new_from_file",
"(",
"cfile",
")",
"\n\n",
"if",
"exifData",
"==",
"nil",
"{",
"return",
"ErrNoExifData",
"\n",
"}",
"\n",
"defer",
"C",
".",
"exif_data_unref",
"(",
"exifData",
")",
"\n\n",
"return",
"d",
".",
"parseExifData",
"(",
"exifData",
")",
"\n",
"}"
] | // Open opens a file path and loads its EXIF data. | [
"Open",
"opens",
"a",
"file",
"path",
"and",
"loads",
"its",
"EXIF",
"data",
"."
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L75-L88 |
12,695 | xiam/exif | exif.go | Write | func (d *Data) Write(p []byte) (n int, err error) {
if d.exifLoader == nil {
d.exifLoader = C.exif_loader_new()
runtime.SetFinalizer(d, (*Data).cleanup)
}
res := C.exif_loader_write(d.exifLoader, (*C.uchar)(unsafe.Pointer(&p[0])), C.uint(len(p)))
if res == 1 {
return len(p), nil
}
return len(p), ErrFoundExifInData
} | go | func (d *Data) Write(p []byte) (n int, err error) {
if d.exifLoader == nil {
d.exifLoader = C.exif_loader_new()
runtime.SetFinalizer(d, (*Data).cleanup)
}
res := C.exif_loader_write(d.exifLoader, (*C.uchar)(unsafe.Pointer(&p[0])), C.uint(len(p)))
if res == 1 {
return len(p), nil
}
return len(p), ErrFoundExifInData
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"d",
".",
"exifLoader",
"==",
"nil",
"{",
"d",
".",
"exifLoader",
"=",
"C",
".",
"exif_loader_new",
"(",
")",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"d",
",",
"(",
"*",
"Data",
")",
".",
"cleanup",
")",
"\n",
"}",
"\n\n",
"res",
":=",
"C",
".",
"exif_loader_write",
"(",
"d",
".",
"exifLoader",
",",
"(",
"*",
"C",
".",
"uchar",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"p",
"[",
"0",
"]",
")",
")",
",",
"C",
".",
"uint",
"(",
"len",
"(",
"p",
")",
")",
")",
"\n\n",
"if",
"res",
"==",
"1",
"{",
"return",
"len",
"(",
"p",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"len",
"(",
"p",
")",
",",
"ErrFoundExifInData",
"\n",
"}"
] | // Write writes bytes to the exif loader. Sends ErrFoundExifInData error when
// enough bytes have been sent. | [
"Write",
"writes",
"bytes",
"to",
"the",
"exif",
"loader",
".",
"Sends",
"ErrFoundExifInData",
"error",
"when",
"enough",
"bytes",
"have",
"been",
"sent",
"."
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L109-L121 |
12,696 | xiam/exif | exif.go | Parse | func (d *Data) Parse() error {
defer d.cleanup()
exifData := C.exif_loader_get_data(d.exifLoader)
if exifData == nil {
return fmt.Errorf(ErrNoExifData.Error(), "")
}
defer func() {
C.exif_data_unref(exifData)
}()
return d.parseExifData(exifData)
} | go | func (d *Data) Parse() error {
defer d.cleanup()
exifData := C.exif_loader_get_data(d.exifLoader)
if exifData == nil {
return fmt.Errorf(ErrNoExifData.Error(), "")
}
defer func() {
C.exif_data_unref(exifData)
}()
return d.parseExifData(exifData)
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Parse",
"(",
")",
"error",
"{",
"defer",
"d",
".",
"cleanup",
"(",
")",
"\n\n",
"exifData",
":=",
"C",
".",
"exif_loader_get_data",
"(",
"d",
".",
"exifLoader",
")",
"\n",
"if",
"exifData",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"ErrNoExifData",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"C",
".",
"exif_data_unref",
"(",
"exifData",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"d",
".",
"parseExifData",
"(",
"exifData",
")",
"\n",
"}"
] | // Parse finalizes the data loader and sets the tags | [
"Parse",
"finalizes",
"the",
"data",
"loader",
"and",
"sets",
"the",
"tags"
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L124-L137 |
12,697 | tomcraven/goga | bitset.go | Create | func (b *Bitset) Create(size int) {
b.size = size
b.bits = make([]int, size)
} | go | func (b *Bitset) Create(size int) {
b.size = size
b.bits = make([]int, size)
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Create",
"(",
"size",
"int",
")",
"{",
"b",
".",
"size",
"=",
"size",
"\n",
"b",
".",
"bits",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"size",
")",
"\n",
"}"
] | // Create - creates a bitset of length 'size' | [
"Create",
"-",
"creates",
"a",
"bitset",
"of",
"length",
"size"
] | 3b7915ecdd7bb6616dc3ceed450068e092ed87bc | https://github.com/tomcraven/goga/blob/3b7915ecdd7bb6616dc3ceed450068e092ed87bc/bitset.go#L10-L13 |
12,698 | tomcraven/goga | bitset.go | Get | func (b *Bitset) Get(index int) int {
if index < b.size {
return b.bits[index]
}
return -1
} | go | func (b *Bitset) Get(index int) int {
if index < b.size {
return b.bits[index]
}
return -1
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Get",
"(",
"index",
"int",
")",
"int",
"{",
"if",
"index",
"<",
"b",
".",
"size",
"{",
"return",
"b",
".",
"bits",
"[",
"index",
"]",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // Get returns the value in the bitset at index 'index'
// or -1 if the index is out of range | [
"Get",
"returns",
"the",
"value",
"in",
"the",
"bitset",
"at",
"index",
"index",
"or",
"-",
"1",
"if",
"the",
"index",
"is",
"out",
"of",
"range"
] | 3b7915ecdd7bb6616dc3ceed450068e092ed87bc | https://github.com/tomcraven/goga/blob/3b7915ecdd7bb6616dc3ceed450068e092ed87bc/bitset.go#L22-L27 |
12,699 | tomcraven/goga | bitset.go | Set | func (b *Bitset) Set(index, value int) bool {
if index < b.size {
b.setImpl(index, value)
return true
}
return false
} | go | func (b *Bitset) Set(index, value int) bool {
if index < b.size {
b.setImpl(index, value)
return true
}
return false
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Set",
"(",
"index",
",",
"value",
"int",
")",
"bool",
"{",
"if",
"index",
"<",
"b",
".",
"size",
"{",
"b",
".",
"setImpl",
"(",
"index",
",",
"value",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Set assigns value 'value' to the bit at index 'index' | [
"Set",
"assigns",
"value",
"value",
"to",
"the",
"bit",
"at",
"index",
"index"
] | 3b7915ecdd7bb6616dc3ceed450068e092ed87bc | https://github.com/tomcraven/goga/blob/3b7915ecdd7bb6616dc3ceed450068e092ed87bc/bitset.go#L39-L45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.