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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
16,200 |
coocood/qbs
|
migration.go
|
dropTableIfExists
|
func (mg *Migration) dropTableIfExists(structPtr interface{}) {
tn := tableName(structPtr)
_, err := mg.db.Exec(mg.dialect.dropTableSql(tn))
if err != nil && !mg.dialect.catchMigrationError(err) {
panic(err)
}
}
|
go
|
func (mg *Migration) dropTableIfExists(structPtr interface{}) {
tn := tableName(structPtr)
_, err := mg.db.Exec(mg.dialect.dropTableSql(tn))
if err != nil && !mg.dialect.catchMigrationError(err) {
panic(err)
}
}
|
[
"func",
"(",
"mg",
"*",
"Migration",
")",
"dropTableIfExists",
"(",
"structPtr",
"interface",
"{",
"}",
")",
"{",
"tn",
":=",
"tableName",
"(",
"structPtr",
")",
"\n",
"_",
",",
"err",
":=",
"mg",
".",
"db",
".",
"Exec",
"(",
"mg",
".",
"dialect",
".",
"dropTableSql",
"(",
"tn",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"mg",
".",
"dialect",
".",
"catchMigrationError",
"(",
"err",
")",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// this is only used for testing.
|
[
"this",
"is",
"only",
"used",
"for",
"testing",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/migration.go#L57-L63
|
16,201 |
coocood/qbs
|
migration.go
|
DropTable
|
func (mg *Migration) DropTable(strutPtr interface{}) {
if !strings.HasSuffix(mg.dbName, "test") {
panic("Drop table can only be executed on database which name has 'test' suffix")
}
mg.dropTableIfExists(strutPtr)
}
|
go
|
func (mg *Migration) DropTable(strutPtr interface{}) {
if !strings.HasSuffix(mg.dbName, "test") {
panic("Drop table can only be executed on database which name has 'test' suffix")
}
mg.dropTableIfExists(strutPtr)
}
|
[
"func",
"(",
"mg",
"*",
"Migration",
")",
"DropTable",
"(",
"strutPtr",
"interface",
"{",
"}",
")",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"mg",
".",
"dbName",
",",
"\"",
"\"",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"mg",
".",
"dropTableIfExists",
"(",
"strutPtr",
")",
"\n",
"}"
] |
//Can only drop table on database which name has "test" suffix.
//Used for testing
|
[
"Can",
"only",
"drop",
"table",
"on",
"database",
"which",
"name",
"has",
"test",
"suffix",
".",
"Used",
"for",
"testing"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/migration.go#L67-L72
|
16,202 |
coocood/qbs
|
migration.go
|
CreateIndexIfNotExists
|
func (mg *Migration) CreateIndexIfNotExists(table interface{}, name string, unique bool, columns ...string) error {
tn := tableName(table)
name = tn + "_" + name
if !mg.dialect.indexExists(mg, tn, name) {
sql := mg.dialect.createIndexSql(name, tn, unique, columns...)
if mg.Log {
fmt.Println(sql)
}
_, err := mg.db.Exec(sql)
return err
}
return nil
}
|
go
|
func (mg *Migration) CreateIndexIfNotExists(table interface{}, name string, unique bool, columns ...string) error {
tn := tableName(table)
name = tn + "_" + name
if !mg.dialect.indexExists(mg, tn, name) {
sql := mg.dialect.createIndexSql(name, tn, unique, columns...)
if mg.Log {
fmt.Println(sql)
}
_, err := mg.db.Exec(sql)
return err
}
return nil
}
|
[
"func",
"(",
"mg",
"*",
"Migration",
")",
"CreateIndexIfNotExists",
"(",
"table",
"interface",
"{",
"}",
",",
"name",
"string",
",",
"unique",
"bool",
",",
"columns",
"...",
"string",
")",
"error",
"{",
"tn",
":=",
"tableName",
"(",
"table",
")",
"\n",
"name",
"=",
"tn",
"+",
"\"",
"\"",
"+",
"name",
"\n",
"if",
"!",
"mg",
".",
"dialect",
".",
"indexExists",
"(",
"mg",
",",
"tn",
",",
"name",
")",
"{",
"sql",
":=",
"mg",
".",
"dialect",
".",
"createIndexSql",
"(",
"name",
",",
"tn",
",",
"unique",
",",
"columns",
"...",
")",
"\n",
"if",
"mg",
".",
"Log",
"{",
"fmt",
".",
"Println",
"(",
"sql",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"mg",
".",
"db",
".",
"Exec",
"(",
"sql",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CreateIndex creates the specified index on table.
// Some databases like mysql do not support this feature directly,
// So dialect may need to query the database schema table to find out if an index exists.
// Normally you don't need to do it explicitly, it will be created automatically in CreateTableIfNotExists method.
|
[
"CreateIndex",
"creates",
"the",
"specified",
"index",
"on",
"table",
".",
"Some",
"databases",
"like",
"mysql",
"do",
"not",
"support",
"this",
"feature",
"directly",
"So",
"dialect",
"may",
"need",
"to",
"query",
"the",
"database",
"schema",
"table",
"to",
"find",
"out",
"if",
"an",
"index",
"exists",
".",
"Normally",
"you",
"don",
"t",
"need",
"to",
"do",
"it",
"explicitly",
"it",
"will",
"be",
"created",
"automatically",
"in",
"CreateTableIfNotExists",
"method",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/migration.go#L89-L101
|
16,203 |
coocood/qbs
|
migration.go
|
GetMigration
|
func GetMigration() (mg *Migration, err error) {
if driver == "" || dial == nil {
panic("database driver has not been registered, should call Register first.")
}
db, err := sql.Open(driver, driverSource)
if err != nil {
return nil, err
}
return &Migration{db, dbName, dial, false}, nil
}
|
go
|
func GetMigration() (mg *Migration, err error) {
if driver == "" || dial == nil {
panic("database driver has not been registered, should call Register first.")
}
db, err := sql.Open(driver, driverSource)
if err != nil {
return nil, err
}
return &Migration{db, dbName, dial, false}, nil
}
|
[
"func",
"GetMigration",
"(",
")",
"(",
"mg",
"*",
"Migration",
",",
"err",
"error",
")",
"{",
"if",
"driver",
"==",
"\"",
"\"",
"||",
"dial",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"db",
",",
"err",
":=",
"sql",
".",
"Open",
"(",
"driver",
",",
"driverSource",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"Migration",
"{",
"db",
",",
"dbName",
",",
"dial",
",",
"false",
"}",
",",
"nil",
"\n",
"}"
] |
// Get a Migration instance should get closed like Qbs instance.
|
[
"Get",
"a",
"Migration",
"instance",
"should",
"get",
"closed",
"like",
"Qbs",
"instance",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/migration.go#L113-L122
|
16,204 |
coocood/qbs
|
migration.go
|
WithMigration
|
func WithMigration(task func(mg *Migration) error) error {
mg, err := GetMigration()
if err != nil {
return err
}
defer mg.Close()
return task(mg)
}
|
go
|
func WithMigration(task func(mg *Migration) error) error {
mg, err := GetMigration()
if err != nil {
return err
}
defer mg.Close()
return task(mg)
}
|
[
"func",
"WithMigration",
"(",
"task",
"func",
"(",
"mg",
"*",
"Migration",
")",
"error",
")",
"error",
"{",
"mg",
",",
"err",
":=",
"GetMigration",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"mg",
".",
"Close",
"(",
")",
"\n",
"return",
"task",
"(",
"mg",
")",
"\n",
"}"
] |
// A safe and easy way to work with Migration instance without the need to open and close it.
|
[
"A",
"safe",
"and",
"easy",
"way",
"to",
"work",
"with",
"Migration",
"instance",
"without",
"the",
"need",
"to",
"open",
"and",
"close",
"it",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/migration.go#L125-L132
|
16,205 |
coocood/qbs
|
qbs.go
|
Register
|
func Register(driverName, driverSourceName, databaseName string, dialect Dialect) {
driverSource = driverSourceName
dbName = databaseName
if db == nil {
var err error
var database *sql.DB
database, err = sql.Open(driverName, driverSource)
if err != nil {
panic(err)
}
RegisterWithDb(driverName, database, dialect)
}
}
|
go
|
func Register(driverName, driverSourceName, databaseName string, dialect Dialect) {
driverSource = driverSourceName
dbName = databaseName
if db == nil {
var err error
var database *sql.DB
database, err = sql.Open(driverName, driverSource)
if err != nil {
panic(err)
}
RegisterWithDb(driverName, database, dialect)
}
}
|
[
"func",
"Register",
"(",
"driverName",
",",
"driverSourceName",
",",
"databaseName",
"string",
",",
"dialect",
"Dialect",
")",
"{",
"driverSource",
"=",
"driverSourceName",
"\n",
"dbName",
"=",
"databaseName",
"\n",
"if",
"db",
"==",
"nil",
"{",
"var",
"err",
"error",
"\n",
"var",
"database",
"*",
"sql",
".",
"DB",
"\n",
"database",
",",
"err",
"=",
"sql",
".",
"Open",
"(",
"driverName",
",",
"driverSource",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"RegisterWithDb",
"(",
"driverName",
",",
"database",
",",
"dialect",
")",
"\n",
"}",
"\n",
"}"
] |
//Register a database, should be call at the beginning of the application.
|
[
"Register",
"a",
"database",
"should",
"be",
"call",
"at",
"the",
"beginning",
"of",
"the",
"application",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L40-L52
|
16,206 |
coocood/qbs
|
qbs.go
|
SetConnectionLimit
|
func SetConnectionLimit(maxCon int, blocking bool) {
if maxCon > 0 {
connectionLimit = make(chan struct{}, maxCon)
} else if maxCon < 0 {
connectionLimit = nil
}
blockingOnLimit = blocking
}
|
go
|
func SetConnectionLimit(maxCon int, blocking bool) {
if maxCon > 0 {
connectionLimit = make(chan struct{}, maxCon)
} else if maxCon < 0 {
connectionLimit = nil
}
blockingOnLimit = blocking
}
|
[
"func",
"SetConnectionLimit",
"(",
"maxCon",
"int",
",",
"blocking",
"bool",
")",
"{",
"if",
"maxCon",
">",
"0",
"{",
"connectionLimit",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"maxCon",
")",
"\n",
"}",
"else",
"if",
"maxCon",
"<",
"0",
"{",
"connectionLimit",
"=",
"nil",
"\n",
"}",
"\n",
"blockingOnLimit",
"=",
"blocking",
"\n",
"}"
] |
//Set the connection limit, there is no limit by default.
//If blocking is true, GetQbs method will be blocked, otherwise returns ConnectionLimitError.
|
[
"Set",
"the",
"connection",
"limit",
"there",
"is",
"no",
"limit",
"by",
"default",
".",
"If",
"blocking",
"is",
"true",
"GetQbs",
"method",
"will",
"be",
"blocked",
"otherwise",
"returns",
"ConnectionLimitError",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L116-L123
|
16,207 |
coocood/qbs
|
qbs.go
|
Begin
|
func (q *Qbs) Begin() error {
if q.tx != nil {
panic("cannot start nested transaction")
}
tx, err := db.Begin()
q.tx = tx
q.txStmtMap = make(map[string]*sql.Stmt)
return err
}
|
go
|
func (q *Qbs) Begin() error {
if q.tx != nil {
panic("cannot start nested transaction")
}
tx, err := db.Begin()
q.tx = tx
q.txStmtMap = make(map[string]*sql.Stmt)
return err
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Begin",
"(",
")",
"error",
"{",
"if",
"q",
".",
"tx",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tx",
",",
"err",
":=",
"db",
".",
"Begin",
"(",
")",
"\n",
"q",
".",
"tx",
"=",
"tx",
"\n",
"q",
".",
"txStmtMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"sql",
".",
"Stmt",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Begin create a transaction object internally
// You can perform queries with the same Qbs object
// no matter it is in transaction or not.
// It panics if it's already in a transaction.
|
[
"Begin",
"create",
"a",
"transaction",
"object",
"internally",
"You",
"can",
"perform",
"queries",
"with",
"the",
"same",
"Qbs",
"object",
"no",
"matter",
"it",
"is",
"in",
"transaction",
"or",
"not",
".",
"It",
"panics",
"if",
"it",
"s",
"already",
"in",
"a",
"transaction",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L134-L142
|
16,208 |
coocood/qbs
|
qbs.go
|
Commit
|
func (q *Qbs) Commit() error {
err := q.tx.Commit()
q.updateTxError(err)
q.tx = nil
for _, v := range q.txStmtMap {
v.Close()
}
q.txStmtMap = nil
return q.firstTxError
}
|
go
|
func (q *Qbs) Commit() error {
err := q.tx.Commit()
q.updateTxError(err)
q.tx = nil
for _, v := range q.txStmtMap {
v.Close()
}
q.txStmtMap = nil
return q.firstTxError
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Commit",
"(",
")",
"error",
"{",
"err",
":=",
"q",
".",
"tx",
".",
"Commit",
"(",
")",
"\n",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"q",
".",
"tx",
"=",
"nil",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"q",
".",
"txStmtMap",
"{",
"v",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"q",
".",
"txStmtMap",
"=",
"nil",
"\n",
"return",
"q",
".",
"firstTxError",
"\n",
"}"
] |
// Commit commits a started transaction and will report the first error that
// occurred inside the transaction.
|
[
"Commit",
"commits",
"a",
"started",
"transaction",
"and",
"will",
"report",
"the",
"first",
"error",
"that",
"occurred",
"inside",
"the",
"transaction",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L163-L172
|
16,209 |
coocood/qbs
|
qbs.go
|
Rollback
|
func (q *Qbs) Rollback() error {
err := q.tx.Rollback()
q.tx = nil
for _, v := range q.txStmtMap {
v.Close()
}
q.txStmtMap = nil
return q.updateTxError(err)
}
|
go
|
func (q *Qbs) Rollback() error {
err := q.tx.Rollback()
q.tx = nil
for _, v := range q.txStmtMap {
v.Close()
}
q.txStmtMap = nil
return q.updateTxError(err)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Rollback",
"(",
")",
"error",
"{",
"err",
":=",
"q",
".",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"q",
".",
"tx",
"=",
"nil",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"q",
".",
"txStmtMap",
"{",
"v",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"q",
".",
"txStmtMap",
"=",
"nil",
"\n",
"return",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}"
] |
// Rollback rolls back a started transaction.
|
[
"Rollback",
"rolls",
"back",
"a",
"started",
"transaction",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L175-L183
|
16,210 |
coocood/qbs
|
qbs.go
|
Condition
|
func (q *Qbs) Condition(condition *Condition) *Qbs {
q.criteria.condition = condition
return q
}
|
go
|
func (q *Qbs) Condition(condition *Condition) *Qbs {
q.criteria.condition = condition
return q
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Condition",
"(",
"condition",
"*",
"Condition",
")",
"*",
"Qbs",
"{",
"q",
".",
"criteria",
".",
"condition",
"=",
"condition",
"\n",
"return",
"q",
"\n",
"}"
] |
//Condition defines the SQL "WHERE" clause
//If other condition can be inferred by the struct argument in
//Find method, it will be merged with AND
|
[
"Condition",
"defines",
"the",
"SQL",
"WHERE",
"clause",
"If",
"other",
"condition",
"can",
"be",
"inferred",
"by",
"the",
"struct",
"argument",
"in",
"Find",
"method",
"it",
"will",
"be",
"merged",
"with",
"AND"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L205-L208
|
16,211 |
coocood/qbs
|
qbs.go
|
OmitFields
|
func (q *Qbs) OmitFields(fieldName ...string) *Qbs {
q.criteria.omitFields = fieldName
return q
}
|
go
|
func (q *Qbs) OmitFields(fieldName ...string) *Qbs {
q.criteria.omitFields = fieldName
return q
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"OmitFields",
"(",
"fieldName",
"...",
"string",
")",
"*",
"Qbs",
"{",
"q",
".",
"criteria",
".",
"omitFields",
"=",
"fieldName",
"\n",
"return",
"q",
"\n",
"}"
] |
// Camel case field names
|
[
"Camel",
"case",
"field",
"names"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L231-L234
|
16,212 |
coocood/qbs
|
qbs.go
|
Find
|
func (q *Qbs) Find(structPtr interface{}) error {
q.criteria.model = structPtrToModel(structPtr, !q.criteria.omitJoin, q.criteria.omitFields)
q.criteria.limit = 1
if !q.criteria.model.pkZero() {
idPath := q.Dialect.quote(q.criteria.model.table) + "." + q.Dialect.quote(q.criteria.model.pk.name)
idCondition := NewCondition(idPath+" = ?", q.criteria.model.pk.value)
if q.criteria.condition == nil {
q.criteria.condition = idCondition
} else {
q.criteria.condition = idCondition.AndCondition(q.criteria.condition)
}
}
query, args := q.Dialect.querySql(q.criteria)
return q.doQueryRow(structPtr, query, args...)
}
|
go
|
func (q *Qbs) Find(structPtr interface{}) error {
q.criteria.model = structPtrToModel(structPtr, !q.criteria.omitJoin, q.criteria.omitFields)
q.criteria.limit = 1
if !q.criteria.model.pkZero() {
idPath := q.Dialect.quote(q.criteria.model.table) + "." + q.Dialect.quote(q.criteria.model.pk.name)
idCondition := NewCondition(idPath+" = ?", q.criteria.model.pk.value)
if q.criteria.condition == nil {
q.criteria.condition = idCondition
} else {
q.criteria.condition = idCondition.AndCondition(q.criteria.condition)
}
}
query, args := q.Dialect.querySql(q.criteria)
return q.doQueryRow(structPtr, query, args...)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Find",
"(",
"structPtr",
"interface",
"{",
"}",
")",
"error",
"{",
"q",
".",
"criteria",
".",
"model",
"=",
"structPtrToModel",
"(",
"structPtr",
",",
"!",
"q",
".",
"criteria",
".",
"omitJoin",
",",
"q",
".",
"criteria",
".",
"omitFields",
")",
"\n",
"q",
".",
"criteria",
".",
"limit",
"=",
"1",
"\n",
"if",
"!",
"q",
".",
"criteria",
".",
"model",
".",
"pkZero",
"(",
")",
"{",
"idPath",
":=",
"q",
".",
"Dialect",
".",
"quote",
"(",
"q",
".",
"criteria",
".",
"model",
".",
"table",
")",
"+",
"\"",
"\"",
"+",
"q",
".",
"Dialect",
".",
"quote",
"(",
"q",
".",
"criteria",
".",
"model",
".",
"pk",
".",
"name",
")",
"\n",
"idCondition",
":=",
"NewCondition",
"(",
"idPath",
"+",
"\"",
"\"",
",",
"q",
".",
"criteria",
".",
"model",
".",
"pk",
".",
"value",
")",
"\n",
"if",
"q",
".",
"criteria",
".",
"condition",
"==",
"nil",
"{",
"q",
".",
"criteria",
".",
"condition",
"=",
"idCondition",
"\n",
"}",
"else",
"{",
"q",
".",
"criteria",
".",
"condition",
"=",
"idCondition",
".",
"AndCondition",
"(",
"q",
".",
"criteria",
".",
"condition",
")",
"\n",
"}",
"\n",
"}",
"\n",
"query",
",",
"args",
":=",
"q",
".",
"Dialect",
".",
"querySql",
"(",
"q",
".",
"criteria",
")",
"\n",
"return",
"q",
".",
"doQueryRow",
"(",
"structPtr",
",",
"query",
",",
"args",
"...",
")",
"\n",
"}"
] |
// Perform select query by parsing the struct's type and then fill the values into the struct
// All fields of supported types in the struct will be added in select clause.
// If Id value is provided, it will be added into the where clause
// If a foreign key field with its referenced struct pointer field are provided,
// It will perform a join query, the referenced struct pointer field will be filled in
// the values obtained by the query.
// If not found, "sql.ErrNoRows" will be returned.
|
[
"Perform",
"select",
"query",
"by",
"parsing",
"the",
"struct",
"s",
"type",
"and",
"then",
"fill",
"the",
"values",
"into",
"the",
"struct",
"All",
"fields",
"of",
"supported",
"types",
"in",
"the",
"struct",
"will",
"be",
"added",
"in",
"select",
"clause",
".",
"If",
"Id",
"value",
"is",
"provided",
"it",
"will",
"be",
"added",
"into",
"the",
"where",
"clause",
"If",
"a",
"foreign",
"key",
"field",
"with",
"its",
"referenced",
"struct",
"pointer",
"field",
"are",
"provided",
"It",
"will",
"perform",
"a",
"join",
"query",
"the",
"referenced",
"struct",
"pointer",
"field",
"will",
"be",
"filled",
"in",
"the",
"values",
"obtained",
"by",
"the",
"query",
".",
"If",
"not",
"found",
"sql",
".",
"ErrNoRows",
"will",
"be",
"returned",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L248-L262
|
16,213 |
coocood/qbs
|
qbs.go
|
FindAll
|
func (q *Qbs) FindAll(ptrOfSliceOfStructPtr interface{}) error {
strucType := reflect.TypeOf(ptrOfSliceOfStructPtr).Elem().Elem().Elem()
strucPtr := reflect.New(strucType).Interface()
q.criteria.model = structPtrToModel(strucPtr, !q.criteria.omitJoin, q.criteria.omitFields)
query, args := q.Dialect.querySql(q.criteria)
return q.doQueryRows(ptrOfSliceOfStructPtr, query, args...)
}
|
go
|
func (q *Qbs) FindAll(ptrOfSliceOfStructPtr interface{}) error {
strucType := reflect.TypeOf(ptrOfSliceOfStructPtr).Elem().Elem().Elem()
strucPtr := reflect.New(strucType).Interface()
q.criteria.model = structPtrToModel(strucPtr, !q.criteria.omitJoin, q.criteria.omitFields)
query, args := q.Dialect.querySql(q.criteria)
return q.doQueryRows(ptrOfSliceOfStructPtr, query, args...)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"FindAll",
"(",
"ptrOfSliceOfStructPtr",
"interface",
"{",
"}",
")",
"error",
"{",
"strucType",
":=",
"reflect",
".",
"TypeOf",
"(",
"ptrOfSliceOfStructPtr",
")",
".",
"Elem",
"(",
")",
".",
"Elem",
"(",
")",
".",
"Elem",
"(",
")",
"\n",
"strucPtr",
":=",
"reflect",
".",
"New",
"(",
"strucType",
")",
".",
"Interface",
"(",
")",
"\n",
"q",
".",
"criteria",
".",
"model",
"=",
"structPtrToModel",
"(",
"strucPtr",
",",
"!",
"q",
".",
"criteria",
".",
"omitJoin",
",",
"q",
".",
"criteria",
".",
"omitFields",
")",
"\n",
"query",
",",
"args",
":=",
"q",
".",
"Dialect",
".",
"querySql",
"(",
"q",
".",
"criteria",
")",
"\n",
"return",
"q",
".",
"doQueryRows",
"(",
"ptrOfSliceOfStructPtr",
",",
"query",
",",
"args",
"...",
")",
"\n",
"}"
] |
// Similar to Find, except that FindAll accept pointer of slice of struct pointer,
// rows will be appended to the slice.
|
[
"Similar",
"to",
"Find",
"except",
"that",
"FindAll",
"accept",
"pointer",
"of",
"slice",
"of",
"struct",
"pointer",
"rows",
"will",
"be",
"appended",
"to",
"the",
"slice",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L266-L272
|
16,214 |
coocood/qbs
|
qbs.go
|
Exec
|
func (q *Qbs) Exec(query string, args ...interface{}) (sql.Result, error) {
defer q.Reset()
query = q.Dialect.substituteMarkers(query)
q.log(query, args...)
stmt, err := q.prepare(query)
if err != nil {
return nil, q.updateTxError(err)
}
result, err := stmt.Exec(args...)
if err != nil {
return nil, q.updateTxError(err)
}
return result, nil
}
|
go
|
func (q *Qbs) Exec(query string, args ...interface{}) (sql.Result, error) {
defer q.Reset()
query = q.Dialect.substituteMarkers(query)
q.log(query, args...)
stmt, err := q.prepare(query)
if err != nil {
return nil, q.updateTxError(err)
}
result, err := stmt.Exec(args...)
if err != nil {
return nil, q.updateTxError(err)
}
return result, nil
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Exec",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"sql",
".",
"Result",
",",
"error",
")",
"{",
"defer",
"q",
".",
"Reset",
"(",
")",
"\n",
"query",
"=",
"q",
".",
"Dialect",
".",
"substituteMarkers",
"(",
"query",
")",
"\n",
"q",
".",
"log",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"stmt",
",",
"err",
":=",
"q",
".",
"prepare",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// Same as sql.Db.Exec or sql.Tx.Exec depends on if transaction has began
|
[
"Same",
"as",
"sql",
".",
"Db",
".",
"Exec",
"or",
"sql",
".",
"Tx",
".",
"Exec",
"depends",
"on",
"if",
"transaction",
"has",
"began"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L367-L380
|
16,215 |
coocood/qbs
|
qbs.go
|
QueryRow
|
func (q *Qbs) QueryRow(query string, args ...interface{}) *sql.Row {
q.log(query, args...)
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
q.updateTxError(err)
return nil
}
return stmt.QueryRow(args...)
}
|
go
|
func (q *Qbs) QueryRow(query string, args ...interface{}) *sql.Row {
q.log(query, args...)
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
q.updateTxError(err)
return nil
}
return stmt.QueryRow(args...)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"QueryRow",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"*",
"sql",
".",
"Row",
"{",
"q",
".",
"log",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"query",
"=",
"q",
".",
"Dialect",
".",
"substituteMarkers",
"(",
"query",
")",
"\n",
"stmt",
",",
"err",
":=",
"q",
".",
"prepare",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"stmt",
".",
"QueryRow",
"(",
"args",
"...",
")",
"\n",
"}"
] |
// Same as sql.Db.QueryRow or sql.Tx.QueryRow depends on if transaction has began
|
[
"Same",
"as",
"sql",
".",
"Db",
".",
"QueryRow",
"or",
"sql",
".",
"Tx",
".",
"QueryRow",
"depends",
"on",
"if",
"transaction",
"has",
"began"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L383-L392
|
16,216 |
coocood/qbs
|
qbs.go
|
Query
|
func (q *Qbs) Query(query string, args ...interface{}) (rows *sql.Rows, err error) {
q.log(query, args...)
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
q.updateTxError(err)
return
}
return stmt.Query(args...)
}
|
go
|
func (q *Qbs) Query(query string, args ...interface{}) (rows *sql.Rows, err error) {
q.log(query, args...)
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
q.updateTxError(err)
return
}
return stmt.Query(args...)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Query",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"rows",
"*",
"sql",
".",
"Rows",
",",
"err",
"error",
")",
"{",
"q",
".",
"log",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"query",
"=",
"q",
".",
"Dialect",
".",
"substituteMarkers",
"(",
"query",
")",
"\n",
"stmt",
",",
"err",
":=",
"q",
".",
"prepare",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"return",
"stmt",
".",
"Query",
"(",
"args",
"...",
")",
"\n",
"}"
] |
// Same as sql.Db.Query or sql.Tx.Query depends on if transaction has began
|
[
"Same",
"as",
"sql",
".",
"Db",
".",
"Query",
"or",
"sql",
".",
"Tx",
".",
"Query",
"depends",
"on",
"if",
"transaction",
"has",
"began"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L395-L404
|
16,217 |
coocood/qbs
|
qbs.go
|
prepare
|
func (q *Qbs) prepare(query string) (stmt *sql.Stmt, err error) {
var ok bool
if q.tx != nil {
stmt, ok = q.txStmtMap[query]
if ok {
return
}
stmt, err = q.tx.Prepare(query)
if err != nil {
q.updateTxError(err)
return
}
q.txStmtMap[query] = stmt
} else {
mu.RLock()
stmt, ok = stmtMap[query]
mu.RUnlock()
if ok {
return
}
stmt, err = db.Prepare(query + ";")
if err != nil {
q.updateTxError(err)
return
}
mu.Lock()
stmtMap[query] = stmt
mu.Unlock()
}
return
}
|
go
|
func (q *Qbs) prepare(query string) (stmt *sql.Stmt, err error) {
var ok bool
if q.tx != nil {
stmt, ok = q.txStmtMap[query]
if ok {
return
}
stmt, err = q.tx.Prepare(query)
if err != nil {
q.updateTxError(err)
return
}
q.txStmtMap[query] = stmt
} else {
mu.RLock()
stmt, ok = stmtMap[query]
mu.RUnlock()
if ok {
return
}
stmt, err = db.Prepare(query + ";")
if err != nil {
q.updateTxError(err)
return
}
mu.Lock()
stmtMap[query] = stmt
mu.Unlock()
}
return
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"prepare",
"(",
"query",
"string",
")",
"(",
"stmt",
"*",
"sql",
".",
"Stmt",
",",
"err",
"error",
")",
"{",
"var",
"ok",
"bool",
"\n",
"if",
"q",
".",
"tx",
"!=",
"nil",
"{",
"stmt",
",",
"ok",
"=",
"q",
".",
"txStmtMap",
"[",
"query",
"]",
"\n",
"if",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"stmt",
",",
"err",
"=",
"q",
".",
"tx",
".",
"Prepare",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
".",
"txStmtMap",
"[",
"query",
"]",
"=",
"stmt",
"\n",
"}",
"else",
"{",
"mu",
".",
"RLock",
"(",
")",
"\n",
"stmt",
",",
"ok",
"=",
"stmtMap",
"[",
"query",
"]",
"\n",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"\n",
"}",
"\n\n",
"stmt",
",",
"err",
"=",
"db",
".",
"Prepare",
"(",
"query",
"+",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"mu",
".",
"Lock",
"(",
")",
"\n",
"stmtMap",
"[",
"query",
"]",
"=",
"stmt",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Same as sql.Db.Prepare or sql.Tx.Prepare depends on if transaction has began
|
[
"Same",
"as",
"sql",
".",
"Db",
".",
"Prepare",
"or",
"sql",
".",
"Tx",
".",
"Prepare",
"depends",
"on",
"if",
"transaction",
"has",
"began"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L407-L438
|
16,218 |
coocood/qbs
|
qbs.go
|
Save
|
func (q *Qbs) Save(structPtr interface{}) (affected int64, err error) {
if v, ok := structPtr.(Validator); ok {
err = v.Validate(q)
if err != nil {
return
}
}
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
if model.pk == nil {
panic("no primary key field")
}
q.criteria.model = model
now := time.Now()
var id int64 = 0
updateModelField := model.timeField("updated")
if updateModelField != nil {
updateModelField.value = now
}
createdModelField := model.timeField("created")
var isInsert bool
if !model.pkZero() && q.WhereEqual(model.pk.name, model.pk.value).Count(model.table) > 0 { //id is given, can be an update operation.
affected, err = q.Dialect.update(q)
} else {
if createdModelField != nil {
createdModelField.value = now
}
id, err = q.Dialect.insert(q)
isInsert = true
if err == nil {
affected = 1
}
}
if err == nil {
structValue := reflect.Indirect(reflect.ValueOf(structPtr))
if _, ok := model.pk.value.(int64); ok && id != 0 {
idField := structValue.FieldByName(model.pk.camelName)
idField.SetInt(id)
}
if updateModelField != nil {
updateField := structValue.FieldByName(updateModelField.camelName)
updateField.Set(reflect.ValueOf(now))
}
if isInsert {
if createdModelField != nil {
createdField := structValue.FieldByName(createdModelField.camelName)
createdField.Set(reflect.ValueOf(now))
}
}
}
return affected, q.updateTxError(err)
}
|
go
|
func (q *Qbs) Save(structPtr interface{}) (affected int64, err error) {
if v, ok := structPtr.(Validator); ok {
err = v.Validate(q)
if err != nil {
return
}
}
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
if model.pk == nil {
panic("no primary key field")
}
q.criteria.model = model
now := time.Now()
var id int64 = 0
updateModelField := model.timeField("updated")
if updateModelField != nil {
updateModelField.value = now
}
createdModelField := model.timeField("created")
var isInsert bool
if !model.pkZero() && q.WhereEqual(model.pk.name, model.pk.value).Count(model.table) > 0 { //id is given, can be an update operation.
affected, err = q.Dialect.update(q)
} else {
if createdModelField != nil {
createdModelField.value = now
}
id, err = q.Dialect.insert(q)
isInsert = true
if err == nil {
affected = 1
}
}
if err == nil {
structValue := reflect.Indirect(reflect.ValueOf(structPtr))
if _, ok := model.pk.value.(int64); ok && id != 0 {
idField := structValue.FieldByName(model.pk.camelName)
idField.SetInt(id)
}
if updateModelField != nil {
updateField := structValue.FieldByName(updateModelField.camelName)
updateField.Set(reflect.ValueOf(now))
}
if isInsert {
if createdModelField != nil {
createdField := structValue.FieldByName(createdModelField.camelName)
createdField.Set(reflect.ValueOf(now))
}
}
}
return affected, q.updateTxError(err)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Save",
"(",
"structPtr",
"interface",
"{",
"}",
")",
"(",
"affected",
"int64",
",",
"err",
"error",
")",
"{",
"if",
"v",
",",
"ok",
":=",
"structPtr",
".",
"(",
"Validator",
")",
";",
"ok",
"{",
"err",
"=",
"v",
".",
"Validate",
"(",
"q",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"model",
":=",
"structPtrToModel",
"(",
"structPtr",
",",
"true",
",",
"q",
".",
"criteria",
".",
"omitFields",
")",
"\n",
"if",
"model",
".",
"pk",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"q",
".",
"criteria",
".",
"model",
"=",
"model",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"var",
"id",
"int64",
"=",
"0",
"\n",
"updateModelField",
":=",
"model",
".",
"timeField",
"(",
"\"",
"\"",
")",
"\n",
"if",
"updateModelField",
"!=",
"nil",
"{",
"updateModelField",
".",
"value",
"=",
"now",
"\n",
"}",
"\n",
"createdModelField",
":=",
"model",
".",
"timeField",
"(",
"\"",
"\"",
")",
"\n",
"var",
"isInsert",
"bool",
"\n",
"if",
"!",
"model",
".",
"pkZero",
"(",
")",
"&&",
"q",
".",
"WhereEqual",
"(",
"model",
".",
"pk",
".",
"name",
",",
"model",
".",
"pk",
".",
"value",
")",
".",
"Count",
"(",
"model",
".",
"table",
")",
">",
"0",
"{",
"//id is given, can be an update operation.",
"affected",
",",
"err",
"=",
"q",
".",
"Dialect",
".",
"update",
"(",
"q",
")",
"\n",
"}",
"else",
"{",
"if",
"createdModelField",
"!=",
"nil",
"{",
"createdModelField",
".",
"value",
"=",
"now",
"\n",
"}",
"\n",
"id",
",",
"err",
"=",
"q",
".",
"Dialect",
".",
"insert",
"(",
"q",
")",
"\n",
"isInsert",
"=",
"true",
"\n",
"if",
"err",
"==",
"nil",
"{",
"affected",
"=",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"structValue",
":=",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"structPtr",
")",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"model",
".",
"pk",
".",
"value",
".",
"(",
"int64",
")",
";",
"ok",
"&&",
"id",
"!=",
"0",
"{",
"idField",
":=",
"structValue",
".",
"FieldByName",
"(",
"model",
".",
"pk",
".",
"camelName",
")",
"\n",
"idField",
".",
"SetInt",
"(",
"id",
")",
"\n",
"}",
"\n",
"if",
"updateModelField",
"!=",
"nil",
"{",
"updateField",
":=",
"structValue",
".",
"FieldByName",
"(",
"updateModelField",
".",
"camelName",
")",
"\n",
"updateField",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"now",
")",
")",
"\n",
"}",
"\n",
"if",
"isInsert",
"{",
"if",
"createdModelField",
"!=",
"nil",
"{",
"createdField",
":=",
"structValue",
".",
"FieldByName",
"(",
"createdModelField",
".",
"camelName",
")",
"\n",
"createdField",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"now",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"affected",
",",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}"
] |
// If Id value is not provided, save will insert the record, and the Id value will
// be filled in the struct after insertion.
// If Id value is provided, save will do a query count first to see if the row exists, if not then insert it,
// otherwise update it.
// If struct implements Validator interface, it will be validated first
|
[
"If",
"Id",
"value",
"is",
"not",
"provided",
"save",
"will",
"insert",
"the",
"record",
"and",
"the",
"Id",
"value",
"will",
"be",
"filled",
"in",
"the",
"struct",
"after",
"insertion",
".",
"If",
"Id",
"value",
"is",
"provided",
"save",
"will",
"do",
"a",
"query",
"count",
"first",
"to",
"see",
"if",
"the",
"row",
"exists",
"if",
"not",
"then",
"insert",
"it",
"otherwise",
"update",
"it",
".",
"If",
"struct",
"implements",
"Validator",
"interface",
"it",
"will",
"be",
"validated",
"first"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L445-L495
|
16,219 |
coocood/qbs
|
qbs.go
|
Update
|
func (q *Qbs) Update(structPtr interface{}) (affected int64, err error) {
if v, ok := structPtr.(Validator); ok {
err := v.Validate(q)
if err != nil {
return 0, err
}
}
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
q.criteria.model = model
q.criteria.mergePkCondition(q.Dialect)
if q.criteria.condition == nil {
panic("Can not update without condition")
}
return q.Dialect.update(q)
}
|
go
|
func (q *Qbs) Update(structPtr interface{}) (affected int64, err error) {
if v, ok := structPtr.(Validator); ok {
err := v.Validate(q)
if err != nil {
return 0, err
}
}
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
q.criteria.model = model
q.criteria.mergePkCondition(q.Dialect)
if q.criteria.condition == nil {
panic("Can not update without condition")
}
return q.Dialect.update(q)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Update",
"(",
"structPtr",
"interface",
"{",
"}",
")",
"(",
"affected",
"int64",
",",
"err",
"error",
")",
"{",
"if",
"v",
",",
"ok",
":=",
"structPtr",
".",
"(",
"Validator",
")",
";",
"ok",
"{",
"err",
":=",
"v",
".",
"Validate",
"(",
"q",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"model",
":=",
"structPtrToModel",
"(",
"structPtr",
",",
"true",
",",
"q",
".",
"criteria",
".",
"omitFields",
")",
"\n",
"q",
".",
"criteria",
".",
"model",
"=",
"model",
"\n",
"q",
".",
"criteria",
".",
"mergePkCondition",
"(",
"q",
".",
"Dialect",
")",
"\n",
"if",
"q",
".",
"criteria",
".",
"condition",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"q",
".",
"Dialect",
".",
"update",
"(",
"q",
")",
"\n",
"}"
] |
// If the struct type implements Validator interface, values will be validated before update.
// In order to avoid inadvertently update the struct field to zero value, it is better to define a
// temporary struct in function, only define the fields that should be updated.
// But the temporary struct can not implement Validator interface, we have to validate values manually.
// The update condition can be inferred by the Id value of the struct.
// If neither Id value or condition are provided, it would cause runtime panic
|
[
"If",
"the",
"struct",
"type",
"implements",
"Validator",
"interface",
"values",
"will",
"be",
"validated",
"before",
"update",
".",
"In",
"order",
"to",
"avoid",
"inadvertently",
"update",
"the",
"struct",
"field",
"to",
"zero",
"value",
"it",
"is",
"better",
"to",
"define",
"a",
"temporary",
"struct",
"in",
"function",
"only",
"define",
"the",
"fields",
"that",
"should",
"be",
"updated",
".",
"But",
"the",
"temporary",
"struct",
"can",
"not",
"implement",
"Validator",
"interface",
"we",
"have",
"to",
"validate",
"values",
"manually",
".",
"The",
"update",
"condition",
"can",
"be",
"inferred",
"by",
"the",
"Id",
"value",
"of",
"the",
"struct",
".",
"If",
"neither",
"Id",
"value",
"or",
"condition",
"are",
"provided",
"it",
"would",
"cause",
"runtime",
"panic"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L544-L558
|
16,220 |
coocood/qbs
|
qbs.go
|
Delete
|
func (q *Qbs) Delete(structPtr interface{}) (affected int64, err error) {
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
q.criteria.model = model
q.criteria.mergePkCondition(q.Dialect)
if q.criteria.condition == nil {
panic("Can not delete without condition")
}
return q.Dialect.delete(q)
}
|
go
|
func (q *Qbs) Delete(structPtr interface{}) (affected int64, err error) {
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
q.criteria.model = model
q.criteria.mergePkCondition(q.Dialect)
if q.criteria.condition == nil {
panic("Can not delete without condition")
}
return q.Dialect.delete(q)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Delete",
"(",
"structPtr",
"interface",
"{",
"}",
")",
"(",
"affected",
"int64",
",",
"err",
"error",
")",
"{",
"model",
":=",
"structPtrToModel",
"(",
"structPtr",
",",
"true",
",",
"q",
".",
"criteria",
".",
"omitFields",
")",
"\n",
"q",
".",
"criteria",
".",
"model",
"=",
"model",
"\n",
"q",
".",
"criteria",
".",
"mergePkCondition",
"(",
"q",
".",
"Dialect",
")",
"\n",
"if",
"q",
".",
"criteria",
".",
"condition",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"q",
".",
"Dialect",
".",
"delete",
"(",
"q",
")",
"\n",
"}"
] |
// The delete condition can be inferred by the Id value of the struct
// If neither Id value or condition are provided, it would cause runtime panic
|
[
"The",
"delete",
"condition",
"can",
"be",
"inferred",
"by",
"the",
"Id",
"value",
"of",
"the",
"struct",
"If",
"neither",
"Id",
"value",
"or",
"condition",
"are",
"provided",
"it",
"would",
"cause",
"runtime",
"panic"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L562-L570
|
16,221 |
coocood/qbs
|
qbs.go
|
ContainsValue
|
func (q *Qbs) ContainsValue(table interface{}, column string, value interface{}) bool {
quotedColumn := q.Dialect.quote(column)
quotedTable := q.Dialect.quote(tableName(table))
query := fmt.Sprintf("SELECT %v FROM %v WHERE %v = ?", quotedColumn, quotedTable, quotedColumn)
row := q.QueryRow(query, value)
var result interface{}
err := row.Scan(&result)
q.updateTxError(err)
return err == nil
}
|
go
|
func (q *Qbs) ContainsValue(table interface{}, column string, value interface{}) bool {
quotedColumn := q.Dialect.quote(column)
quotedTable := q.Dialect.quote(tableName(table))
query := fmt.Sprintf("SELECT %v FROM %v WHERE %v = ?", quotedColumn, quotedTable, quotedColumn)
row := q.QueryRow(query, value)
var result interface{}
err := row.Scan(&result)
q.updateTxError(err)
return err == nil
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"ContainsValue",
"(",
"table",
"interface",
"{",
"}",
",",
"column",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"bool",
"{",
"quotedColumn",
":=",
"q",
".",
"Dialect",
".",
"quote",
"(",
"column",
")",
"\n",
"quotedTable",
":=",
"q",
".",
"Dialect",
".",
"quote",
"(",
"tableName",
"(",
"table",
")",
")",
"\n",
"query",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"quotedColumn",
",",
"quotedTable",
",",
"quotedColumn",
")",
"\n",
"row",
":=",
"q",
".",
"QueryRow",
"(",
"query",
",",
"value",
")",
"\n",
"var",
"result",
"interface",
"{",
"}",
"\n",
"err",
":=",
"row",
".",
"Scan",
"(",
"&",
"result",
")",
"\n",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// This method can be used to validate unique column before trying to save
// The table parameter can be either a string or a struct pointer
|
[
"This",
"method",
"can",
"be",
"used",
"to",
"validate",
"unique",
"column",
"before",
"trying",
"to",
"save",
"The",
"table",
"parameter",
"can",
"be",
"either",
"a",
"string",
"or",
"a",
"struct",
"pointer"
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L574-L583
|
16,222 |
coocood/qbs
|
qbs.go
|
Close
|
func (q *Qbs) Close() error {
if connectionLimit != nil {
<-connectionLimit
}
if q.tx != nil {
return q.Rollback()
}
return nil
}
|
go
|
func (q *Qbs) Close() error {
if connectionLimit != nil {
<-connectionLimit
}
if q.tx != nil {
return q.Rollback()
}
return nil
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"connectionLimit",
"!=",
"nil",
"{",
"<-",
"connectionLimit",
"\n",
"}",
"\n",
"if",
"q",
".",
"tx",
"!=",
"nil",
"{",
"return",
"q",
".",
"Rollback",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// If the connection pool is not full, the Db will be sent back into the pool, otherwise the Db will get closed.
|
[
"If",
"the",
"connection",
"pool",
"is",
"not",
"full",
"the",
"Db",
"will",
"be",
"sent",
"back",
"into",
"the",
"pool",
"otherwise",
"the",
"Db",
"will",
"get",
"closed",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L586-L594
|
16,223 |
coocood/qbs
|
qbs.go
|
Count
|
func (q *Qbs) Count(table interface{}) int64 {
quotedTable := q.Dialect.quote(tableName(table))
query := "SELECT COUNT(*) FROM " + quotedTable
var row *sql.Row
if q.criteria.condition != nil {
conditionSql, args := q.criteria.condition.Merge()
query += " WHERE " + conditionSql
row = q.QueryRow(query, args...)
} else {
row = q.QueryRow(query)
}
var count int64
err := row.Scan(&count)
if err == sql.ErrNoRows {
return 0
} else if err != nil {
q.updateTxError(err)
}
return count
}
|
go
|
func (q *Qbs) Count(table interface{}) int64 {
quotedTable := q.Dialect.quote(tableName(table))
query := "SELECT COUNT(*) FROM " + quotedTable
var row *sql.Row
if q.criteria.condition != nil {
conditionSql, args := q.criteria.condition.Merge()
query += " WHERE " + conditionSql
row = q.QueryRow(query, args...)
} else {
row = q.QueryRow(query)
}
var count int64
err := row.Scan(&count)
if err == sql.ErrNoRows {
return 0
} else if err != nil {
q.updateTxError(err)
}
return count
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Count",
"(",
"table",
"interface",
"{",
"}",
")",
"int64",
"{",
"quotedTable",
":=",
"q",
".",
"Dialect",
".",
"quote",
"(",
"tableName",
"(",
"table",
")",
")",
"\n",
"query",
":=",
"\"",
"\"",
"+",
"quotedTable",
"\n",
"var",
"row",
"*",
"sql",
".",
"Row",
"\n",
"if",
"q",
".",
"criteria",
".",
"condition",
"!=",
"nil",
"{",
"conditionSql",
",",
"args",
":=",
"q",
".",
"criteria",
".",
"condition",
".",
"Merge",
"(",
")",
"\n",
"query",
"+=",
"\"",
"\"",
"+",
"conditionSql",
"\n",
"row",
"=",
"q",
".",
"QueryRow",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"}",
"else",
"{",
"row",
"=",
"q",
".",
"QueryRow",
"(",
"query",
")",
"\n",
"}",
"\n",
"var",
"count",
"int64",
"\n",
"err",
":=",
"row",
".",
"Scan",
"(",
"&",
"count",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"0",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"count",
"\n",
"}"
] |
//Query the count of rows in a table the talbe parameter can be either a string or struct pointer.
//If condition is given, the count will be the count of rows meet that condition.
|
[
"Query",
"the",
"count",
"of",
"rows",
"in",
"a",
"table",
"the",
"talbe",
"parameter",
"can",
"be",
"either",
"a",
"string",
"or",
"struct",
"pointer",
".",
"If",
"condition",
"is",
"given",
"the",
"count",
"will",
"be",
"the",
"count",
"of",
"rows",
"meet",
"that",
"condition",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L598-L617
|
16,224 |
coocood/qbs
|
qbs.go
|
QueryMap
|
func (q *Qbs) QueryMap(query string, args ...interface{}) (map[string]interface{}, error) {
mapSlice, err := q.doQueryMap(query, true, args...)
if len(mapSlice) == 1 {
return mapSlice[0], err
}
return nil, sql.ErrNoRows
}
|
go
|
func (q *Qbs) QueryMap(query string, args ...interface{}) (map[string]interface{}, error) {
mapSlice, err := q.doQueryMap(query, true, args...)
if len(mapSlice) == 1 {
return mapSlice[0], err
}
return nil, sql.ErrNoRows
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"QueryMap",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"mapSlice",
",",
"err",
":=",
"q",
".",
"doQueryMap",
"(",
"query",
",",
"true",
",",
"args",
"...",
")",
"\n",
"if",
"len",
"(",
"mapSlice",
")",
"==",
"1",
"{",
"return",
"mapSlice",
"[",
"0",
"]",
",",
"err",
"\n",
"}",
"\n",
"return",
"nil",
",",
"sql",
".",
"ErrNoRows",
"\n\n",
"}"
] |
//Query raw sql and return a map.
|
[
"Query",
"raw",
"sql",
"and",
"return",
"a",
"map",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L620-L627
|
16,225 |
coocood/qbs
|
qbs.go
|
QueryMapSlice
|
func (q *Qbs) QueryMapSlice(query string, args ...interface{}) ([]map[string]interface{}, error) {
return q.doQueryMap(query, false, args...)
}
|
go
|
func (q *Qbs) QueryMapSlice(query string, args ...interface{}) ([]map[string]interface{}, error) {
return q.doQueryMap(query, false, args...)
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"QueryMapSlice",
"(",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"q",
".",
"doQueryMap",
"(",
"query",
",",
"false",
",",
"args",
"...",
")",
"\n",
"}"
] |
//Query raw sql and return a slice of map..
|
[
"Query",
"raw",
"sql",
"and",
"return",
"a",
"slice",
"of",
"map",
".."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L630-L632
|
16,226 |
coocood/qbs
|
qbs.go
|
QueryStruct
|
func (q *Qbs) QueryStruct(dest interface{}, query string, args ...interface{}) error {
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
defer rows.Close()
outPtr := reflect.ValueOf(dest)
outValue := outPtr.Elem()
var structType reflect.Type
var single bool
if outValue.Kind() == reflect.Slice {
structType = outValue.Type().Elem().Elem()
} else {
structType = outValue.Type()
single = true
}
columns, _ := rows.Columns()
fieldNames := make([]string, len(columns))
for i, v := range columns {
upper := snakeToUpperCamel(v)
_, ok := structType.FieldByName(upper)
if ok {
fieldNames[i] = upper
} else {
fieldNames[i] = "-"
}
}
for rows.Next() {
var rowStructPointer reflect.Value
if single { //query row
rowStructPointer = outPtr
} else { //query rows
rowStructPointer = reflect.New(structType)
}
dests := make([]interface{}, len(columns))
for i := 0; i < len(dests); i++ {
fieldName := fieldNames[i]
if fieldName == "-" {
var placeholder interface{}
dests[i] = &placeholder
} else {
field := rowStructPointer.Elem().FieldByName(fieldName)
dests[i] = field.Addr().Interface()
}
}
err = rows.Scan(dests...)
if err != nil {
return err
}
if single {
return nil
}
outValue.Set(reflect.Append(outValue, rowStructPointer))
}
return nil
}
|
go
|
func (q *Qbs) QueryStruct(dest interface{}, query string, args ...interface{}) error {
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
defer rows.Close()
outPtr := reflect.ValueOf(dest)
outValue := outPtr.Elem()
var structType reflect.Type
var single bool
if outValue.Kind() == reflect.Slice {
structType = outValue.Type().Elem().Elem()
} else {
structType = outValue.Type()
single = true
}
columns, _ := rows.Columns()
fieldNames := make([]string, len(columns))
for i, v := range columns {
upper := snakeToUpperCamel(v)
_, ok := structType.FieldByName(upper)
if ok {
fieldNames[i] = upper
} else {
fieldNames[i] = "-"
}
}
for rows.Next() {
var rowStructPointer reflect.Value
if single { //query row
rowStructPointer = outPtr
} else { //query rows
rowStructPointer = reflect.New(structType)
}
dests := make([]interface{}, len(columns))
for i := 0; i < len(dests); i++ {
fieldName := fieldNames[i]
if fieldName == "-" {
var placeholder interface{}
dests[i] = &placeholder
} else {
field := rowStructPointer.Elem().FieldByName(fieldName)
dests[i] = field.Addr().Interface()
}
}
err = rows.Scan(dests...)
if err != nil {
return err
}
if single {
return nil
}
outValue.Set(reflect.Append(outValue, rowStructPointer))
}
return nil
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"QueryStruct",
"(",
"dest",
"interface",
"{",
"}",
",",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"query",
"=",
"q",
".",
"Dialect",
".",
"substituteMarkers",
"(",
"query",
")",
"\n",
"stmt",
",",
"err",
":=",
"q",
".",
"prepare",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"stmt",
".",
"Query",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"outPtr",
":=",
"reflect",
".",
"ValueOf",
"(",
"dest",
")",
"\n",
"outValue",
":=",
"outPtr",
".",
"Elem",
"(",
")",
"\n",
"var",
"structType",
"reflect",
".",
"Type",
"\n",
"var",
"single",
"bool",
"\n",
"if",
"outValue",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"{",
"structType",
"=",
"outValue",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
".",
"Elem",
"(",
")",
"\n",
"}",
"else",
"{",
"structType",
"=",
"outValue",
".",
"Type",
"(",
")",
"\n",
"single",
"=",
"true",
"\n",
"}",
"\n",
"columns",
",",
"_",
":=",
"rows",
".",
"Columns",
"(",
")",
"\n",
"fieldNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"columns",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"columns",
"{",
"upper",
":=",
"snakeToUpperCamel",
"(",
"v",
")",
"\n",
"_",
",",
"ok",
":=",
"structType",
".",
"FieldByName",
"(",
"upper",
")",
"\n",
"if",
"ok",
"{",
"fieldNames",
"[",
"i",
"]",
"=",
"upper",
"\n",
"}",
"else",
"{",
"fieldNames",
"[",
"i",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"var",
"rowStructPointer",
"reflect",
".",
"Value",
"\n",
"if",
"single",
"{",
"//query row",
"rowStructPointer",
"=",
"outPtr",
"\n",
"}",
"else",
"{",
"//query rows",
"rowStructPointer",
"=",
"reflect",
".",
"New",
"(",
"structType",
")",
"\n",
"}",
"\n",
"dests",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"columns",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"dests",
")",
";",
"i",
"++",
"{",
"fieldName",
":=",
"fieldNames",
"[",
"i",
"]",
"\n",
"if",
"fieldName",
"==",
"\"",
"\"",
"{",
"var",
"placeholder",
"interface",
"{",
"}",
"\n",
"dests",
"[",
"i",
"]",
"=",
"&",
"placeholder",
"\n",
"}",
"else",
"{",
"field",
":=",
"rowStructPointer",
".",
"Elem",
"(",
")",
".",
"FieldByName",
"(",
"fieldName",
")",
"\n",
"dests",
"[",
"i",
"]",
"=",
"field",
".",
"Addr",
"(",
")",
".",
"Interface",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"dests",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"single",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"outValue",
".",
"Set",
"(",
"reflect",
".",
"Append",
"(",
"outValue",
",",
"rowStructPointer",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
//Do a raw sql query and set the result values in dest parameter.
//The dest parameter can be either a struct pointer or a pointer of struct pointer.slice
//This method do not support pointer field in the struct.
|
[
"Do",
"a",
"raw",
"sql",
"query",
"and",
"set",
"the",
"result",
"values",
"in",
"dest",
"parameter",
".",
"The",
"dest",
"parameter",
"can",
"be",
"either",
"a",
"struct",
"pointer",
"or",
"a",
"pointer",
"of",
"struct",
"pointer",
".",
"slice",
"This",
"method",
"do",
"not",
"support",
"pointer",
"field",
"in",
"the",
"struct",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L679-L739
|
16,227 |
coocood/qbs
|
qbs.go
|
Iterate
|
func (q *Qbs) Iterate(structPtr interface{}, do func() error) error {
q.criteria.model = structPtrToModel(structPtr, !q.criteria.omitJoin, q.criteria.omitFields)
query, args := q.Dialect.querySql(q.criteria)
q.log(query, args...)
defer q.Reset()
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
rowValue := reflect.ValueOf(structPtr)
defer rows.Close()
for rows.Next() {
err = q.scanRows(rowValue, rows)
if err != nil {
return err
}
if err = do(); err != nil {
return err
}
}
return nil
}
|
go
|
func (q *Qbs) Iterate(structPtr interface{}, do func() error) error {
q.criteria.model = structPtrToModel(structPtr, !q.criteria.omitJoin, q.criteria.omitFields)
query, args := q.Dialect.querySql(q.criteria)
q.log(query, args...)
defer q.Reset()
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
rowValue := reflect.ValueOf(structPtr)
defer rows.Close()
for rows.Next() {
err = q.scanRows(rowValue, rows)
if err != nil {
return err
}
if err = do(); err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"q",
"*",
"Qbs",
")",
"Iterate",
"(",
"structPtr",
"interface",
"{",
"}",
",",
"do",
"func",
"(",
")",
"error",
")",
"error",
"{",
"q",
".",
"criteria",
".",
"model",
"=",
"structPtrToModel",
"(",
"structPtr",
",",
"!",
"q",
".",
"criteria",
".",
"omitJoin",
",",
"q",
".",
"criteria",
".",
"omitFields",
")",
"\n",
"query",
",",
"args",
":=",
"q",
".",
"Dialect",
".",
"querySql",
"(",
"q",
".",
"criteria",
")",
"\n",
"q",
".",
"log",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"defer",
"q",
".",
"Reset",
"(",
")",
"\n",
"stmt",
",",
"err",
":=",
"q",
".",
"prepare",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"stmt",
".",
"Query",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"q",
".",
"updateTxError",
"(",
"err",
")",
"\n",
"}",
"\n",
"rowValue",
":=",
"reflect",
".",
"ValueOf",
"(",
"structPtr",
")",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"err",
"=",
"q",
".",
"scanRows",
"(",
"rowValue",
",",
"rows",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"do",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
//Iterate the rows, the first parameter is a struct pointer, the second parameter is a fucntion
//which will get called on each row, the in `do` function the structPtr's value will be set to the current row's value..
//if `do` function returns an error, the iteration will be stopped.
|
[
"Iterate",
"the",
"rows",
"the",
"first",
"parameter",
"is",
"a",
"struct",
"pointer",
"the",
"second",
"parameter",
"is",
"a",
"fucntion",
"which",
"will",
"get",
"called",
"on",
"each",
"row",
"the",
"in",
"do",
"function",
"the",
"structPtr",
"s",
"value",
"will",
"be",
"set",
"to",
"the",
"current",
"row",
"s",
"value",
"..",
"if",
"do",
"function",
"returns",
"an",
"error",
"the",
"iteration",
"will",
"be",
"stopped",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/qbs.go#L744-L769
|
16,228 |
coocood/qbs
|
criteria.go
|
StringsToInterfaces
|
func StringsToInterfaces(strs ...string) []interface{} {
ret := make([]interface{}, len(strs))
for i := 0; i < len(strs); i++ {
ret[i] = strs[i]
}
return ret
}
|
go
|
func StringsToInterfaces(strs ...string) []interface{} {
ret := make([]interface{}, len(strs))
for i := 0; i < len(strs); i++ {
ret[i] = strs[i]
}
return ret
}
|
[
"func",
"StringsToInterfaces",
"(",
"strs",
"...",
"string",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"ret",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"strs",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"strs",
")",
";",
"i",
"++",
"{",
"ret",
"[",
"i",
"]",
"=",
"strs",
"[",
"i",
"]",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] |
//Used for in condition.
|
[
"Used",
"for",
"in",
"condition",
"."
] |
8554e18a96c91918e49c8cb375ece4876e69c1f0
|
https://github.com/coocood/qbs/blob/8554e18a96c91918e49c8cb375ece4876e69c1f0/criteria.go#L134-L140
|
16,229 |
antage/eventsource
|
eventsource.go
|
New
|
func New(settings *Settings, customHeadersFunc func(*http.Request) [][]byte) EventSource {
if settings == nil {
settings = DefaultSettings()
}
es := new(eventSource)
es.customHeadersFunc = customHeadersFunc
es.sink = make(chan message, 1)
es.close = make(chan bool)
es.staled = make(chan *consumer, 1)
es.add = make(chan *consumer)
es.consumers = list.New()
es.timeout = settings.Timeout
es.idleTimeout = settings.IdleTimeout
es.closeOnTimeout = settings.CloseOnTimeout
es.gzip = settings.Gzip
go controlProcess(es)
return es
}
|
go
|
func New(settings *Settings, customHeadersFunc func(*http.Request) [][]byte) EventSource {
if settings == nil {
settings = DefaultSettings()
}
es := new(eventSource)
es.customHeadersFunc = customHeadersFunc
es.sink = make(chan message, 1)
es.close = make(chan bool)
es.staled = make(chan *consumer, 1)
es.add = make(chan *consumer)
es.consumers = list.New()
es.timeout = settings.Timeout
es.idleTimeout = settings.IdleTimeout
es.closeOnTimeout = settings.CloseOnTimeout
es.gzip = settings.Gzip
go controlProcess(es)
return es
}
|
[
"func",
"New",
"(",
"settings",
"*",
"Settings",
",",
"customHeadersFunc",
"func",
"(",
"*",
"http",
".",
"Request",
")",
"[",
"]",
"[",
"]",
"byte",
")",
"EventSource",
"{",
"if",
"settings",
"==",
"nil",
"{",
"settings",
"=",
"DefaultSettings",
"(",
")",
"\n",
"}",
"\n\n",
"es",
":=",
"new",
"(",
"eventSource",
")",
"\n",
"es",
".",
"customHeadersFunc",
"=",
"customHeadersFunc",
"\n",
"es",
".",
"sink",
"=",
"make",
"(",
"chan",
"message",
",",
"1",
")",
"\n",
"es",
".",
"close",
"=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"es",
".",
"staled",
"=",
"make",
"(",
"chan",
"*",
"consumer",
",",
"1",
")",
"\n",
"es",
".",
"add",
"=",
"make",
"(",
"chan",
"*",
"consumer",
")",
"\n",
"es",
".",
"consumers",
"=",
"list",
".",
"New",
"(",
")",
"\n",
"es",
".",
"timeout",
"=",
"settings",
".",
"Timeout",
"\n",
"es",
".",
"idleTimeout",
"=",
"settings",
".",
"IdleTimeout",
"\n",
"es",
".",
"closeOnTimeout",
"=",
"settings",
".",
"CloseOnTimeout",
"\n",
"es",
".",
"gzip",
"=",
"settings",
".",
"Gzip",
"\n",
"go",
"controlProcess",
"(",
"es",
")",
"\n",
"return",
"es",
"\n",
"}"
] |
// New creates new EventSource instance.
|
[
"New",
"creates",
"new",
"EventSource",
"instance",
"."
] |
84b66123687192d6c2cf1d4bac2787c43d6943e3
|
https://github.com/antage/eventsource/blob/84b66123687192d6c2cf1d4bac2787c43d6943e3/eventsource.go#L192-L210
|
16,230 |
gernest/wow
|
scripts/generate_spin.go
|
ExampleAll
|
func ExampleAll() error {
b, err := ioutil.ReadFile("cli-spinners/spinners.json")
if err != nil {
return err
}
o := make(map[string]interface{})
err = json.Unmarshal(b, &o)
if err != nil {
return err
}
// Generate example/all/main.go
tpl, err := template.New("example-all").Funcs(helpers()).Parse(exampleAllTpl)
if err != nil {
return err
}
var buf bytes.Buffer
err = tpl.Execute(&buf, o)
if err != nil {
return err
}
bo, err := format.Source(buf.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile("example/all/main.go", bo, 0600)
}
|
go
|
func ExampleAll() error {
b, err := ioutil.ReadFile("cli-spinners/spinners.json")
if err != nil {
return err
}
o := make(map[string]interface{})
err = json.Unmarshal(b, &o)
if err != nil {
return err
}
// Generate example/all/main.go
tpl, err := template.New("example-all").Funcs(helpers()).Parse(exampleAllTpl)
if err != nil {
return err
}
var buf bytes.Buffer
err = tpl.Execute(&buf, o)
if err != nil {
return err
}
bo, err := format.Source(buf.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile("example/all/main.go", bo, 0600)
}
|
[
"func",
"ExampleAll",
"(",
")",
"error",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"o",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Generate example/all/main.go",
"tpl",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Funcs",
"(",
"helpers",
"(",
")",
")",
".",
"Parse",
"(",
"exampleAllTpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"err",
"=",
"tpl",
".",
"Execute",
"(",
"&",
"buf",
",",
"o",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"bo",
",",
"err",
":=",
"format",
".",
"Source",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"\"",
"\"",
",",
"bo",
",",
"0600",
")",
"\n",
"}"
] |
// ExampleAll generates example executable file to demo all spinners
|
[
"ExampleAll",
"generates",
"example",
"executable",
"file",
"to",
"demo",
"all",
"spinners"
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/scripts/generate_spin.go#L64-L90
|
16,231 |
gernest/wow
|
wow.go
|
New
|
func New(o io.Writer, s spin.Spinner, text string, options ...func(*Wow)) *Wow {
isTerminal := terminal.IsTerminal(int(os.Stdout.Fd()))
wow := Wow{out: o, s: s, txt: text, IsTerminal: isTerminal}
for _, option := range options {
option(&wow)
}
return &wow
}
|
go
|
func New(o io.Writer, s spin.Spinner, text string, options ...func(*Wow)) *Wow {
isTerminal := terminal.IsTerminal(int(os.Stdout.Fd()))
wow := Wow{out: o, s: s, txt: text, IsTerminal: isTerminal}
for _, option := range options {
option(&wow)
}
return &wow
}
|
[
"func",
"New",
"(",
"o",
"io",
".",
"Writer",
",",
"s",
"spin",
".",
"Spinner",
",",
"text",
"string",
",",
"options",
"...",
"func",
"(",
"*",
"Wow",
")",
")",
"*",
"Wow",
"{",
"isTerminal",
":=",
"terminal",
".",
"IsTerminal",
"(",
"int",
"(",
"os",
".",
"Stdout",
".",
"Fd",
"(",
")",
")",
")",
"\n\n",
"wow",
":=",
"Wow",
"{",
"out",
":",
"o",
",",
"s",
":",
"s",
",",
"txt",
":",
"text",
",",
"IsTerminal",
":",
"isTerminal",
"}",
"\n\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"&",
"wow",
")",
"\n",
"}",
"\n",
"return",
"&",
"wow",
"\n",
"}"
] |
// New creates a new wow instance ready to start spinning.
|
[
"New",
"creates",
"a",
"new",
"wow",
"instance",
"ready",
"to",
"start",
"spinning",
"."
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L31-L40
|
16,232 |
gernest/wow
|
wow.go
|
Start
|
func (w *Wow) Start() {
if !w.running {
ctx, done := context.WithCancel(context.Background())
w.done = done
w.running = true
go w.run(ctx)
}
}
|
go
|
func (w *Wow) Start() {
if !w.running {
ctx, done := context.WithCancel(context.Background())
w.done = done
w.running = true
go w.run(ctx)
}
}
|
[
"func",
"(",
"w",
"*",
"Wow",
")",
"Start",
"(",
")",
"{",
"if",
"!",
"w",
".",
"running",
"{",
"ctx",
",",
"done",
":=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"w",
".",
"done",
"=",
"done",
"\n",
"w",
".",
"running",
"=",
"true",
"\n",
"go",
"w",
".",
"run",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"}"
] |
// Start starts the spinner. The frames are written based on the spinner
// interval.
|
[
"Start",
"starts",
"the",
"spinner",
".",
"The",
"frames",
"are",
"written",
"based",
"on",
"the",
"spinner",
"interval",
"."
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L62-L69
|
16,233 |
gernest/wow
|
wow.go
|
Stop
|
func (w *Wow) Stop() {
if w.done != nil {
w.done()
}
w.running = false
}
|
go
|
func (w *Wow) Stop() {
if w.done != nil {
w.done()
}
w.running = false
}
|
[
"func",
"(",
"w",
"*",
"Wow",
")",
"Stop",
"(",
")",
"{",
"if",
"w",
".",
"done",
"!=",
"nil",
"{",
"w",
".",
"done",
"(",
")",
"\n",
"}",
"\n",
"w",
".",
"running",
"=",
"false",
"\n",
"}"
] |
// Stop stops the spinner
|
[
"Stop",
"stops",
"the",
"spinner"
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L72-L77
|
16,234 |
gernest/wow
|
wow.go
|
Spinner
|
func (w *Wow) Spinner(s spin.Spinner) *Wow {
w.Stop()
w.s = s
w.Start()
return w
}
|
go
|
func (w *Wow) Spinner(s spin.Spinner) *Wow {
w.Stop()
w.s = s
w.Start()
return w
}
|
[
"func",
"(",
"w",
"*",
"Wow",
")",
"Spinner",
"(",
"s",
"spin",
".",
"Spinner",
")",
"*",
"Wow",
"{",
"w",
".",
"Stop",
"(",
")",
"\n",
"w",
".",
"s",
"=",
"s",
"\n",
"w",
".",
"Start",
"(",
")",
"\n",
"return",
"w",
"\n",
"}"
] |
// Spinner sets s to the current spinner
|
[
"Spinner",
"sets",
"s",
"to",
"the",
"current",
"spinner"
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L80-L85
|
16,235 |
gernest/wow
|
wow.go
|
Text
|
func (w *Wow) Text(txt string) *Wow {
w.mu.Lock()
w.txt = txt
w.mu.Unlock()
return w
}
|
go
|
func (w *Wow) Text(txt string) *Wow {
w.mu.Lock()
w.txt = txt
w.mu.Unlock()
return w
}
|
[
"func",
"(",
"w",
"*",
"Wow",
")",
"Text",
"(",
"txt",
"string",
")",
"*",
"Wow",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"txt",
"=",
"txt",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"w",
"\n",
"}"
] |
// Text adds text to the current spinner
|
[
"Text",
"adds",
"text",
"to",
"the",
"current",
"spinner"
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L88-L93
|
16,236 |
gernest/wow
|
wow.go
|
Persist
|
func (w *Wow) Persist() {
w.Stop()
at := len(w.s.Frames) - 1
txt := erase + w.s.Frames[at] + w.txt + "\n"
if w.IsTerminal {
fmt.Fprint(w.out, txt)
}
}
|
go
|
func (w *Wow) Persist() {
w.Stop()
at := len(w.s.Frames) - 1
txt := erase + w.s.Frames[at] + w.txt + "\n"
if w.IsTerminal {
fmt.Fprint(w.out, txt)
}
}
|
[
"func",
"(",
"w",
"*",
"Wow",
")",
"Persist",
"(",
")",
"{",
"w",
".",
"Stop",
"(",
")",
"\n",
"at",
":=",
"len",
"(",
"w",
".",
"s",
".",
"Frames",
")",
"-",
"1",
"\n",
"txt",
":=",
"erase",
"+",
"w",
".",
"s",
".",
"Frames",
"[",
"at",
"]",
"+",
"w",
".",
"txt",
"+",
"\"",
"\\n",
"\"",
"\n",
"if",
"w",
".",
"IsTerminal",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
".",
"out",
",",
"txt",
")",
"\n",
"}",
"\n",
"}"
] |
// Persist writes the last character of the currect spinner frames together with
// the text on stdout.
//
// A new line is added at the end to ensure the text stay that way.
|
[
"Persist",
"writes",
"the",
"last",
"character",
"of",
"the",
"currect",
"spinner",
"frames",
"together",
"with",
"the",
"text",
"on",
"stdout",
".",
"A",
"new",
"line",
"is",
"added",
"at",
"the",
"end",
"to",
"ensure",
"the",
"text",
"stay",
"that",
"way",
"."
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L99-L106
|
16,237 |
gernest/wow
|
wow.go
|
PersistWith
|
func (w *Wow) PersistWith(s spin.Spinner, text string) {
w.Stop()
var a string
if len(s.Frames) > 0 {
a = s.Frames[len(s.Frames)-1]
}
txt := erase + a + text + "\n"
if w.IsTerminal {
fmt.Fprint(w.out, txt)
}
}
|
go
|
func (w *Wow) PersistWith(s spin.Spinner, text string) {
w.Stop()
var a string
if len(s.Frames) > 0 {
a = s.Frames[len(s.Frames)-1]
}
txt := erase + a + text + "\n"
if w.IsTerminal {
fmt.Fprint(w.out, txt)
}
}
|
[
"func",
"(",
"w",
"*",
"Wow",
")",
"PersistWith",
"(",
"s",
"spin",
".",
"Spinner",
",",
"text",
"string",
")",
"{",
"w",
".",
"Stop",
"(",
")",
"\n",
"var",
"a",
"string",
"\n",
"if",
"len",
"(",
"s",
".",
"Frames",
")",
">",
"0",
"{",
"a",
"=",
"s",
".",
"Frames",
"[",
"len",
"(",
"s",
".",
"Frames",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"txt",
":=",
"erase",
"+",
"a",
"+",
"text",
"+",
"\"",
"\\n",
"\"",
"\n",
"if",
"w",
".",
"IsTerminal",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
".",
"out",
",",
"txt",
")",
"\n",
"}",
"\n",
"}"
] |
// PersistWith writes the last frame of s together with text with a new line
// added to make it stick.
|
[
"PersistWith",
"writes",
"the",
"last",
"frame",
"of",
"s",
"together",
"with",
"text",
"with",
"a",
"new",
"line",
"added",
"to",
"make",
"it",
"stick",
"."
] |
f84922eda44edbee8c79fd50e9842b25d76f5b4b
|
https://github.com/gernest/wow/blob/f84922eda44edbee8c79fd50e9842b25d76f5b4b/wow.go#L110-L120
|
16,238 |
bluele/slack
|
mpims.go
|
MpIms
|
func (res *MpImListAPIResponse) MpIms() ([]*MpIm, error) {
var mpim []*MpIm
err := json.Unmarshal(res.RawMpIms, &mpim)
if err != nil {
return nil, err
}
return mpim, nil
}
|
go
|
func (res *MpImListAPIResponse) MpIms() ([]*MpIm, error) {
var mpim []*MpIm
err := json.Unmarshal(res.RawMpIms, &mpim)
if err != nil {
return nil, err
}
return mpim, nil
}
|
[
"func",
"(",
"res",
"*",
"MpImListAPIResponse",
")",
"MpIms",
"(",
")",
"(",
"[",
"]",
"*",
"MpIm",
",",
"error",
")",
"{",
"var",
"mpim",
"[",
"]",
"*",
"MpIm",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
".",
"RawMpIms",
",",
"&",
"mpim",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"mpim",
",",
"nil",
"\n",
"}"
] |
// MpIms returns a slice of mpim object from `mpim.list` api.
|
[
"MpIms",
"returns",
"a",
"slice",
"of",
"mpim",
"object",
"from",
"mpim",
".",
"list",
"api",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/mpims.go#L46-L53
|
16,239 |
bluele/slack
|
mpims.go
|
FindMpIm
|
func (sl *Slack) FindMpIm(cb func(*MpIm) bool) (*MpIm, error) {
mpims, err := sl.MpImList()
if err != nil {
return nil, err
}
for _, mpim := range mpims {
if cb(mpim) {
return mpim, nil
}
}
return nil, errors.New("No such mpim.")
}
|
go
|
func (sl *Slack) FindMpIm(cb func(*MpIm) bool) (*MpIm, error) {
mpims, err := sl.MpImList()
if err != nil {
return nil, err
}
for _, mpim := range mpims {
if cb(mpim) {
return mpim, nil
}
}
return nil, errors.New("No such mpim.")
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindMpIm",
"(",
"cb",
"func",
"(",
"*",
"MpIm",
")",
"bool",
")",
"(",
"*",
"MpIm",
",",
"error",
")",
"{",
"mpims",
",",
"err",
":=",
"sl",
".",
"MpImList",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"mpim",
":=",
"range",
"mpims",
"{",
"if",
"cb",
"(",
"mpim",
")",
"{",
"return",
"mpim",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// FindMpIm returns a mpim object that satisfy conditions specified.
|
[
"FindMpIm",
"returns",
"a",
"mpim",
"object",
"that",
"satisfy",
"conditions",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/mpims.go#L56-L67
|
16,240 |
bluele/slack
|
groups.go
|
Groups
|
func (res *GroupsListAPIResponse) Groups() ([]*Group, error) {
var groups []*Group
err := json.Unmarshal(res.RawGroups, &groups)
if err != nil {
return nil, err
}
return groups, nil
}
|
go
|
func (res *GroupsListAPIResponse) Groups() ([]*Group, error) {
var groups []*Group
err := json.Unmarshal(res.RawGroups, &groups)
if err != nil {
return nil, err
}
return groups, nil
}
|
[
"func",
"(",
"res",
"*",
"GroupsListAPIResponse",
")",
"Groups",
"(",
")",
"(",
"[",
"]",
"*",
"Group",
",",
"error",
")",
"{",
"var",
"groups",
"[",
"]",
"*",
"Group",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
".",
"RawGroups",
",",
"&",
"groups",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"groups",
",",
"nil",
"\n",
"}"
] |
// Groups returns a slice of group object from `groups.list` api.
|
[
"Groups",
"returns",
"a",
"slice",
"of",
"group",
"object",
"from",
"groups",
".",
"list",
"api",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/groups.go#L57-L64
|
16,241 |
bluele/slack
|
groups.go
|
FindGroup
|
func (sl *Slack) FindGroup(cb func(*Group) bool) (*Group, error) {
groups, err := sl.GroupsList()
if err != nil {
return nil, err
}
for _, group := range groups {
if cb(group) {
return group, nil
}
}
return nil, errors.New("No such group.")
}
|
go
|
func (sl *Slack) FindGroup(cb func(*Group) bool) (*Group, error) {
groups, err := sl.GroupsList()
if err != nil {
return nil, err
}
for _, group := range groups {
if cb(group) {
return group, nil
}
}
return nil, errors.New("No such group.")
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindGroup",
"(",
"cb",
"func",
"(",
"*",
"Group",
")",
"bool",
")",
"(",
"*",
"Group",
",",
"error",
")",
"{",
"groups",
",",
"err",
":=",
"sl",
".",
"GroupsList",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"group",
":=",
"range",
"groups",
"{",
"if",
"cb",
"(",
"group",
")",
"{",
"return",
"group",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// FindGroup returns a group object that satisfy conditions specified.
|
[
"FindGroup",
"returns",
"a",
"group",
"object",
"that",
"satisfy",
"conditions",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/groups.go#L82-L93
|
16,242 |
bluele/slack
|
groups.go
|
FindGroupByName
|
func (sl *Slack) FindGroupByName(name string) (*Group, error) {
return sl.FindGroup(func(group *Group) bool {
return group.Name == name
})
}
|
go
|
func (sl *Slack) FindGroupByName(name string) (*Group, error) {
return sl.FindGroup(func(group *Group) bool {
return group.Name == name
})
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindGroupByName",
"(",
"name",
"string",
")",
"(",
"*",
"Group",
",",
"error",
")",
"{",
"return",
"sl",
".",
"FindGroup",
"(",
"func",
"(",
"group",
"*",
"Group",
")",
"bool",
"{",
"return",
"group",
".",
"Name",
"==",
"name",
"\n",
"}",
")",
"\n",
"}"
] |
// FindGroupByName returns a group object that matches name specified.
|
[
"FindGroupByName",
"returns",
"a",
"group",
"object",
"that",
"matches",
"name",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/groups.go#L96-L100
|
16,243 |
bluele/slack
|
users.go
|
FindUser
|
func (sl *Slack) FindUser(cb func(*User) bool) (*User, error) {
members, err := sl.UsersList()
if err != nil {
return nil, err
}
for _, member := range members {
if cb(member) {
return member, nil
}
}
return nil, errors.New("No such user.")
}
|
go
|
func (sl *Slack) FindUser(cb func(*User) bool) (*User, error) {
members, err := sl.UsersList()
if err != nil {
return nil, err
}
for _, member := range members {
if cb(member) {
return member, nil
}
}
return nil, errors.New("No such user.")
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindUser",
"(",
"cb",
"func",
"(",
"*",
"User",
")",
"bool",
")",
"(",
"*",
"User",
",",
"error",
")",
"{",
"members",
",",
"err",
":=",
"sl",
".",
"UsersList",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"member",
":=",
"range",
"members",
"{",
"if",
"cb",
"(",
"member",
")",
"{",
"return",
"member",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// FindUser returns a user object that satisfy conditions specified.
|
[
"FindUser",
"returns",
"a",
"user",
"object",
"that",
"satisfy",
"conditions",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/users.go#L70-L81
|
16,244 |
bluele/slack
|
users.go
|
FindUserByName
|
func (sl *Slack) FindUserByName(name string) (*User, error) {
return sl.FindUser(func(user *User) bool {
return user.Name == name
})
}
|
go
|
func (sl *Slack) FindUserByName(name string) (*User, error) {
return sl.FindUser(func(user *User) bool {
return user.Name == name
})
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindUserByName",
"(",
"name",
"string",
")",
"(",
"*",
"User",
",",
"error",
")",
"{",
"return",
"sl",
".",
"FindUser",
"(",
"func",
"(",
"user",
"*",
"User",
")",
"bool",
"{",
"return",
"user",
".",
"Name",
"==",
"name",
"\n",
"}",
")",
"\n",
"}"
] |
// FindUserByName returns a user object that matches name specified.
|
[
"FindUserByName",
"returns",
"a",
"user",
"object",
"that",
"matches",
"name",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/users.go#L84-L88
|
16,245 |
bluele/slack
|
channels.go
|
Channels
|
func (res *ChannelsListAPIResponse) Channels() ([]*Channel, error) {
var chs []*Channel
err := json.Unmarshal(res.RawChannels, &chs)
if err != nil {
return nil, err
}
return chs, nil
}
|
go
|
func (res *ChannelsListAPIResponse) Channels() ([]*Channel, error) {
var chs []*Channel
err := json.Unmarshal(res.RawChannels, &chs)
if err != nil {
return nil, err
}
return chs, nil
}
|
[
"func",
"(",
"res",
"*",
"ChannelsListAPIResponse",
")",
"Channels",
"(",
")",
"(",
"[",
"]",
"*",
"Channel",
",",
"error",
")",
"{",
"var",
"chs",
"[",
"]",
"*",
"Channel",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
".",
"RawChannels",
",",
"&",
"chs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"chs",
",",
"nil",
"\n",
"}"
] |
// Channels returns a slice of channel object from a response of `channels.list` api.
|
[
"Channels",
"returns",
"a",
"slice",
"of",
"channel",
"object",
"from",
"a",
"response",
"of",
"channels",
".",
"list",
"api",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/channels.go#L52-L59
|
16,246 |
bluele/slack
|
channels.go
|
FindChannel
|
func (sl *Slack) FindChannel(cb func(*Channel) bool) (*Channel, error) {
channels, err := sl.ChannelsList()
if err != nil {
return nil, err
}
for _, channel := range channels {
if cb(channel) {
return channel, nil
}
}
return nil, errors.New("No such channel.")
}
|
go
|
func (sl *Slack) FindChannel(cb func(*Channel) bool) (*Channel, error) {
channels, err := sl.ChannelsList()
if err != nil {
return nil, err
}
for _, channel := range channels {
if cb(channel) {
return channel, nil
}
}
return nil, errors.New("No such channel.")
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindChannel",
"(",
"cb",
"func",
"(",
"*",
"Channel",
")",
"bool",
")",
"(",
"*",
"Channel",
",",
"error",
")",
"{",
"channels",
",",
"err",
":=",
"sl",
".",
"ChannelsList",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"channel",
":=",
"range",
"channels",
"{",
"if",
"cb",
"(",
"channel",
")",
"{",
"return",
"channel",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// FindChannel returns a channel object that satisfy conditions specified.
|
[
"FindChannel",
"returns",
"a",
"channel",
"object",
"that",
"satisfy",
"conditions",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/channels.go#L80-L91
|
16,247 |
bluele/slack
|
channels.go
|
FindChannelByName
|
func (sl *Slack) FindChannelByName(name string) (*Channel, error) {
return sl.FindChannel(func(channel *Channel) bool {
return channel.Name == name
})
}
|
go
|
func (sl *Slack) FindChannelByName(name string) (*Channel, error) {
return sl.FindChannel(func(channel *Channel) bool {
return channel.Name == name
})
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindChannelByName",
"(",
"name",
"string",
")",
"(",
"*",
"Channel",
",",
"error",
")",
"{",
"return",
"sl",
".",
"FindChannel",
"(",
"func",
"(",
"channel",
"*",
"Channel",
")",
"bool",
"{",
"return",
"channel",
".",
"Name",
"==",
"name",
"\n",
"}",
")",
"\n",
"}"
] |
// FindChannelByName returns a channel object that matches name specified.
|
[
"FindChannelByName",
"returns",
"a",
"channel",
"object",
"that",
"matches",
"name",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/channels.go#L94-L98
|
16,248 |
bluele/slack
|
ims.go
|
Ims
|
func (res *ImListAPIResponse) Ims() ([]*Im, error) {
var im []*Im
err := json.Unmarshal(res.RawIms, &im)
if err != nil {
return nil, err
}
return im, nil
}
|
go
|
func (res *ImListAPIResponse) Ims() ([]*Im, error) {
var im []*Im
err := json.Unmarshal(res.RawIms, &im)
if err != nil {
return nil, err
}
return im, nil
}
|
[
"func",
"(",
"res",
"*",
"ImListAPIResponse",
")",
"Ims",
"(",
")",
"(",
"[",
"]",
"*",
"Im",
",",
"error",
")",
"{",
"var",
"im",
"[",
"]",
"*",
"Im",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
".",
"RawIms",
",",
"&",
"im",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"im",
",",
"nil",
"\n",
"}"
] |
// Ims returns a slice of im object from `im.list` api.
|
[
"Ims",
"returns",
"a",
"slice",
"of",
"im",
"object",
"from",
"im",
".",
"list",
"api",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/ims.go#L42-L49
|
16,249 |
bluele/slack
|
ims.go
|
FindIm
|
func (sl *Slack) FindIm(cb func(*Im) bool) (*Im, error) {
ims, err := sl.ImList()
if err != nil {
return nil, err
}
for _, im := range ims {
if cb(im) {
return im, nil
}
}
return nil, errors.New("No such im.")
}
|
go
|
func (sl *Slack) FindIm(cb func(*Im) bool) (*Im, error) {
ims, err := sl.ImList()
if err != nil {
return nil, err
}
for _, im := range ims {
if cb(im) {
return im, nil
}
}
return nil, errors.New("No such im.")
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindIm",
"(",
"cb",
"func",
"(",
"*",
"Im",
")",
"bool",
")",
"(",
"*",
"Im",
",",
"error",
")",
"{",
"ims",
",",
"err",
":=",
"sl",
".",
"ImList",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"im",
":=",
"range",
"ims",
"{",
"if",
"cb",
"(",
"im",
")",
"{",
"return",
"im",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// FindIm returns a im object that satisfy conditions specified.
|
[
"FindIm",
"returns",
"a",
"im",
"object",
"that",
"satisfy",
"conditions",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/ims.go#L52-L63
|
16,250 |
bluele/slack
|
ims.go
|
FindImByName
|
func (sl *Slack) FindImByName(name string) (*Im, error) {
user, err := sl.FindUserByName(name)
if err != nil {
return nil, err
}
id := user.Id
return sl.FindIm(func(im *Im) bool {
return im.User == id
})
}
|
go
|
func (sl *Slack) FindImByName(name string) (*Im, error) {
user, err := sl.FindUserByName(name)
if err != nil {
return nil, err
}
id := user.Id
return sl.FindIm(func(im *Im) bool {
return im.User == id
})
}
|
[
"func",
"(",
"sl",
"*",
"Slack",
")",
"FindImByName",
"(",
"name",
"string",
")",
"(",
"*",
"Im",
",",
"error",
")",
"{",
"user",
",",
"err",
":=",
"sl",
".",
"FindUserByName",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"id",
":=",
"user",
".",
"Id",
"\n",
"return",
"sl",
".",
"FindIm",
"(",
"func",
"(",
"im",
"*",
"Im",
")",
"bool",
"{",
"return",
"im",
".",
"User",
"==",
"id",
"\n",
"}",
")",
"\n",
"}"
] |
// FindImByName returns a im object that matches name specified.
|
[
"FindImByName",
"returns",
"a",
"im",
"object",
"that",
"matches",
"name",
"specified",
"."
] |
b4b4d354a079fbf4bd948faad01b32cecb2ffe03
|
https://github.com/bluele/slack/blob/b4b4d354a079fbf4bd948faad01b32cecb2ffe03/ims.go#L66-L75
|
16,251 |
remyoudompheng/bigfft
|
fermat.go
|
Add
|
func (z fermat) Add(x, y fermat) fermat {
if len(z) != len(x) {
panic("Add: len(z) != len(x)")
}
addVV(z, x, y) // there cannot be a carry here.
z.norm()
return z
}
|
go
|
func (z fermat) Add(x, y fermat) fermat {
if len(z) != len(x) {
panic("Add: len(z) != len(x)")
}
addVV(z, x, y) // there cannot be a carry here.
z.norm()
return z
}
|
[
"func",
"(",
"z",
"fermat",
")",
"Add",
"(",
"x",
",",
"y",
"fermat",
")",
"fermat",
"{",
"if",
"len",
"(",
"z",
")",
"!=",
"len",
"(",
"x",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"addVV",
"(",
"z",
",",
"x",
",",
"y",
")",
"// there cannot be a carry here.",
"\n",
"z",
".",
"norm",
"(",
")",
"\n",
"return",
"z",
"\n",
"}"
] |
// Add computes addition mod 2^n+1.
|
[
"Add",
"computes",
"addition",
"mod",
"2^n",
"+",
"1",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fermat.go#L116-L123
|
16,252 |
remyoudompheng/bigfft
|
fermat.go
|
Sub
|
func (z fermat) Sub(x, y fermat) fermat {
if len(z) != len(x) {
panic("Add: len(z) != len(x)")
}
n := len(y) - 1
b := subVV(z[:n], x[:n], y[:n])
b += y[n]
// If b > 0, we need to subtract b<<n, which is the same as adding b.
z[n] = x[n]
if z[0] <= ^big.Word(0)-b {
z[0] += b
} else {
addVW(z, z, b)
}
z.norm()
return z
}
|
go
|
func (z fermat) Sub(x, y fermat) fermat {
if len(z) != len(x) {
panic("Add: len(z) != len(x)")
}
n := len(y) - 1
b := subVV(z[:n], x[:n], y[:n])
b += y[n]
// If b > 0, we need to subtract b<<n, which is the same as adding b.
z[n] = x[n]
if z[0] <= ^big.Word(0)-b {
z[0] += b
} else {
addVW(z, z, b)
}
z.norm()
return z
}
|
[
"func",
"(",
"z",
"fermat",
")",
"Sub",
"(",
"x",
",",
"y",
"fermat",
")",
"fermat",
"{",
"if",
"len",
"(",
"z",
")",
"!=",
"len",
"(",
"x",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"n",
":=",
"len",
"(",
"y",
")",
"-",
"1",
"\n",
"b",
":=",
"subVV",
"(",
"z",
"[",
":",
"n",
"]",
",",
"x",
"[",
":",
"n",
"]",
",",
"y",
"[",
":",
"n",
"]",
")",
"\n",
"b",
"+=",
"y",
"[",
"n",
"]",
"\n",
"// If b > 0, we need to subtract b<<n, which is the same as adding b.",
"z",
"[",
"n",
"]",
"=",
"x",
"[",
"n",
"]",
"\n",
"if",
"z",
"[",
"0",
"]",
"<=",
"^",
"big",
".",
"Word",
"(",
"0",
")",
"-",
"b",
"{",
"z",
"[",
"0",
"]",
"+=",
"b",
"\n",
"}",
"else",
"{",
"addVW",
"(",
"z",
",",
"z",
",",
"b",
")",
"\n",
"}",
"\n",
"z",
".",
"norm",
"(",
")",
"\n",
"return",
"z",
"\n",
"}"
] |
// Sub computes substraction mod 2^n+1.
|
[
"Sub",
"computes",
"substraction",
"mod",
"2^n",
"+",
"1",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fermat.go#L126-L142
|
16,253 |
remyoudompheng/bigfft
|
fft.go
|
polyFromNat
|
func polyFromNat(x nat, k uint, m int) poly {
p := poly{k: k, m: m}
length := len(x)/m + 1
p.a = make([]nat, length)
for i := range p.a {
if len(x) < m {
p.a[i] = make(nat, m)
copy(p.a[i], x)
break
}
p.a[i] = x[:m]
x = x[m:]
}
return p
}
|
go
|
func polyFromNat(x nat, k uint, m int) poly {
p := poly{k: k, m: m}
length := len(x)/m + 1
p.a = make([]nat, length)
for i := range p.a {
if len(x) < m {
p.a[i] = make(nat, m)
copy(p.a[i], x)
break
}
p.a[i] = x[:m]
x = x[m:]
}
return p
}
|
[
"func",
"polyFromNat",
"(",
"x",
"nat",
",",
"k",
"uint",
",",
"m",
"int",
")",
"poly",
"{",
"p",
":=",
"poly",
"{",
"k",
":",
"k",
",",
"m",
":",
"m",
"}",
"\n",
"length",
":=",
"len",
"(",
"x",
")",
"/",
"m",
"+",
"1",
"\n",
"p",
".",
"a",
"=",
"make",
"(",
"[",
"]",
"nat",
",",
"length",
")",
"\n",
"for",
"i",
":=",
"range",
"p",
".",
"a",
"{",
"if",
"len",
"(",
"x",
")",
"<",
"m",
"{",
"p",
".",
"a",
"[",
"i",
"]",
"=",
"make",
"(",
"nat",
",",
"m",
")",
"\n",
"copy",
"(",
"p",
".",
"a",
"[",
"i",
"]",
",",
"x",
")",
"\n",
"break",
"\n",
"}",
"\n",
"p",
".",
"a",
"[",
"i",
"]",
"=",
"x",
"[",
":",
"m",
"]",
"\n",
"x",
"=",
"x",
"[",
"m",
":",
"]",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] |
// polyFromNat slices the number x into a polynomial
// with 1<<k coefficients made of m words.
|
[
"polyFromNat",
"slices",
"the",
"number",
"x",
"into",
"a",
"polynomial",
"with",
"1<<k",
"coefficients",
"made",
"of",
"m",
"words",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fft.go#L119-L133
|
16,254 |
remyoudompheng/bigfft
|
fft.go
|
Int
|
func (p *poly) Int() nat {
length := len(p.a)*p.m + 1
if na := len(p.a); na > 0 {
length += len(p.a[na-1])
}
n := make(nat, length)
m := p.m
np := n
for i := range p.a {
l := len(p.a[i])
c := addVV(np[:l], np[:l], p.a[i])
if np[l] < ^big.Word(0) {
np[l] += c
} else {
addVW(np[l:], np[l:], c)
}
np = np[m:]
}
n = trim(n)
return n
}
|
go
|
func (p *poly) Int() nat {
length := len(p.a)*p.m + 1
if na := len(p.a); na > 0 {
length += len(p.a[na-1])
}
n := make(nat, length)
m := p.m
np := n
for i := range p.a {
l := len(p.a[i])
c := addVV(np[:l], np[:l], p.a[i])
if np[l] < ^big.Word(0) {
np[l] += c
} else {
addVW(np[l:], np[l:], c)
}
np = np[m:]
}
n = trim(n)
return n
}
|
[
"func",
"(",
"p",
"*",
"poly",
")",
"Int",
"(",
")",
"nat",
"{",
"length",
":=",
"len",
"(",
"p",
".",
"a",
")",
"*",
"p",
".",
"m",
"+",
"1",
"\n",
"if",
"na",
":=",
"len",
"(",
"p",
".",
"a",
")",
";",
"na",
">",
"0",
"{",
"length",
"+=",
"len",
"(",
"p",
".",
"a",
"[",
"na",
"-",
"1",
"]",
")",
"\n",
"}",
"\n",
"n",
":=",
"make",
"(",
"nat",
",",
"length",
")",
"\n",
"m",
":=",
"p",
".",
"m",
"\n",
"np",
":=",
"n",
"\n",
"for",
"i",
":=",
"range",
"p",
".",
"a",
"{",
"l",
":=",
"len",
"(",
"p",
".",
"a",
"[",
"i",
"]",
")",
"\n",
"c",
":=",
"addVV",
"(",
"np",
"[",
":",
"l",
"]",
",",
"np",
"[",
":",
"l",
"]",
",",
"p",
".",
"a",
"[",
"i",
"]",
")",
"\n",
"if",
"np",
"[",
"l",
"]",
"<",
"^",
"big",
".",
"Word",
"(",
"0",
")",
"{",
"np",
"[",
"l",
"]",
"+=",
"c",
"\n",
"}",
"else",
"{",
"addVW",
"(",
"np",
"[",
"l",
":",
"]",
",",
"np",
"[",
"l",
":",
"]",
",",
"c",
")",
"\n",
"}",
"\n",
"np",
"=",
"np",
"[",
"m",
":",
"]",
"\n",
"}",
"\n",
"n",
"=",
"trim",
"(",
"n",
")",
"\n",
"return",
"n",
"\n",
"}"
] |
// Int evaluates back a poly to its integer value.
|
[
"Int",
"evaluates",
"back",
"a",
"poly",
"to",
"its",
"integer",
"value",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fft.go#L136-L156
|
16,255 |
remyoudompheng/bigfft
|
fft.go
|
Mul
|
func (p *poly) Mul(q *poly) poly {
// extra=2 because:
// * some power of 2 is a K-th root of unity when n is a multiple of K/2.
// * 2 itself is a square (see fermat.ShiftHalf)
n := valueSize(p.k, p.m, 2)
pv, qv := p.Transform(n), q.Transform(n)
rv := pv.Mul(&qv)
r := rv.InvTransform()
r.m = p.m
return r
}
|
go
|
func (p *poly) Mul(q *poly) poly {
// extra=2 because:
// * some power of 2 is a K-th root of unity when n is a multiple of K/2.
// * 2 itself is a square (see fermat.ShiftHalf)
n := valueSize(p.k, p.m, 2)
pv, qv := p.Transform(n), q.Transform(n)
rv := pv.Mul(&qv)
r := rv.InvTransform()
r.m = p.m
return r
}
|
[
"func",
"(",
"p",
"*",
"poly",
")",
"Mul",
"(",
"q",
"*",
"poly",
")",
"poly",
"{",
"// extra=2 because:",
"// * some power of 2 is a K-th root of unity when n is a multiple of K/2.",
"// * 2 itself is a square (see fermat.ShiftHalf)",
"n",
":=",
"valueSize",
"(",
"p",
".",
"k",
",",
"p",
".",
"m",
",",
"2",
")",
"\n\n",
"pv",
",",
"qv",
":=",
"p",
".",
"Transform",
"(",
"n",
")",
",",
"q",
".",
"Transform",
"(",
"n",
")",
"\n",
"rv",
":=",
"pv",
".",
"Mul",
"(",
"&",
"qv",
")",
"\n",
"r",
":=",
"rv",
".",
"InvTransform",
"(",
")",
"\n",
"r",
".",
"m",
"=",
"p",
".",
"m",
"\n",
"return",
"r",
"\n",
"}"
] |
// Mul multiplies p and q modulo X^K-1, where K = 1<<p.k.
// The product is done via a Fourier transform.
|
[
"Mul",
"multiplies",
"p",
"and",
"q",
"modulo",
"X^K",
"-",
"1",
"where",
"K",
"=",
"1<<p",
".",
"k",
".",
"The",
"product",
"is",
"done",
"via",
"a",
"Fourier",
"transform",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fft.go#L169-L180
|
16,256 |
remyoudompheng/bigfft
|
fft.go
|
InvNTransform
|
func (v *polValues) InvNTransform() poly {
k := v.k
n := v.n
θshift := (n * _W) >> k
// Perform an inverse Fourier transform to recover q.
qbits := make([]big.Word, (n+1)<<k)
q := make([]fermat, 1<<k)
for i := range q {
q[i] = fermat(qbits[i*(n+1) : (i+1)*(n+1)])
}
fourier(q, v.values, true, n, k)
// Divide by K, and untwist q to recover p.
u := make(fermat, n+1)
a := make([]nat, 1<<k)
for i := range q {
u.Shift(q[i], -int(k)-i*θshift)
copy(q[i], u)
a[i] = nat(q[i])
}
return poly{k: k, m: 0, a: a}
}
|
go
|
func (v *polValues) InvNTransform() poly {
k := v.k
n := v.n
θshift := (n * _W) >> k
// Perform an inverse Fourier transform to recover q.
qbits := make([]big.Word, (n+1)<<k)
q := make([]fermat, 1<<k)
for i := range q {
q[i] = fermat(qbits[i*(n+1) : (i+1)*(n+1)])
}
fourier(q, v.values, true, n, k)
// Divide by K, and untwist q to recover p.
u := make(fermat, n+1)
a := make([]nat, 1<<k)
for i := range q {
u.Shift(q[i], -int(k)-i*θshift)
copy(q[i], u)
a[i] = nat(q[i])
}
return poly{k: k, m: 0, a: a}
}
|
[
"func",
"(",
"v",
"*",
"polValues",
")",
"InvNTransform",
"(",
")",
"poly",
"{",
"k",
":=",
"v",
".",
"k",
"\n",
"n",
":=",
"v",
".",
"n",
"\n",
"θshift ",
"= ",
"n",
" ",
" ",
"W)",
" ",
"> ",
"",
"\n\n",
"// Perform an inverse Fourier transform to recover q.",
"qbits",
":=",
"make",
"(",
"[",
"]",
"big",
".",
"Word",
",",
"(",
"n",
"+",
"1",
")",
"<<",
"k",
")",
"\n",
"q",
":=",
"make",
"(",
"[",
"]",
"fermat",
",",
"1",
"<<",
"k",
")",
"\n",
"for",
"i",
":=",
"range",
"q",
"{",
"q",
"[",
"i",
"]",
"=",
"fermat",
"(",
"qbits",
"[",
"i",
"*",
"(",
"n",
"+",
"1",
")",
":",
"(",
"i",
"+",
"1",
")",
"*",
"(",
"n",
"+",
"1",
")",
"]",
")",
"\n",
"}",
"\n",
"fourier",
"(",
"q",
",",
"v",
".",
"values",
",",
"true",
",",
"n",
",",
"k",
")",
"\n\n",
"// Divide by K, and untwist q to recover p.",
"u",
":=",
"make",
"(",
"fermat",
",",
"n",
"+",
"1",
")",
"\n",
"a",
":=",
"make",
"(",
"[",
"]",
"nat",
",",
"1",
"<<",
"k",
")",
"\n",
"for",
"i",
":=",
"range",
"q",
"{",
"u",
".",
"Shift",
"(",
"q",
"[",
"i",
"]",
",",
"-",
"int",
"(",
"k",
")",
"-",
"i",
"*",
"θshift)",
"",
"\n",
"copy",
"(",
"q",
"[",
"i",
"]",
",",
"u",
")",
"\n",
"a",
"[",
"i",
"]",
"=",
"nat",
"(",
"q",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"return",
"poly",
"{",
"k",
":",
"k",
",",
"m",
":",
"0",
",",
"a",
":",
"a",
"}",
"\n",
"}"
] |
// InvTransform reconstructs a polynomial from its values at
// roots of x^K+1. The m field of the returned polynomial
// is unspecified.
|
[
"InvTransform",
"reconstructs",
"a",
"polynomial",
"from",
"its",
"values",
"at",
"roots",
"of",
"x^K",
"+",
"1",
".",
"The",
"m",
"field",
"of",
"the",
"returned",
"polynomial",
"is",
"unspecified",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fft.go#L275-L297
|
16,257 |
remyoudompheng/bigfft
|
fft.go
|
fourier
|
func fourier(dst []fermat, src []fermat, backward bool, n int, k uint) {
var rec func(dst, src []fermat, size uint)
tmp := make(fermat, n+1) // pre-allocate temporary variables.
tmp2 := make(fermat, n+1) // pre-allocate temporary variables.
// The recursion function of the FFT.
// The root of unity used in the transform is ω=1<<(ω2shift/2).
// The source array may use shifted indices (i.e. the i-th
// element is src[i << idxShift]).
rec = func(dst, src []fermat, size uint) {
idxShift := k - size
ω2shift := (4 * n * _W) >> size
if backward {
ω2shift = -ω2shift
}
// Easy cases.
if len(src[0]) != n+1 || len(dst[0]) != n+1 {
panic("len(src[0]) != n+1 || len(dst[0]) != n+1")
}
switch size {
case 0:
copy(dst[0], src[0])
return
case 1:
dst[0].Add(src[0], src[1<<idxShift]) // dst[0] = src[0] + src[1]
dst[1].Sub(src[0], src[1<<idxShift]) // dst[1] = src[0] - src[1]
return
}
// Let P(x) = src[0] + src[1<<idxShift] * x + ... + src[K-1 << idxShift] * x^(K-1)
// The P(x) = Q1(x²) + x*Q2(x²)
// where Q1's coefficients are src with indices shifted by 1
// where Q2's coefficients are src[1<<idxShift:] with indices shifted by 1
// Split destination vectors in halves.
dst1 := dst[:1<<(size-1)]
dst2 := dst[1<<(size-1):]
// Transform Q1 and Q2 in the halves.
rec(dst1, src, size-1)
rec(dst2, src[1<<idxShift:], size-1)
// Reconstruct P's transform from transforms of Q1 and Q2.
// dst[i] is dst1[i] + ω^i * dst2[i]
// dst[i + 1<<(k-1)] is dst1[i] + ω^(i+K/2) * dst2[i]
//
for i := range dst1 {
tmp.ShiftHalf(dst2[i], i*ω2shift, tmp2) // ω^i * dst2[i]
dst2[i].Sub(dst1[i], tmp)
dst1[i].Add(dst1[i], tmp)
}
}
rec(dst, src, k)
}
|
go
|
func fourier(dst []fermat, src []fermat, backward bool, n int, k uint) {
var rec func(dst, src []fermat, size uint)
tmp := make(fermat, n+1) // pre-allocate temporary variables.
tmp2 := make(fermat, n+1) // pre-allocate temporary variables.
// The recursion function of the FFT.
// The root of unity used in the transform is ω=1<<(ω2shift/2).
// The source array may use shifted indices (i.e. the i-th
// element is src[i << idxShift]).
rec = func(dst, src []fermat, size uint) {
idxShift := k - size
ω2shift := (4 * n * _W) >> size
if backward {
ω2shift = -ω2shift
}
// Easy cases.
if len(src[0]) != n+1 || len(dst[0]) != n+1 {
panic("len(src[0]) != n+1 || len(dst[0]) != n+1")
}
switch size {
case 0:
copy(dst[0], src[0])
return
case 1:
dst[0].Add(src[0], src[1<<idxShift]) // dst[0] = src[0] + src[1]
dst[1].Sub(src[0], src[1<<idxShift]) // dst[1] = src[0] - src[1]
return
}
// Let P(x) = src[0] + src[1<<idxShift] * x + ... + src[K-1 << idxShift] * x^(K-1)
// The P(x) = Q1(x²) + x*Q2(x²)
// where Q1's coefficients are src with indices shifted by 1
// where Q2's coefficients are src[1<<idxShift:] with indices shifted by 1
// Split destination vectors in halves.
dst1 := dst[:1<<(size-1)]
dst2 := dst[1<<(size-1):]
// Transform Q1 and Q2 in the halves.
rec(dst1, src, size-1)
rec(dst2, src[1<<idxShift:], size-1)
// Reconstruct P's transform from transforms of Q1 and Q2.
// dst[i] is dst1[i] + ω^i * dst2[i]
// dst[i + 1<<(k-1)] is dst1[i] + ω^(i+K/2) * dst2[i]
//
for i := range dst1 {
tmp.ShiftHalf(dst2[i], i*ω2shift, tmp2) // ω^i * dst2[i]
dst2[i].Sub(dst1[i], tmp)
dst1[i].Add(dst1[i], tmp)
}
}
rec(dst, src, k)
}
|
[
"func",
"fourier",
"(",
"dst",
"[",
"]",
"fermat",
",",
"src",
"[",
"]",
"fermat",
",",
"backward",
"bool",
",",
"n",
"int",
",",
"k",
"uint",
")",
"{",
"var",
"rec",
"func",
"(",
"dst",
",",
"src",
"[",
"]",
"fermat",
",",
"size",
"uint",
")",
"\n",
"tmp",
":=",
"make",
"(",
"fermat",
",",
"n",
"+",
"1",
")",
"// pre-allocate temporary variables.",
"\n",
"tmp2",
":=",
"make",
"(",
"fermat",
",",
"n",
"+",
"1",
")",
"// pre-allocate temporary variables.",
"\n\n",
"// The recursion function of the FFT.",
"// The root of unity used in the transform is ω=1<<(ω2shift/2).",
"// The source array may use shifted indices (i.e. the i-th",
"// element is src[i << idxShift]).",
"rec",
"=",
"func",
"(",
"dst",
",",
"src",
"[",
"]",
"fermat",
",",
"size",
"uint",
")",
"{",
"idxShift",
":=",
"k",
"-",
"size",
"\n",
"ω2shift ",
"= ",
"4",
" ",
" ",
" ",
" ",
"W)",
" ",
"> ",
"ize",
"\n",
"if",
"backward",
"{",
"ω2shift ",
" ",
"ω",
"2shift",
"\n",
"}",
"\n\n",
"// Easy cases.",
"if",
"len",
"(",
"src",
"[",
"0",
"]",
")",
"!=",
"n",
"+",
"1",
"||",
"len",
"(",
"dst",
"[",
"0",
"]",
")",
"!=",
"n",
"+",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"switch",
"size",
"{",
"case",
"0",
":",
"copy",
"(",
"dst",
"[",
"0",
"]",
",",
"src",
"[",
"0",
"]",
")",
"\n",
"return",
"\n",
"case",
"1",
":",
"dst",
"[",
"0",
"]",
".",
"Add",
"(",
"src",
"[",
"0",
"]",
",",
"src",
"[",
"1",
"<<",
"idxShift",
"]",
")",
"// dst[0] = src[0] + src[1]",
"\n",
"dst",
"[",
"1",
"]",
".",
"Sub",
"(",
"src",
"[",
"0",
"]",
",",
"src",
"[",
"1",
"<<",
"idxShift",
"]",
")",
"// dst[1] = src[0] - src[1]",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Let P(x) = src[0] + src[1<<idxShift] * x + ... + src[K-1 << idxShift] * x^(K-1)",
"// The P(x) = Q1(x²) + x*Q2(x²)",
"// where Q1's coefficients are src with indices shifted by 1",
"// where Q2's coefficients are src[1<<idxShift:] with indices shifted by 1",
"// Split destination vectors in halves.",
"dst1",
":=",
"dst",
"[",
":",
"1",
"<<",
"(",
"size",
"-",
"1",
")",
"]",
"\n",
"dst2",
":=",
"dst",
"[",
"1",
"<<",
"(",
"size",
"-",
"1",
")",
":",
"]",
"\n",
"// Transform Q1 and Q2 in the halves.",
"rec",
"(",
"dst1",
",",
"src",
",",
"size",
"-",
"1",
")",
"\n",
"rec",
"(",
"dst2",
",",
"src",
"[",
"1",
"<<",
"idxShift",
":",
"]",
",",
"size",
"-",
"1",
")",
"\n\n",
"// Reconstruct P's transform from transforms of Q1 and Q2.",
"// dst[i] is dst1[i] + ω^i * dst2[i]",
"// dst[i + 1<<(k-1)] is dst1[i] + ω^(i+K/2) * dst2[i]",
"//",
"for",
"i",
":=",
"range",
"dst1",
"{",
"tmp",
".",
"ShiftHalf",
"(",
"dst2",
"[",
"i",
"]",
",",
"i",
"*",
"ω2shift,",
" ",
"mp2)",
" ",
"/ ω^i * dst2[i]",
"\n",
"dst2",
"[",
"i",
"]",
".",
"Sub",
"(",
"dst1",
"[",
"i",
"]",
",",
"tmp",
")",
"\n",
"dst1",
"[",
"i",
"]",
".",
"Add",
"(",
"dst1",
"[",
"i",
"]",
",",
"tmp",
")",
"\n",
"}",
"\n",
"}",
"\n",
"rec",
"(",
"dst",
",",
"src",
",",
"k",
")",
"\n",
"}"
] |
// fourier performs an unnormalized Fourier transform
// of src, a length 1<<k vector of numbers modulo b^n+1
// where b = 1<<_W.
|
[
"fourier",
"performs",
"an",
"unnormalized",
"Fourier",
"transform",
"of",
"src",
"a",
"length",
"1<<k",
"vector",
"of",
"numbers",
"modulo",
"b^n",
"+",
"1",
"where",
"b",
"=",
"1<<_W",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fft.go#L302-L355
|
16,258 |
remyoudompheng/bigfft
|
fft.go
|
Mul
|
func (p *polValues) Mul(q *polValues) (r polValues) {
n := p.n
r.k, r.n = p.k, p.n
r.values = make([]fermat, len(p.values))
bits := make([]big.Word, len(p.values)*(n+1))
buf := make(fermat, 8*n)
for i := range r.values {
r.values[i] = bits[i*(n+1) : (i+1)*(n+1)]
z := buf.Mul(p.values[i], q.values[i])
copy(r.values[i], z)
}
return
}
|
go
|
func (p *polValues) Mul(q *polValues) (r polValues) {
n := p.n
r.k, r.n = p.k, p.n
r.values = make([]fermat, len(p.values))
bits := make([]big.Word, len(p.values)*(n+1))
buf := make(fermat, 8*n)
for i := range r.values {
r.values[i] = bits[i*(n+1) : (i+1)*(n+1)]
z := buf.Mul(p.values[i], q.values[i])
copy(r.values[i], z)
}
return
}
|
[
"func",
"(",
"p",
"*",
"polValues",
")",
"Mul",
"(",
"q",
"*",
"polValues",
")",
"(",
"r",
"polValues",
")",
"{",
"n",
":=",
"p",
".",
"n",
"\n",
"r",
".",
"k",
",",
"r",
".",
"n",
"=",
"p",
".",
"k",
",",
"p",
".",
"n",
"\n",
"r",
".",
"values",
"=",
"make",
"(",
"[",
"]",
"fermat",
",",
"len",
"(",
"p",
".",
"values",
")",
")",
"\n",
"bits",
":=",
"make",
"(",
"[",
"]",
"big",
".",
"Word",
",",
"len",
"(",
"p",
".",
"values",
")",
"*",
"(",
"n",
"+",
"1",
")",
")",
"\n",
"buf",
":=",
"make",
"(",
"fermat",
",",
"8",
"*",
"n",
")",
"\n",
"for",
"i",
":=",
"range",
"r",
".",
"values",
"{",
"r",
".",
"values",
"[",
"i",
"]",
"=",
"bits",
"[",
"i",
"*",
"(",
"n",
"+",
"1",
")",
":",
"(",
"i",
"+",
"1",
")",
"*",
"(",
"n",
"+",
"1",
")",
"]",
"\n",
"z",
":=",
"buf",
".",
"Mul",
"(",
"p",
".",
"values",
"[",
"i",
"]",
",",
"q",
".",
"values",
"[",
"i",
"]",
")",
"\n",
"copy",
"(",
"r",
".",
"values",
"[",
"i",
"]",
",",
"z",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Mul returns the pointwise product of p and q.
|
[
"Mul",
"returns",
"the",
"pointwise",
"product",
"of",
"p",
"and",
"q",
"."
] |
2f0d2b0e0001de06353cbb0b73aa00072ecf879a
|
https://github.com/remyoudompheng/bigfft/blob/2f0d2b0e0001de06353cbb0b73aa00072ecf879a/fft.go#L358-L370
|
16,259 |
go-redis/redis_rate
|
rate.go
|
Reset
|
func (l *Limiter) Reset(name string, period time.Duration) error {
secs := int64(period / time.Second)
slot := time.Now().Unix() / secs
name = allowName(name, slot)
return l.redis.Del(name).Err()
}
|
go
|
func (l *Limiter) Reset(name string, period time.Duration) error {
secs := int64(period / time.Second)
slot := time.Now().Unix() / secs
name = allowName(name, slot)
return l.redis.Del(name).Err()
}
|
[
"func",
"(",
"l",
"*",
"Limiter",
")",
"Reset",
"(",
"name",
"string",
",",
"period",
"time",
".",
"Duration",
")",
"error",
"{",
"secs",
":=",
"int64",
"(",
"period",
"/",
"time",
".",
"Second",
")",
"\n",
"slot",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"/",
"secs",
"\n\n",
"name",
"=",
"allowName",
"(",
"name",
",",
"slot",
")",
"\n",
"return",
"l",
".",
"redis",
".",
"Del",
"(",
"name",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] |
// Reset resets the rate limit for the name in the given rate limit period.
|
[
"Reset",
"resets",
"the",
"rate",
"limit",
"for",
"the",
"name",
"in",
"the",
"given",
"rate",
"limit",
"period",
"."
] |
87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3
|
https://github.com/go-redis/redis_rate/blob/87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3/rate.go#L33-L39
|
16,260 |
go-redis/redis_rate
|
rate.go
|
ResetRate
|
func (l *Limiter) ResetRate(name string, rateLimit rate.Limit) error {
if rateLimit == 0 {
return nil
}
if rateLimit == rate.Inf {
return nil
}
_, period := limitPeriod(rateLimit)
slot := time.Now().UnixNano() / period.Nanoseconds()
name = allowRateName(name, period, slot)
return l.redis.Del(name).Err()
}
|
go
|
func (l *Limiter) ResetRate(name string, rateLimit rate.Limit) error {
if rateLimit == 0 {
return nil
}
if rateLimit == rate.Inf {
return nil
}
_, period := limitPeriod(rateLimit)
slot := time.Now().UnixNano() / period.Nanoseconds()
name = allowRateName(name, period, slot)
return l.redis.Del(name).Err()
}
|
[
"func",
"(",
"l",
"*",
"Limiter",
")",
"ResetRate",
"(",
"name",
"string",
",",
"rateLimit",
"rate",
".",
"Limit",
")",
"error",
"{",
"if",
"rateLimit",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"rateLimit",
"==",
"rate",
".",
"Inf",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"_",
",",
"period",
":=",
"limitPeriod",
"(",
"rateLimit",
")",
"\n",
"slot",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
"/",
"period",
".",
"Nanoseconds",
"(",
")",
"\n\n",
"name",
"=",
"allowRateName",
"(",
"name",
",",
"period",
",",
"slot",
")",
"\n",
"return",
"l",
".",
"redis",
".",
"Del",
"(",
"name",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] |
// ResetRate resets the rate limit for the name and limit.
|
[
"ResetRate",
"resets",
"the",
"rate",
"limit",
"for",
"the",
"name",
"and",
"limit",
"."
] |
87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3
|
https://github.com/go-redis/redis_rate/blob/87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3/rate.go#L42-L55
|
16,261 |
go-redis/redis_rate
|
rate.go
|
AllowN
|
func (l *Limiter) AllowN(
name string, maxn int64, period time.Duration, n int64,
) (count int64, delay time.Duration, allow bool) {
secs := int64(period / time.Second)
utime := time.Now().Unix()
slot := utime / secs
delay = time.Duration((slot+1)*secs-utime) * time.Second
if l.Fallback != nil {
allow = l.Fallback.Allow()
}
name = allowName(name, slot)
count, err := l.incr(name, period, n)
if err == nil {
allow = count <= maxn
}
return count, delay, allow
}
|
go
|
func (l *Limiter) AllowN(
name string, maxn int64, period time.Duration, n int64,
) (count int64, delay time.Duration, allow bool) {
secs := int64(period / time.Second)
utime := time.Now().Unix()
slot := utime / secs
delay = time.Duration((slot+1)*secs-utime) * time.Second
if l.Fallback != nil {
allow = l.Fallback.Allow()
}
name = allowName(name, slot)
count, err := l.incr(name, period, n)
if err == nil {
allow = count <= maxn
}
return count, delay, allow
}
|
[
"func",
"(",
"l",
"*",
"Limiter",
")",
"AllowN",
"(",
"name",
"string",
",",
"maxn",
"int64",
",",
"period",
"time",
".",
"Duration",
",",
"n",
"int64",
",",
")",
"(",
"count",
"int64",
",",
"delay",
"time",
".",
"Duration",
",",
"allow",
"bool",
")",
"{",
"secs",
":=",
"int64",
"(",
"period",
"/",
"time",
".",
"Second",
")",
"\n",
"utime",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"slot",
":=",
"utime",
"/",
"secs",
"\n",
"delay",
"=",
"time",
".",
"Duration",
"(",
"(",
"slot",
"+",
"1",
")",
"*",
"secs",
"-",
"utime",
")",
"*",
"time",
".",
"Second",
"\n\n",
"if",
"l",
".",
"Fallback",
"!=",
"nil",
"{",
"allow",
"=",
"l",
".",
"Fallback",
".",
"Allow",
"(",
")",
"\n",
"}",
"\n\n",
"name",
"=",
"allowName",
"(",
"name",
",",
"slot",
")",
"\n",
"count",
",",
"err",
":=",
"l",
".",
"incr",
"(",
"name",
",",
"period",
",",
"n",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"allow",
"=",
"count",
"<=",
"maxn",
"\n",
"}",
"\n\n",
"return",
"count",
",",
"delay",
",",
"allow",
"\n",
"}"
] |
// AllowN reports whether an event with given name may happen at time now.
// It allows up to maxn events within period, with each interaction
// incrementing the limit by n.
|
[
"AllowN",
"reports",
"whether",
"an",
"event",
"with",
"given",
"name",
"may",
"happen",
"at",
"time",
"now",
".",
"It",
"allows",
"up",
"to",
"maxn",
"events",
"within",
"period",
"with",
"each",
"interaction",
"incrementing",
"the",
"limit",
"by",
"n",
"."
] |
87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3
|
https://github.com/go-redis/redis_rate/blob/87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3/rate.go#L60-L79
|
16,262 |
go-redis/redis_rate
|
rate.go
|
AllowRate
|
func (l *Limiter) AllowRate(name string, rateLimit rate.Limit) (delay time.Duration, allow bool) {
if rateLimit == 0 {
return 0, false
}
if rateLimit == rate.Inf {
return 0, true
}
limit, period := limitPeriod(rateLimit)
now := time.Now()
slot := now.UnixNano() / period.Nanoseconds()
name = allowRateName(name, period, slot)
count, err := l.incr(name, period, 1)
if err == nil {
allow = count <= limit
} else if l.Fallback != nil {
allow = l.Fallback.Allow()
}
if !allow {
delay = time.Duration(slot+1)*period - time.Duration(now.UnixNano())
}
return delay, allow
}
|
go
|
func (l *Limiter) AllowRate(name string, rateLimit rate.Limit) (delay time.Duration, allow bool) {
if rateLimit == 0 {
return 0, false
}
if rateLimit == rate.Inf {
return 0, true
}
limit, period := limitPeriod(rateLimit)
now := time.Now()
slot := now.UnixNano() / period.Nanoseconds()
name = allowRateName(name, period, slot)
count, err := l.incr(name, period, 1)
if err == nil {
allow = count <= limit
} else if l.Fallback != nil {
allow = l.Fallback.Allow()
}
if !allow {
delay = time.Duration(slot+1)*period - time.Duration(now.UnixNano())
}
return delay, allow
}
|
[
"func",
"(",
"l",
"*",
"Limiter",
")",
"AllowRate",
"(",
"name",
"string",
",",
"rateLimit",
"rate",
".",
"Limit",
")",
"(",
"delay",
"time",
".",
"Duration",
",",
"allow",
"bool",
")",
"{",
"if",
"rateLimit",
"==",
"0",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n",
"if",
"rateLimit",
"==",
"rate",
".",
"Inf",
"{",
"return",
"0",
",",
"true",
"\n",
"}",
"\n\n",
"limit",
",",
"period",
":=",
"limitPeriod",
"(",
"rateLimit",
")",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"slot",
":=",
"now",
".",
"UnixNano",
"(",
")",
"/",
"period",
".",
"Nanoseconds",
"(",
")",
"\n\n",
"name",
"=",
"allowRateName",
"(",
"name",
",",
"period",
",",
"slot",
")",
"\n",
"count",
",",
"err",
":=",
"l",
".",
"incr",
"(",
"name",
",",
"period",
",",
"1",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"allow",
"=",
"count",
"<=",
"limit",
"\n",
"}",
"else",
"if",
"l",
".",
"Fallback",
"!=",
"nil",
"{",
"allow",
"=",
"l",
".",
"Fallback",
".",
"Allow",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"allow",
"{",
"delay",
"=",
"time",
".",
"Duration",
"(",
"slot",
"+",
"1",
")",
"*",
"period",
"-",
"time",
".",
"Duration",
"(",
"now",
".",
"UnixNano",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"delay",
",",
"allow",
"\n",
"}"
] |
// AllowRate reports whether an event may happen at time now.
// It allows up to rateLimit events each second.
|
[
"AllowRate",
"reports",
"whether",
"an",
"event",
"may",
"happen",
"at",
"time",
"now",
".",
"It",
"allows",
"up",
"to",
"rateLimit",
"events",
"each",
"second",
"."
] |
87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3
|
https://github.com/go-redis/redis_rate/blob/87f829b37c2c4902cd7d16e1a20bd3e1eb7513e3/rate.go#L98-L123
|
16,263 |
ipfs/ipfs-update
|
lib/install.go
|
StashOldBinary
|
func StashOldBinary(tag string, keep bool) (string, error) {
loc, err := exec.LookPath(util.OsExeFileName("ipfs"))
if err != nil {
return "", fmt.Errorf("could not find old binary: %s", err)
}
loc, err = filepath.Abs(loc)
if err != nil {
return "", fmt.Errorf("could not determine absolute path for old binary: %s", err)
}
ipfsdir := util.IpfsDir()
olddir := filepath.Join(ipfsdir, "old-bin")
npath := filepath.Join(olddir, "ipfs-"+tag)
pathpath := filepath.Join(olddir, "path-old")
err = os.MkdirAll(olddir, 0700)
if err != nil {
return "", fmt.Errorf("could not create dir to backup old binary: %s", err)
}
// write the old path of the binary to the backup dir
err = ioutil.WriteFile(pathpath, []byte(loc), 0644)
if err != nil {
return "", fmt.Errorf("could not stash path: %s", err)
}
f := util.Move
if keep {
f = util.CopyTo
}
stump.VLog(" - moving %s to %s", loc, npath)
err = f(loc, npath)
if err != nil {
return "", fmt.Errorf("could not move old binary: %s", err)
}
return loc, nil
}
|
go
|
func StashOldBinary(tag string, keep bool) (string, error) {
loc, err := exec.LookPath(util.OsExeFileName("ipfs"))
if err != nil {
return "", fmt.Errorf("could not find old binary: %s", err)
}
loc, err = filepath.Abs(loc)
if err != nil {
return "", fmt.Errorf("could not determine absolute path for old binary: %s", err)
}
ipfsdir := util.IpfsDir()
olddir := filepath.Join(ipfsdir, "old-bin")
npath := filepath.Join(olddir, "ipfs-"+tag)
pathpath := filepath.Join(olddir, "path-old")
err = os.MkdirAll(olddir, 0700)
if err != nil {
return "", fmt.Errorf("could not create dir to backup old binary: %s", err)
}
// write the old path of the binary to the backup dir
err = ioutil.WriteFile(pathpath, []byte(loc), 0644)
if err != nil {
return "", fmt.Errorf("could not stash path: %s", err)
}
f := util.Move
if keep {
f = util.CopyTo
}
stump.VLog(" - moving %s to %s", loc, npath)
err = f(loc, npath)
if err != nil {
return "", fmt.Errorf("could not move old binary: %s", err)
}
return loc, nil
}
|
[
"func",
"StashOldBinary",
"(",
"tag",
"string",
",",
"keep",
"bool",
")",
"(",
"string",
",",
"error",
")",
"{",
"loc",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"util",
".",
"OsExeFileName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"loc",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"loc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"ipfsdir",
":=",
"util",
".",
"IpfsDir",
"(",
")",
"\n\n",
"olddir",
":=",
"filepath",
".",
"Join",
"(",
"ipfsdir",
",",
"\"",
"\"",
")",
"\n",
"npath",
":=",
"filepath",
".",
"Join",
"(",
"olddir",
",",
"\"",
"\"",
"+",
"tag",
")",
"\n",
"pathpath",
":=",
"filepath",
".",
"Join",
"(",
"olddir",
",",
"\"",
"\"",
")",
"\n\n",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"olddir",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// write the old path of the binary to the backup dir",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"pathpath",
",",
"[",
"]",
"byte",
"(",
"loc",
")",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"f",
":=",
"util",
".",
"Move",
"\n",
"if",
"keep",
"{",
"f",
"=",
"util",
".",
"CopyTo",
"\n",
"}",
"\n\n",
"stump",
".",
"VLog",
"(",
"\"",
"\"",
",",
"loc",
",",
"npath",
")",
"\n",
"err",
"=",
"f",
"(",
"loc",
",",
"npath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"loc",
",",
"nil",
"\n",
"}"
] |
// StashOldBinary moves the existing ipfs binary to a backup directory
// and returns the path to the original location of the old binary
|
[
"StashOldBinary",
"moves",
"the",
"existing",
"ipfs",
"binary",
"to",
"a",
"backup",
"directory",
"and",
"returns",
"the",
"path",
"to",
"the",
"original",
"location",
"of",
"the",
"old",
"binary"
] |
596d840f5ca157fda37fcbbf72b91680edcc7b4c
|
https://github.com/ipfs/ipfs-update/blob/596d840f5ca157fda37fcbbf72b91680edcc7b4c/lib/install.go#L182-L221
|
16,264 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
checkVersionAbove
|
func checkVersionAbove(major, minor, micro uint) bool {
return (verMajor > major) ||
(verMajor == major && verMinor > minor) ||
(verMajor == major && verMinor == minor && verMicro >= micro)
}
|
go
|
func checkVersionAbove(major, minor, micro uint) bool {
return (verMajor > major) ||
(verMajor == major && verMinor > minor) ||
(verMajor == major && verMinor == minor && verMicro >= micro)
}
|
[
"func",
"checkVersionAbove",
"(",
"major",
",",
"minor",
",",
"micro",
"uint",
")",
"bool",
"{",
"return",
"(",
"verMajor",
">",
"major",
")",
"||",
"(",
"verMajor",
"==",
"major",
"&&",
"verMinor",
">",
"minor",
")",
"||",
"(",
"verMajor",
"==",
"major",
"&&",
"verMinor",
"==",
"minor",
"&&",
"verMicro",
">=",
"micro",
")",
"\n",
"}"
] |
// Nonexported functions
// Check if library version is greater than or equal to the given one
|
[
"Nonexported",
"functions",
"Check",
"if",
"library",
"version",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"given",
"one"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L224-L228
|
16,265 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
getApi
|
func getApi() (uint, error) {
api := C.seccomp_api_get()
if api == 0 {
return 0, fmt.Errorf("API level operations are not supported")
}
return uint(api), nil
}
|
go
|
func getApi() (uint, error) {
api := C.seccomp_api_get()
if api == 0 {
return 0, fmt.Errorf("API level operations are not supported")
}
return uint(api), nil
}
|
[
"func",
"getApi",
"(",
")",
"(",
"uint",
",",
"error",
")",
"{",
"api",
":=",
"C",
".",
"seccomp_api_get",
"(",
")",
"\n",
"if",
"api",
"==",
"0",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"uint",
"(",
"api",
")",
",",
"nil",
"\n",
"}"
] |
// Get the API level
|
[
"Get",
"the",
"API",
"level"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L239-L246
|
16,266 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
setApi
|
func setApi(api uint) error {
if retCode := C.seccomp_api_set(C.uint(api)); retCode != 0 {
if syscall.Errno(-1*retCode) == syscall.EOPNOTSUPP {
return fmt.Errorf("API level operations are not supported")
}
return fmt.Errorf("could not set API level: %v", retCode)
}
return nil
}
|
go
|
func setApi(api uint) error {
if retCode := C.seccomp_api_set(C.uint(api)); retCode != 0 {
if syscall.Errno(-1*retCode) == syscall.EOPNOTSUPP {
return fmt.Errorf("API level operations are not supported")
}
return fmt.Errorf("could not set API level: %v", retCode)
}
return nil
}
|
[
"func",
"setApi",
"(",
"api",
"uint",
")",
"error",
"{",
"if",
"retCode",
":=",
"C",
".",
"seccomp_api_set",
"(",
"C",
".",
"uint",
"(",
"api",
")",
")",
";",
"retCode",
"!=",
"0",
"{",
"if",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"==",
"syscall",
".",
"EOPNOTSUPP",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Set the API level
|
[
"Set",
"the",
"API",
"level"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L249-L259
|
16,267 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
getFilterAttr
|
func (f *ScmpFilter) getFilterAttr(attr scmpFilterAttr) (C.uint32_t, error) {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return 0x0, errBadFilter
}
var attribute C.uint32_t
retCode := C.seccomp_attr_get(f.filterCtx, attr.toNative(), &attribute)
if retCode != 0 {
return 0x0, syscall.Errno(-1 * retCode)
}
return attribute, nil
}
|
go
|
func (f *ScmpFilter) getFilterAttr(attr scmpFilterAttr) (C.uint32_t, error) {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return 0x0, errBadFilter
}
var attribute C.uint32_t
retCode := C.seccomp_attr_get(f.filterCtx, attr.toNative(), &attribute)
if retCode != 0 {
return 0x0, syscall.Errno(-1 * retCode)
}
return attribute, nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"getFilterAttr",
"(",
"attr",
"scmpFilterAttr",
")",
"(",
"C",
".",
"uint32_t",
",",
"error",
")",
"{",
"f",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"f",
".",
"valid",
"{",
"return",
"0x0",
",",
"errBadFilter",
"\n",
"}",
"\n\n",
"var",
"attribute",
"C",
".",
"uint32_t",
"\n\n",
"retCode",
":=",
"C",
".",
"seccomp_attr_get",
"(",
"f",
".",
"filterCtx",
",",
"attr",
".",
"toNative",
"(",
")",
",",
"&",
"attribute",
")",
"\n",
"if",
"retCode",
"!=",
"0",
"{",
"return",
"0x0",
",",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"attribute",
",",
"nil",
"\n",
"}"
] |
// Get a raw filter attribute
|
[
"Get",
"a",
"raw",
"filter",
"attribute"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L269-L285
|
16,268 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
setFilterAttr
|
func (f *ScmpFilter) setFilterAttr(attr scmpFilterAttr, value C.uint32_t) error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
retCode := C.seccomp_attr_set(f.filterCtx, attr.toNative(), value)
if retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
go
|
func (f *ScmpFilter) setFilterAttr(attr scmpFilterAttr, value C.uint32_t) error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
retCode := C.seccomp_attr_set(f.filterCtx, attr.toNative(), value)
if retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"setFilterAttr",
"(",
"attr",
"scmpFilterAttr",
",",
"value",
"C",
".",
"uint32_t",
")",
"error",
"{",
"f",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"f",
".",
"valid",
"{",
"return",
"errBadFilter",
"\n",
"}",
"\n\n",
"retCode",
":=",
"C",
".",
"seccomp_attr_set",
"(",
"f",
".",
"filterCtx",
",",
"attr",
".",
"toNative",
"(",
")",
",",
"value",
")",
"\n",
"if",
"retCode",
"!=",
"0",
"{",
"return",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Set a raw filter attribute
|
[
"Set",
"a",
"raw",
"filter",
"attribute"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L288-L302
|
16,269 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
addRuleWrapper
|
func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, length C.uint, cond C.scmp_cast_t) error {
if length != 0 && cond == nil {
return fmt.Errorf("null conditions list, but length is nonzero")
}
var retCode C.int
if exact {
retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
} else {
retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
}
if syscall.Errno(-1*retCode) == syscall.EFAULT {
return fmt.Errorf("unrecognized syscall %#x", int32(call))
} else if syscall.Errno(-1*retCode) == syscall.EPERM {
return fmt.Errorf("requested action matches default action of filter")
} else if syscall.Errno(-1*retCode) == syscall.EINVAL {
return fmt.Errorf("two checks on same syscall argument")
} else if retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
go
|
func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, length C.uint, cond C.scmp_cast_t) error {
if length != 0 && cond == nil {
return fmt.Errorf("null conditions list, but length is nonzero")
}
var retCode C.int
if exact {
retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
} else {
retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
}
if syscall.Errno(-1*retCode) == syscall.EFAULT {
return fmt.Errorf("unrecognized syscall %#x", int32(call))
} else if syscall.Errno(-1*retCode) == syscall.EPERM {
return fmt.Errorf("requested action matches default action of filter")
} else if syscall.Errno(-1*retCode) == syscall.EINVAL {
return fmt.Errorf("two checks on same syscall argument")
} else if retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"addRuleWrapper",
"(",
"call",
"ScmpSyscall",
",",
"action",
"ScmpAction",
",",
"exact",
"bool",
",",
"length",
"C",
".",
"uint",
",",
"cond",
"C",
".",
"scmp_cast_t",
")",
"error",
"{",
"if",
"length",
"!=",
"0",
"&&",
"cond",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"retCode",
"C",
".",
"int",
"\n",
"if",
"exact",
"{",
"retCode",
"=",
"C",
".",
"seccomp_rule_add_exact_array",
"(",
"f",
".",
"filterCtx",
",",
"action",
".",
"toNative",
"(",
")",
",",
"C",
".",
"int",
"(",
"call",
")",
",",
"length",
",",
"cond",
")",
"\n",
"}",
"else",
"{",
"retCode",
"=",
"C",
".",
"seccomp_rule_add_array",
"(",
"f",
".",
"filterCtx",
",",
"action",
".",
"toNative",
"(",
")",
",",
"C",
".",
"int",
"(",
"call",
")",
",",
"length",
",",
"cond",
")",
"\n",
"}",
"\n\n",
"if",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"==",
"syscall",
".",
"EFAULT",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"int32",
"(",
"call",
")",
")",
"\n",
"}",
"else",
"if",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"==",
"syscall",
".",
"EPERM",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"==",
"syscall",
".",
"EINVAL",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"retCode",
"!=",
"0",
"{",
"return",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DOES NOT LOCK OR CHECK VALIDITY
// Assumes caller has already done this
// Wrapper for seccomp_rule_add_... functions
|
[
"DOES",
"NOT",
"LOCK",
"OR",
"CHECK",
"VALIDITY",
"Assumes",
"caller",
"has",
"already",
"done",
"this",
"Wrapper",
"for",
"seccomp_rule_add_",
"...",
"functions"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L307-L330
|
16,270 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
addRuleGeneric
|
func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
if len(conds) == 0 {
if err := f.addRuleWrapper(call, action, exact, 0, nil); err != nil {
return err
}
} else {
// We don't support conditional filtering in library version v2.1
if !checkVersionAbove(2, 2, 1) {
return VersionError{
message: "conditional filtering is not supported",
minimum: "2.2.1",
}
}
argsArr := C.make_arg_cmp_array(C.uint(len(conds)))
if argsArr == nil {
return fmt.Errorf("error allocating memory for conditions")
}
defer C.free(argsArr)
for i, cond := range conds {
C.add_struct_arg_cmp(C.scmp_cast_t(argsArr), C.uint(i),
C.uint(cond.Argument), cond.Op.toNative(),
C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2))
}
if err := f.addRuleWrapper(call, action, exact, C.uint(len(conds)), C.scmp_cast_t(argsArr)); err != nil {
return err
}
}
return nil
}
|
go
|
func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
if len(conds) == 0 {
if err := f.addRuleWrapper(call, action, exact, 0, nil); err != nil {
return err
}
} else {
// We don't support conditional filtering in library version v2.1
if !checkVersionAbove(2, 2, 1) {
return VersionError{
message: "conditional filtering is not supported",
minimum: "2.2.1",
}
}
argsArr := C.make_arg_cmp_array(C.uint(len(conds)))
if argsArr == nil {
return fmt.Errorf("error allocating memory for conditions")
}
defer C.free(argsArr)
for i, cond := range conds {
C.add_struct_arg_cmp(C.scmp_cast_t(argsArr), C.uint(i),
C.uint(cond.Argument), cond.Op.toNative(),
C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2))
}
if err := f.addRuleWrapper(call, action, exact, C.uint(len(conds)), C.scmp_cast_t(argsArr)); err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"addRuleGeneric",
"(",
"call",
"ScmpSyscall",
",",
"action",
"ScmpAction",
",",
"exact",
"bool",
",",
"conds",
"[",
"]",
"ScmpCondition",
")",
"error",
"{",
"f",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"f",
".",
"valid",
"{",
"return",
"errBadFilter",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"conds",
")",
"==",
"0",
"{",
"if",
"err",
":=",
"f",
".",
"addRuleWrapper",
"(",
"call",
",",
"action",
",",
"exact",
",",
"0",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// We don't support conditional filtering in library version v2.1",
"if",
"!",
"checkVersionAbove",
"(",
"2",
",",
"2",
",",
"1",
")",
"{",
"return",
"VersionError",
"{",
"message",
":",
"\"",
"\"",
",",
"minimum",
":",
"\"",
"\"",
",",
"}",
"\n",
"}",
"\n\n",
"argsArr",
":=",
"C",
".",
"make_arg_cmp_array",
"(",
"C",
".",
"uint",
"(",
"len",
"(",
"conds",
")",
")",
")",
"\n",
"if",
"argsArr",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"C",
".",
"free",
"(",
"argsArr",
")",
"\n\n",
"for",
"i",
",",
"cond",
":=",
"range",
"conds",
"{",
"C",
".",
"add_struct_arg_cmp",
"(",
"C",
".",
"scmp_cast_t",
"(",
"argsArr",
")",
",",
"C",
".",
"uint",
"(",
"i",
")",
",",
"C",
".",
"uint",
"(",
"cond",
".",
"Argument",
")",
",",
"cond",
".",
"Op",
".",
"toNative",
"(",
")",
",",
"C",
".",
"uint64_t",
"(",
"cond",
".",
"Operand1",
")",
",",
"C",
".",
"uint64_t",
"(",
"cond",
".",
"Operand2",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"f",
".",
"addRuleWrapper",
"(",
"call",
",",
"action",
",",
"exact",
",",
"C",
".",
"uint",
"(",
"len",
"(",
"conds",
")",
")",
",",
"C",
".",
"scmp_cast_t",
"(",
"argsArr",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Generic add function for filter rules
|
[
"Generic",
"add",
"function",
"for",
"filter",
"rules"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L333-L372
|
16,271 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
sanitizeArch
|
func sanitizeArch(in ScmpArch) error {
if in < archStart || in > archEnd {
return fmt.Errorf("unrecognized architecture %#x", uint(in))
}
if in.toNative() == C.C_ARCH_BAD {
return fmt.Errorf("architecture %v is not supported on this version of the library", in)
}
return nil
}
|
go
|
func sanitizeArch(in ScmpArch) error {
if in < archStart || in > archEnd {
return fmt.Errorf("unrecognized architecture %#x", uint(in))
}
if in.toNative() == C.C_ARCH_BAD {
return fmt.Errorf("architecture %v is not supported on this version of the library", in)
}
return nil
}
|
[
"func",
"sanitizeArch",
"(",
"in",
"ScmpArch",
")",
"error",
"{",
"if",
"in",
"<",
"archStart",
"||",
"in",
">",
"archEnd",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uint",
"(",
"in",
")",
")",
"\n",
"}",
"\n\n",
"if",
"in",
".",
"toNative",
"(",
")",
"==",
"C",
".",
"C_ARCH_BAD",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"in",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Generic Helpers
// Helper - Sanitize Arch token input
|
[
"Generic",
"Helpers",
"Helper",
"-",
"Sanitize",
"Arch",
"token",
"input"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L377-L387
|
16,272 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
toNative
|
func (a ScmpCompareOp) toNative() C.int {
switch a {
case CompareNotEqual:
return C.C_CMP_NE
case CompareLess:
return C.C_CMP_LT
case CompareLessOrEqual:
return C.C_CMP_LE
case CompareEqual:
return C.C_CMP_EQ
case CompareGreaterEqual:
return C.C_CMP_GE
case CompareGreater:
return C.C_CMP_GT
case CompareMaskedEqual:
return C.C_CMP_MASKED_EQ
default:
return 0x0
}
}
|
go
|
func (a ScmpCompareOp) toNative() C.int {
switch a {
case CompareNotEqual:
return C.C_CMP_NE
case CompareLess:
return C.C_CMP_LT
case CompareLessOrEqual:
return C.C_CMP_LE
case CompareEqual:
return C.C_CMP_EQ
case CompareGreaterEqual:
return C.C_CMP_GE
case CompareGreater:
return C.C_CMP_GT
case CompareMaskedEqual:
return C.C_CMP_MASKED_EQ
default:
return 0x0
}
}
|
[
"func",
"(",
"a",
"ScmpCompareOp",
")",
"toNative",
"(",
")",
"C",
".",
"int",
"{",
"switch",
"a",
"{",
"case",
"CompareNotEqual",
":",
"return",
"C",
".",
"C_CMP_NE",
"\n",
"case",
"CompareLess",
":",
"return",
"C",
".",
"C_CMP_LT",
"\n",
"case",
"CompareLessOrEqual",
":",
"return",
"C",
".",
"C_CMP_LE",
"\n",
"case",
"CompareEqual",
":",
"return",
"C",
".",
"C_CMP_EQ",
"\n",
"case",
"CompareGreaterEqual",
":",
"return",
"C",
".",
"C_CMP_GE",
"\n",
"case",
"CompareGreater",
":",
"return",
"C",
".",
"C_CMP_GT",
"\n",
"case",
"CompareMaskedEqual",
":",
"return",
"C",
".",
"C_CMP_MASKED_EQ",
"\n",
"default",
":",
"return",
"0x0",
"\n",
"}",
"\n",
"}"
] |
// Only use with sanitized ops, no error handling
|
[
"Only",
"use",
"with",
"sanitized",
"ops",
"no",
"error",
"handling"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L494-L513
|
16,273 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
toNative
|
func (a ScmpAction) toNative() C.uint32_t {
switch a & 0xFFFF {
case ActKill:
return C.C_ACT_KILL
case ActTrap:
return C.C_ACT_TRAP
case ActErrno:
return C.C_ACT_ERRNO | (C.uint32_t(a) >> 16)
case ActTrace:
return C.C_ACT_TRACE | (C.uint32_t(a) >> 16)
case ActLog:
return C.C_ACT_LOG
case ActAllow:
return C.C_ACT_ALLOW
default:
return 0x0
}
}
|
go
|
func (a ScmpAction) toNative() C.uint32_t {
switch a & 0xFFFF {
case ActKill:
return C.C_ACT_KILL
case ActTrap:
return C.C_ACT_TRAP
case ActErrno:
return C.C_ACT_ERRNO | (C.uint32_t(a) >> 16)
case ActTrace:
return C.C_ACT_TRACE | (C.uint32_t(a) >> 16)
case ActLog:
return C.C_ACT_LOG
case ActAllow:
return C.C_ACT_ALLOW
default:
return 0x0
}
}
|
[
"func",
"(",
"a",
"ScmpAction",
")",
"toNative",
"(",
")",
"C",
".",
"uint32_t",
"{",
"switch",
"a",
"&",
"0xFFFF",
"{",
"case",
"ActKill",
":",
"return",
"C",
".",
"C_ACT_KILL",
"\n",
"case",
"ActTrap",
":",
"return",
"C",
".",
"C_ACT_TRAP",
"\n",
"case",
"ActErrno",
":",
"return",
"C",
".",
"C_ACT_ERRNO",
"|",
"(",
"C",
".",
"uint32_t",
"(",
"a",
")",
">>",
"16",
")",
"\n",
"case",
"ActTrace",
":",
"return",
"C",
".",
"C_ACT_TRACE",
"|",
"(",
"C",
".",
"uint32_t",
"(",
"a",
")",
">>",
"16",
")",
"\n",
"case",
"ActLog",
":",
"return",
"C",
".",
"C_ACT_LOG",
"\n",
"case",
"ActAllow",
":",
"return",
"C",
".",
"C_ACT_ALLOW",
"\n",
"default",
":",
"return",
"0x0",
"\n",
"}",
"\n",
"}"
] |
// Only use with sanitized actions, no error handling
|
[
"Only",
"use",
"with",
"sanitized",
"actions",
"no",
"error",
"handling"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L536-L553
|
16,274 |
seccomp/libseccomp-golang
|
seccomp_internal.go
|
toNative
|
func (a scmpFilterAttr) toNative() uint32 {
switch a {
case filterAttrActDefault:
return uint32(C.C_ATTRIBUTE_DEFAULT)
case filterAttrActBadArch:
return uint32(C.C_ATTRIBUTE_BADARCH)
case filterAttrNNP:
return uint32(C.C_ATTRIBUTE_NNP)
case filterAttrTsync:
return uint32(C.C_ATTRIBUTE_TSYNC)
case filterAttrLog:
return uint32(C.C_ATTRIBUTE_LOG)
default:
return 0x0
}
}
|
go
|
func (a scmpFilterAttr) toNative() uint32 {
switch a {
case filterAttrActDefault:
return uint32(C.C_ATTRIBUTE_DEFAULT)
case filterAttrActBadArch:
return uint32(C.C_ATTRIBUTE_BADARCH)
case filterAttrNNP:
return uint32(C.C_ATTRIBUTE_NNP)
case filterAttrTsync:
return uint32(C.C_ATTRIBUTE_TSYNC)
case filterAttrLog:
return uint32(C.C_ATTRIBUTE_LOG)
default:
return 0x0
}
}
|
[
"func",
"(",
"a",
"scmpFilterAttr",
")",
"toNative",
"(",
")",
"uint32",
"{",
"switch",
"a",
"{",
"case",
"filterAttrActDefault",
":",
"return",
"uint32",
"(",
"C",
".",
"C_ATTRIBUTE_DEFAULT",
")",
"\n",
"case",
"filterAttrActBadArch",
":",
"return",
"uint32",
"(",
"C",
".",
"C_ATTRIBUTE_BADARCH",
")",
"\n",
"case",
"filterAttrNNP",
":",
"return",
"uint32",
"(",
"C",
".",
"C_ATTRIBUTE_NNP",
")",
"\n",
"case",
"filterAttrTsync",
":",
"return",
"uint32",
"(",
"C",
".",
"C_ATTRIBUTE_TSYNC",
")",
"\n",
"case",
"filterAttrLog",
":",
"return",
"uint32",
"(",
"C",
".",
"C_ATTRIBUTE_LOG",
")",
"\n",
"default",
":",
"return",
"0x0",
"\n",
"}",
"\n",
"}"
] |
// Internal only, assumes safe attribute
|
[
"Internal",
"only",
"assumes",
"safe",
"attribute"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp_internal.go#L556-L571
|
16,275 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetArchFromString
|
func GetArchFromString(arch string) (ScmpArch, error) {
if err := ensureSupportedVersion(); err != nil {
return ArchInvalid, err
}
switch strings.ToLower(arch) {
case "x86":
return ArchX86, nil
case "amd64", "x86-64", "x86_64", "x64":
return ArchAMD64, nil
case "x32":
return ArchX32, nil
case "arm":
return ArchARM, nil
case "arm64", "aarch64":
return ArchARM64, nil
case "mips":
return ArchMIPS, nil
case "mips64":
return ArchMIPS64, nil
case "mips64n32":
return ArchMIPS64N32, nil
case "mipsel":
return ArchMIPSEL, nil
case "mipsel64":
return ArchMIPSEL64, nil
case "mipsel64n32":
return ArchMIPSEL64N32, nil
case "ppc":
return ArchPPC, nil
case "ppc64":
return ArchPPC64, nil
case "ppc64le":
return ArchPPC64LE, nil
case "s390":
return ArchS390, nil
case "s390x":
return ArchS390X, nil
default:
return ArchInvalid, fmt.Errorf("cannot convert unrecognized string %q", arch)
}
}
|
go
|
func GetArchFromString(arch string) (ScmpArch, error) {
if err := ensureSupportedVersion(); err != nil {
return ArchInvalid, err
}
switch strings.ToLower(arch) {
case "x86":
return ArchX86, nil
case "amd64", "x86-64", "x86_64", "x64":
return ArchAMD64, nil
case "x32":
return ArchX32, nil
case "arm":
return ArchARM, nil
case "arm64", "aarch64":
return ArchARM64, nil
case "mips":
return ArchMIPS, nil
case "mips64":
return ArchMIPS64, nil
case "mips64n32":
return ArchMIPS64N32, nil
case "mipsel":
return ArchMIPSEL, nil
case "mipsel64":
return ArchMIPSEL64, nil
case "mipsel64n32":
return ArchMIPSEL64N32, nil
case "ppc":
return ArchPPC, nil
case "ppc64":
return ArchPPC64, nil
case "ppc64le":
return ArchPPC64LE, nil
case "s390":
return ArchS390, nil
case "s390x":
return ArchS390X, nil
default:
return ArchInvalid, fmt.Errorf("cannot convert unrecognized string %q", arch)
}
}
|
[
"func",
"GetArchFromString",
"(",
"arch",
"string",
")",
"(",
"ScmpArch",
",",
"error",
")",
"{",
"if",
"err",
":=",
"ensureSupportedVersion",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ArchInvalid",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"strings",
".",
"ToLower",
"(",
"arch",
")",
"{",
"case",
"\"",
"\"",
":",
"return",
"ArchX86",
",",
"nil",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"ArchAMD64",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchX32",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchARM",
",",
"nil",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"ArchARM64",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchMIPS",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchMIPS64",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchMIPS64N32",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchMIPSEL",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchMIPSEL64",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchMIPSEL64N32",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchPPC",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchPPC64",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchPPC64LE",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchS390",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ArchS390X",
",",
"nil",
"\n",
"default",
":",
"return",
"ArchInvalid",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"arch",
")",
"\n",
"}",
"\n",
"}"
] |
// Helpers for types
// GetArchFromString returns an ScmpArch constant from a string representing an
// architecture
|
[
"Helpers",
"for",
"types",
"GetArchFromString",
"returns",
"an",
"ScmpArch",
"constant",
"from",
"a",
"string",
"representing",
"an",
"architecture"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L179-L220
|
16,276 |
seccomp/libseccomp-golang
|
seccomp.go
|
String
|
func (a ScmpArch) String() string {
switch a {
case ArchX86:
return "x86"
case ArchAMD64:
return "amd64"
case ArchX32:
return "x32"
case ArchARM:
return "arm"
case ArchARM64:
return "arm64"
case ArchMIPS:
return "mips"
case ArchMIPS64:
return "mips64"
case ArchMIPS64N32:
return "mips64n32"
case ArchMIPSEL:
return "mipsel"
case ArchMIPSEL64:
return "mipsel64"
case ArchMIPSEL64N32:
return "mipsel64n32"
case ArchPPC:
return "ppc"
case ArchPPC64:
return "ppc64"
case ArchPPC64LE:
return "ppc64le"
case ArchS390:
return "s390"
case ArchS390X:
return "s390x"
case ArchNative:
return "native"
case ArchInvalid:
return "Invalid architecture"
default:
return fmt.Sprintf("Unknown architecture %#x", uint(a))
}
}
|
go
|
func (a ScmpArch) String() string {
switch a {
case ArchX86:
return "x86"
case ArchAMD64:
return "amd64"
case ArchX32:
return "x32"
case ArchARM:
return "arm"
case ArchARM64:
return "arm64"
case ArchMIPS:
return "mips"
case ArchMIPS64:
return "mips64"
case ArchMIPS64N32:
return "mips64n32"
case ArchMIPSEL:
return "mipsel"
case ArchMIPSEL64:
return "mipsel64"
case ArchMIPSEL64N32:
return "mipsel64n32"
case ArchPPC:
return "ppc"
case ArchPPC64:
return "ppc64"
case ArchPPC64LE:
return "ppc64le"
case ArchS390:
return "s390"
case ArchS390X:
return "s390x"
case ArchNative:
return "native"
case ArchInvalid:
return "Invalid architecture"
default:
return fmt.Sprintf("Unknown architecture %#x", uint(a))
}
}
|
[
"func",
"(",
"a",
"ScmpArch",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"a",
"{",
"case",
"ArchX86",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchAMD64",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchX32",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchARM",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchARM64",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchMIPS",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchMIPS64",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchMIPS64N32",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchMIPSEL",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchMIPSEL64",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchMIPSEL64N32",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchPPC",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchPPC64",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchPPC64LE",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchS390",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchS390X",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchNative",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ArchInvalid",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uint",
"(",
"a",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// String returns a string representation of an architecture constant
|
[
"String",
"returns",
"a",
"string",
"representation",
"of",
"an",
"architecture",
"constant"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L223-L264
|
16,277 |
seccomp/libseccomp-golang
|
seccomp.go
|
String
|
func (a ScmpCompareOp) String() string {
switch a {
case CompareNotEqual:
return "Not equal"
case CompareLess:
return "Less than"
case CompareLessOrEqual:
return "Less than or equal to"
case CompareEqual:
return "Equal"
case CompareGreaterEqual:
return "Greater than or equal to"
case CompareGreater:
return "Greater than"
case CompareMaskedEqual:
return "Masked equality"
case CompareInvalid:
return "Invalid comparison operator"
default:
return fmt.Sprintf("Unrecognized comparison operator %#x", uint(a))
}
}
|
go
|
func (a ScmpCompareOp) String() string {
switch a {
case CompareNotEqual:
return "Not equal"
case CompareLess:
return "Less than"
case CompareLessOrEqual:
return "Less than or equal to"
case CompareEqual:
return "Equal"
case CompareGreaterEqual:
return "Greater than or equal to"
case CompareGreater:
return "Greater than"
case CompareMaskedEqual:
return "Masked equality"
case CompareInvalid:
return "Invalid comparison operator"
default:
return fmt.Sprintf("Unrecognized comparison operator %#x", uint(a))
}
}
|
[
"func",
"(",
"a",
"ScmpCompareOp",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"a",
"{",
"case",
"CompareNotEqual",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareLess",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareLessOrEqual",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareEqual",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareGreaterEqual",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareGreater",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareMaskedEqual",
":",
"return",
"\"",
"\"",
"\n",
"case",
"CompareInvalid",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uint",
"(",
"a",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// String returns a string representation of a comparison operator constant
|
[
"String",
"returns",
"a",
"string",
"representation",
"of",
"a",
"comparison",
"operator",
"constant"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L267-L288
|
16,278 |
seccomp/libseccomp-golang
|
seccomp.go
|
String
|
func (a ScmpAction) String() string {
switch a & 0xFFFF {
case ActKill:
return "Action: Kill Process"
case ActTrap:
return "Action: Send SIGSYS"
case ActErrno:
return fmt.Sprintf("Action: Return error code %d", (a >> 16))
case ActTrace:
return fmt.Sprintf("Action: Notify tracing processes with code %d",
(a >> 16))
case ActLog:
return "Action: Log system call"
case ActAllow:
return "Action: Allow system call"
default:
return fmt.Sprintf("Unrecognized Action %#x", uint(a))
}
}
|
go
|
func (a ScmpAction) String() string {
switch a & 0xFFFF {
case ActKill:
return "Action: Kill Process"
case ActTrap:
return "Action: Send SIGSYS"
case ActErrno:
return fmt.Sprintf("Action: Return error code %d", (a >> 16))
case ActTrace:
return fmt.Sprintf("Action: Notify tracing processes with code %d",
(a >> 16))
case ActLog:
return "Action: Log system call"
case ActAllow:
return "Action: Allow system call"
default:
return fmt.Sprintf("Unrecognized Action %#x", uint(a))
}
}
|
[
"func",
"(",
"a",
"ScmpAction",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"a",
"&",
"0xFFFF",
"{",
"case",
"ActKill",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ActTrap",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ActErrno",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"(",
"a",
">>",
"16",
")",
")",
"\n",
"case",
"ActTrace",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"(",
"a",
">>",
"16",
")",
")",
"\n",
"case",
"ActLog",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ActAllow",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uint",
"(",
"a",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// String returns a string representation of a seccomp match action
|
[
"String",
"returns",
"a",
"string",
"representation",
"of",
"a",
"seccomp",
"match",
"action"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L291-L309
|
16,279 |
seccomp/libseccomp-golang
|
seccomp.go
|
SetReturnCode
|
func (a ScmpAction) SetReturnCode(code int16) ScmpAction {
aTmp := a & 0x0000FFFF
if aTmp == ActErrno || aTmp == ActTrace {
return (aTmp | (ScmpAction(code)&0xFFFF)<<16)
}
return a
}
|
go
|
func (a ScmpAction) SetReturnCode(code int16) ScmpAction {
aTmp := a & 0x0000FFFF
if aTmp == ActErrno || aTmp == ActTrace {
return (aTmp | (ScmpAction(code)&0xFFFF)<<16)
}
return a
}
|
[
"func",
"(",
"a",
"ScmpAction",
")",
"SetReturnCode",
"(",
"code",
"int16",
")",
"ScmpAction",
"{",
"aTmp",
":=",
"a",
"&",
"0x0000FFFF",
"\n",
"if",
"aTmp",
"==",
"ActErrno",
"||",
"aTmp",
"==",
"ActTrace",
"{",
"return",
"(",
"aTmp",
"|",
"(",
"ScmpAction",
"(",
"code",
")",
"&",
"0xFFFF",
")",
"<<",
"16",
")",
"\n",
"}",
"\n",
"return",
"a",
"\n",
"}"
] |
// SetReturnCode adds a return code to a supporting ScmpAction, clearing any
// existing code Only valid on ActErrno and ActTrace. Takes no action otherwise.
// Accepts 16-bit return code as argument.
// Returns a valid ScmpAction of the original type with the new error code set.
|
[
"SetReturnCode",
"adds",
"a",
"return",
"code",
"to",
"a",
"supporting",
"ScmpAction",
"clearing",
"any",
"existing",
"code",
"Only",
"valid",
"on",
"ActErrno",
"and",
"ActTrace",
".",
"Takes",
"no",
"action",
"otherwise",
".",
"Accepts",
"16",
"-",
"bit",
"return",
"code",
"as",
"argument",
".",
"Returns",
"a",
"valid",
"ScmpAction",
"of",
"the",
"original",
"type",
"with",
"the",
"new",
"error",
"code",
"set",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L315-L321
|
16,280 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetNameByArch
|
func (s ScmpSyscall) GetNameByArch(arch ScmpArch) (string, error) {
if err := sanitizeArch(arch); err != nil {
return "", err
}
cString := C.seccomp_syscall_resolve_num_arch(arch.toNative(), C.int(s))
if cString == nil {
return "", fmt.Errorf("could not resolve syscall name for %#x", int32(s))
}
defer C.free(unsafe.Pointer(cString))
finalStr := C.GoString(cString)
return finalStr, nil
}
|
go
|
func (s ScmpSyscall) GetNameByArch(arch ScmpArch) (string, error) {
if err := sanitizeArch(arch); err != nil {
return "", err
}
cString := C.seccomp_syscall_resolve_num_arch(arch.toNative(), C.int(s))
if cString == nil {
return "", fmt.Errorf("could not resolve syscall name for %#x", int32(s))
}
defer C.free(unsafe.Pointer(cString))
finalStr := C.GoString(cString)
return finalStr, nil
}
|
[
"func",
"(",
"s",
"ScmpSyscall",
")",
"GetNameByArch",
"(",
"arch",
"ScmpArch",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"sanitizeArch",
"(",
"arch",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"cString",
":=",
"C",
".",
"seccomp_syscall_resolve_num_arch",
"(",
"arch",
".",
"toNative",
"(",
")",
",",
"C",
".",
"int",
"(",
"s",
")",
")",
"\n",
"if",
"cString",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"int32",
"(",
"s",
")",
")",
"\n",
"}",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cString",
")",
")",
"\n\n",
"finalStr",
":=",
"C",
".",
"GoString",
"(",
"cString",
")",
"\n",
"return",
"finalStr",
",",
"nil",
"\n",
"}"
] |
// GetNameByArch retrieves the name of a syscall from its number for a given
// architecture.
// Acts on any syscall number.
// Accepts a valid architecture constant.
// Returns either a string containing the name of the syscall, or an error.
// if the syscall is unrecognized or an issue occurred.
|
[
"GetNameByArch",
"retrieves",
"the",
"name",
"of",
"a",
"syscall",
"from",
"its",
"number",
"for",
"a",
"given",
"architecture",
".",
"Acts",
"on",
"any",
"syscall",
"number",
".",
"Accepts",
"a",
"valid",
"architecture",
"constant",
".",
"Returns",
"either",
"a",
"string",
"containing",
"the",
"name",
"of",
"the",
"syscall",
"or",
"an",
"error",
".",
"if",
"the",
"syscall",
"is",
"unrecognized",
"or",
"an",
"issue",
"occurred",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L371-L384
|
16,281 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetSyscallFromName
|
func GetSyscallFromName(name string) (ScmpSyscall, error) {
if err := ensureSupportedVersion(); err != nil {
return 0, err
}
cString := C.CString(name)
defer C.free(unsafe.Pointer(cString))
result := C.seccomp_syscall_resolve_name(cString)
if result == scmpError {
return 0, fmt.Errorf("could not resolve name to syscall: %q", name)
}
return ScmpSyscall(result), nil
}
|
go
|
func GetSyscallFromName(name string) (ScmpSyscall, error) {
if err := ensureSupportedVersion(); err != nil {
return 0, err
}
cString := C.CString(name)
defer C.free(unsafe.Pointer(cString))
result := C.seccomp_syscall_resolve_name(cString)
if result == scmpError {
return 0, fmt.Errorf("could not resolve name to syscall: %q", name)
}
return ScmpSyscall(result), nil
}
|
[
"func",
"GetSyscallFromName",
"(",
"name",
"string",
")",
"(",
"ScmpSyscall",
",",
"error",
")",
"{",
"if",
"err",
":=",
"ensureSupportedVersion",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"cString",
":=",
"C",
".",
"CString",
"(",
"name",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cString",
")",
")",
"\n\n",
"result",
":=",
"C",
".",
"seccomp_syscall_resolve_name",
"(",
"cString",
")",
"\n",
"if",
"result",
"==",
"scmpError",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"return",
"ScmpSyscall",
"(",
"result",
")",
",",
"nil",
"\n",
"}"
] |
// GetSyscallFromName returns the number of a syscall by name on the kernel's
// native architecture.
// Accepts a string containing the name of a syscall.
// Returns the number of the syscall, or an error if no syscall with that name
// was found.
|
[
"GetSyscallFromName",
"returns",
"the",
"number",
"of",
"a",
"syscall",
"by",
"name",
"on",
"the",
"kernel",
"s",
"native",
"architecture",
".",
"Accepts",
"a",
"string",
"containing",
"the",
"name",
"of",
"a",
"syscall",
".",
"Returns",
"the",
"number",
"of",
"the",
"syscall",
"or",
"an",
"error",
"if",
"no",
"syscall",
"with",
"that",
"name",
"was",
"found",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L391-L405
|
16,282 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetSyscallFromNameByArch
|
func GetSyscallFromNameByArch(name string, arch ScmpArch) (ScmpSyscall, error) {
if err := ensureSupportedVersion(); err != nil {
return 0, err
}
if err := sanitizeArch(arch); err != nil {
return 0, err
}
cString := C.CString(name)
defer C.free(unsafe.Pointer(cString))
result := C.seccomp_syscall_resolve_name_arch(arch.toNative(), cString)
if result == scmpError {
return 0, fmt.Errorf("could not resolve name to syscall: %q on %v", name, arch)
}
return ScmpSyscall(result), nil
}
|
go
|
func GetSyscallFromNameByArch(name string, arch ScmpArch) (ScmpSyscall, error) {
if err := ensureSupportedVersion(); err != nil {
return 0, err
}
if err := sanitizeArch(arch); err != nil {
return 0, err
}
cString := C.CString(name)
defer C.free(unsafe.Pointer(cString))
result := C.seccomp_syscall_resolve_name_arch(arch.toNative(), cString)
if result == scmpError {
return 0, fmt.Errorf("could not resolve name to syscall: %q on %v", name, arch)
}
return ScmpSyscall(result), nil
}
|
[
"func",
"GetSyscallFromNameByArch",
"(",
"name",
"string",
",",
"arch",
"ScmpArch",
")",
"(",
"ScmpSyscall",
",",
"error",
")",
"{",
"if",
"err",
":=",
"ensureSupportedVersion",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sanitizeArch",
"(",
"arch",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"cString",
":=",
"C",
".",
"CString",
"(",
"name",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cString",
")",
")",
"\n\n",
"result",
":=",
"C",
".",
"seccomp_syscall_resolve_name_arch",
"(",
"arch",
".",
"toNative",
"(",
")",
",",
"cString",
")",
"\n",
"if",
"result",
"==",
"scmpError",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"arch",
")",
"\n",
"}",
"\n\n",
"return",
"ScmpSyscall",
"(",
"result",
")",
",",
"nil",
"\n",
"}"
] |
// GetSyscallFromNameByArch returns the number of a syscall by name for a given
// architecture's ABI.
// Accepts the name of a syscall and an architecture constant.
// Returns the number of the syscall, or an error if an invalid architecture is
// passed or a syscall with that name was not found.
|
[
"GetSyscallFromNameByArch",
"returns",
"the",
"number",
"of",
"a",
"syscall",
"by",
"name",
"for",
"a",
"given",
"architecture",
"s",
"ABI",
".",
"Accepts",
"the",
"name",
"of",
"a",
"syscall",
"and",
"an",
"architecture",
"constant",
".",
"Returns",
"the",
"number",
"of",
"the",
"syscall",
"or",
"an",
"error",
"if",
"an",
"invalid",
"architecture",
"is",
"passed",
"or",
"a",
"syscall",
"with",
"that",
"name",
"was",
"not",
"found",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L412-L429
|
16,283 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetNativeArch
|
func GetNativeArch() (ScmpArch, error) {
if err := ensureSupportedVersion(); err != nil {
return ArchInvalid, err
}
arch := C.seccomp_arch_native()
return archFromNative(arch)
}
|
go
|
func GetNativeArch() (ScmpArch, error) {
if err := ensureSupportedVersion(); err != nil {
return ArchInvalid, err
}
arch := C.seccomp_arch_native()
return archFromNative(arch)
}
|
[
"func",
"GetNativeArch",
"(",
")",
"(",
"ScmpArch",
",",
"error",
")",
"{",
"if",
"err",
":=",
"ensureSupportedVersion",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ArchInvalid",
",",
"err",
"\n",
"}",
"\n\n",
"arch",
":=",
"C",
".",
"seccomp_arch_native",
"(",
")",
"\n\n",
"return",
"archFromNative",
"(",
"arch",
")",
"\n",
"}"
] |
// Utility Functions
// GetNativeArch returns architecture token representing the native kernel
// architecture
|
[
"Utility",
"Functions",
"GetNativeArch",
"returns",
"architecture",
"token",
"representing",
"the",
"native",
"kernel",
"architecture"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L477-L485
|
16,284 |
seccomp/libseccomp-golang
|
seccomp.go
|
NewFilter
|
func NewFilter(defaultAction ScmpAction) (*ScmpFilter, error) {
if err := ensureSupportedVersion(); err != nil {
return nil, err
}
if err := sanitizeAction(defaultAction); err != nil {
return nil, err
}
fPtr := C.seccomp_init(defaultAction.toNative())
if fPtr == nil {
return nil, fmt.Errorf("could not create filter")
}
filter := new(ScmpFilter)
filter.filterCtx = fPtr
filter.valid = true
runtime.SetFinalizer(filter, filterFinalizer)
// Enable TSync so all goroutines will receive the same rules
// If the kernel does not support TSYNC, allow us to continue without error
if err := filter.setFilterAttr(filterAttrTsync, 0x1); err != nil && err != syscall.ENOTSUP {
filter.Release()
return nil, fmt.Errorf("could not create filter - error setting tsync bit: %v", err)
}
return filter, nil
}
|
go
|
func NewFilter(defaultAction ScmpAction) (*ScmpFilter, error) {
if err := ensureSupportedVersion(); err != nil {
return nil, err
}
if err := sanitizeAction(defaultAction); err != nil {
return nil, err
}
fPtr := C.seccomp_init(defaultAction.toNative())
if fPtr == nil {
return nil, fmt.Errorf("could not create filter")
}
filter := new(ScmpFilter)
filter.filterCtx = fPtr
filter.valid = true
runtime.SetFinalizer(filter, filterFinalizer)
// Enable TSync so all goroutines will receive the same rules
// If the kernel does not support TSYNC, allow us to continue without error
if err := filter.setFilterAttr(filterAttrTsync, 0x1); err != nil && err != syscall.ENOTSUP {
filter.Release()
return nil, fmt.Errorf("could not create filter - error setting tsync bit: %v", err)
}
return filter, nil
}
|
[
"func",
"NewFilter",
"(",
"defaultAction",
"ScmpAction",
")",
"(",
"*",
"ScmpFilter",
",",
"error",
")",
"{",
"if",
"err",
":=",
"ensureSupportedVersion",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"sanitizeAction",
"(",
"defaultAction",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"fPtr",
":=",
"C",
".",
"seccomp_init",
"(",
"defaultAction",
".",
"toNative",
"(",
")",
")",
"\n",
"if",
"fPtr",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"filter",
":=",
"new",
"(",
"ScmpFilter",
")",
"\n",
"filter",
".",
"filterCtx",
"=",
"fPtr",
"\n",
"filter",
".",
"valid",
"=",
"true",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"filter",
",",
"filterFinalizer",
")",
"\n\n",
"// Enable TSync so all goroutines will receive the same rules",
"// If the kernel does not support TSYNC, allow us to continue without error",
"if",
"err",
":=",
"filter",
".",
"setFilterAttr",
"(",
"filterAttrTsync",
",",
"0x1",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"syscall",
".",
"ENOTSUP",
"{",
"filter",
".",
"Release",
"(",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"filter",
",",
"nil",
"\n",
"}"
] |
// NewFilter creates and returns a new filter context.
// Accepts a default action to be taken for syscalls which match no rules in
// the filter.
// Returns a reference to a valid filter context, or nil and an error if the
// filter context could not be created or an invalid default action was given.
|
[
"NewFilter",
"creates",
"and",
"returns",
"a",
"new",
"filter",
"context",
".",
"Accepts",
"a",
"default",
"action",
"to",
"be",
"taken",
"for",
"syscalls",
"which",
"match",
"no",
"rules",
"in",
"the",
"filter",
".",
"Returns",
"a",
"reference",
"to",
"a",
"valid",
"filter",
"context",
"or",
"nil",
"and",
"an",
"error",
"if",
"the",
"filter",
"context",
"could",
"not",
"be",
"created",
"or",
"an",
"invalid",
"default",
"action",
"was",
"given",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L503-L530
|
16,285 |
seccomp/libseccomp-golang
|
seccomp.go
|
Reset
|
func (f *ScmpFilter) Reset(defaultAction ScmpAction) error {
f.lock.Lock()
defer f.lock.Unlock()
if err := sanitizeAction(defaultAction); err != nil {
return err
} else if !f.valid {
return errBadFilter
}
retCode := C.seccomp_reset(f.filterCtx, defaultAction.toNative())
if retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
go
|
func (f *ScmpFilter) Reset(defaultAction ScmpAction) error {
f.lock.Lock()
defer f.lock.Unlock()
if err := sanitizeAction(defaultAction); err != nil {
return err
} else if !f.valid {
return errBadFilter
}
retCode := C.seccomp_reset(f.filterCtx, defaultAction.toNative())
if retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"Reset",
"(",
"defaultAction",
"ScmpAction",
")",
"error",
"{",
"f",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"err",
":=",
"sanitizeAction",
"(",
"defaultAction",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"!",
"f",
".",
"valid",
"{",
"return",
"errBadFilter",
"\n",
"}",
"\n\n",
"retCode",
":=",
"C",
".",
"seccomp_reset",
"(",
"f",
".",
"filterCtx",
",",
"defaultAction",
".",
"toNative",
"(",
")",
")",
"\n",
"if",
"retCode",
"!=",
"0",
"{",
"return",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Reset resets a filter context, removing all its existing state.
// Accepts a new default action to be taken for syscalls which do not match.
// Returns an error if the filter or action provided are invalid.
|
[
"Reset",
"resets",
"a",
"filter",
"context",
"removing",
"all",
"its",
"existing",
"state",
".",
"Accepts",
"a",
"new",
"default",
"action",
"to",
"be",
"taken",
"for",
"syscalls",
"which",
"do",
"not",
"match",
".",
"Returns",
"an",
"error",
"if",
"the",
"filter",
"or",
"action",
"provided",
"are",
"invalid",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L545-L561
|
16,286 |
seccomp/libseccomp-golang
|
seccomp.go
|
AddArch
|
func (f *ScmpFilter) AddArch(arch ScmpArch) error {
f.lock.Lock()
defer f.lock.Unlock()
if err := sanitizeArch(arch); err != nil {
return err
} else if !f.valid {
return errBadFilter
}
// Libseccomp returns -EEXIST if the specified architecture is already
// present. Succeed silently in this case, as it's not fatal, and the
// architecture is present already.
retCode := C.seccomp_arch_add(f.filterCtx, arch.toNative())
if retCode != 0 && syscall.Errno(-1*retCode) != syscall.EEXIST {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
go
|
func (f *ScmpFilter) AddArch(arch ScmpArch) error {
f.lock.Lock()
defer f.lock.Unlock()
if err := sanitizeArch(arch); err != nil {
return err
} else if !f.valid {
return errBadFilter
}
// Libseccomp returns -EEXIST if the specified architecture is already
// present. Succeed silently in this case, as it's not fatal, and the
// architecture is present already.
retCode := C.seccomp_arch_add(f.filterCtx, arch.toNative())
if retCode != 0 && syscall.Errno(-1*retCode) != syscall.EEXIST {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"AddArch",
"(",
"arch",
"ScmpArch",
")",
"error",
"{",
"f",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"err",
":=",
"sanitizeArch",
"(",
"arch",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"!",
"f",
".",
"valid",
"{",
"return",
"errBadFilter",
"\n",
"}",
"\n\n",
"// Libseccomp returns -EEXIST if the specified architecture is already",
"// present. Succeed silently in this case, as it's not fatal, and the",
"// architecture is present already.",
"retCode",
":=",
"C",
".",
"seccomp_arch_add",
"(",
"f",
".",
"filterCtx",
",",
"arch",
".",
"toNative",
"(",
")",
")",
"\n",
"if",
"retCode",
"!=",
"0",
"&&",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"!=",
"syscall",
".",
"EEXIST",
"{",
"return",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// AddArch adds an architecture to the filter.
// Accepts an architecture constant.
// Returns an error on invalid filter context or architecture token, or an
// issue with the call to libseccomp.
|
[
"AddArch",
"adds",
"an",
"architecture",
"to",
"the",
"filter",
".",
"Accepts",
"an",
"architecture",
"constant",
".",
"Returns",
"an",
"error",
"on",
"invalid",
"filter",
"context",
"or",
"architecture",
"token",
"or",
"an",
"issue",
"with",
"the",
"call",
"to",
"libseccomp",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L651-L670
|
16,287 |
seccomp/libseccomp-golang
|
seccomp.go
|
Load
|
func (f *ScmpFilter) Load() error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
if retCode := C.seccomp_load(f.filterCtx); retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
go
|
func (f *ScmpFilter) Load() error {
f.lock.Lock()
defer f.lock.Unlock()
if !f.valid {
return errBadFilter
}
if retCode := C.seccomp_load(f.filterCtx); retCode != 0 {
return syscall.Errno(-1 * retCode)
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"Load",
"(",
")",
"error",
"{",
"f",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"f",
".",
"valid",
"{",
"return",
"errBadFilter",
"\n",
"}",
"\n\n",
"if",
"retCode",
":=",
"C",
".",
"seccomp_load",
"(",
"f",
".",
"filterCtx",
")",
";",
"retCode",
"!=",
"0",
"{",
"return",
"syscall",
".",
"Errno",
"(",
"-",
"1",
"*",
"retCode",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Load loads a filter context into the kernel.
// Returns an error if the filter context is invalid or the syscall failed.
|
[
"Load",
"loads",
"a",
"filter",
"context",
"into",
"the",
"kernel",
".",
"Returns",
"an",
"error",
"if",
"the",
"filter",
"context",
"is",
"invalid",
"or",
"the",
"syscall",
"failed",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L699-L712
|
16,288 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetDefaultAction
|
func (f *ScmpFilter) GetDefaultAction() (ScmpAction, error) {
action, err := f.getFilterAttr(filterAttrActDefault)
if err != nil {
return 0x0, err
}
return actionFromNative(action)
}
|
go
|
func (f *ScmpFilter) GetDefaultAction() (ScmpAction, error) {
action, err := f.getFilterAttr(filterAttrActDefault)
if err != nil {
return 0x0, err
}
return actionFromNative(action)
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"GetDefaultAction",
"(",
")",
"(",
"ScmpAction",
",",
"error",
")",
"{",
"action",
",",
"err",
":=",
"f",
".",
"getFilterAttr",
"(",
"filterAttrActDefault",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0x0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"actionFromNative",
"(",
"action",
")",
"\n",
"}"
] |
// GetDefaultAction returns the default action taken on a syscall which does not
// match a rule in the filter, or an error if an issue was encountered
// retrieving the value.
|
[
"GetDefaultAction",
"returns",
"the",
"default",
"action",
"taken",
"on",
"a",
"syscall",
"which",
"does",
"not",
"match",
"a",
"rule",
"in",
"the",
"filter",
"or",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"retrieving",
"the",
"value",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L717-L724
|
16,289 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetBadArchAction
|
func (f *ScmpFilter) GetBadArchAction() (ScmpAction, error) {
action, err := f.getFilterAttr(filterAttrActBadArch)
if err != nil {
return 0x0, err
}
return actionFromNative(action)
}
|
go
|
func (f *ScmpFilter) GetBadArchAction() (ScmpAction, error) {
action, err := f.getFilterAttr(filterAttrActBadArch)
if err != nil {
return 0x0, err
}
return actionFromNative(action)
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"GetBadArchAction",
"(",
")",
"(",
"ScmpAction",
",",
"error",
")",
"{",
"action",
",",
"err",
":=",
"f",
".",
"getFilterAttr",
"(",
"filterAttrActBadArch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0x0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"actionFromNative",
"(",
"action",
")",
"\n",
"}"
] |
// GetBadArchAction returns the default action taken on a syscall for an
// architecture not in the filter, or an error if an issue was encountered
// retrieving the value.
|
[
"GetBadArchAction",
"returns",
"the",
"default",
"action",
"taken",
"on",
"a",
"syscall",
"for",
"an",
"architecture",
"not",
"in",
"the",
"filter",
"or",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"retrieving",
"the",
"value",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L729-L736
|
16,290 |
seccomp/libseccomp-golang
|
seccomp.go
|
GetLogBit
|
func (f *ScmpFilter) GetLogBit() (bool, error) {
log, err := f.getFilterAttr(filterAttrLog)
if err != nil {
api, apiErr := getApi()
if (apiErr != nil && api == 0) || (apiErr == nil && api < 3) {
return false, fmt.Errorf("getting the log bit is only supported in libseccomp 2.4.0 and newer with API level 3 or higher")
}
return false, err
}
if log == 0 {
return false, nil
}
return true, nil
}
|
go
|
func (f *ScmpFilter) GetLogBit() (bool, error) {
log, err := f.getFilterAttr(filterAttrLog)
if err != nil {
api, apiErr := getApi()
if (apiErr != nil && api == 0) || (apiErr == nil && api < 3) {
return false, fmt.Errorf("getting the log bit is only supported in libseccomp 2.4.0 and newer with API level 3 or higher")
}
return false, err
}
if log == 0 {
return false, nil
}
return true, nil
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"GetLogBit",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"log",
",",
"err",
":=",
"f",
".",
"getFilterAttr",
"(",
"filterAttrLog",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
",",
"apiErr",
":=",
"getApi",
"(",
")",
"\n",
"if",
"(",
"apiErr",
"!=",
"nil",
"&&",
"api",
"==",
"0",
")",
"||",
"(",
"apiErr",
"==",
"nil",
"&&",
"api",
"<",
"3",
")",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"log",
"==",
"0",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// GetLogBit returns the current state the Log bit will be set to on the filter
// being loaded, or an error if an issue was encountered retrieving the value.
// The Log bit tells the kernel that all actions taken by the filter, with the
// exception of ActAllow, should be logged.
// The Log bit is only usable when libseccomp API level 3 or higher is
// supported.
|
[
"GetLogBit",
"returns",
"the",
"current",
"state",
"the",
"Log",
"bit",
"will",
"be",
"set",
"to",
"on",
"the",
"filter",
"being",
"loaded",
"or",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"retrieving",
"the",
"value",
".",
"The",
"Log",
"bit",
"tells",
"the",
"kernel",
"that",
"all",
"actions",
"taken",
"by",
"the",
"filter",
"with",
"the",
"exception",
"of",
"ActAllow",
"should",
"be",
"logged",
".",
"The",
"Log",
"bit",
"is",
"only",
"usable",
"when",
"libseccomp",
"API",
"level",
"3",
"or",
"higher",
"is",
"supported",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L764-L780
|
16,291 |
seccomp/libseccomp-golang
|
seccomp.go
|
SetBadArchAction
|
func (f *ScmpFilter) SetBadArchAction(action ScmpAction) error {
if err := sanitizeAction(action); err != nil {
return err
}
return f.setFilterAttr(filterAttrActBadArch, action.toNative())
}
|
go
|
func (f *ScmpFilter) SetBadArchAction(action ScmpAction) error {
if err := sanitizeAction(action); err != nil {
return err
}
return f.setFilterAttr(filterAttrActBadArch, action.toNative())
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"SetBadArchAction",
"(",
"action",
"ScmpAction",
")",
"error",
"{",
"if",
"err",
":=",
"sanitizeAction",
"(",
"action",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"f",
".",
"setFilterAttr",
"(",
"filterAttrActBadArch",
",",
"action",
".",
"toNative",
"(",
")",
")",
"\n",
"}"
] |
// SetBadArchAction sets the default action taken on a syscall for an
// architecture not in the filter, or an error if an issue was encountered
// setting the value.
|
[
"SetBadArchAction",
"sets",
"the",
"default",
"action",
"taken",
"on",
"a",
"syscall",
"for",
"an",
"architecture",
"not",
"in",
"the",
"filter",
"or",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"setting",
"the",
"value",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L785-L791
|
16,292 |
seccomp/libseccomp-golang
|
seccomp.go
|
SetNoNewPrivsBit
|
func (f *ScmpFilter) SetNoNewPrivsBit(state bool) error {
var toSet C.uint32_t = 0x0
if state {
toSet = 0x1
}
return f.setFilterAttr(filterAttrNNP, toSet)
}
|
go
|
func (f *ScmpFilter) SetNoNewPrivsBit(state bool) error {
var toSet C.uint32_t = 0x0
if state {
toSet = 0x1
}
return f.setFilterAttr(filterAttrNNP, toSet)
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"SetNoNewPrivsBit",
"(",
"state",
"bool",
")",
"error",
"{",
"var",
"toSet",
"C",
".",
"uint32_t",
"=",
"0x0",
"\n\n",
"if",
"state",
"{",
"toSet",
"=",
"0x1",
"\n",
"}",
"\n\n",
"return",
"f",
".",
"setFilterAttr",
"(",
"filterAttrNNP",
",",
"toSet",
")",
"\n",
"}"
] |
// SetNoNewPrivsBit sets the state of the No New Privileges bit, which will be
// applied on filter load, or an error if an issue was encountered setting the
// value.
// Filters with No New Privileges set to 0 can only be loaded if the process
// has the CAP_SYS_ADMIN capability.
|
[
"SetNoNewPrivsBit",
"sets",
"the",
"state",
"of",
"the",
"No",
"New",
"Privileges",
"bit",
"which",
"will",
"be",
"applied",
"on",
"filter",
"load",
"or",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"setting",
"the",
"value",
".",
"Filters",
"with",
"No",
"New",
"Privileges",
"set",
"to",
"0",
"can",
"only",
"be",
"loaded",
"if",
"the",
"process",
"has",
"the",
"CAP_SYS_ADMIN",
"capability",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L798-L806
|
16,293 |
seccomp/libseccomp-golang
|
seccomp.go
|
SetLogBit
|
func (f *ScmpFilter) SetLogBit(state bool) error {
var toSet C.uint32_t = 0x0
if state {
toSet = 0x1
}
err := f.setFilterAttr(filterAttrLog, toSet)
if err != nil {
api, apiErr := getApi()
if (apiErr != nil && api == 0) || (apiErr == nil && api < 3) {
return fmt.Errorf("setting the log bit is only supported in libseccomp 2.4.0 and newer with API level 3 or higher")
}
}
return err
}
|
go
|
func (f *ScmpFilter) SetLogBit(state bool) error {
var toSet C.uint32_t = 0x0
if state {
toSet = 0x1
}
err := f.setFilterAttr(filterAttrLog, toSet)
if err != nil {
api, apiErr := getApi()
if (apiErr != nil && api == 0) || (apiErr == nil && api < 3) {
return fmt.Errorf("setting the log bit is only supported in libseccomp 2.4.0 and newer with API level 3 or higher")
}
}
return err
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"SetLogBit",
"(",
"state",
"bool",
")",
"error",
"{",
"var",
"toSet",
"C",
".",
"uint32_t",
"=",
"0x0",
"\n\n",
"if",
"state",
"{",
"toSet",
"=",
"0x1",
"\n",
"}",
"\n\n",
"err",
":=",
"f",
".",
"setFilterAttr",
"(",
"filterAttrLog",
",",
"toSet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
",",
"apiErr",
":=",
"getApi",
"(",
")",
"\n",
"if",
"(",
"apiErr",
"!=",
"nil",
"&&",
"api",
"==",
"0",
")",
"||",
"(",
"apiErr",
"==",
"nil",
"&&",
"api",
"<",
"3",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// SetLogBit sets the state of the Log bit, which will be applied on filter
// load, or an error if an issue was encountered setting the value.
// The Log bit is only usable when libseccomp API level 3 or higher is
// supported.
|
[
"SetLogBit",
"sets",
"the",
"state",
"of",
"the",
"Log",
"bit",
"which",
"will",
"be",
"applied",
"on",
"filter",
"load",
"or",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"setting",
"the",
"value",
".",
"The",
"Log",
"bit",
"is",
"only",
"usable",
"when",
"libseccomp",
"API",
"level",
"3",
"or",
"higher",
"is",
"supported",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L812-L828
|
16,294 |
seccomp/libseccomp-golang
|
seccomp.go
|
AddRule
|
func (f *ScmpFilter) AddRule(call ScmpSyscall, action ScmpAction) error {
return f.addRuleGeneric(call, action, false, nil)
}
|
go
|
func (f *ScmpFilter) AddRule(call ScmpSyscall, action ScmpAction) error {
return f.addRuleGeneric(call, action, false, nil)
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"AddRule",
"(",
"call",
"ScmpSyscall",
",",
"action",
"ScmpAction",
")",
"error",
"{",
"return",
"f",
".",
"addRuleGeneric",
"(",
"call",
",",
"action",
",",
"false",
",",
"nil",
")",
"\n",
"}"
] |
// AddRule adds a single rule for an unconditional action on a syscall.
// Accepts the number of the syscall and the action to be taken on the call
// being made.
// Returns an error if an issue was encountered adding the rule.
|
[
"AddRule",
"adds",
"a",
"single",
"rule",
"for",
"an",
"unconditional",
"action",
"on",
"a",
"syscall",
".",
"Accepts",
"the",
"number",
"of",
"the",
"syscall",
"and",
"the",
"action",
"to",
"be",
"taken",
"on",
"the",
"call",
"being",
"made",
".",
"Returns",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"adding",
"the",
"rule",
"."
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L855-L857
|
16,295 |
seccomp/libseccomp-golang
|
seccomp.go
|
AddRuleConditional
|
func (f *ScmpFilter) AddRuleConditional(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error {
return f.addRuleGeneric(call, action, false, conds)
}
|
go
|
func (f *ScmpFilter) AddRuleConditional(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error {
return f.addRuleGeneric(call, action, false, conds)
}
|
[
"func",
"(",
"f",
"*",
"ScmpFilter",
")",
"AddRuleConditional",
"(",
"call",
"ScmpSyscall",
",",
"action",
"ScmpAction",
",",
"conds",
"[",
"]",
"ScmpCondition",
")",
"error",
"{",
"return",
"f",
".",
"addRuleGeneric",
"(",
"call",
",",
"action",
",",
"false",
",",
"conds",
")",
"\n",
"}"
] |
// AddRuleConditional adds a single rule for a conditional action on a syscall.
// Returns an error if an issue was encountered adding the rule.
// All conditions must match for the rule to match.
// There is a bug in library versions below v2.2.1 which can, in some cases,
// cause conditions to be lost when more than one are used. Consequently,
// AddRuleConditional is disabled on library versions lower than v2.2.1
|
[
"AddRuleConditional",
"adds",
"a",
"single",
"rule",
"for",
"a",
"conditional",
"action",
"on",
"a",
"syscall",
".",
"Returns",
"an",
"error",
"if",
"an",
"issue",
"was",
"encountered",
"adding",
"the",
"rule",
".",
"All",
"conditions",
"must",
"match",
"for",
"the",
"rule",
"to",
"match",
".",
"There",
"is",
"a",
"bug",
"in",
"library",
"versions",
"below",
"v2",
".",
"2",
".",
"1",
"which",
"can",
"in",
"some",
"cases",
"cause",
"conditions",
"to",
"be",
"lost",
"when",
"more",
"than",
"one",
"are",
"used",
".",
"Consequently",
"AddRuleConditional",
"is",
"disabled",
"on",
"library",
"versions",
"lower",
"than",
"v2",
".",
"2",
".",
"1"
] |
0353a0bef25711a9c6e041351e13f350c0e075a1
|
https://github.com/seccomp/libseccomp-golang/blob/0353a0bef25711a9c6e041351e13f350c0e075a1/seccomp.go#L877-L879
|
16,296 |
dpapathanasiou/go-recaptcha
|
recaptcha.go
|
check
|
func check(remoteip, response string) (r RecaptchaResponse, err error) {
resp, err := http.PostForm(recaptchaServerName,
url.Values{"secret": {recaptchaPrivateKey}, "remoteip": {remoteip}, "response": {response}})
if err != nil {
log.Printf("Post error: %s\n", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Read error: could not read body: %s", err)
return
}
err = json.Unmarshal(body, &r)
if err != nil {
log.Println("Read error: got invalid JSON: %s", err)
return
}
return
}
|
go
|
func check(remoteip, response string) (r RecaptchaResponse, err error) {
resp, err := http.PostForm(recaptchaServerName,
url.Values{"secret": {recaptchaPrivateKey}, "remoteip": {remoteip}, "response": {response}})
if err != nil {
log.Printf("Post error: %s\n", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Read error: could not read body: %s", err)
return
}
err = json.Unmarshal(body, &r)
if err != nil {
log.Println("Read error: got invalid JSON: %s", err)
return
}
return
}
|
[
"func",
"check",
"(",
"remoteip",
",",
"response",
"string",
")",
"(",
"r",
"RecaptchaResponse",
",",
"err",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"PostForm",
"(",
"recaptchaServerName",
",",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"recaptchaPrivateKey",
"}",
",",
"\"",
"\"",
":",
"{",
"remoteip",
"}",
",",
"\"",
"\"",
":",
"{",
"response",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// check uses the client ip address, the challenge code from the reCaptcha form,
// and the client's response input to that challenge to determine whether or not
// the client answered the reCaptcha input question correctly.
// It returns a boolean value indicating whether or not the client answered correctly.
|
[
"check",
"uses",
"the",
"client",
"ip",
"address",
"the",
"challenge",
"code",
"from",
"the",
"reCaptcha",
"form",
"and",
"the",
"client",
"s",
"response",
"input",
"to",
"that",
"challenge",
"to",
"determine",
"whether",
"or",
"not",
"the",
"client",
"answered",
"the",
"reCaptcha",
"input",
"question",
"correctly",
".",
"It",
"returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"or",
"not",
"the",
"client",
"answered",
"correctly",
"."
] |
be5090b17804c90a577d345b6d67acbf01dc90ed
|
https://github.com/dpapathanasiou/go-recaptcha/blob/be5090b17804c90a577d345b6d67acbf01dc90ed/recaptcha.go#L35-L54
|
16,297 |
dpapathanasiou/go-recaptcha
|
recaptcha.go
|
Confirm
|
func Confirm(remoteip, response string) (result bool, err error) {
resp, err := check(remoteip, response)
result = resp.Success
return
}
|
go
|
func Confirm(remoteip, response string) (result bool, err error) {
resp, err := check(remoteip, response)
result = resp.Success
return
}
|
[
"func",
"Confirm",
"(",
"remoteip",
",",
"response",
"string",
")",
"(",
"result",
"bool",
",",
"err",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"check",
"(",
"remoteip",
",",
"response",
")",
"\n",
"result",
"=",
"resp",
".",
"Success",
"\n",
"return",
"\n",
"}"
] |
// Confirm is the public interface function.
// It calls check, which the client ip address, the challenge code from the reCaptcha form,
// and the client's response input to that challenge to determine whether or not
// the client answered the reCaptcha input question correctly.
// It returns a boolean value indicating whether or not the client answered correctly.
|
[
"Confirm",
"is",
"the",
"public",
"interface",
"function",
".",
"It",
"calls",
"check",
"which",
"the",
"client",
"ip",
"address",
"the",
"challenge",
"code",
"from",
"the",
"reCaptcha",
"form",
"and",
"the",
"client",
"s",
"response",
"input",
"to",
"that",
"challenge",
"to",
"determine",
"whether",
"or",
"not",
"the",
"client",
"answered",
"the",
"reCaptcha",
"input",
"question",
"correctly",
".",
"It",
"returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"or",
"not",
"the",
"client",
"answered",
"correctly",
"."
] |
be5090b17804c90a577d345b6d67acbf01dc90ed
|
https://github.com/dpapathanasiou/go-recaptcha/blob/be5090b17804c90a577d345b6d67acbf01dc90ed/recaptcha.go#L61-L65
|
16,298 |
openfaas/faas-provider
|
auth/basic_auth.go
|
DecorateWithBasicAuth
|
func DecorateWithBasicAuth(next http.HandlerFunc, credentials *BasicAuthCredentials) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, password, ok := r.BasicAuth()
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
if !ok || !(credentials.Password == password && user == credentials.User) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("invalid credentials"))
return
}
next.ServeHTTP(w, r)
}
}
|
go
|
func DecorateWithBasicAuth(next http.HandlerFunc, credentials *BasicAuthCredentials) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, password, ok := r.BasicAuth()
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
if !ok || !(credentials.Password == password && user == credentials.User) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("invalid credentials"))
return
}
next.ServeHTTP(w, r)
}
}
|
[
"func",
"DecorateWithBasicAuth",
"(",
"next",
"http",
".",
"HandlerFunc",
",",
"credentials",
"*",
"BasicAuthCredentials",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"user",
",",
"password",
",",
"ok",
":=",
"r",
".",
"BasicAuth",
"(",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"`Basic realm=\"Restricted\"`",
")",
"\n\n",
"if",
"!",
"ok",
"||",
"!",
"(",
"credentials",
".",
"Password",
"==",
"password",
"&&",
"user",
"==",
"credentials",
".",
"User",
")",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// DecorateWithBasicAuth enforces basic auth as a middleware with given credentials
|
[
"DecorateWithBasicAuth",
"enforces",
"basic",
"auth",
"as",
"a",
"middleware",
"with",
"given",
"credentials"
] |
6a76a052deb12fd94b373c082963d8a8ad44d4d1
|
https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/auth/basic_auth.go#L11-L26
|
16,299 |
openfaas/faas-provider
|
proxy/proxy.go
|
proxyRequest
|
func proxyRequest(w http.ResponseWriter, originalReq *http.Request, proxyClient http.Client, resolver BaseURLResolver) {
ctx := originalReq.Context()
pathVars := mux.Vars(originalReq)
functionName := pathVars["name"]
if functionName == "" {
writeError(w, http.StatusBadRequest, errMissingFunctionName)
return
}
functionAddr, resolveErr := resolver.Resolve(functionName)
if resolveErr != nil {
// TODO: Should record the 404/not found error in Prometheus.
log.Printf("resolver error: cannot find %s: %s\n", functionName, resolveErr.Error())
writeError(w, http.StatusNotFound, "Cannot find service: %s.", functionName)
return
}
proxyReq, err := buildProxyRequest(originalReq, functionAddr, pathVars["params"])
if err != nil {
writeError(w, http.StatusInternalServerError, "Failed to resolve service: %s.", functionName)
return
}
defer proxyReq.Body.Close()
start := time.Now()
response, err := proxyClient.Do(proxyReq.WithContext(ctx))
seconds := time.Since(start)
if err != nil {
log.Printf("error with proxy request to: %s, %s\n", proxyReq.URL.String(), err.Error())
writeError(w, http.StatusInternalServerError, "Can't reach service for: %s.", functionName)
return
}
log.Printf("%s took %f seconds\n", functionName, seconds.Seconds())
clientHeader := w.Header()
copyHeaders(clientHeader, &response.Header)
w.Header().Set("Content-Type", getContentType(response.Header, originalReq.Header))
w.WriteHeader(http.StatusOK)
io.Copy(w, response.Body)
}
|
go
|
func proxyRequest(w http.ResponseWriter, originalReq *http.Request, proxyClient http.Client, resolver BaseURLResolver) {
ctx := originalReq.Context()
pathVars := mux.Vars(originalReq)
functionName := pathVars["name"]
if functionName == "" {
writeError(w, http.StatusBadRequest, errMissingFunctionName)
return
}
functionAddr, resolveErr := resolver.Resolve(functionName)
if resolveErr != nil {
// TODO: Should record the 404/not found error in Prometheus.
log.Printf("resolver error: cannot find %s: %s\n", functionName, resolveErr.Error())
writeError(w, http.StatusNotFound, "Cannot find service: %s.", functionName)
return
}
proxyReq, err := buildProxyRequest(originalReq, functionAddr, pathVars["params"])
if err != nil {
writeError(w, http.StatusInternalServerError, "Failed to resolve service: %s.", functionName)
return
}
defer proxyReq.Body.Close()
start := time.Now()
response, err := proxyClient.Do(proxyReq.WithContext(ctx))
seconds := time.Since(start)
if err != nil {
log.Printf("error with proxy request to: %s, %s\n", proxyReq.URL.String(), err.Error())
writeError(w, http.StatusInternalServerError, "Can't reach service for: %s.", functionName)
return
}
log.Printf("%s took %f seconds\n", functionName, seconds.Seconds())
clientHeader := w.Header()
copyHeaders(clientHeader, &response.Header)
w.Header().Set("Content-Type", getContentType(response.Header, originalReq.Header))
w.WriteHeader(http.StatusOK)
io.Copy(w, response.Body)
}
|
[
"func",
"proxyRequest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"originalReq",
"*",
"http",
".",
"Request",
",",
"proxyClient",
"http",
".",
"Client",
",",
"resolver",
"BaseURLResolver",
")",
"{",
"ctx",
":=",
"originalReq",
".",
"Context",
"(",
")",
"\n\n",
"pathVars",
":=",
"mux",
".",
"Vars",
"(",
"originalReq",
")",
"\n",
"functionName",
":=",
"pathVars",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"functionName",
"==",
"\"",
"\"",
"{",
"writeError",
"(",
"w",
",",
"http",
".",
"StatusBadRequest",
",",
"errMissingFunctionName",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"functionAddr",
",",
"resolveErr",
":=",
"resolver",
".",
"Resolve",
"(",
"functionName",
")",
"\n",
"if",
"resolveErr",
"!=",
"nil",
"{",
"// TODO: Should record the 404/not found error in Prometheus.",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"functionName",
",",
"resolveErr",
".",
"Error",
"(",
")",
")",
"\n",
"writeError",
"(",
"w",
",",
"http",
".",
"StatusNotFound",
",",
"\"",
"\"",
",",
"functionName",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"proxyReq",
",",
"err",
":=",
"buildProxyRequest",
"(",
"originalReq",
",",
"functionAddr",
",",
"pathVars",
"[",
"\"",
"\"",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"writeError",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"\"",
"\"",
",",
"functionName",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"proxyReq",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"response",
",",
"err",
":=",
"proxyClient",
".",
"Do",
"(",
"proxyReq",
".",
"WithContext",
"(",
"ctx",
")",
")",
"\n",
"seconds",
":=",
"time",
".",
"Since",
"(",
"start",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"proxyReq",
".",
"URL",
".",
"String",
"(",
")",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n\n",
"writeError",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"\"",
"\"",
",",
"functionName",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"functionName",
",",
"seconds",
".",
"Seconds",
"(",
")",
")",
"\n\n",
"clientHeader",
":=",
"w",
".",
"Header",
"(",
")",
"\n",
"copyHeaders",
"(",
"clientHeader",
",",
"&",
"response",
".",
"Header",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"getContentType",
"(",
"response",
".",
"Header",
",",
"originalReq",
".",
"Header",
")",
")",
"\n\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"io",
".",
"Copy",
"(",
"w",
",",
"response",
".",
"Body",
")",
"\n",
"}"
] |
// proxyRequest handles the actual resolution of and then request to the function service.
|
[
"proxyRequest",
"handles",
"the",
"actual",
"resolution",
"of",
"and",
"then",
"request",
"to",
"the",
"function",
"service",
"."
] |
6a76a052deb12fd94b373c082963d8a8ad44d4d1
|
https://github.com/openfaas/faas-provider/blob/6a76a052deb12fd94b373c082963d8a8ad44d4d1/proxy/proxy.go#L109-L153
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.