repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
microcosm-cc/bluemonday | policy.go | SkipElementsContent | func (p *Policy) SkipElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
element = strings.ToLower(element)
if _, ok := p.setOfElementsToSkipContent[element]; !ok {
p.setOfElementsToSkipContent[element] = struct{}{}
}
}
return p
} | go | func (p *Policy) SkipElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
element = strings.ToLower(element)
if _, ok := p.setOfElementsToSkipContent[element]; !ok {
p.setOfElementsToSkipContent[element] = struct{}{}
}
}
return p
} | [
"func",
"(",
"p",
"*",
"Policy",
")",
"SkipElementsContent",
"(",
"names",
"...",
"string",
")",
"*",
"Policy",
"{",
"p",
".",
"init",
"(",
")",
"\n\n",
"for",
"_",
",",
"element",
":=",
"range",
"names",
"{",
"element",
"=",
"strings",
".",
"ToLower",
"(",
"element",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"setOfElementsToSkipContent",
"[",
"element",
"]",
";",
"!",
"ok",
"{",
"p",
".",
"setOfElementsToSkipContent",
"[",
"element",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] | // SkipElementsContent adds the HTML elements whose tags is needed to be removed
// with its content. | [
"SkipElementsContent",
"adds",
"the",
"HTML",
"elements",
"whose",
"tags",
"is",
"needed",
"to",
"be",
"removed",
"with",
"its",
"content",
"."
] | 89802068f71166e95c92040512bf2e11767721ed | https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L406-L419 | train |
microcosm-cc/bluemonday | policy.go | AllowElementsContent | func (p *Policy) AllowElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
delete(p.setOfElementsToSkipContent, strings.ToLower(element))
}
return p
} | go | func (p *Policy) AllowElementsContent(names ...string) *Policy {
p.init()
for _, element := range names {
delete(p.setOfElementsToSkipContent, strings.ToLower(element))
}
return p
} | [
"func",
"(",
"p",
"*",
"Policy",
")",
"AllowElementsContent",
"(",
"names",
"...",
"string",
")",
"*",
"Policy",
"{",
"p",
".",
"init",
"(",
")",
"\n\n",
"for",
"_",
",",
"element",
":=",
"range",
"names",
"{",
"delete",
"(",
"p",
".",
"setOfElementsToSkipContent",
",",
"strings",
".",
"ToLower",
"(",
"element",
")",
")",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] | // AllowElementsContent marks the HTML elements whose content should be
// retained after removing the tag. | [
"AllowElementsContent",
"marks",
"the",
"HTML",
"elements",
"whose",
"content",
"should",
"be",
"retained",
"after",
"removing",
"the",
"tag",
"."
] | 89802068f71166e95c92040512bf2e11767721ed | https://github.com/microcosm-cc/bluemonday/blob/89802068f71166e95c92040512bf2e11767721ed/policy.go#L423-L432 | train |
pierrre/imageserver | source/file/file.go | IdentifyMime | func IdentifyMime(pth string, data []byte) (format string, err error) {
ext := filepath.Ext(pth)
if ext == "" {
return "", fmt.Errorf("no file extension: %s", pth)
}
typ := mime.TypeByExtension(ext)
if typ == "" {
return "", fmt.Errorf("unkwnon file type for extension %s", ext)
}
const pref = "image/"
if !strings.HasPrefix(typ, pref) {
return "", fmt.Errorf("file type does not begin with \"%s\": %s", pref, typ)
}
return typ[len(pref):], nil
} | go | func IdentifyMime(pth string, data []byte) (format string, err error) {
ext := filepath.Ext(pth)
if ext == "" {
return "", fmt.Errorf("no file extension: %s", pth)
}
typ := mime.TypeByExtension(ext)
if typ == "" {
return "", fmt.Errorf("unkwnon file type for extension %s", ext)
}
const pref = "image/"
if !strings.HasPrefix(typ, pref) {
return "", fmt.Errorf("file type does not begin with \"%s\": %s", pref, typ)
}
return typ[len(pref):], nil
} | [
"func",
"IdentifyMime",
"(",
"pth",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"format",
"string",
",",
"err",
"error",
")",
"{",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"pth",
")",
"\n",
"if",
"ext",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pth",
")",
"\n",
"}",
"\n",
"typ",
":=",
"mime",
".",
"TypeByExtension",
"(",
"ext",
")",
"\n",
"if",
"typ",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ext",
")",
"\n",
"}",
"\n",
"const",
"pref",
"=",
"\"",
"\"",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"typ",
",",
"pref",
")",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"pref",
",",
"typ",
")",
"\n",
"}",
"\n",
"return",
"typ",
"[",
"len",
"(",
"pref",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] | // IdentifyMime identifies the Image format with the "mime" package. | [
"IdentifyMime",
"identifies",
"the",
"Image",
"format",
"with",
"the",
"mime",
"package",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/source/file/file.go#L87-L101 | train |
pierrre/imageserver | http/parser.go | Parse | func (lp ListParser) Parse(req *http.Request, params imageserver.Params) error {
for _, subParser := range lp {
err := subParser.Parse(req, params)
if err != nil {
return err
}
}
return nil
} | go | func (lp ListParser) Parse(req *http.Request, params imageserver.Params) error {
for _, subParser := range lp {
err := subParser.Parse(req, params)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"lp",
"ListParser",
")",
"Parse",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"for",
"_",
",",
"subParser",
":=",
"range",
"lp",
"{",
"err",
":=",
"subParser",
".",
"Parse",
"(",
"req",
",",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Parse implements Parser.
//
// It iterates through all sub parsers.
// An error interrupts the iteration. | [
"Parse",
"implements",
"Parser",
".",
"It",
"iterates",
"through",
"all",
"sub",
"parsers",
".",
"An",
"error",
"interrupts",
"the",
"iteration",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L30-L38 | train |
pierrre/imageserver | http/parser.go | Resolve | func (lp ListParser) Resolve(param string) string {
for _, subParser := range lp {
httpParam := subParser.Resolve(param)
if httpParam != "" {
return httpParam
}
}
return ""
} | go | func (lp ListParser) Resolve(param string) string {
for _, subParser := range lp {
httpParam := subParser.Resolve(param)
if httpParam != "" {
return httpParam
}
}
return ""
} | [
"func",
"(",
"lp",
"ListParser",
")",
"Resolve",
"(",
"param",
"string",
")",
"string",
"{",
"for",
"_",
",",
"subParser",
":=",
"range",
"lp",
"{",
"httpParam",
":=",
"subParser",
".",
"Resolve",
"(",
"param",
")",
"\n",
"if",
"httpParam",
"!=",
"\"",
"\"",
"{",
"return",
"httpParam",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Resolve implements Parser.
//
// It iterates through sub parsers, and return the first non-empty string. | [
"Resolve",
"implements",
"Parser",
".",
"It",
"iterates",
"through",
"sub",
"parsers",
"and",
"return",
"the",
"first",
"non",
"-",
"empty",
"string",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L43-L51 | train |
pierrre/imageserver | http/parser.go | Resolve | func (parser *SourceParser) Resolve(param string) string {
if param == imageserver_source.Param {
return imageserver_source.Param
}
return ""
} | go | func (parser *SourceParser) Resolve(param string) string {
if param == imageserver_source.Param {
return imageserver_source.Param
}
return ""
} | [
"func",
"(",
"parser",
"*",
"SourceParser",
")",
"Resolve",
"(",
"param",
"string",
")",
"string",
"{",
"if",
"param",
"==",
"imageserver_source",
".",
"Param",
"{",
"return",
"imageserver_source",
".",
"Param",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Resolve implements Parser. | [
"Resolve",
"implements",
"Parser",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L63-L68 | train |
pierrre/imageserver | http/parser.go | ParseQueryString | func ParseQueryString(param string, req *http.Request, params imageserver.Params) {
s := req.URL.Query().Get(param)
if s != "" {
params.Set(param, s)
}
} | go | func ParseQueryString(param string, req *http.Request, params imageserver.Params) {
s := req.URL.Query().Get(param)
if s != "" {
params.Set(param, s)
}
} | [
"func",
"ParseQueryString",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"!=",
"\"",
"\"",
"{",
"params",
".",
"Set",
"(",
"param",
",",
"s",
")",
"\n",
"}",
"\n",
"}"
] | // ParseQueryString takes the param from the HTTP URL query and add it to the Params. | [
"ParseQueryString",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L131-L136 | train |
pierrre/imageserver | http/parser.go | ParseQueryInt | func ParseQueryInt(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
i, err := strconv.Atoi(s)
if err != nil {
return newParseTypeParamError(param, "int", err)
}
params.Set(param, i)
return nil
} | go | func ParseQueryInt(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
i, err := strconv.Atoi(s)
if err != nil {
return newParseTypeParamError(param, "int", err)
}
params.Set(param, i)
return nil
} | [
"func",
"ParseQueryInt",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newParseTypeParamError",
"(",
"param",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"params",
".",
"Set",
"(",
"param",
",",
"i",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // ParseQueryInt takes the param from the HTTP URL query, parse it as an int and add it to the Params. | [
"ParseQueryInt",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"parse",
"it",
"as",
"an",
"int",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L139-L150 | train |
pierrre/imageserver | http/parser.go | ParseQueryFloat | func ParseQueryFloat(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return newParseTypeParamError(param, "float", err)
}
params.Set(param, f)
return nil
} | go | func ParseQueryFloat(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return newParseTypeParamError(param, "float", err)
}
params.Set(param, f)
return nil
} | [
"func",
"ParseQueryFloat",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"s",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newParseTypeParamError",
"(",
"param",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"params",
".",
"Set",
"(",
"param",
",",
"f",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // ParseQueryFloat takes the param from the HTTP URL query, parse it as a float64 and add it to the Params. | [
"ParseQueryFloat",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"parse",
"it",
"as",
"a",
"float64",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L167-L178 | train |
pierrre/imageserver | http/parser.go | ParseQueryBool | func ParseQueryBool(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
b, err := strconv.ParseBool(s)
if err != nil {
return newParseTypeParamError(param, "bool", err)
}
params.Set(param, b)
return nil
} | go | func ParseQueryBool(param string, req *http.Request, params imageserver.Params) error {
s := req.URL.Query().Get(param)
if s == "" {
return nil
}
b, err := strconv.ParseBool(s)
if err != nil {
return newParseTypeParamError(param, "bool", err)
}
params.Set(param, b)
return nil
} | [
"func",
"ParseQueryBool",
"(",
"param",
"string",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"s",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"newParseTypeParamError",
"(",
"param",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"params",
".",
"Set",
"(",
"param",
",",
"b",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // ParseQueryBool takes the param from the HTTP URL query, parse it as an bool and add it to the Params. | [
"ParseQueryBool",
"takes",
"the",
"param",
"from",
"the",
"HTTP",
"URL",
"query",
"parse",
"it",
"as",
"an",
"bool",
"and",
"add",
"it",
"to",
"the",
"Params",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/parser.go#L181-L192 | train |
pierrre/imageserver | cache/groupcache/http.go | HTTPPoolContext | func HTTPPoolContext(req *http.Request) groupcache.Context {
ctx, err := getContext(req)
if err != nil {
return nil
}
return ctx
} | go | func HTTPPoolContext(req *http.Request) groupcache.Context {
ctx, err := getContext(req)
if err != nil {
return nil
}
return ctx
} | [
"func",
"HTTPPoolContext",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"groupcache",
".",
"Context",
"{",
"ctx",
",",
"err",
":=",
"getContext",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"ctx",
"\n",
"}"
] | // HTTPPoolContext must be used in groupcache.HTTPPool.Context. | [
"HTTPPoolContext",
"must",
"be",
"used",
"in",
"groupcache",
".",
"HTTPPool",
".",
"Context",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/groupcache/http.go#L18-L24 | train |
pierrre/imageserver | cache/groupcache/http.go | NewHTTPPoolTransport | func NewHTTPPoolTransport(rt http.RoundTripper) func(groupcache.Context) http.RoundTripper {
if rt == nil {
rt = http.DefaultTransport
}
return func(ctx groupcache.Context) http.RoundTripper {
return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if ctx, ok := ctx.(*Context); ok && ctx != nil {
err := setContext(req, ctx)
if err != nil {
return nil, err
}
}
return rt.RoundTrip(req)
})
}
} | go | func NewHTTPPoolTransport(rt http.RoundTripper) func(groupcache.Context) http.RoundTripper {
if rt == nil {
rt = http.DefaultTransport
}
return func(ctx groupcache.Context) http.RoundTripper {
return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if ctx, ok := ctx.(*Context); ok && ctx != nil {
err := setContext(req, ctx)
if err != nil {
return nil, err
}
}
return rt.RoundTrip(req)
})
}
} | [
"func",
"NewHTTPPoolTransport",
"(",
"rt",
"http",
".",
"RoundTripper",
")",
"func",
"(",
"groupcache",
".",
"Context",
")",
"http",
".",
"RoundTripper",
"{",
"if",
"rt",
"==",
"nil",
"{",
"rt",
"=",
"http",
".",
"DefaultTransport",
"\n",
"}",
"\n",
"return",
"func",
"(",
"ctx",
"groupcache",
".",
"Context",
")",
"http",
".",
"RoundTripper",
"{",
"return",
"roundTripperFunc",
"(",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"ctx",
",",
"ok",
":=",
"ctx",
".",
"(",
"*",
"Context",
")",
";",
"ok",
"&&",
"ctx",
"!=",
"nil",
"{",
"err",
":=",
"setContext",
"(",
"req",
",",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rt",
".",
"RoundTrip",
"(",
"req",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // NewHTTPPoolTransport returns a function that must be used in groupcache.HTTPPool.Transport.
//
// rt is optional, http.DefaultTransport is used by default. | [
"NewHTTPPoolTransport",
"returns",
"a",
"function",
"that",
"must",
"be",
"used",
"in",
"groupcache",
".",
"HTTPPool",
".",
"Transport",
".",
"rt",
"is",
"optional",
"http",
".",
"DefaultTransport",
"is",
"used",
"by",
"default",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/groupcache/http.go#L50-L65 | train |
pierrre/imageserver | params.go | Get | func (params Params) Get(key string) (interface{}, error) {
v, ok := params[key]
if !ok {
return nil, &ParamError{Param: key, Message: "not set"}
}
return v, nil
} | go | func (params Params) Get(key string) (interface{}, error) {
v, ok := params[key]
if !ok {
return nil, &ParamError{Param: key, Message: "not set"}
}
return v, nil
} | [
"func",
"(",
"params",
"Params",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"v",
",",
"ok",
":=",
"params",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"&",
"ParamError",
"{",
"Param",
":",
"key",
",",
"Message",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"return",
"v",
",",
"nil",
"\n",
"}"
] | // Get returns the value for the key. | [
"Get",
"returns",
"the",
"value",
"for",
"the",
"key",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L24-L30 | train |
pierrre/imageserver | params.go | GetString | func (params Params) GetString(key string) (string, error) {
v, err := params.Get(key)
if err != nil {
return "", err
}
vt, ok := v.(string)
if !ok {
return vt, newErrorType(key, v, "string")
}
return vt, nil
} | go | func (params Params) GetString(key string) (string, error) {
v, err := params.Get(key)
if err != nil {
return "", err
}
vt, ok := v.(string)
if !ok {
return vt, newErrorType(key, v, "string")
}
return vt, nil
} | [
"func",
"(",
"params",
"Params",
")",
"GetString",
"(",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"params",
".",
"Get",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"vt",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"vt",
",",
"newErrorType",
"(",
"key",
",",
"v",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"vt",
",",
"nil",
"\n",
"}"
] | // GetString returns the string value for the key. | [
"GetString",
"returns",
"the",
"string",
"value",
"for",
"the",
"key",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L33-L43 | train |
pierrre/imageserver | params.go | GetBool | func (params Params) GetBool(key string) (bool, error) {
v, err := params.Get(key)
if err != nil {
return false, err
}
vt, ok := v.(bool)
if !ok {
return false, newErrorType(key, v, "bool")
}
return vt, nil
} | go | func (params Params) GetBool(key string) (bool, error) {
v, err := params.Get(key)
if err != nil {
return false, err
}
vt, ok := v.(bool)
if !ok {
return false, newErrorType(key, v, "bool")
}
return vt, nil
} | [
"func",
"(",
"params",
"Params",
")",
"GetBool",
"(",
"key",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"params",
".",
"Get",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"vt",
",",
"ok",
":=",
"v",
".",
"(",
"bool",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
",",
"newErrorType",
"(",
"key",
",",
"v",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"vt",
",",
"nil",
"\n",
"}"
] | // GetBool returns the bool value for the key. | [
"GetBool",
"returns",
"the",
"bool",
"value",
"for",
"the",
"key",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L85-L95 | train |
pierrre/imageserver | params.go | Has | func (params Params) Has(key string) bool {
_, ok := params[key]
return ok
} | go | func (params Params) Has(key string) bool {
_, ok := params[key]
return ok
} | [
"func",
"(",
"params",
"Params",
")",
"Has",
"(",
"key",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"params",
"[",
"key",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // Has returns true if the key exists and false otherwise. | [
"Has",
"returns",
"true",
"if",
"the",
"key",
"exists",
"and",
"false",
"otherwise",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L115-L118 | train |
pierrre/imageserver | params.go | Keys | func (params Params) Keys() []string {
length := params.Len()
keys := make([]string, length)
i := 0
for key := range params {
keys[i] = key
i++
}
return keys
} | go | func (params Params) Keys() []string {
length := params.Len()
keys := make([]string, length)
i := 0
for key := range params {
keys[i] = key
i++
}
return keys
} | [
"func",
"(",
"params",
"Params",
")",
"Keys",
"(",
")",
"[",
"]",
"string",
"{",
"length",
":=",
"params",
".",
"Len",
"(",
")",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"length",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"key",
":=",
"range",
"params",
"{",
"keys",
"[",
"i",
"]",
"=",
"key",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"keys",
"\n",
"}"
] | // Keys returns the keys. | [
"Keys",
"returns",
"the",
"keys",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L131-L140 | train |
pierrre/imageserver | params.go | String | func (params Params) String() string {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufferPool.Put(buf)
params.toBuffer(buf)
return buf.String()
} | go | func (params Params) String() string {
buf := bufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufferPool.Put(buf)
params.toBuffer(buf)
return buf.String()
} | [
"func",
"(",
"params",
"Params",
")",
"String",
"(",
")",
"string",
"{",
"buf",
":=",
"bufferPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"bytes",
".",
"Buffer",
")",
"\n",
"buf",
".",
"Reset",
"(",
")",
"\n",
"defer",
"bufferPool",
".",
"Put",
"(",
"buf",
")",
"\n",
"params",
".",
"toBuffer",
"(",
"buf",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // String returns the string representation.
//
// Keys are sorted alphabetically. | [
"String",
"returns",
"the",
"string",
"representation",
".",
"Keys",
"are",
"sorted",
"alphabetically",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L151-L157 | train |
pierrre/imageserver | params.go | Copy | func (params Params) Copy() Params {
p := Params{}
for k, v := range params {
if q, ok := v.(Params); ok {
v = q.Copy()
}
p[k] = v
}
return p
} | go | func (params Params) Copy() Params {
p := Params{}
for k, v := range params {
if q, ok := v.(Params); ok {
v = q.Copy()
}
p[k] = v
}
return p
} | [
"func",
"(",
"params",
"Params",
")",
"Copy",
"(",
")",
"Params",
"{",
"p",
":=",
"Params",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"params",
"{",
"if",
"q",
",",
"ok",
":=",
"v",
".",
"(",
"Params",
")",
";",
"ok",
"{",
"v",
"=",
"q",
".",
"Copy",
"(",
")",
"\n",
"}",
"\n",
"p",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // Copy returns a deep copy of the Params. | [
"Copy",
"returns",
"a",
"deep",
"copy",
"of",
"the",
"Params",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/params.go#L181-L190 | train |
pierrre/imageserver | image.go | UnmarshalBinaryNoCopy | func (im *Image) UnmarshalBinaryNoCopy(data []byte) error {
readData := func(length int) ([]byte, error) {
if length > len(data) {
return nil, &ImageError{Message: "unmarshal: unexpected end of data"}
}
res := data[:length]
data = data[length:]
return res, nil
}
var buf []byte
var err error
buf, err = readData(4)
if err != nil {
return err
}
formatLen := imageByteOrder.Uint32(buf)
if formatLen > ImageFormatMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: format length %d is greater than the maximum value %d", formatLen, ImageFormatMaxLen)}
}
buf, err = readData(int(formatLen))
if err != nil {
return err
}
im.Format = string(buf)
buf, err = readData(4)
if err != nil {
return err
}
dataLen := imageByteOrder.Uint32(buf)
if dataLen > ImageDataMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: data length %d is greater than the maximum value %d", dataLen, ImageDataMaxLen)}
}
buf, err = readData(int(dataLen))
if err != nil {
return err
}
im.Data = buf
return nil
} | go | func (im *Image) UnmarshalBinaryNoCopy(data []byte) error {
readData := func(length int) ([]byte, error) {
if length > len(data) {
return nil, &ImageError{Message: "unmarshal: unexpected end of data"}
}
res := data[:length]
data = data[length:]
return res, nil
}
var buf []byte
var err error
buf, err = readData(4)
if err != nil {
return err
}
formatLen := imageByteOrder.Uint32(buf)
if formatLen > ImageFormatMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: format length %d is greater than the maximum value %d", formatLen, ImageFormatMaxLen)}
}
buf, err = readData(int(formatLen))
if err != nil {
return err
}
im.Format = string(buf)
buf, err = readData(4)
if err != nil {
return err
}
dataLen := imageByteOrder.Uint32(buf)
if dataLen > ImageDataMaxLen {
return &ImageError{Message: fmt.Sprintf("unmarshal: data length %d is greater than the maximum value %d", dataLen, ImageDataMaxLen)}
}
buf, err = readData(int(dataLen))
if err != nil {
return err
}
im.Data = buf
return nil
} | [
"func",
"(",
"im",
"*",
"Image",
")",
"UnmarshalBinaryNoCopy",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"readData",
":=",
"func",
"(",
"length",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"length",
">",
"len",
"(",
"data",
")",
"{",
"return",
"nil",
",",
"&",
"ImageError",
"{",
"Message",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"res",
":=",
"data",
"[",
":",
"length",
"]",
"\n",
"data",
"=",
"data",
"[",
"length",
":",
"]",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}",
"\n\n",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"formatLen",
":=",
"imageByteOrder",
".",
"Uint32",
"(",
"buf",
")",
"\n",
"if",
"formatLen",
">",
"ImageFormatMaxLen",
"{",
"return",
"&",
"ImageError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"formatLen",
",",
"ImageFormatMaxLen",
")",
"}",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"int",
"(",
"formatLen",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"im",
".",
"Format",
"=",
"string",
"(",
"buf",
")",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"dataLen",
":=",
"imageByteOrder",
".",
"Uint32",
"(",
"buf",
")",
"\n",
"if",
"dataLen",
">",
"ImageDataMaxLen",
"{",
"return",
"&",
"ImageError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"dataLen",
",",
"ImageDataMaxLen",
")",
"}",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
"=",
"readData",
"(",
"int",
"(",
"dataLen",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"im",
".",
"Data",
"=",
"buf",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalBinaryNoCopy is like encoding.BinaryUnmarshaler but does no copy.
//
// The caller must not reuse data after that. | [
"UnmarshalBinaryNoCopy",
"is",
"like",
"encoding",
".",
"BinaryUnmarshaler",
"but",
"does",
"no",
"copy",
".",
"The",
"caller",
"must",
"not",
"reuse",
"data",
"after",
"that",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image.go#L72-L116 | train |
pierrre/imageserver | server.go | NewLimitServer | func NewLimitServer(s Server, limit int) Server {
return &limitServer{
Server: s,
limitCh: make(chan struct{}, limit),
}
} | go | func NewLimitServer(s Server, limit int) Server {
return &limitServer{
Server: s,
limitCh: make(chan struct{}, limit),
}
} | [
"func",
"NewLimitServer",
"(",
"s",
"Server",
",",
"limit",
"int",
")",
"Server",
"{",
"return",
"&",
"limitServer",
"{",
"Server",
":",
"s",
",",
"limitCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"limit",
")",
",",
"}",
"\n",
"}"
] | // NewLimitServer creates a new Server that limits the number of concurrent executions.
//
// It uses a buffered channel to limit the number of concurrent executions. | [
"NewLimitServer",
"creates",
"a",
"new",
"Server",
"that",
"limits",
"the",
"number",
"of",
"concurrent",
"executions",
".",
"It",
"uses",
"a",
"buffered",
"channel",
"to",
"limit",
"the",
"number",
"of",
"concurrent",
"executions",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/server.go#L20-L25 | train |
pierrre/imageserver | source/http/http.go | IdentifyHeader | func IdentifyHeader(resp *http.Response, data []byte) (format string, err error) {
ct := resp.Header.Get("Content-Type")
if ct == "" {
return "", fmt.Errorf("no HTTP \"Content-Type\" header")
}
const pref = "image/"
if !strings.HasPrefix(ct, pref) {
return "", fmt.Errorf("HTTP \"Content-Type\" header does not begin with \"%s\": %s", pref, ct)
}
return ct[len(pref):], nil
} | go | func IdentifyHeader(resp *http.Response, data []byte) (format string, err error) {
ct := resp.Header.Get("Content-Type")
if ct == "" {
return "", fmt.Errorf("no HTTP \"Content-Type\" header")
}
const pref = "image/"
if !strings.HasPrefix(ct, pref) {
return "", fmt.Errorf("HTTP \"Content-Type\" header does not begin with \"%s\": %s", pref, ct)
}
return ct[len(pref):], nil
} | [
"func",
"IdentifyHeader",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"format",
"string",
",",
"err",
"error",
")",
"{",
"ct",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"ct",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n",
"const",
"pref",
"=",
"\"",
"\"",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"ct",
",",
"pref",
")",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"pref",
",",
"ct",
")",
"\n",
"}",
"\n",
"return",
"ct",
"[",
"len",
"(",
"pref",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] | // IdentifyHeader identifies the Image format with the "Content-Type" header. | [
"IdentifyHeader",
"identifies",
"the",
"Image",
"format",
"with",
"the",
"Content",
"-",
"Type",
"header",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/source/http/http.go#L102-L112 | train |
pierrre/imageserver | image/processor.go | Change | func (prc ListProcessor) Change(params imageserver.Params) bool {
for _, p := range prc {
if p.Change(params) {
return true
}
}
return false
} | go | func (prc ListProcessor) Change(params imageserver.Params) bool {
for _, p := range prc {
if p.Change(params) {
return true
}
}
return false
} | [
"func",
"(",
"prc",
"ListProcessor",
")",
"Change",
"(",
"params",
"imageserver",
".",
"Params",
")",
"bool",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"prc",
"{",
"if",
"p",
".",
"Change",
"(",
"params",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Change implements Processor. | [
"Change",
"implements",
"Processor",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/processor.go#L46-L53 | train |
pierrre/imageserver | image/gamma/gamma.go | NewProcessor | func NewProcessor(gamma float64, highQuality bool) *Processor {
prc := new(Processor)
gammaInv := 1 / gamma
for i := range prc.vals {
prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5)
}
if highQuality {
prc.newDrawable = func(p image.Image) draw.Image {
return image.NewNRGBA64(p.Bounds())
}
} else {
prc.newDrawable = imageserver_image_internal.NewDrawable
}
return prc
} | go | func NewProcessor(gamma float64, highQuality bool) *Processor {
prc := new(Processor)
gammaInv := 1 / gamma
for i := range prc.vals {
prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5)
}
if highQuality {
prc.newDrawable = func(p image.Image) draw.Image {
return image.NewNRGBA64(p.Bounds())
}
} else {
prc.newDrawable = imageserver_image_internal.NewDrawable
}
return prc
} | [
"func",
"NewProcessor",
"(",
"gamma",
"float64",
",",
"highQuality",
"bool",
")",
"*",
"Processor",
"{",
"prc",
":=",
"new",
"(",
"Processor",
")",
"\n",
"gammaInv",
":=",
"1",
"/",
"gamma",
"\n",
"for",
"i",
":=",
"range",
"prc",
".",
"vals",
"{",
"prc",
".",
"vals",
"[",
"i",
"]",
"=",
"uint16",
"(",
"math",
".",
"Pow",
"(",
"float64",
"(",
"i",
")",
"/",
"65535",
",",
"gammaInv",
")",
"*",
"65535",
"+",
"0.5",
")",
"\n",
"}",
"\n",
"if",
"highQuality",
"{",
"prc",
".",
"newDrawable",
"=",
"func",
"(",
"p",
"image",
".",
"Image",
")",
"draw",
".",
"Image",
"{",
"return",
"image",
".",
"NewNRGBA64",
"(",
"p",
".",
"Bounds",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"prc",
".",
"newDrawable",
"=",
"imageserver_image_internal",
".",
"NewDrawable",
"\n",
"}",
"\n",
"return",
"prc",
"\n",
"}"
] | // NewProcessor creates a Processor.
//
// "highQuality" indicates if the Processor return a NRGBA64 Image or an Image with the same quality as the given Image. | [
"NewProcessor",
"creates",
"a",
"Processor",
".",
"highQuality",
"indicates",
"if",
"the",
"Processor",
"return",
"a",
"NRGBA64",
"Image",
"or",
"an",
"Image",
"with",
"the",
"same",
"quality",
"as",
"the",
"given",
"Image",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/gamma/gamma.go#L24-L38 | train |
pierrre/imageserver | image/gamma/gamma.go | NewCorrectionProcessor | func NewCorrectionProcessor(prc imageserver_image.Processor, enabled bool) *CorrectionProcessor {
return &CorrectionProcessor{
Processor: prc,
enabled: enabled,
before: NewProcessor(1/correct, true),
after: NewProcessor(correct, true),
}
} | go | func NewCorrectionProcessor(prc imageserver_image.Processor, enabled bool) *CorrectionProcessor {
return &CorrectionProcessor{
Processor: prc,
enabled: enabled,
before: NewProcessor(1/correct, true),
after: NewProcessor(correct, true),
}
} | [
"func",
"NewCorrectionProcessor",
"(",
"prc",
"imageserver_image",
".",
"Processor",
",",
"enabled",
"bool",
")",
"*",
"CorrectionProcessor",
"{",
"return",
"&",
"CorrectionProcessor",
"{",
"Processor",
":",
"prc",
",",
"enabled",
":",
"enabled",
",",
"before",
":",
"NewProcessor",
"(",
"1",
"/",
"correct",
",",
"true",
")",
",",
"after",
":",
"NewProcessor",
"(",
"correct",
",",
"true",
")",
",",
"}",
"\n",
"}"
] | // NewCorrectionProcessor creates a CorrectionProcessor.
//
// "enabled" indicated if the CorrectionProcessor is enabled by default. | [
"NewCorrectionProcessor",
"creates",
"a",
"CorrectionProcessor",
".",
"enabled",
"indicated",
"if",
"the",
"CorrectionProcessor",
"is",
"enabled",
"by",
"default",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/gamma/gamma.go#L91-L98 | train |
pierrre/imageserver | handler.go | Handle | func (f HandlerFunc) Handle(im *Image, params Params) (*Image, error) {
return f(im, params)
} | go | func (f HandlerFunc) Handle(im *Image, params Params) (*Image, error) {
return f(im, params)
} | [
"func",
"(",
"f",
"HandlerFunc",
")",
"Handle",
"(",
"im",
"*",
"Image",
",",
"params",
"Params",
")",
"(",
"*",
"Image",
",",
"error",
")",
"{",
"return",
"f",
"(",
"im",
",",
"params",
")",
"\n",
"}"
] | // Handle implements Handler. | [
"Handle",
"implements",
"Handler",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/handler.go#L12-L14 | train |
pierrre/imageserver | handler.go | Get | func (srv *HandlerServer) Get(params Params) (*Image, error) {
im, err := srv.Server.Get(params)
if err != nil {
return nil, err
}
im, err = srv.Handler.Handle(im, params)
if err != nil {
return nil, err
}
return im, nil
} | go | func (srv *HandlerServer) Get(params Params) (*Image, error) {
im, err := srv.Server.Get(params)
if err != nil {
return nil, err
}
im, err = srv.Handler.Handle(im, params)
if err != nil {
return nil, err
}
return im, nil
} | [
"func",
"(",
"srv",
"*",
"HandlerServer",
")",
"Get",
"(",
"params",
"Params",
")",
"(",
"*",
"Image",
",",
"error",
")",
"{",
"im",
",",
"err",
":=",
"srv",
".",
"Server",
".",
"Get",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"im",
",",
"err",
"=",
"srv",
".",
"Handler",
".",
"Handle",
"(",
"im",
",",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"im",
",",
"nil",
"\n",
"}"
] | // Get implements Server. | [
"Get",
"implements",
"Server",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/handler.go#L23-L33 | train |
pierrre/imageserver | cache/groupcache/groupcache.go | NewServer | func NewServer(srv imageserver.Server, kg imageserver_cache.KeyGenerator, name string, cacheBytes int64) *Server {
return &Server{
Group: groupcache.NewGroup(name, cacheBytes, &Getter{Server: srv}),
KeyGenerator: kg,
}
} | go | func NewServer(srv imageserver.Server, kg imageserver_cache.KeyGenerator, name string, cacheBytes int64) *Server {
return &Server{
Group: groupcache.NewGroup(name, cacheBytes, &Getter{Server: srv}),
KeyGenerator: kg,
}
} | [
"func",
"NewServer",
"(",
"srv",
"imageserver",
".",
"Server",
",",
"kg",
"imageserver_cache",
".",
"KeyGenerator",
",",
"name",
"string",
",",
"cacheBytes",
"int64",
")",
"*",
"Server",
"{",
"return",
"&",
"Server",
"{",
"Group",
":",
"groupcache",
".",
"NewGroup",
"(",
"name",
",",
"cacheBytes",
",",
"&",
"Getter",
"{",
"Server",
":",
"srv",
"}",
")",
",",
"KeyGenerator",
":",
"kg",
",",
"}",
"\n",
"}"
] | // NewServer is a helper to create a new groupcache Server. | [
"NewServer",
"is",
"a",
"helper",
"to",
"create",
"a",
"new",
"groupcache",
"Server",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/groupcache/groupcache.go#L13-L18 | train |
pierrre/imageserver | cache/groupcache/groupcache.go | Get | func (gt *Getter) Get(ctx groupcache.Context, key string, dest groupcache.Sink) error {
myctx, ok := ctx.(*Context)
if !ok {
return fmt.Errorf("invalid context type: %T", ctx)
}
if myctx == nil {
return fmt.Errorf("context is nil")
}
if myctx.Params == nil {
return fmt.Errorf("context has nil Params")
}
im, err := gt.Server.Get(myctx.Params)
if err != nil {
return err
}
data, err := im.MarshalBinary()
if err != nil {
return err
}
return dest.SetBytes(data)
} | go | func (gt *Getter) Get(ctx groupcache.Context, key string, dest groupcache.Sink) error {
myctx, ok := ctx.(*Context)
if !ok {
return fmt.Errorf("invalid context type: %T", ctx)
}
if myctx == nil {
return fmt.Errorf("context is nil")
}
if myctx.Params == nil {
return fmt.Errorf("context has nil Params")
}
im, err := gt.Server.Get(myctx.Params)
if err != nil {
return err
}
data, err := im.MarshalBinary()
if err != nil {
return err
}
return dest.SetBytes(data)
} | [
"func",
"(",
"gt",
"*",
"Getter",
")",
"Get",
"(",
"ctx",
"groupcache",
".",
"Context",
",",
"key",
"string",
",",
"dest",
"groupcache",
".",
"Sink",
")",
"error",
"{",
"myctx",
",",
"ok",
":=",
"ctx",
".",
"(",
"*",
"Context",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ctx",
")",
"\n",
"}",
"\n",
"if",
"myctx",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"myctx",
".",
"Params",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"im",
",",
"err",
":=",
"gt",
".",
"Server",
".",
"Get",
"(",
"myctx",
".",
"Params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"data",
",",
"err",
":=",
"im",
".",
"MarshalBinary",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"dest",
".",
"SetBytes",
"(",
"data",
")",
"\n",
"}"
] | // Get implements groupcache.Getter. | [
"Get",
"implements",
"groupcache",
".",
"Getter",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/groupcache/groupcache.go#L54-L74 | train |
pierrre/imageserver | http/error.go | NewErrorDefaultText | func NewErrorDefaultText(code int) *Error {
return &Error{Code: code, Text: http.StatusText(code)}
} | go | func NewErrorDefaultText(code int) *Error {
return &Error{Code: code, Text: http.StatusText(code)}
} | [
"func",
"NewErrorDefaultText",
"(",
"code",
"int",
")",
"*",
"Error",
"{",
"return",
"&",
"Error",
"{",
"Code",
":",
"code",
",",
"Text",
":",
"http",
".",
"StatusText",
"(",
"code",
")",
"}",
"\n",
"}"
] | // NewErrorDefaultText creates an Error with the default message associated with the code. | [
"NewErrorDefaultText",
"creates",
"an",
"Error",
"with",
"the",
"default",
"message",
"associated",
"with",
"the",
"code",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/http/error.go#L17-L19 | train |
pierrre/imageserver | image/encoder.go | Encode | func (f EncoderFunc) Encode(w io.Writer, nim image.Image, params imageserver.Params) error {
return f(w, nim, params)
} | go | func (f EncoderFunc) Encode(w io.Writer, nim image.Image, params imageserver.Params) error {
return f(w, nim, params)
} | [
"func",
"(",
"f",
"EncoderFunc",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
",",
"nim",
"image",
".",
"Image",
",",
"params",
"imageserver",
".",
"Params",
")",
"error",
"{",
"return",
"f",
"(",
"w",
",",
"nim",
",",
"params",
")",
"\n",
"}"
] | // Encode implements Encoder. | [
"Encode",
"implements",
"Encoder",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/encoder.go#L24-L26 | train |
pierrre/imageserver | image/encoder.go | Decode | func Decode(im *imageserver.Image) (image.Image, error) {
nim, format, err := image.Decode(bytes.NewReader(im.Data))
if err != nil {
return nil, &imageserver.ImageError{Message: err.Error()}
}
if format != im.Format {
return nil, &imageserver.ImageError{Message: fmt.Sprintf("decoded format \"%s\" does not match image format \"%s\"", format, im.Format)}
}
return nim, nil
} | go | func Decode(im *imageserver.Image) (image.Image, error) {
nim, format, err := image.Decode(bytes.NewReader(im.Data))
if err != nil {
return nil, &imageserver.ImageError{Message: err.Error()}
}
if format != im.Format {
return nil, &imageserver.ImageError{Message: fmt.Sprintf("decoded format \"%s\" does not match image format \"%s\"", format, im.Format)}
}
return nim, nil
} | [
"func",
"Decode",
"(",
"im",
"*",
"imageserver",
".",
"Image",
")",
"(",
"image",
".",
"Image",
",",
"error",
")",
"{",
"nim",
",",
"format",
",",
"err",
":=",
"image",
".",
"Decode",
"(",
"bytes",
".",
"NewReader",
"(",
"im",
".",
"Data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"&",
"imageserver",
".",
"ImageError",
"{",
"Message",
":",
"err",
".",
"Error",
"(",
")",
"}",
"\n",
"}",
"\n",
"if",
"format",
"!=",
"im",
".",
"Format",
"{",
"return",
"nil",
",",
"&",
"imageserver",
".",
"ImageError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"format",
",",
"im",
".",
"Format",
")",
"}",
"\n",
"}",
"\n",
"return",
"nim",
",",
"nil",
"\n",
"}"
] | // Decode decodes a raw Image to a Go Image.
//
// It returns an error if the decoded Image format does not match the raw Image format. | [
"Decode",
"decodes",
"a",
"raw",
"Image",
"to",
"a",
"Go",
"Image",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"decoded",
"Image",
"format",
"does",
"not",
"match",
"the",
"raw",
"Image",
"format",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/encoder.go#L85-L94 | train |
pierrre/imageserver | cache/server.go | NewParamsHashKeyGenerator | func NewParamsHashKeyGenerator(newHashFunc func() hash.Hash) KeyGenerator {
pool := &sync.Pool{
New: func() interface{} {
return newHashFunc()
},
}
return KeyGeneratorFunc(func(params imageserver.Params) string {
h := pool.Get().(hash.Hash)
_, _ = io.WriteString(h, params.String())
data := h.Sum(nil)
h.Reset()
pool.Put(h)
return hex.EncodeToString(data)
})
} | go | func NewParamsHashKeyGenerator(newHashFunc func() hash.Hash) KeyGenerator {
pool := &sync.Pool{
New: func() interface{} {
return newHashFunc()
},
}
return KeyGeneratorFunc(func(params imageserver.Params) string {
h := pool.Get().(hash.Hash)
_, _ = io.WriteString(h, params.String())
data := h.Sum(nil)
h.Reset()
pool.Put(h)
return hex.EncodeToString(data)
})
} | [
"func",
"NewParamsHashKeyGenerator",
"(",
"newHashFunc",
"func",
"(",
")",
"hash",
".",
"Hash",
")",
"KeyGenerator",
"{",
"pool",
":=",
"&",
"sync",
".",
"Pool",
"{",
"New",
":",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"return",
"newHashFunc",
"(",
")",
"\n",
"}",
",",
"}",
"\n",
"return",
"KeyGeneratorFunc",
"(",
"func",
"(",
"params",
"imageserver",
".",
"Params",
")",
"string",
"{",
"h",
":=",
"pool",
".",
"Get",
"(",
")",
".",
"(",
"hash",
".",
"Hash",
")",
"\n",
"_",
",",
"_",
"=",
"io",
".",
"WriteString",
"(",
"h",
",",
"params",
".",
"String",
"(",
")",
")",
"\n",
"data",
":=",
"h",
".",
"Sum",
"(",
"nil",
")",
"\n",
"h",
".",
"Reset",
"(",
")",
"\n",
"pool",
".",
"Put",
"(",
"h",
")",
"\n",
"return",
"hex",
".",
"EncodeToString",
"(",
"data",
")",
"\n",
"}",
")",
"\n",
"}"
] | // NewParamsHashKeyGenerator returns a new KeyGenerator that hashes the Params. | [
"NewParamsHashKeyGenerator",
"returns",
"a",
"new",
"KeyGenerator",
"that",
"hashes",
"the",
"Params",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/server.go#L61-L75 | train |
pierrre/imageserver | cache/server.go | GetKey | func (g *PrefixKeyGenerator) GetKey(params imageserver.Params) string {
return g.Prefix + g.KeyGenerator.GetKey(params)
} | go | func (g *PrefixKeyGenerator) GetKey(params imageserver.Params) string {
return g.Prefix + g.KeyGenerator.GetKey(params)
} | [
"func",
"(",
"g",
"*",
"PrefixKeyGenerator",
")",
"GetKey",
"(",
"params",
"imageserver",
".",
"Params",
")",
"string",
"{",
"return",
"g",
".",
"Prefix",
"+",
"g",
".",
"KeyGenerator",
".",
"GetKey",
"(",
"params",
")",
"\n",
"}"
] | // GetKey implements KeyGenerator. | [
"GetKey",
"implements",
"KeyGenerator",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/cache/server.go#L84-L86 | train |
pierrre/imageserver | image/internal/internal.go | NewDrawable | func NewDrawable(p image.Image) draw.Image {
r := p.Bounds()
if _, ok := p.(*image.Uniform); ok {
r = image.Rect(0, 0, 1, 1)
}
return NewDrawableSize(p, r)
} | go | func NewDrawable(p image.Image) draw.Image {
r := p.Bounds()
if _, ok := p.(*image.Uniform); ok {
r = image.Rect(0, 0, 1, 1)
}
return NewDrawableSize(p, r)
} | [
"func",
"NewDrawable",
"(",
"p",
"image",
".",
"Image",
")",
"draw",
".",
"Image",
"{",
"r",
":=",
"p",
".",
"Bounds",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"p",
".",
"(",
"*",
"image",
".",
"Uniform",
")",
";",
"ok",
"{",
"r",
"=",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
"\n",
"}",
"\n",
"return",
"NewDrawableSize",
"(",
"p",
",",
"r",
")",
"\n",
"}"
] | // NewDrawable returns a new draw.Image with the same type and size as p.
//
// If p has no size, 1x1 is used.
//
// See NewDrawableSize. | [
"NewDrawable",
"returns",
"a",
"new",
"draw",
".",
"Image",
"with",
"the",
"same",
"type",
"and",
"size",
"as",
"p",
".",
"If",
"p",
"has",
"no",
"size",
"1x1",
"is",
"used",
".",
"See",
"NewDrawableSize",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/internal/internal.go#L17-L23 | train |
pierrre/imageserver | image/internal/internal.go | Copy | func Copy(dst draw.Image, src image.Image) {
bd := src.Bounds().Intersect(dst.Bounds())
at := imageutil.NewAtFunc(src)
set := imageutil.NewSetFunc(dst)
imageutil.Parallel1D(bd, func(bd image.Rectangle) {
for y := bd.Min.Y; y < bd.Max.Y; y++ {
for x := bd.Min.X; x < bd.Max.X; x++ {
r, g, b, a := at(x, y)
set(x, y, r, g, b, a)
}
}
})
} | go | func Copy(dst draw.Image, src image.Image) {
bd := src.Bounds().Intersect(dst.Bounds())
at := imageutil.NewAtFunc(src)
set := imageutil.NewSetFunc(dst)
imageutil.Parallel1D(bd, func(bd image.Rectangle) {
for y := bd.Min.Y; y < bd.Max.Y; y++ {
for x := bd.Min.X; x < bd.Max.X; x++ {
r, g, b, a := at(x, y)
set(x, y, r, g, b, a)
}
}
})
} | [
"func",
"Copy",
"(",
"dst",
"draw",
".",
"Image",
",",
"src",
"image",
".",
"Image",
")",
"{",
"bd",
":=",
"src",
".",
"Bounds",
"(",
")",
".",
"Intersect",
"(",
"dst",
".",
"Bounds",
"(",
")",
")",
"\n",
"at",
":=",
"imageutil",
".",
"NewAtFunc",
"(",
"src",
")",
"\n",
"set",
":=",
"imageutil",
".",
"NewSetFunc",
"(",
"dst",
")",
"\n",
"imageutil",
".",
"Parallel1D",
"(",
"bd",
",",
"func",
"(",
"bd",
"image",
".",
"Rectangle",
")",
"{",
"for",
"y",
":=",
"bd",
".",
"Min",
".",
"Y",
";",
"y",
"<",
"bd",
".",
"Max",
".",
"Y",
";",
"y",
"++",
"{",
"for",
"x",
":=",
"bd",
".",
"Min",
".",
"X",
";",
"x",
"<",
"bd",
".",
"Max",
".",
"X",
";",
"x",
"++",
"{",
"r",
",",
"g",
",",
"b",
",",
"a",
":=",
"at",
"(",
"x",
",",
"y",
")",
"\n",
"set",
"(",
"x",
",",
"y",
",",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}"
] | // Copy copies src to dst. | [
"Copy",
"copies",
"src",
"to",
"dst",
"."
] | 05bccbfbe5b29f4842ff43827f6768b04b1d3a55 | https://github.com/pierrre/imageserver/blob/05bccbfbe5b29f4842ff43827f6768b04b1d3a55/image/internal/internal.go#L60-L72 | train |
c9s/goprocinfo | linux/diskstat.go | GetReadTicks | func (ds *DiskStat) GetReadTicks() time.Duration {
return time.Duration(ds.ReadTicks) * time.Millisecond
} | go | func (ds *DiskStat) GetReadTicks() time.Duration {
return time.Duration(ds.ReadTicks) * time.Millisecond
} | [
"func",
"(",
"ds",
"*",
"DiskStat",
")",
"GetReadTicks",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"ds",
".",
"ReadTicks",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}"
] | // GetReadTicks returns the duration waited for read requests. | [
"GetReadTicks",
"returns",
"the",
"duration",
"waited",
"for",
"read",
"requests",
"."
] | 0b2ad9ac246b05c4f5750721d0c4d230888cac5e | https://github.com/c9s/goprocinfo/blob/0b2ad9ac246b05c4f5750721d0c4d230888cac5e/linux/diskstat.go#L78-L80 | train |
c9s/goprocinfo | linux/diskstat.go | GetWriteTicks | func (ds *DiskStat) GetWriteTicks() time.Duration {
return time.Duration(ds.WriteTicks) * time.Millisecond
} | go | func (ds *DiskStat) GetWriteTicks() time.Duration {
return time.Duration(ds.WriteTicks) * time.Millisecond
} | [
"func",
"(",
"ds",
"*",
"DiskStat",
")",
"GetWriteTicks",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"ds",
".",
"WriteTicks",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}"
] | // GetWriteTicks returns the duration waited for write requests. | [
"GetWriteTicks",
"returns",
"the",
"duration",
"waited",
"for",
"write",
"requests",
"."
] | 0b2ad9ac246b05c4f5750721d0c4d230888cac5e | https://github.com/c9s/goprocinfo/blob/0b2ad9ac246b05c4f5750721d0c4d230888cac5e/linux/diskstat.go#L88-L90 | train |
c9s/goprocinfo | linux/diskstat.go | GetIOTicks | func (ds *DiskStat) GetIOTicks() time.Duration {
return time.Duration(ds.IOTicks) * time.Millisecond
} | go | func (ds *DiskStat) GetIOTicks() time.Duration {
return time.Duration(ds.IOTicks) * time.Millisecond
} | [
"func",
"(",
"ds",
"*",
"DiskStat",
")",
"GetIOTicks",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"ds",
".",
"IOTicks",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}"
] | // GetIOTicks returns the duration the disk has been active. | [
"GetIOTicks",
"returns",
"the",
"duration",
"the",
"disk",
"has",
"been",
"active",
"."
] | 0b2ad9ac246b05c4f5750721d0c4d230888cac5e | https://github.com/c9s/goprocinfo/blob/0b2ad9ac246b05c4f5750721d0c4d230888cac5e/linux/diskstat.go#L93-L95 | train |
c9s/goprocinfo | linux/diskstat.go | GetTimeInQueue | func (ds *DiskStat) GetTimeInQueue() time.Duration {
return time.Duration(ds.TimeInQueue) * time.Millisecond
} | go | func (ds *DiskStat) GetTimeInQueue() time.Duration {
return time.Duration(ds.TimeInQueue) * time.Millisecond
} | [
"func",
"(",
"ds",
"*",
"DiskStat",
")",
"GetTimeInQueue",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"ds",
".",
"TimeInQueue",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}"
] | // GetTimeInQueue returns the duration waited for all requests. | [
"GetTimeInQueue",
"returns",
"the",
"duration",
"waited",
"for",
"all",
"requests",
"."
] | 0b2ad9ac246b05c4f5750721d0c4d230888cac5e | https://github.com/c9s/goprocinfo/blob/0b2ad9ac246b05c4f5750721d0c4d230888cac5e/linux/diskstat.go#L98-L100 | train |
ugorji/go | codec/decode.go | NewDecoderBytes | func NewDecoderBytes(in []byte, h Handle) *Decoder {
d := newDecoder(h)
d.ResetBytes(in)
return d
} | go | func NewDecoderBytes(in []byte, h Handle) *Decoder {
d := newDecoder(h)
d.ResetBytes(in)
return d
} | [
"func",
"NewDecoderBytes",
"(",
"in",
"[",
"]",
"byte",
",",
"h",
"Handle",
")",
"*",
"Decoder",
"{",
"d",
":=",
"newDecoder",
"(",
"h",
")",
"\n",
"d",
".",
"ResetBytes",
"(",
"in",
")",
"\n",
"return",
"d",
"\n",
"}"
] | // NewDecoderBytes returns a Decoder which efficiently decodes directly
// from a byte slice with zero copying. | [
"NewDecoderBytes",
"returns",
"a",
"Decoder",
"which",
"efficiently",
"decodes",
"directly",
"from",
"a",
"byte",
"slice",
"with",
"zero",
"copying",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/decode.go#L2336-L2340 | train |
ugorji/go | codec/decode.go | newDecoder | func newDecoder(h Handle) *Decoder {
d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized}
d.bytes = true
if useFinalizers {
runtime.SetFinalizer(d, (*Decoder).finalize)
// xdebugf(">>>> new(Decoder) with finalizer")
}
d.r = &d.decReaderSwitch
d.hh = h
d.be = h.isBinary()
// NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
var jh *JsonHandle
jh, d.js = h.(*JsonHandle)
if d.js {
d.jsms = jh.MapKeyAsString
}
d.esep = d.hh.hasElemSeparators()
if d.h.InternString {
d.is = make(map[string]string, 32)
}
d.d = h.newDecDriver(d)
// d.cr, _ = d.d.(containerStateRecv)
return d
} | go | func newDecoder(h Handle) *Decoder {
d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized}
d.bytes = true
if useFinalizers {
runtime.SetFinalizer(d, (*Decoder).finalize)
// xdebugf(">>>> new(Decoder) with finalizer")
}
d.r = &d.decReaderSwitch
d.hh = h
d.be = h.isBinary()
// NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
var jh *JsonHandle
jh, d.js = h.(*JsonHandle)
if d.js {
d.jsms = jh.MapKeyAsString
}
d.esep = d.hh.hasElemSeparators()
if d.h.InternString {
d.is = make(map[string]string, 32)
}
d.d = h.newDecDriver(d)
// d.cr, _ = d.d.(containerStateRecv)
return d
} | [
"func",
"newDecoder",
"(",
"h",
"Handle",
")",
"*",
"Decoder",
"{",
"d",
":=",
"&",
"Decoder",
"{",
"h",
":",
"basicHandle",
"(",
"h",
")",
",",
"err",
":",
"errDecoderNotInitialized",
"}",
"\n",
"d",
".",
"bytes",
"=",
"true",
"\n",
"if",
"useFinalizers",
"{",
"runtime",
".",
"SetFinalizer",
"(",
"d",
",",
"(",
"*",
"Decoder",
")",
".",
"finalize",
")",
"\n",
"// xdebugf(\">>>> new(Decoder) with finalizer\")",
"}",
"\n",
"d",
".",
"r",
"=",
"&",
"d",
".",
"decReaderSwitch",
"\n",
"d",
".",
"hh",
"=",
"h",
"\n",
"d",
".",
"be",
"=",
"h",
".",
"isBinary",
"(",
")",
"\n",
"// NOTE: do not initialize d.n here. It is lazily initialized in d.naked()",
"var",
"jh",
"*",
"JsonHandle",
"\n",
"jh",
",",
"d",
".",
"js",
"=",
"h",
".",
"(",
"*",
"JsonHandle",
")",
"\n",
"if",
"d",
".",
"js",
"{",
"d",
".",
"jsms",
"=",
"jh",
".",
"MapKeyAsString",
"\n",
"}",
"\n",
"d",
".",
"esep",
"=",
"d",
".",
"hh",
".",
"hasElemSeparators",
"(",
")",
"\n",
"if",
"d",
".",
"h",
".",
"InternString",
"{",
"d",
".",
"is",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"32",
")",
"\n",
"}",
"\n",
"d",
".",
"d",
"=",
"h",
".",
"newDecDriver",
"(",
"d",
")",
"\n",
"// d.cr, _ = d.d.(containerStateRecv)",
"return",
"d",
"\n",
"}"
] | // var defaultDecNaked decNaked | [
"var",
"defaultDecNaked",
"decNaked"
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/decode.go#L2344-L2367 | train |
ugorji/go | codec/decode.go | nextValueBytes | func (d *Decoder) nextValueBytes() (bs []byte) {
d.d.uncacheRead()
d.r.track()
d.swallow()
bs = d.r.stopTrack()
return
} | go | func (d *Decoder) nextValueBytes() (bs []byte) {
d.d.uncacheRead()
d.r.track()
d.swallow()
bs = d.r.stopTrack()
return
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"nextValueBytes",
"(",
")",
"(",
"bs",
"[",
"]",
"byte",
")",
"{",
"d",
".",
"d",
".",
"uncacheRead",
"(",
")",
"\n",
"d",
".",
"r",
".",
"track",
"(",
")",
"\n",
"d",
".",
"swallow",
"(",
")",
"\n",
"bs",
"=",
"d",
".",
"r",
".",
"stopTrack",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // nextValueBytes returns the next value in the stream as a set of bytes. | [
"nextValueBytes",
"returns",
"the",
"next",
"value",
"in",
"the",
"stream",
"as",
"a",
"set",
"of",
"bytes",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/decode.go#L2899-L2905 | train |
ugorji/go | codec/helper.go | basicHandle | func basicHandle(hh Handle) (x *BasicHandle) {
x = hh.getBasicHandle()
// ** We need to simulate once.Do, to ensure no data race within the block.
// ** Consequently, below would not work.
// if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {
// x.be = hh.isBinary()
// _, x.js = hh.(*JsonHandle)
// x.n = hh.Name()[0]
// }
// simulate once.Do using our own stored flag and mutex as a CompareAndSwap
// is not sufficient, since a race condition can occur within init(Handle) function.
// init is made noinline, so that this function can be inlined by its caller.
if atomic.LoadUint32(&x.inited) == 0 {
x.init(hh)
}
return
} | go | func basicHandle(hh Handle) (x *BasicHandle) {
x = hh.getBasicHandle()
// ** We need to simulate once.Do, to ensure no data race within the block.
// ** Consequently, below would not work.
// if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {
// x.be = hh.isBinary()
// _, x.js = hh.(*JsonHandle)
// x.n = hh.Name()[0]
// }
// simulate once.Do using our own stored flag and mutex as a CompareAndSwap
// is not sufficient, since a race condition can occur within init(Handle) function.
// init is made noinline, so that this function can be inlined by its caller.
if atomic.LoadUint32(&x.inited) == 0 {
x.init(hh)
}
return
} | [
"func",
"basicHandle",
"(",
"hh",
"Handle",
")",
"(",
"x",
"*",
"BasicHandle",
")",
"{",
"x",
"=",
"hh",
".",
"getBasicHandle",
"(",
")",
"\n",
"// ** We need to simulate once.Do, to ensure no data race within the block.",
"// ** Consequently, below would not work.",
"// if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {",
"// \tx.be = hh.isBinary()",
"// \t_, x.js = hh.(*JsonHandle)",
"// \tx.n = hh.Name()[0]",
"// }",
"// simulate once.Do using our own stored flag and mutex as a CompareAndSwap",
"// is not sufficient, since a race condition can occur within init(Handle) function.",
"// init is made noinline, so that this function can be inlined by its caller.",
"if",
"atomic",
".",
"LoadUint32",
"(",
"&",
"x",
".",
"inited",
")",
"==",
"0",
"{",
"x",
".",
"init",
"(",
"hh",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // basicHandle returns an initialized BasicHandle from the Handle. | [
"basicHandle",
"returns",
"an",
"initialized",
"BasicHandle",
"from",
"the",
"Handle",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/helper.go#L583-L600 | train |
ugorji/go | codec/helper.go | field | func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
// replicate FieldByIndex
for i, x := range si.is {
if uint8(i) == si.nis {
break
}
if v, valid = baseStructRv(v, update); !valid {
return
}
v = v.Field(int(x))
}
return v, true
} | go | func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
// replicate FieldByIndex
for i, x := range si.is {
if uint8(i) == si.nis {
break
}
if v, valid = baseStructRv(v, update); !valid {
return
}
v = v.Field(int(x))
}
return v, true
} | [
"func",
"(",
"si",
"*",
"structFieldInfo",
")",
"field",
"(",
"v",
"reflect",
".",
"Value",
",",
"update",
"bool",
")",
"(",
"rv2",
"reflect",
".",
"Value",
",",
"valid",
"bool",
")",
"{",
"// replicate FieldByIndex",
"for",
"i",
",",
"x",
":=",
"range",
"si",
".",
"is",
"{",
"if",
"uint8",
"(",
"i",
")",
"==",
"si",
".",
"nis",
"{",
"break",
"\n",
"}",
"\n",
"if",
"v",
",",
"valid",
"=",
"baseStructRv",
"(",
"v",
",",
"update",
")",
";",
"!",
"valid",
"{",
"return",
"\n",
"}",
"\n",
"v",
"=",
"v",
".",
"Field",
"(",
"int",
"(",
"x",
")",
")",
"\n",
"}",
"\n\n",
"return",
"v",
",",
"true",
"\n",
"}"
] | // rv returns the field of the struct.
// If anonymous, it returns an Invalid | [
"rv",
"returns",
"the",
"field",
"of",
"the",
"struct",
".",
"If",
"anonymous",
"it",
"returns",
"an",
"Invalid"
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/helper.go#L1236-L1249 | train |
ugorji/go | codec/encode.go | NewEncoderBytes | func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
e := newEncoder(h)
e.ResetBytes(out)
return e
} | go | func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
e := newEncoder(h)
e.ResetBytes(out)
return e
} | [
"func",
"NewEncoderBytes",
"(",
"out",
"*",
"[",
"]",
"byte",
",",
"h",
"Handle",
")",
"*",
"Encoder",
"{",
"e",
":=",
"newEncoder",
"(",
"h",
")",
"\n",
"e",
".",
"ResetBytes",
"(",
"out",
")",
"\n",
"return",
"e",
"\n",
"}"
] | // NewEncoderBytes returns an encoder for encoding directly and efficiently
// into a byte slice, using zero-copying to temporary slices.
//
// It will potentially replace the output byte slice pointed to.
// After encoding, the out parameter contains the encoded contents. | [
"NewEncoderBytes",
"returns",
"an",
"encoder",
"for",
"encoding",
"directly",
"and",
"efficiently",
"into",
"a",
"byte",
"slice",
"using",
"zero",
"-",
"copying",
"to",
"temporary",
"slices",
".",
"It",
"will",
"potentially",
"replace",
"the",
"output",
"byte",
"slice",
"pointed",
"to",
".",
"After",
"encoding",
"the",
"out",
"parameter",
"contains",
"the",
"encoded",
"contents",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/encode.go#L1272-L1276 | train |
ugorji/go | codec/encode.go | Reset | func (e *Encoder) Reset(w io.Writer) {
if w == nil {
return
}
// var ok bool
e.bytes = false
if e.wf == nil {
e.wf = new(bufioEncWriter)
}
// e.typ = entryTypeUnset
// if e.h.WriterBufferSize > 0 {
// // bw := bufio.NewWriterSize(w, e.h.WriterBufferSize)
// // e.wi.bw = bw
// // e.wi.sw = bw
// // e.wi.fw = bw
// // e.wi.ww = bw
// if e.wf == nil {
// e.wf = new(bufioEncWriter)
// }
// e.wf.reset(w, e.h.WriterBufferSize)
// e.typ = entryTypeBufio
// } else {
// if e.wi == nil {
// e.wi = new(ioEncWriter)
// }
// e.wi.reset(w)
// e.typ = entryTypeIo
// }
e.wf.reset(w, e.h.WriterBufferSize)
// e.typ = entryTypeBufio
// e.w = e.wi
e.resetCommon()
} | go | func (e *Encoder) Reset(w io.Writer) {
if w == nil {
return
}
// var ok bool
e.bytes = false
if e.wf == nil {
e.wf = new(bufioEncWriter)
}
// e.typ = entryTypeUnset
// if e.h.WriterBufferSize > 0 {
// // bw := bufio.NewWriterSize(w, e.h.WriterBufferSize)
// // e.wi.bw = bw
// // e.wi.sw = bw
// // e.wi.fw = bw
// // e.wi.ww = bw
// if e.wf == nil {
// e.wf = new(bufioEncWriter)
// }
// e.wf.reset(w, e.h.WriterBufferSize)
// e.typ = entryTypeBufio
// } else {
// if e.wi == nil {
// e.wi = new(ioEncWriter)
// }
// e.wi.reset(w)
// e.typ = entryTypeIo
// }
e.wf.reset(w, e.h.WriterBufferSize)
// e.typ = entryTypeBufio
// e.w = e.wi
e.resetCommon()
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"Reset",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"if",
"w",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// var ok bool",
"e",
".",
"bytes",
"=",
"false",
"\n",
"if",
"e",
".",
"wf",
"==",
"nil",
"{",
"e",
".",
"wf",
"=",
"new",
"(",
"bufioEncWriter",
")",
"\n",
"}",
"\n",
"// e.typ = entryTypeUnset",
"// if e.h.WriterBufferSize > 0 {",
"// \t// bw := bufio.NewWriterSize(w, e.h.WriterBufferSize)",
"// \t// e.wi.bw = bw",
"// \t// e.wi.sw = bw",
"// \t// e.wi.fw = bw",
"// \t// e.wi.ww = bw",
"// \tif e.wf == nil {",
"// \t\te.wf = new(bufioEncWriter)",
"// \t}",
"// \te.wf.reset(w, e.h.WriterBufferSize)",
"// \te.typ = entryTypeBufio",
"// } else {",
"// \tif e.wi == nil {",
"// \t\te.wi = new(ioEncWriter)",
"// \t}",
"// \te.wi.reset(w)",
"// \te.typ = entryTypeIo",
"// }",
"e",
".",
"wf",
".",
"reset",
"(",
"w",
",",
"e",
".",
"h",
".",
"WriterBufferSize",
")",
"\n",
"// e.typ = entryTypeBufio",
"// e.w = e.wi",
"e",
".",
"resetCommon",
"(",
")",
"\n",
"}"
] | // Reset resets the Encoder with a new output stream.
//
// This accommodates using the state of the Encoder,
// where it has "cached" information about sub-engines. | [
"Reset",
"resets",
"the",
"Encoder",
"with",
"a",
"new",
"output",
"stream",
".",
"This",
"accommodates",
"using",
"the",
"state",
"of",
"the",
"Encoder",
"where",
"it",
"has",
"cached",
"information",
"about",
"sub",
"-",
"engines",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/encode.go#L1309-L1342 | train |
ugorji/go | codec/encode.go | MustEncode | func (e *Encoder) MustEncode(v interface{}) {
if e.err != nil {
panic(e.err)
}
e.mustEncode(v)
} | go | func (e *Encoder) MustEncode(v interface{}) {
if e.err != nil {
panic(e.err)
}
e.mustEncode(v)
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"MustEncode",
"(",
"v",
"interface",
"{",
"}",
")",
"{",
"if",
"e",
".",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"e",
".",
"err",
")",
"\n",
"}",
"\n",
"e",
".",
"mustEncode",
"(",
"v",
")",
"\n",
"}"
] | // MustEncode is like Encode, but panics if unable to Encode.
// This provides insight to the code location that triggered the error. | [
"MustEncode",
"is",
"like",
"Encode",
"but",
"panics",
"if",
"unable",
"to",
"Encode",
".",
"This",
"provides",
"insight",
"to",
"the",
"code",
"location",
"that",
"triggered",
"the",
"error",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/encode.go#L1474-L1479 | train |
ugorji/go | codec/cbor.go | SetInterfaceExt | func (h *CborHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext})
} | go | func (h *CborHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext})
} | [
"func",
"(",
"h",
"*",
"CborHandle",
")",
"SetInterfaceExt",
"(",
"rt",
"reflect",
".",
"Type",
",",
"tag",
"uint64",
",",
"ext",
"InterfaceExt",
")",
"(",
"err",
"error",
")",
"{",
"return",
"h",
".",
"SetExt",
"(",
"rt",
",",
"tag",
",",
"&",
"extWrapper",
"{",
"bytesExtFailer",
"{",
"}",
",",
"ext",
"}",
")",
"\n",
"}"
] | // SetInterfaceExt sets an extension | [
"SetInterfaceExt",
"sets",
"an",
"extension"
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/cbor.go#L745-L747 | train |
ugorji/go | codec/msgpack.go | DecodeBool | func (d *msgpackDecDriver) DecodeBool() (b bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == mpFalse || d.bd == 0 {
// b = false
} else if d.bd == mpTrue || d.bd == 1 {
b = true
} else {
d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
return
}
d.bdRead = false
return
} | go | func (d *msgpackDecDriver) DecodeBool() (b bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == mpFalse || d.bd == 0 {
// b = false
} else if d.bd == mpTrue || d.bd == 1 {
b = true
} else {
d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
return
}
d.bdRead = false
return
} | [
"func",
"(",
"d",
"*",
"msgpackDecDriver",
")",
"DecodeBool",
"(",
")",
"(",
"b",
"bool",
")",
"{",
"if",
"!",
"d",
".",
"bdRead",
"{",
"d",
".",
"readNextBd",
"(",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"bd",
"==",
"mpFalse",
"||",
"d",
".",
"bd",
"==",
"0",
"{",
"// b = false",
"}",
"else",
"if",
"d",
".",
"bd",
"==",
"mpTrue",
"||",
"d",
".",
"bd",
"==",
"1",
"{",
"b",
"=",
"true",
"\n",
"}",
"else",
"{",
"d",
".",
"d",
".",
"errorf",
"(",
"\"",
"\"",
",",
"msgBadDesc",
",",
"d",
".",
"bd",
",",
"mpdesc",
"(",
"d",
".",
"bd",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"d",
".",
"bdRead",
"=",
"false",
"\n",
"return",
"\n",
"}"
] | // bool can be decoded from bool, fixnum 0 or 1. | [
"bool",
"can",
"be",
"decoded",
"from",
"bool",
"fixnum",
"0",
"or",
"1",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/msgpack.go#L680-L694 | train |
ugorji/go | codec/gen.go | xtraSM | func (x *genRunner) xtraSM(varname string, t reflect.Type, encode, isptr bool) {
var ptrPfx, addrPfx string
if isptr {
ptrPfx = "*"
} else {
addrPfx = "&"
}
if encode {
x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname)
} else {
x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname)
}
x.registerXtraT(t)
} | go | func (x *genRunner) xtraSM(varname string, t reflect.Type, encode, isptr bool) {
var ptrPfx, addrPfx string
if isptr {
ptrPfx = "*"
} else {
addrPfx = "&"
}
if encode {
x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname)
} else {
x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname)
}
x.registerXtraT(t)
} | [
"func",
"(",
"x",
"*",
"genRunner",
")",
"xtraSM",
"(",
"varname",
"string",
",",
"t",
"reflect",
".",
"Type",
",",
"encode",
",",
"isptr",
"bool",
")",
"{",
"var",
"ptrPfx",
",",
"addrPfx",
"string",
"\n",
"if",
"isptr",
"{",
"ptrPfx",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"addrPfx",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"encode",
"{",
"x",
".",
"linef",
"(",
"\"",
"\"",
",",
"x",
".",
"genMethodNameT",
"(",
"t",
")",
",",
"ptrPfx",
",",
"x",
".",
"genTypeName",
"(",
"t",
")",
",",
"varname",
")",
"\n",
"}",
"else",
"{",
"x",
".",
"linef",
"(",
"\"",
"\"",
",",
"x",
".",
"genMethodNameT",
"(",
"t",
")",
",",
"x",
".",
"genTypeName",
"(",
"t",
")",
",",
"addrPfx",
",",
"varname",
")",
"\n",
"}",
"\n",
"x",
".",
"registerXtraT",
"(",
"t",
")",
"\n",
"}"
] | // used for chan, array, slice, map | [
"used",
"for",
"chan",
"array",
"slice",
"map"
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/gen.go#L601-L614 | train |
ugorji/go | codec/gen.go | encVar | func (x *genRunner) encVar(varname string, t reflect.Type) {
// fmt.Printf(">>>>>> varname: %s, t: %v\n", varname, t)
var checkNil bool
switch t.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan:
checkNil = true
}
if checkNil {
x.linef("if %s == nil { r.EncodeNil() } else { ", varname)
}
switch t.Kind() {
case reflect.Ptr:
telem := t.Elem()
tek := telem.Kind()
if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) {
x.enc(varname, genNonPtr(t))
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := *" + varname)
x.enc(genTempVarPfx+i, genNonPtr(t))
case reflect.Struct, reflect.Array:
if t == timeTyp {
x.enc(varname, t)
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := &" + varname)
x.enc(genTempVarPfx+i, t)
default:
x.enc(varname, t)
}
if checkNil {
x.line("}")
}
} | go | func (x *genRunner) encVar(varname string, t reflect.Type) {
// fmt.Printf(">>>>>> varname: %s, t: %v\n", varname, t)
var checkNil bool
switch t.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan:
checkNil = true
}
if checkNil {
x.linef("if %s == nil { r.EncodeNil() } else { ", varname)
}
switch t.Kind() {
case reflect.Ptr:
telem := t.Elem()
tek := telem.Kind()
if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) {
x.enc(varname, genNonPtr(t))
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := *" + varname)
x.enc(genTempVarPfx+i, genNonPtr(t))
case reflect.Struct, reflect.Array:
if t == timeTyp {
x.enc(varname, t)
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := &" + varname)
x.enc(genTempVarPfx+i, t)
default:
x.enc(varname, t)
}
if checkNil {
x.line("}")
}
} | [
"func",
"(",
"x",
"*",
"genRunner",
")",
"encVar",
"(",
"varname",
"string",
",",
"t",
"reflect",
".",
"Type",
")",
"{",
"// fmt.Printf(\">>>>>> varname: %s, t: %v\\n\", varname, t)",
"var",
"checkNil",
"bool",
"\n",
"switch",
"t",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Ptr",
",",
"reflect",
".",
"Interface",
",",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Chan",
":",
"checkNil",
"=",
"true",
"\n",
"}",
"\n",
"if",
"checkNil",
"{",
"x",
".",
"linef",
"(",
"\"",
"\"",
",",
"varname",
")",
"\n",
"}",
"\n\n",
"switch",
"t",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Ptr",
":",
"telem",
":=",
"t",
".",
"Elem",
"(",
")",
"\n",
"tek",
":=",
"telem",
".",
"Kind",
"(",
")",
"\n",
"if",
"tek",
"==",
"reflect",
".",
"Array",
"||",
"(",
"tek",
"==",
"reflect",
".",
"Struct",
"&&",
"telem",
"!=",
"timeTyp",
")",
"{",
"x",
".",
"enc",
"(",
"varname",
",",
"genNonPtr",
"(",
"t",
")",
")",
"\n",
"break",
"\n",
"}",
"\n",
"i",
":=",
"x",
".",
"varsfx",
"(",
")",
"\n",
"x",
".",
"line",
"(",
"genTempVarPfx",
"+",
"i",
"+",
"\"",
"\"",
"+",
"varname",
")",
"\n",
"x",
".",
"enc",
"(",
"genTempVarPfx",
"+",
"i",
",",
"genNonPtr",
"(",
"t",
")",
")",
"\n",
"case",
"reflect",
".",
"Struct",
",",
"reflect",
".",
"Array",
":",
"if",
"t",
"==",
"timeTyp",
"{",
"x",
".",
"enc",
"(",
"varname",
",",
"t",
")",
"\n",
"break",
"\n",
"}",
"\n",
"i",
":=",
"x",
".",
"varsfx",
"(",
")",
"\n",
"x",
".",
"line",
"(",
"genTempVarPfx",
"+",
"i",
"+",
"\"",
"\"",
"+",
"varname",
")",
"\n",
"x",
".",
"enc",
"(",
"genTempVarPfx",
"+",
"i",
",",
"t",
")",
"\n",
"default",
":",
"x",
".",
"enc",
"(",
"varname",
",",
"t",
")",
"\n",
"}",
"\n\n",
"if",
"checkNil",
"{",
"x",
".",
"line",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"}"
] | // encVar will encode a variable.
// The parameter, t, is the reflect.Type of the variable itself | [
"encVar",
"will",
"encode",
"a",
"variable",
".",
"The",
"parameter",
"t",
"is",
"the",
"reflect",
".",
"Type",
"of",
"the",
"variable",
"itself"
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/gen.go#L640-L678 | train |
ugorji/go | codec/gen.go | genImportPath | func genImportPath(t reflect.Type) (s string) {
s = t.PkgPath()
if genCheckVendor {
// HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
s = genStripVendor(s)
}
return
} | go | func genImportPath(t reflect.Type) (s string) {
s = t.PkgPath()
if genCheckVendor {
// HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
s = genStripVendor(s)
}
return
} | [
"func",
"genImportPath",
"(",
"t",
"reflect",
".",
"Type",
")",
"(",
"s",
"string",
")",
"{",
"s",
"=",
"t",
".",
"PkgPath",
"(",
")",
"\n",
"if",
"genCheckVendor",
"{",
"// HACK: always handle vendoring. It should be typically on in go 1.6, 1.7",
"s",
"=",
"genStripVendor",
"(",
"s",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // genImportPath returns import path of a non-predeclared named typed, or an empty string otherwise.
//
// This handles the misbehaviour that occurs when 1.5-style vendoring is enabled,
// where PkgPath returns the full path, including the vendoring pre-fix that should have been stripped.
// We strip it here. | [
"genImportPath",
"returns",
"import",
"path",
"of",
"a",
"non",
"-",
"predeclared",
"named",
"typed",
"or",
"an",
"empty",
"string",
"otherwise",
".",
"This",
"handles",
"the",
"misbehaviour",
"that",
"occurs",
"when",
"1",
".",
"5",
"-",
"style",
"vendoring",
"is",
"enabled",
"where",
"PkgPath",
"returns",
"the",
"full",
"path",
"including",
"the",
"vendoring",
"pre",
"-",
"fix",
"that",
"should",
"have",
"been",
"stripped",
".",
"We",
"strip",
"it",
"here",
"."
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/gen.go#L1754-L1761 | train |
ugorji/go | codec/simple.go | SetBytesExt | func (h *SimpleHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}})
} | go | func (h *SimpleHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}})
} | [
"func",
"(",
"h",
"*",
"SimpleHandle",
")",
"SetBytesExt",
"(",
"rt",
"reflect",
".",
"Type",
",",
"tag",
"uint64",
",",
"ext",
"BytesExt",
")",
"(",
"err",
"error",
")",
"{",
"return",
"h",
".",
"SetExt",
"(",
"rt",
",",
"tag",
",",
"&",
"extWrapper",
"{",
"ext",
",",
"interfaceExtFailer",
"{",
"}",
"}",
")",
"\n",
"}"
] | // SetBytesExt sets an extension | [
"SetBytesExt",
"sets",
"an",
"extension"
] | 1d7ab5c50b36701116070c4c612259f93c262367 | https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/simple.go#L640-L642 | train |
go-validator/validator | builtins.go | nonzero | func nonzero(v interface{}, param string) error {
st := reflect.ValueOf(v)
valid := true
switch st.Kind() {
case reflect.String:
valid = len(st.String()) != 0
case reflect.Ptr, reflect.Interface:
valid = !st.IsNil()
case reflect.Slice, reflect.Map, reflect.Array:
valid = st.Len() != 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
valid = st.Int() != 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
valid = st.Uint() != 0
case reflect.Float32, reflect.Float64:
valid = st.Float() != 0
case reflect.Bool:
valid = st.Bool()
case reflect.Invalid:
valid = false // always invalid
case reflect.Struct:
valid = true // always valid since only nil pointers are empty
default:
return ErrUnsupported
}
if !valid {
return ErrZeroValue
}
return nil
} | go | func nonzero(v interface{}, param string) error {
st := reflect.ValueOf(v)
valid := true
switch st.Kind() {
case reflect.String:
valid = len(st.String()) != 0
case reflect.Ptr, reflect.Interface:
valid = !st.IsNil()
case reflect.Slice, reflect.Map, reflect.Array:
valid = st.Len() != 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
valid = st.Int() != 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
valid = st.Uint() != 0
case reflect.Float32, reflect.Float64:
valid = st.Float() != 0
case reflect.Bool:
valid = st.Bool()
case reflect.Invalid:
valid = false // always invalid
case reflect.Struct:
valid = true // always valid since only nil pointers are empty
default:
return ErrUnsupported
}
if !valid {
return ErrZeroValue
}
return nil
} | [
"func",
"nonzero",
"(",
"v",
"interface",
"{",
"}",
",",
"param",
"string",
")",
"error",
"{",
"st",
":=",
"reflect",
".",
"ValueOf",
"(",
"v",
")",
"\n",
"valid",
":=",
"true",
"\n",
"switch",
"st",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"valid",
"=",
"len",
"(",
"st",
".",
"String",
"(",
")",
")",
"!=",
"0",
"\n",
"case",
"reflect",
".",
"Ptr",
",",
"reflect",
".",
"Interface",
":",
"valid",
"=",
"!",
"st",
".",
"IsNil",
"(",
")",
"\n",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Array",
":",
"valid",
"=",
"st",
".",
"Len",
"(",
")",
"!=",
"0",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"valid",
"=",
"st",
".",
"Int",
"(",
")",
"!=",
"0",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
":",
"valid",
"=",
"st",
".",
"Uint",
"(",
")",
"!=",
"0",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"valid",
"=",
"st",
".",
"Float",
"(",
")",
"!=",
"0",
"\n",
"case",
"reflect",
".",
"Bool",
":",
"valid",
"=",
"st",
".",
"Bool",
"(",
")",
"\n",
"case",
"reflect",
".",
"Invalid",
":",
"valid",
"=",
"false",
"// always invalid",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"valid",
"=",
"true",
"// always valid since only nil pointers are empty",
"\n",
"default",
":",
"return",
"ErrUnsupported",
"\n",
"}",
"\n\n",
"if",
"!",
"valid",
"{",
"return",
"ErrZeroValue",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // nonzero tests whether a variable value non-zero
// as defined by the golang spec. | [
"nonzero",
"tests",
"whether",
"a",
"variable",
"value",
"non",
"-",
"zero",
"as",
"defined",
"by",
"the",
"golang",
"spec",
"."
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/builtins.go#L27-L57 | train |
go-validator/validator | builtins.go | length | func length(v interface{}, param string) error {
st := reflect.ValueOf(v)
valid := true
if st.Kind() == reflect.Ptr {
if st.IsNil() {
return nil
}
st = st.Elem()
}
switch st.Kind() {
case reflect.String:
p, err := asInt(param)
if err != nil {
return ErrBadParameter
}
valid = int64(len(st.String())) == p
case reflect.Slice, reflect.Map, reflect.Array:
p, err := asInt(param)
if err != nil {
return ErrBadParameter
}
valid = int64(st.Len()) == p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p, err := asInt(param)
if err != nil {
return ErrBadParameter
}
valid = st.Int() == p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p, err := asUint(param)
if err != nil {
return ErrBadParameter
}
valid = st.Uint() == p
case reflect.Float32, reflect.Float64:
p, err := asFloat(param)
if err != nil {
return ErrBadParameter
}
valid = st.Float() == p
default:
return ErrUnsupported
}
if !valid {
return ErrLen
}
return nil
} | go | func length(v interface{}, param string) error {
st := reflect.ValueOf(v)
valid := true
if st.Kind() == reflect.Ptr {
if st.IsNil() {
return nil
}
st = st.Elem()
}
switch st.Kind() {
case reflect.String:
p, err := asInt(param)
if err != nil {
return ErrBadParameter
}
valid = int64(len(st.String())) == p
case reflect.Slice, reflect.Map, reflect.Array:
p, err := asInt(param)
if err != nil {
return ErrBadParameter
}
valid = int64(st.Len()) == p
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p, err := asInt(param)
if err != nil {
return ErrBadParameter
}
valid = st.Int() == p
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p, err := asUint(param)
if err != nil {
return ErrBadParameter
}
valid = st.Uint() == p
case reflect.Float32, reflect.Float64:
p, err := asFloat(param)
if err != nil {
return ErrBadParameter
}
valid = st.Float() == p
default:
return ErrUnsupported
}
if !valid {
return ErrLen
}
return nil
} | [
"func",
"length",
"(",
"v",
"interface",
"{",
"}",
",",
"param",
"string",
")",
"error",
"{",
"st",
":=",
"reflect",
".",
"ValueOf",
"(",
"v",
")",
"\n",
"valid",
":=",
"true",
"\n",
"if",
"st",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"if",
"st",
".",
"IsNil",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"st",
"=",
"st",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"switch",
"st",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"p",
",",
"err",
":=",
"asInt",
"(",
"param",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrBadParameter",
"\n",
"}",
"\n",
"valid",
"=",
"int64",
"(",
"len",
"(",
"st",
".",
"String",
"(",
")",
")",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
",",
"reflect",
".",
"Array",
":",
"p",
",",
"err",
":=",
"asInt",
"(",
"param",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrBadParameter",
"\n",
"}",
"\n",
"valid",
"=",
"int64",
"(",
"st",
".",
"Len",
"(",
")",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"p",
",",
"err",
":=",
"asInt",
"(",
"param",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrBadParameter",
"\n",
"}",
"\n",
"valid",
"=",
"st",
".",
"Int",
"(",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
":",
"p",
",",
"err",
":=",
"asUint",
"(",
"param",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrBadParameter",
"\n",
"}",
"\n",
"valid",
"=",
"st",
".",
"Uint",
"(",
")",
"==",
"p",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"p",
",",
"err",
":=",
"asFloat",
"(",
"param",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrBadParameter",
"\n",
"}",
"\n",
"valid",
"=",
"st",
".",
"Float",
"(",
")",
"==",
"p",
"\n",
"default",
":",
"return",
"ErrUnsupported",
"\n",
"}",
"\n",
"if",
"!",
"valid",
"{",
"return",
"ErrLen",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // length tests whether a variable's length is equal to a given
// value. For strings it tests the number of characters whereas
// for maps and slices it tests the number of items. | [
"length",
"tests",
"whether",
"a",
"variable",
"s",
"length",
"is",
"equal",
"to",
"a",
"given",
"value",
".",
"For",
"strings",
"it",
"tests",
"the",
"number",
"of",
"characters",
"whereas",
"for",
"maps",
"and",
"slices",
"it",
"tests",
"the",
"number",
"of",
"items",
"."
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/builtins.go#L62-L109 | train |
go-validator/validator | builtins.go | regex | func regex(v interface{}, param string) error {
s, ok := v.(string)
if !ok {
sptr, ok := v.(*string)
if !ok {
return ErrUnsupported
}
if sptr == nil {
return nil
}
s = *sptr
}
re, err := regexp.Compile(param)
if err != nil {
return ErrBadParameter
}
if !re.MatchString(s) {
return ErrRegexp
}
return nil
} | go | func regex(v interface{}, param string) error {
s, ok := v.(string)
if !ok {
sptr, ok := v.(*string)
if !ok {
return ErrUnsupported
}
if sptr == nil {
return nil
}
s = *sptr
}
re, err := regexp.Compile(param)
if err != nil {
return ErrBadParameter
}
if !re.MatchString(s) {
return ErrRegexp
}
return nil
} | [
"func",
"regex",
"(",
"v",
"interface",
"{",
"}",
",",
"param",
"string",
")",
"error",
"{",
"s",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"sptr",
",",
"ok",
":=",
"v",
".",
"(",
"*",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrUnsupported",
"\n",
"}",
"\n",
"if",
"sptr",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
"=",
"*",
"sptr",
"\n",
"}",
"\n\n",
"re",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"param",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrBadParameter",
"\n",
"}",
"\n\n",
"if",
"!",
"re",
".",
"MatchString",
"(",
"s",
")",
"{",
"return",
"ErrRegexp",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // regex is the builtin validation function that checks
// whether the string variable matches a regular expression | [
"regex",
"is",
"the",
"builtin",
"validation",
"function",
"that",
"checks",
"whether",
"the",
"string",
"variable",
"matches",
"a",
"regular",
"expression"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/builtins.go#L219-L241 | train |
go-validator/validator | builtins.go | asInt | func asInt(param string) (int64, error) {
i, err := strconv.ParseInt(param, 0, 64)
if err != nil {
return 0, ErrBadParameter
}
return i, nil
} | go | func asInt(param string) (int64, error) {
i, err := strconv.ParseInt(param, 0, 64)
if err != nil {
return 0, ErrBadParameter
}
return i, nil
} | [
"func",
"asInt",
"(",
"param",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"param",
",",
"0",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"ErrBadParameter",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}"
] | // asInt retuns the parameter as a int64
// or panics if it can't convert | [
"asInt",
"retuns",
"the",
"parameter",
"as",
"a",
"int64",
"or",
"panics",
"if",
"it",
"can",
"t",
"convert"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/builtins.go#L245-L251 | train |
go-validator/validator | builtins.go | asUint | func asUint(param string) (uint64, error) {
i, err := strconv.ParseUint(param, 0, 64)
if err != nil {
return 0, ErrBadParameter
}
return i, nil
} | go | func asUint(param string) (uint64, error) {
i, err := strconv.ParseUint(param, 0, 64)
if err != nil {
return 0, ErrBadParameter
}
return i, nil
} | [
"func",
"asUint",
"(",
"param",
"string",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"param",
",",
"0",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"ErrBadParameter",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}"
] | // asUint retuns the parameter as a uint64
// or panics if it can't convert | [
"asUint",
"retuns",
"the",
"parameter",
"as",
"a",
"uint64",
"or",
"panics",
"if",
"it",
"can",
"t",
"convert"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/builtins.go#L255-L261 | train |
go-validator/validator | builtins.go | asFloat | func asFloat(param string) (float64, error) {
i, err := strconv.ParseFloat(param, 64)
if err != nil {
return 0.0, ErrBadParameter
}
return i, nil
} | go | func asFloat(param string) (float64, error) {
i, err := strconv.ParseFloat(param, 64)
if err != nil {
return 0.0, ErrBadParameter
}
return i, nil
} | [
"func",
"asFloat",
"(",
"param",
"string",
")",
"(",
"float64",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"param",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0.0",
",",
"ErrBadParameter",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}"
] | // asFloat retuns the parameter as a float64
// or panics if it can't convert | [
"asFloat",
"retuns",
"the",
"parameter",
"as",
"a",
"float64",
"or",
"panics",
"if",
"it",
"can",
"t",
"convert"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/builtins.go#L265-L271 | train |
go-validator/validator | validator.go | MarshalText | func (t TextErr) MarshalText() ([]byte, error) {
return []byte(t.Err.Error()), nil
} | go | func (t TextErr) MarshalText() ([]byte, error) {
return []byte(t.Err.Error()), nil
} | [
"func",
"(",
"t",
"TextErr",
")",
"MarshalText",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"t",
".",
"Err",
".",
"Error",
"(",
")",
")",
",",
"nil",
"\n",
"}"
] | // MarshalText implements the TextMarshaller | [
"MarshalText",
"implements",
"the",
"TextMarshaller"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/validator.go#L42-L44 | train |
go-validator/validator | validator.go | Error | func (err ErrorMap) Error() string {
for k, errs := range err {
if len(errs) > 0 {
return fmt.Sprintf("%s: %s", k, errs.Error())
}
}
return ""
} | go | func (err ErrorMap) Error() string {
for k, errs := range err {
if len(errs) > 0 {
return fmt.Sprintf("%s: %s", k, errs.Error())
}
}
return ""
} | [
"func",
"(",
"err",
"ErrorMap",
")",
"Error",
"(",
")",
"string",
"{",
"for",
"k",
",",
"errs",
":=",
"range",
"err",
"{",
"if",
"len",
"(",
"errs",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
",",
"errs",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // ErrorMap implements the Error interface so we can check error against nil.
// The returned error is if existent the first error which was added to the map. | [
"ErrorMap",
"implements",
"the",
"Error",
"interface",
"so",
"we",
"can",
"check",
"error",
"against",
"nil",
".",
"The",
"returned",
"error",
"is",
"if",
"existent",
"the",
"first",
"error",
"which",
"was",
"added",
"to",
"the",
"map",
"."
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/validator.go#L81-L89 | train |
go-validator/validator | validator.go | NewValidator | func NewValidator() *Validator {
return &Validator{
tagName: "validate",
validationFuncs: map[string]ValidationFunc{
"nonzero": nonzero,
"len": length,
"min": min,
"max": max,
"regexp": regex,
},
}
} | go | func NewValidator() *Validator {
return &Validator{
tagName: "validate",
validationFuncs: map[string]ValidationFunc{
"nonzero": nonzero,
"len": length,
"min": min,
"max": max,
"regexp": regex,
},
}
} | [
"func",
"NewValidator",
"(",
")",
"*",
"Validator",
"{",
"return",
"&",
"Validator",
"{",
"tagName",
":",
"\"",
"\"",
",",
"validationFuncs",
":",
"map",
"[",
"string",
"]",
"ValidationFunc",
"{",
"\"",
"\"",
":",
"nonzero",
",",
"\"",
"\"",
":",
"length",
",",
"\"",
"\"",
":",
"min",
",",
"\"",
"\"",
":",
"max",
",",
"\"",
"\"",
":",
"regex",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewValidator creates a new Validator | [
"NewValidator",
"creates",
"a",
"new",
"Validator"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/validator.go#L121-L132 | train |
go-validator/validator | validator.go | Validate | func (mv *Validator) Validate(v interface{}) error {
sv := reflect.ValueOf(v)
st := reflect.TypeOf(v)
if sv.Kind() == reflect.Ptr && !sv.IsNil() {
return mv.Validate(sv.Elem().Interface())
}
if sv.Kind() != reflect.Struct && sv.Kind() != reflect.Interface {
return ErrUnsupported
}
nfields := sv.NumField()
m := make(ErrorMap)
for i := 0; i < nfields; i++ {
fname := st.Field(i).Name
if !unicode.IsUpper(rune(fname[0])) {
continue
}
f := sv.Field(i)
// deal with pointers
for f.Kind() == reflect.Ptr && !f.IsNil() {
f = f.Elem()
}
tag := st.Field(i).Tag.Get(mv.tagName)
if tag == "-" {
continue
}
var errs ErrorArray
if tag != "" {
err := mv.Valid(f.Interface(), tag)
if errors, ok := err.(ErrorArray); ok {
errs = errors
} else {
if err != nil {
errs = ErrorArray{err}
}
}
}
mv.deepValidateCollection(f, fname, m) // no-op if field is not a struct, interface, array, slice or map
if len(errs) > 0 {
m[st.Field(i).Name] = errs
}
}
if len(m) > 0 {
return m
}
return nil
} | go | func (mv *Validator) Validate(v interface{}) error {
sv := reflect.ValueOf(v)
st := reflect.TypeOf(v)
if sv.Kind() == reflect.Ptr && !sv.IsNil() {
return mv.Validate(sv.Elem().Interface())
}
if sv.Kind() != reflect.Struct && sv.Kind() != reflect.Interface {
return ErrUnsupported
}
nfields := sv.NumField()
m := make(ErrorMap)
for i := 0; i < nfields; i++ {
fname := st.Field(i).Name
if !unicode.IsUpper(rune(fname[0])) {
continue
}
f := sv.Field(i)
// deal with pointers
for f.Kind() == reflect.Ptr && !f.IsNil() {
f = f.Elem()
}
tag := st.Field(i).Tag.Get(mv.tagName)
if tag == "-" {
continue
}
var errs ErrorArray
if tag != "" {
err := mv.Valid(f.Interface(), tag)
if errors, ok := err.(ErrorArray); ok {
errs = errors
} else {
if err != nil {
errs = ErrorArray{err}
}
}
}
mv.deepValidateCollection(f, fname, m) // no-op if field is not a struct, interface, array, slice or map
if len(errs) > 0 {
m[st.Field(i).Name] = errs
}
}
if len(m) > 0 {
return m
}
return nil
} | [
"func",
"(",
"mv",
"*",
"Validator",
")",
"Validate",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"sv",
":=",
"reflect",
".",
"ValueOf",
"(",
"v",
")",
"\n",
"st",
":=",
"reflect",
".",
"TypeOf",
"(",
"v",
")",
"\n",
"if",
"sv",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"&&",
"!",
"sv",
".",
"IsNil",
"(",
")",
"{",
"return",
"mv",
".",
"Validate",
"(",
"sv",
".",
"Elem",
"(",
")",
".",
"Interface",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"sv",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"&&",
"sv",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Interface",
"{",
"return",
"ErrUnsupported",
"\n",
"}",
"\n\n",
"nfields",
":=",
"sv",
".",
"NumField",
"(",
")",
"\n",
"m",
":=",
"make",
"(",
"ErrorMap",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nfields",
";",
"i",
"++",
"{",
"fname",
":=",
"st",
".",
"Field",
"(",
"i",
")",
".",
"Name",
"\n",
"if",
"!",
"unicode",
".",
"IsUpper",
"(",
"rune",
"(",
"fname",
"[",
"0",
"]",
")",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"f",
":=",
"sv",
".",
"Field",
"(",
"i",
")",
"\n",
"// deal with pointers",
"for",
"f",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"&&",
"!",
"f",
".",
"IsNil",
"(",
")",
"{",
"f",
"=",
"f",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"tag",
":=",
"st",
".",
"Field",
"(",
"i",
")",
".",
"Tag",
".",
"Get",
"(",
"mv",
".",
"tagName",
")",
"\n",
"if",
"tag",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"var",
"errs",
"ErrorArray",
"\n\n",
"if",
"tag",
"!=",
"\"",
"\"",
"{",
"err",
":=",
"mv",
".",
"Valid",
"(",
"f",
".",
"Interface",
"(",
")",
",",
"tag",
")",
"\n",
"if",
"errors",
",",
"ok",
":=",
"err",
".",
"(",
"ErrorArray",
")",
";",
"ok",
"{",
"errs",
"=",
"errors",
"\n",
"}",
"else",
"{",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"ErrorArray",
"{",
"err",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"mv",
".",
"deepValidateCollection",
"(",
"f",
",",
"fname",
",",
"m",
")",
"// no-op if field is not a struct, interface, array, slice or map",
"\n\n",
"if",
"len",
"(",
"errs",
")",
">",
"0",
"{",
"m",
"[",
"st",
".",
"Field",
"(",
"i",
")",
".",
"Name",
"]",
"=",
"errs",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"m",
")",
">",
"0",
"{",
"return",
"m",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate validates the fields of a struct based
// on 'validator' tags and returns errors found indexed
// by the field name. | [
"Validate",
"validates",
"the",
"fields",
"of",
"a",
"struct",
"based",
"on",
"validator",
"tags",
"and",
"returns",
"errors",
"found",
"indexed",
"by",
"the",
"field",
"name",
"."
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/validator.go#L204-L255 | train |
go-validator/validator | validator.go | validateVar | func (mv *Validator) validateVar(v interface{}, tag string) error {
tags, err := mv.parseTags(tag)
if err != nil {
// unknown tag found, give up.
return err
}
errs := make(ErrorArray, 0, len(tags))
for _, t := range tags {
if err := t.Fn(v, t.Param); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errs
}
return nil
} | go | func (mv *Validator) validateVar(v interface{}, tag string) error {
tags, err := mv.parseTags(tag)
if err != nil {
// unknown tag found, give up.
return err
}
errs := make(ErrorArray, 0, len(tags))
for _, t := range tags {
if err := t.Fn(v, t.Param); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errs
}
return nil
} | [
"func",
"(",
"mv",
"*",
"Validator",
")",
"validateVar",
"(",
"v",
"interface",
"{",
"}",
",",
"tag",
"string",
")",
"error",
"{",
"tags",
",",
"err",
":=",
"mv",
".",
"parseTags",
"(",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// unknown tag found, give up.",
"return",
"err",
"\n",
"}",
"\n",
"errs",
":=",
"make",
"(",
"ErrorArray",
",",
"0",
",",
"len",
"(",
"tags",
")",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tags",
"{",
"if",
"err",
":=",
"t",
".",
"Fn",
"(",
"v",
",",
"t",
".",
"Param",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errs",
")",
">",
"0",
"{",
"return",
"errs",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateVar validates one single variable | [
"validateVar",
"validates",
"one",
"single",
"variable"
] | 135c24b11c19e52befcae2ec3fca5d9b78c4e98e | https://github.com/go-validator/validator/blob/135c24b11c19e52befcae2ec3fca5d9b78c4e98e/validator.go#L306-L322 | train |
mikespook/gorbac | helper.go | Walk | func Walk(rbac *RBAC, h WalkHandler) (err error) {
if h == nil {
return
}
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
for id := range rbac.roles {
var parents []string
r := rbac.roles[id]
for parent := range rbac.parents[id] {
parents = append(parents, parent)
}
if err := h(r, parents); err != nil {
return err
}
}
return
} | go | func Walk(rbac *RBAC, h WalkHandler) (err error) {
if h == nil {
return
}
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
for id := range rbac.roles {
var parents []string
r := rbac.roles[id]
for parent := range rbac.parents[id] {
parents = append(parents, parent)
}
if err := h(r, parents); err != nil {
return err
}
}
return
} | [
"func",
"Walk",
"(",
"rbac",
"*",
"RBAC",
",",
"h",
"WalkHandler",
")",
"(",
"err",
"error",
")",
"{",
"if",
"h",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"for",
"id",
":=",
"range",
"rbac",
".",
"roles",
"{",
"var",
"parents",
"[",
"]",
"string",
"\n",
"r",
":=",
"rbac",
".",
"roles",
"[",
"id",
"]",
"\n",
"for",
"parent",
":=",
"range",
"rbac",
".",
"parents",
"[",
"id",
"]",
"{",
"parents",
"=",
"append",
"(",
"parents",
",",
"parent",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"h",
"(",
"r",
",",
"parents",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Walk passes each Role to WalkHandler | [
"Walk",
"passes",
"each",
"Role",
"to",
"WalkHandler"
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/helper.go#L9-L26 | train |
mikespook/gorbac | helper.go | InherCircle | func InherCircle(rbac *RBAC) (err error) {
rbac.mutex.Lock()
skipped := make(map[string]struct{}, len(rbac.roles))
var stack []string
for id := range rbac.roles {
if err = dfs(rbac, id, skipped, stack); err != nil {
break
}
}
rbac.mutex.Unlock()
return err
} | go | func InherCircle(rbac *RBAC) (err error) {
rbac.mutex.Lock()
skipped := make(map[string]struct{}, len(rbac.roles))
var stack []string
for id := range rbac.roles {
if err = dfs(rbac, id, skipped, stack); err != nil {
break
}
}
rbac.mutex.Unlock()
return err
} | [
"func",
"InherCircle",
"(",
"rbac",
"*",
"RBAC",
")",
"(",
"err",
"error",
")",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n\n",
"skipped",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"rbac",
".",
"roles",
")",
")",
"\n",
"var",
"stack",
"[",
"]",
"string",
"\n\n",
"for",
"id",
":=",
"range",
"rbac",
".",
"roles",
"{",
"if",
"err",
"=",
"dfs",
"(",
"rbac",
",",
"id",
",",
"skipped",
",",
"stack",
")",
";",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // InherCircle returns an error when detecting any circle inheritance. | [
"InherCircle",
"returns",
"an",
"error",
"when",
"detecting",
"any",
"circle",
"inheritance",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/helper.go#L29-L42 | train |
mikespook/gorbac | helper.go | AnyGranted | func AnyGranted(rbac *RBAC, roles []string, permission Permission,
assert AssertionFunc) (rslt bool) {
rbac.mutex.Lock()
for _, role := range roles {
if rbac.isGranted(role, permission, assert) {
rslt = true
break
}
}
rbac.mutex.Unlock()
return rslt
} | go | func AnyGranted(rbac *RBAC, roles []string, permission Permission,
assert AssertionFunc) (rslt bool) {
rbac.mutex.Lock()
for _, role := range roles {
if rbac.isGranted(role, permission, assert) {
rslt = true
break
}
}
rbac.mutex.Unlock()
return rslt
} | [
"func",
"AnyGranted",
"(",
"rbac",
"*",
"RBAC",
",",
"roles",
"[",
"]",
"string",
",",
"permission",
"Permission",
",",
"assert",
"AssertionFunc",
")",
"(",
"rslt",
"bool",
")",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"roles",
"{",
"if",
"rbac",
".",
"isGranted",
"(",
"role",
",",
"permission",
",",
"assert",
")",
"{",
"rslt",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"rslt",
"\n",
"}"
] | // AnyGranted checks if any role has the permission. | [
"AnyGranted",
"checks",
"if",
"any",
"role",
"has",
"the",
"permission",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/helper.go#L74-L85 | train |
mikespook/gorbac | role.go | NewStdRole | func NewStdRole(id string) *StdRole {
role := &StdRole{
IDStr: id,
permissions: make(Permissions),
}
return role
} | go | func NewStdRole(id string) *StdRole {
role := &StdRole{
IDStr: id,
permissions: make(Permissions),
}
return role
} | [
"func",
"NewStdRole",
"(",
"id",
"string",
")",
"*",
"StdRole",
"{",
"role",
":=",
"&",
"StdRole",
"{",
"IDStr",
":",
"id",
",",
"permissions",
":",
"make",
"(",
"Permissions",
")",
",",
"}",
"\n",
"return",
"role",
"\n",
"}"
] | // NewStdRole is the default role factory function.
// It matches the declaration to RoleFactoryFunc. | [
"NewStdRole",
"is",
"the",
"default",
"role",
"factory",
"function",
".",
"It",
"matches",
"the",
"declaration",
"to",
"RoleFactoryFunc",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/role.go#L19-L25 | train |
mikespook/gorbac | role.go | Assign | func (role *StdRole) Assign(p Permission) error {
role.Lock()
role.permissions[p.ID()] = p
role.Unlock()
return nil
} | go | func (role *StdRole) Assign(p Permission) error {
role.Lock()
role.permissions[p.ID()] = p
role.Unlock()
return nil
} | [
"func",
"(",
"role",
"*",
"StdRole",
")",
"Assign",
"(",
"p",
"Permission",
")",
"error",
"{",
"role",
".",
"Lock",
"(",
")",
"\n",
"role",
".",
"permissions",
"[",
"p",
".",
"ID",
"(",
")",
"]",
"=",
"p",
"\n",
"role",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Assign a permission to the role. | [
"Assign",
"a",
"permission",
"to",
"the",
"role",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/role.go#L42-L47 | train |
mikespook/gorbac | role.go | Permit | func (role *StdRole) Permit(p Permission) (rslt bool) {
if p == nil {
return false
}
role.RLock()
for _, rp := range role.permissions {
if rp.Match(p) {
rslt = true
break
}
}
role.RUnlock()
return
} | go | func (role *StdRole) Permit(p Permission) (rslt bool) {
if p == nil {
return false
}
role.RLock()
for _, rp := range role.permissions {
if rp.Match(p) {
rslt = true
break
}
}
role.RUnlock()
return
} | [
"func",
"(",
"role",
"*",
"StdRole",
")",
"Permit",
"(",
"p",
"Permission",
")",
"(",
"rslt",
"bool",
")",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"role",
".",
"RLock",
"(",
")",
"\n",
"for",
"_",
",",
"rp",
":=",
"range",
"role",
".",
"permissions",
"{",
"if",
"rp",
".",
"Match",
"(",
"p",
")",
"{",
"rslt",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"role",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Permit returns true if the role has specific permission. | [
"Permit",
"returns",
"true",
"if",
"the",
"role",
"has",
"specific",
"permission",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/role.go#L50-L64 | train |
mikespook/gorbac | role.go | Revoke | func (role *StdRole) Revoke(p Permission) error {
role.Lock()
delete(role.permissions, p.ID())
role.Unlock()
return nil
} | go | func (role *StdRole) Revoke(p Permission) error {
role.Lock()
delete(role.permissions, p.ID())
role.Unlock()
return nil
} | [
"func",
"(",
"role",
"*",
"StdRole",
")",
"Revoke",
"(",
"p",
"Permission",
")",
"error",
"{",
"role",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"role",
".",
"permissions",
",",
"p",
".",
"ID",
"(",
")",
")",
"\n",
"role",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Revoke the specific permission. | [
"Revoke",
"the",
"specific",
"permission",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/role.go#L67-L72 | train |
mikespook/gorbac | role.go | Permissions | func (role *StdRole) Permissions() []Permission {
role.RLock()
result := make([]Permission, 0, len(role.permissions))
for _, p := range role.permissions {
result = append(result, p)
}
role.RUnlock()
return result
} | go | func (role *StdRole) Permissions() []Permission {
role.RLock()
result := make([]Permission, 0, len(role.permissions))
for _, p := range role.permissions {
result = append(result, p)
}
role.RUnlock()
return result
} | [
"func",
"(",
"role",
"*",
"StdRole",
")",
"Permissions",
"(",
")",
"[",
"]",
"Permission",
"{",
"role",
".",
"RLock",
"(",
")",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"Permission",
",",
"0",
",",
"len",
"(",
"role",
".",
"permissions",
")",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"role",
".",
"permissions",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"p",
")",
"\n",
"}",
"\n",
"role",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"result",
"\n",
"}"
] | // Permissions returns all permissions into a slice. | [
"Permissions",
"returns",
"all",
"permissions",
"into",
"a",
"slice",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/role.go#L75-L83 | train |
mikespook/gorbac | rbac.go | New | func New() *RBAC {
return &RBAC{
roles: make(Roles),
parents: make(map[string]map[string]struct{}),
}
} | go | func New() *RBAC {
return &RBAC{
roles: make(Roles),
parents: make(map[string]map[string]struct{}),
}
} | [
"func",
"New",
"(",
")",
"*",
"RBAC",
"{",
"return",
"&",
"RBAC",
"{",
"roles",
":",
"make",
"(",
"Roles",
")",
",",
"parents",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // New returns a RBAC structure.
// The default role structure will be used. | [
"New",
"returns",
"a",
"RBAC",
"structure",
".",
"The",
"default",
"role",
"structure",
"will",
"be",
"used",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L44-L49 | train |
mikespook/gorbac | rbac.go | GetParents | func (rbac *RBAC) GetParents(id string) ([]string, error) {
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
if _, ok := rbac.roles[id]; !ok {
return nil, ErrRoleNotExist
}
ids, ok := rbac.parents[id]
if !ok {
return nil, nil
}
var parents []string
for parent := range ids {
parents = append(parents, parent)
}
return parents, nil
} | go | func (rbac *RBAC) GetParents(id string) ([]string, error) {
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
if _, ok := rbac.roles[id]; !ok {
return nil, ErrRoleNotExist
}
ids, ok := rbac.parents[id]
if !ok {
return nil, nil
}
var parents []string
for parent := range ids {
parents = append(parents, parent)
}
return parents, nil
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"GetParents",
"(",
"id",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"ids",
",",
"ok",
":=",
"rbac",
".",
"parents",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"var",
"parents",
"[",
"]",
"string",
"\n",
"for",
"parent",
":=",
"range",
"ids",
"{",
"parents",
"=",
"append",
"(",
"parents",
",",
"parent",
")",
"\n",
"}",
"\n",
"return",
"parents",
",",
"nil",
"\n",
"}"
] | // GetParents return `parents` of the role `id`.
// If the role is not existing, an error will be returned.
// Or the role doesn't have any parents,
// a nil slice will be returned. | [
"GetParents",
"return",
"parents",
"of",
"the",
"role",
"id",
".",
"If",
"the",
"role",
"is",
"not",
"existing",
"an",
"error",
"will",
"be",
"returned",
".",
"Or",
"the",
"role",
"doesn",
"t",
"have",
"any",
"parents",
"a",
"nil",
"slice",
"will",
"be",
"returned",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L78-L93 | train |
mikespook/gorbac | rbac.go | SetParent | func (rbac *RBAC) SetParent(id string, parent string) error {
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
if _, ok := rbac.roles[id]; !ok {
return ErrRoleNotExist
}
if _, ok := rbac.roles[parent]; !ok {
return ErrRoleNotExist
}
if _, ok := rbac.parents[id]; !ok {
rbac.parents[id] = make(map[string]struct{})
}
var empty struct{}
rbac.parents[id][parent] = empty
return nil
} | go | func (rbac *RBAC) SetParent(id string, parent string) error {
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
if _, ok := rbac.roles[id]; !ok {
return ErrRoleNotExist
}
if _, ok := rbac.roles[parent]; !ok {
return ErrRoleNotExist
}
if _, ok := rbac.parents[id]; !ok {
rbac.parents[id] = make(map[string]struct{})
}
var empty struct{}
rbac.parents[id][parent] = empty
return nil
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"SetParent",
"(",
"id",
"string",
",",
"parent",
"string",
")",
"error",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"return",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"parent",
"]",
";",
"!",
"ok",
"{",
"return",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"parents",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"rbac",
".",
"parents",
"[",
"id",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"var",
"empty",
"struct",
"{",
"}",
"\n",
"rbac",
".",
"parents",
"[",
"id",
"]",
"[",
"parent",
"]",
"=",
"empty",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetParent bind the `parent` to the role `id`.
// If the role or the parent is not existing,
// an error will be returned. | [
"SetParent",
"bind",
"the",
"parent",
"to",
"the",
"role",
"id",
".",
"If",
"the",
"role",
"or",
"the",
"parent",
"is",
"not",
"existing",
"an",
"error",
"will",
"be",
"returned",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L98-L113 | train |
mikespook/gorbac | rbac.go | RemoveParent | func (rbac *RBAC) RemoveParent(id string, parent string) error {
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
if _, ok := rbac.roles[id]; !ok {
return ErrRoleNotExist
}
if _, ok := rbac.roles[parent]; !ok {
return ErrRoleNotExist
}
delete(rbac.parents[id], parent)
return nil
} | go | func (rbac *RBAC) RemoveParent(id string, parent string) error {
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
if _, ok := rbac.roles[id]; !ok {
return ErrRoleNotExist
}
if _, ok := rbac.roles[parent]; !ok {
return ErrRoleNotExist
}
delete(rbac.parents[id], parent)
return nil
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"RemoveParent",
"(",
"id",
"string",
",",
"parent",
"string",
")",
"error",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"return",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"parent",
"]",
";",
"!",
"ok",
"{",
"return",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"delete",
"(",
"rbac",
".",
"parents",
"[",
"id",
"]",
",",
"parent",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveParent unbind the `parent` with the role `id`.
// If the role or the parent is not existing,
// an error will be returned. | [
"RemoveParent",
"unbind",
"the",
"parent",
"with",
"the",
"role",
"id",
".",
"If",
"the",
"role",
"or",
"the",
"parent",
"is",
"not",
"existing",
"an",
"error",
"will",
"be",
"returned",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L118-L129 | train |
mikespook/gorbac | rbac.go | Add | func (rbac *RBAC) Add(r Role) (err error) {
rbac.mutex.Lock()
if _, ok := rbac.roles[r.ID()]; !ok {
rbac.roles[r.ID()] = r
} else {
err = ErrRoleExist
}
rbac.mutex.Unlock()
return
} | go | func (rbac *RBAC) Add(r Role) (err error) {
rbac.mutex.Lock()
if _, ok := rbac.roles[r.ID()]; !ok {
rbac.roles[r.ID()] = r
} else {
err = ErrRoleExist
}
rbac.mutex.Unlock()
return
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"Add",
"(",
"r",
"Role",
")",
"(",
"err",
"error",
")",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"r",
".",
"ID",
"(",
")",
"]",
";",
"!",
"ok",
"{",
"rbac",
".",
"roles",
"[",
"r",
".",
"ID",
"(",
")",
"]",
"=",
"r",
"\n",
"}",
"else",
"{",
"err",
"=",
"ErrRoleExist",
"\n",
"}",
"\n",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Add a role `r`. | [
"Add",
"a",
"role",
"r",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L132-L141 | train |
mikespook/gorbac | rbac.go | Remove | func (rbac *RBAC) Remove(id string) (err error) {
rbac.mutex.Lock()
if _, ok := rbac.roles[id]; ok {
delete(rbac.roles, id)
for rid, parents := range rbac.parents {
if rid == id {
delete(rbac.parents, rid)
continue
}
for parent := range parents {
if parent == id {
delete(rbac.parents[rid], id)
break
}
}
}
} else {
err = ErrRoleNotExist
}
rbac.mutex.Unlock()
return
} | go | func (rbac *RBAC) Remove(id string) (err error) {
rbac.mutex.Lock()
if _, ok := rbac.roles[id]; ok {
delete(rbac.roles, id)
for rid, parents := range rbac.parents {
if rid == id {
delete(rbac.parents, rid)
continue
}
for parent := range parents {
if parent == id {
delete(rbac.parents[rid], id)
break
}
}
}
} else {
err = ErrRoleNotExist
}
rbac.mutex.Unlock()
return
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"Remove",
"(",
"id",
"string",
")",
"(",
"err",
"error",
")",
"{",
"rbac",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"rbac",
".",
"roles",
"[",
"id",
"]",
";",
"ok",
"{",
"delete",
"(",
"rbac",
".",
"roles",
",",
"id",
")",
"\n",
"for",
"rid",
",",
"parents",
":=",
"range",
"rbac",
".",
"parents",
"{",
"if",
"rid",
"==",
"id",
"{",
"delete",
"(",
"rbac",
".",
"parents",
",",
"rid",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"for",
"parent",
":=",
"range",
"parents",
"{",
"if",
"parent",
"==",
"id",
"{",
"delete",
"(",
"rbac",
".",
"parents",
"[",
"rid",
"]",
",",
"id",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"rbac",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Remove the role by `id`. | [
"Remove",
"the",
"role",
"by",
"id",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L144-L165 | train |
mikespook/gorbac | rbac.go | Get | func (rbac *RBAC) Get(id string) (r Role, parents []string, err error) {
rbac.mutex.RLock()
var ok bool
if r, ok = rbac.roles[id]; ok {
for parent := range rbac.parents[id] {
parents = append(parents, parent)
}
} else {
err = ErrRoleNotExist
}
rbac.mutex.RUnlock()
return
} | go | func (rbac *RBAC) Get(id string) (r Role, parents []string, err error) {
rbac.mutex.RLock()
var ok bool
if r, ok = rbac.roles[id]; ok {
for parent := range rbac.parents[id] {
parents = append(parents, parent)
}
} else {
err = ErrRoleNotExist
}
rbac.mutex.RUnlock()
return
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"Get",
"(",
"id",
"string",
")",
"(",
"r",
"Role",
",",
"parents",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"rbac",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"r",
",",
"ok",
"=",
"rbac",
".",
"roles",
"[",
"id",
"]",
";",
"ok",
"{",
"for",
"parent",
":=",
"range",
"rbac",
".",
"parents",
"[",
"id",
"]",
"{",
"parents",
"=",
"append",
"(",
"parents",
",",
"parent",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"ErrRoleNotExist",
"\n",
"}",
"\n",
"rbac",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Get the role by `id` and a slice of its parents id. | [
"Get",
"the",
"role",
"by",
"id",
"and",
"a",
"slice",
"of",
"its",
"parents",
"id",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L168-L180 | train |
mikespook/gorbac | rbac.go | IsGranted | func (rbac *RBAC) IsGranted(id string, p Permission, assert AssertionFunc) (rslt bool) {
rbac.mutex.RLock()
rslt = rbac.isGranted(id, p, assert)
rbac.mutex.RUnlock()
return
} | go | func (rbac *RBAC) IsGranted(id string, p Permission, assert AssertionFunc) (rslt bool) {
rbac.mutex.RLock()
rslt = rbac.isGranted(id, p, assert)
rbac.mutex.RUnlock()
return
} | [
"func",
"(",
"rbac",
"*",
"RBAC",
")",
"IsGranted",
"(",
"id",
"string",
",",
"p",
"Permission",
",",
"assert",
"AssertionFunc",
")",
"(",
"rslt",
"bool",
")",
"{",
"rbac",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"rslt",
"=",
"rbac",
".",
"isGranted",
"(",
"id",
",",
"p",
",",
"assert",
")",
"\n",
"rbac",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // IsGranted tests if the role `id` has Permission `p` with the condition `assert`. | [
"IsGranted",
"tests",
"if",
"the",
"role",
"id",
"has",
"Permission",
"p",
"with",
"the",
"condition",
"assert",
"."
] | a989d0e80a235460ebe9e8f2e7971e9ed948db88 | https://github.com/mikespook/gorbac/blob/a989d0e80a235460ebe9e8f2e7971e9ed948db88/rbac.go#L183-L188 | train |
tylerb/graceful | graceful.go | Run | func Run(addr string, timeout time.Duration, n http.Handler) {
srv := &Server{
Timeout: timeout,
TCPKeepAlive: 3 * time.Minute,
Server: &http.Server{Addr: addr, Handler: n},
// Logger: DefaultLogger(),
}
if err := srv.ListenAndServe(); err != nil {
if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
srv.logf("%s", err)
os.Exit(1)
}
}
} | go | func Run(addr string, timeout time.Duration, n http.Handler) {
srv := &Server{
Timeout: timeout,
TCPKeepAlive: 3 * time.Minute,
Server: &http.Server{Addr: addr, Handler: n},
// Logger: DefaultLogger(),
}
if err := srv.ListenAndServe(); err != nil {
if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
srv.logf("%s", err)
os.Exit(1)
}
}
} | [
"func",
"Run",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
",",
"n",
"http",
".",
"Handler",
")",
"{",
"srv",
":=",
"&",
"Server",
"{",
"Timeout",
":",
"timeout",
",",
"TCPKeepAlive",
":",
"3",
"*",
"time",
".",
"Minute",
",",
"Server",
":",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"addr",
",",
"Handler",
":",
"n",
"}",
",",
"// Logger: DefaultLogger(),",
"}",
"\n\n",
"if",
"err",
":=",
"srv",
".",
"ListenAndServe",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"opErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"net",
".",
"OpError",
")",
";",
"!",
"ok",
"||",
"(",
"ok",
"&&",
"opErr",
".",
"Op",
"!=",
"\"",
"\"",
")",
"{",
"srv",
".",
"logf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"}"
] | // Run serves the http.Handler with graceful shutdown enabled.
//
// timeout is the duration to wait until killing active requests and stopping the server.
// If timeout is 0, the server never times out. It waits for all active requests to finish. | [
"Run",
"serves",
"the",
"http",
".",
"Handler",
"with",
"graceful",
"shutdown",
"enabled",
".",
"timeout",
"is",
"the",
"duration",
"to",
"wait",
"until",
"killing",
"active",
"requests",
"and",
"stopping",
"the",
"server",
".",
"If",
"timeout",
"is",
"0",
"the",
"server",
"never",
"times",
"out",
".",
"It",
"waits",
"for",
"all",
"active",
"requests",
"to",
"finish",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L94-L109 | train |
tylerb/graceful | graceful.go | RunWithErr | func RunWithErr(addr string, timeout time.Duration, n http.Handler) error {
srv := &Server{
Timeout: timeout,
TCPKeepAlive: 3 * time.Minute,
Server: &http.Server{Addr: addr, Handler: n},
Logger: DefaultLogger(),
}
return srv.ListenAndServe()
} | go | func RunWithErr(addr string, timeout time.Duration, n http.Handler) error {
srv := &Server{
Timeout: timeout,
TCPKeepAlive: 3 * time.Minute,
Server: &http.Server{Addr: addr, Handler: n},
Logger: DefaultLogger(),
}
return srv.ListenAndServe()
} | [
"func",
"RunWithErr",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
",",
"n",
"http",
".",
"Handler",
")",
"error",
"{",
"srv",
":=",
"&",
"Server",
"{",
"Timeout",
":",
"timeout",
",",
"TCPKeepAlive",
":",
"3",
"*",
"time",
".",
"Minute",
",",
"Server",
":",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"addr",
",",
"Handler",
":",
"n",
"}",
",",
"Logger",
":",
"DefaultLogger",
"(",
")",
",",
"}",
"\n\n",
"return",
"srv",
".",
"ListenAndServe",
"(",
")",
"\n",
"}"
] | // RunWithErr is an alternative version of Run function which can return error.
//
// Unlike Run this version will not exit the program if an error is encountered but will
// return it instead. | [
"RunWithErr",
"is",
"an",
"alternative",
"version",
"of",
"Run",
"function",
"which",
"can",
"return",
"error",
".",
"Unlike",
"Run",
"this",
"version",
"will",
"not",
"exit",
"the",
"program",
"if",
"an",
"error",
"is",
"encountered",
"but",
"will",
"return",
"it",
"instead",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L115-L124 | train |
tylerb/graceful | graceful.go | ListenAndServe | func ListenAndServe(server *http.Server, timeout time.Duration) error {
srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()}
return srv.ListenAndServe()
} | go | func ListenAndServe(server *http.Server, timeout time.Duration) error {
srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()}
return srv.ListenAndServe()
} | [
"func",
"ListenAndServe",
"(",
"server",
"*",
"http",
".",
"Server",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"srv",
":=",
"&",
"Server",
"{",
"Timeout",
":",
"timeout",
",",
"Server",
":",
"server",
",",
"Logger",
":",
"DefaultLogger",
"(",
")",
"}",
"\n",
"return",
"srv",
".",
"ListenAndServe",
"(",
")",
"\n",
"}"
] | // ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled.
//
// timeout is the duration to wait until killing active requests and stopping the server.
// If timeout is 0, the server never times out. It waits for all active requests to finish. | [
"ListenAndServe",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"ListenAndServe",
"with",
"graceful",
"shutdown",
"enabled",
".",
"timeout",
"is",
"the",
"duration",
"to",
"wait",
"until",
"killing",
"active",
"requests",
"and",
"stopping",
"the",
"server",
".",
"If",
"timeout",
"is",
"0",
"the",
"server",
"never",
"times",
"out",
".",
"It",
"waits",
"for",
"all",
"active",
"requests",
"to",
"finish",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L130-L133 | train |
tylerb/graceful | graceful.go | ListenAndServe | func (srv *Server) ListenAndServe() error {
// Create the listener so we can control their lifetime
addr := srv.Addr
if addr == "" {
addr = ":http"
}
conn, err := srv.newTCPListener(addr)
if err != nil {
return err
}
return srv.Serve(conn)
} | go | func (srv *Server) ListenAndServe() error {
// Create the listener so we can control their lifetime
addr := srv.Addr
if addr == "" {
addr = ":http"
}
conn, err := srv.newTCPListener(addr)
if err != nil {
return err
}
return srv.Serve(conn)
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"ListenAndServe",
"(",
")",
"error",
"{",
"// Create the listener so we can control their lifetime",
"addr",
":=",
"srv",
".",
"Addr",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"srv",
".",
"newTCPListener",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"srv",
".",
"Serve",
"(",
"conn",
")",
"\n",
"}"
] | // ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled. | [
"ListenAndServe",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"ListenAndServe",
"with",
"graceful",
"shutdown",
"enabled",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L136-L148 | train |
tylerb/graceful | graceful.go | ListenAndServeTLS | func ListenAndServeTLS(server *http.Server, certFile, keyFile string, timeout time.Duration) error {
srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()}
return srv.ListenAndServeTLS(certFile, keyFile)
} | go | func ListenAndServeTLS(server *http.Server, certFile, keyFile string, timeout time.Duration) error {
srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()}
return srv.ListenAndServeTLS(certFile, keyFile)
} | [
"func",
"ListenAndServeTLS",
"(",
"server",
"*",
"http",
".",
"Server",
",",
"certFile",
",",
"keyFile",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"srv",
":=",
"&",
"Server",
"{",
"Timeout",
":",
"timeout",
",",
"Server",
":",
"server",
",",
"Logger",
":",
"DefaultLogger",
"(",
")",
"}",
"\n",
"return",
"srv",
".",
"ListenAndServeTLS",
"(",
"certFile",
",",
"keyFile",
")",
"\n",
"}"
] | // ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled.
//
// timeout is the duration to wait until killing active requests and stopping the server.
// If timeout is 0, the server never times out. It waits for all active requests to finish. | [
"ListenAndServeTLS",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"ListenAndServeTLS",
"with",
"graceful",
"shutdown",
"enabled",
".",
"timeout",
"is",
"the",
"duration",
"to",
"wait",
"until",
"killing",
"active",
"requests",
"and",
"stopping",
"the",
"server",
".",
"If",
"timeout",
"is",
"0",
"the",
"server",
"never",
"times",
"out",
".",
"It",
"waits",
"for",
"all",
"active",
"requests",
"to",
"finish",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L154-L157 | train |
tylerb/graceful | graceful.go | ListenTLS | func (srv *Server) ListenTLS(certFile, keyFile string) (net.Listener, error) {
// Create the listener ourselves so we can control its lifetime
addr := srv.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
var err error
if certFile != "" && keyFile != "" {
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
}
// Enable http2
enableHTTP2ForTLSConfig(config)
conn, err := srv.newTCPListener(addr)
if err != nil {
return nil, err
}
srv.TLSConfig = config
tlsListener := tls.NewListener(conn, config)
return tlsListener, nil
} | go | func (srv *Server) ListenTLS(certFile, keyFile string) (net.Listener, error) {
// Create the listener ourselves so we can control its lifetime
addr := srv.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
var err error
if certFile != "" && keyFile != "" {
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
}
// Enable http2
enableHTTP2ForTLSConfig(config)
conn, err := srv.newTCPListener(addr)
if err != nil {
return nil, err
}
srv.TLSConfig = config
tlsListener := tls.NewListener(conn, config)
return tlsListener, nil
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"ListenTLS",
"(",
"certFile",
",",
"keyFile",
"string",
")",
"(",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"// Create the listener ourselves so we can control its lifetime",
"addr",
":=",
"srv",
".",
"Addr",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"config",
":=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"if",
"srv",
".",
"TLSConfig",
"!=",
"nil",
"{",
"*",
"config",
"=",
"*",
"srv",
".",
"TLSConfig",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"if",
"certFile",
"!=",
"\"",
"\"",
"&&",
"keyFile",
"!=",
"\"",
"\"",
"{",
"config",
".",
"Certificates",
"=",
"make",
"(",
"[",
"]",
"tls",
".",
"Certificate",
",",
"1",
")",
"\n",
"config",
".",
"Certificates",
"[",
"0",
"]",
",",
"err",
"=",
"tls",
".",
"LoadX509KeyPair",
"(",
"certFile",
",",
"keyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Enable http2",
"enableHTTP2ForTLSConfig",
"(",
"config",
")",
"\n\n",
"conn",
",",
"err",
":=",
"srv",
".",
"newTCPListener",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"srv",
".",
"TLSConfig",
"=",
"config",
"\n\n",
"tlsListener",
":=",
"tls",
".",
"NewListener",
"(",
"conn",
",",
"config",
")",
"\n",
"return",
"tlsListener",
",",
"nil",
"\n",
"}"
] | // ListenTLS is a convenience method that creates an https listener using the
// provided cert and key files. Use this method if you need access to the
// listener object directly. When ready, pass it to the Serve method. | [
"ListenTLS",
"is",
"a",
"convenience",
"method",
"that",
"creates",
"an",
"https",
"listener",
"using",
"the",
"provided",
"cert",
"and",
"key",
"files",
".",
"Use",
"this",
"method",
"if",
"you",
"need",
"access",
"to",
"the",
"listener",
"object",
"directly",
".",
"When",
"ready",
"pass",
"it",
"to",
"the",
"Serve",
"method",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L162-L195 | train |
tylerb/graceful | graceful.go | TLSConfigHasHTTP2Enabled | func TLSConfigHasHTTP2Enabled(t *tls.Config) bool {
for _, value := range t.NextProtos {
if value == "h2" {
return true
}
}
return false
} | go | func TLSConfigHasHTTP2Enabled(t *tls.Config) bool {
for _, value := range t.NextProtos {
if value == "h2" {
return true
}
}
return false
} | [
"func",
"TLSConfigHasHTTP2Enabled",
"(",
"t",
"*",
"tls",
".",
"Config",
")",
"bool",
"{",
"for",
"_",
",",
"value",
":=",
"range",
"t",
".",
"NextProtos",
"{",
"if",
"value",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // TLSConfigHasHTTP2Enabled checks to see if a given TLS Config has http2 enabled. | [
"TLSConfigHasHTTP2Enabled",
"checks",
"to",
"see",
"if",
"a",
"given",
"TLS",
"Config",
"has",
"http2",
"enabled",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L210-L217 | train |
tylerb/graceful | graceful.go | ListenAndServeTLS | func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
l, err := srv.ListenTLS(certFile, keyFile)
if err != nil {
return err
}
return srv.Serve(l)
} | go | func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
l, err := srv.ListenTLS(certFile, keyFile)
if err != nil {
return err
}
return srv.Serve(l)
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"ListenAndServeTLS",
"(",
"certFile",
",",
"keyFile",
"string",
")",
"error",
"{",
"l",
",",
"err",
":=",
"srv",
".",
"ListenTLS",
"(",
"certFile",
",",
"keyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"srv",
".",
"Serve",
"(",
"l",
")",
"\n",
"}"
] | // ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled. | [
"ListenAndServeTLS",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"ListenAndServeTLS",
"with",
"graceful",
"shutdown",
"enabled",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L220-L227 | train |
tylerb/graceful | graceful.go | ListenAndServeTLSConfig | func (srv *Server) ListenAndServeTLSConfig(config *tls.Config) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
conn, err := srv.newTCPListener(addr)
if err != nil {
return err
}
srv.TLSConfig = config
tlsListener := tls.NewListener(conn, config)
return srv.Serve(tlsListener)
} | go | func (srv *Server) ListenAndServeTLSConfig(config *tls.Config) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
conn, err := srv.newTCPListener(addr)
if err != nil {
return err
}
srv.TLSConfig = config
tlsListener := tls.NewListener(conn, config)
return srv.Serve(tlsListener)
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"ListenAndServeTLSConfig",
"(",
"config",
"*",
"tls",
".",
"Config",
")",
"error",
"{",
"addr",
":=",
"srv",
".",
"Addr",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"srv",
".",
"newTCPListener",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"srv",
".",
"TLSConfig",
"=",
"config",
"\n\n",
"tlsListener",
":=",
"tls",
".",
"NewListener",
"(",
"conn",
",",
"config",
")",
"\n",
"return",
"srv",
".",
"Serve",
"(",
"tlsListener",
")",
"\n",
"}"
] | // ListenAndServeTLSConfig can be used with an existing TLS config and is equivalent to
// http.Server.ListenAndServeTLS with graceful shutdown enabled, | [
"ListenAndServeTLSConfig",
"can",
"be",
"used",
"with",
"an",
"existing",
"TLS",
"config",
"and",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"ListenAndServeTLS",
"with",
"graceful",
"shutdown",
"enabled"
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L231-L246 | train |
tylerb/graceful | graceful.go | Serve | func Serve(server *http.Server, l net.Listener, timeout time.Duration) error {
srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()}
return srv.Serve(l)
} | go | func Serve(server *http.Server, l net.Listener, timeout time.Duration) error {
srv := &Server{Timeout: timeout, Server: server, Logger: DefaultLogger()}
return srv.Serve(l)
} | [
"func",
"Serve",
"(",
"server",
"*",
"http",
".",
"Server",
",",
"l",
"net",
".",
"Listener",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"srv",
":=",
"&",
"Server",
"{",
"Timeout",
":",
"timeout",
",",
"Server",
":",
"server",
",",
"Logger",
":",
"DefaultLogger",
"(",
")",
"}",
"\n\n",
"return",
"srv",
".",
"Serve",
"(",
"l",
")",
"\n",
"}"
] | // Serve is equivalent to http.Server.Serve with graceful shutdown enabled.
//
// timeout is the duration to wait until killing active requests and stopping the server.
// If timeout is 0, the server never times out. It waits for all active requests to finish. | [
"Serve",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"Serve",
"with",
"graceful",
"shutdown",
"enabled",
".",
"timeout",
"is",
"the",
"duration",
"to",
"wait",
"until",
"killing",
"active",
"requests",
"and",
"stopping",
"the",
"server",
".",
"If",
"timeout",
"is",
"0",
"the",
"server",
"never",
"times",
"out",
".",
"It",
"waits",
"for",
"all",
"active",
"requests",
"to",
"finish",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L252-L256 | train |
tylerb/graceful | graceful.go | Serve | func (srv *Server) Serve(listener net.Listener) error {
if srv.ListenLimit != 0 {
listener = LimitListener(listener, srv.ListenLimit)
}
// Make our stopchan
srv.StopChan()
// Track connection state
add := make(chan net.Conn)
idle := make(chan net.Conn)
active := make(chan net.Conn)
remove := make(chan net.Conn)
srv.Server.ConnState = func(conn net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
add <- conn
case http.StateActive:
active <- conn
case http.StateIdle:
idle <- conn
case http.StateClosed, http.StateHijacked:
remove <- conn
}
srv.stopLock.Lock()
defer srv.stopLock.Unlock()
if srv.ConnState != nil {
srv.ConnState(conn, state)
}
}
// Manage open connections
shutdown := make(chan chan struct{})
kill := make(chan struct{})
go srv.manageConnections(add, idle, active, remove, shutdown, kill)
interrupt := srv.interruptChan()
// Set up the interrupt handler
if !srv.NoSignalHandling {
signalNotify(interrupt)
}
quitting := make(chan struct{})
go srv.handleInterrupt(interrupt, quitting, listener)
// Serve with graceful listener.
// Execution blocks here until listener.Close() is called, above.
err := srv.Server.Serve(listener)
if err != nil {
// If the underlying listening is closed, Serve returns an error
// complaining about listening on a closed socket. This is expected, so
// let's ignore the error if we are the ones who explicitly closed the
// socket.
select {
case <-quitting:
err = nil
default:
}
}
srv.shutdown(shutdown, kill)
return err
} | go | func (srv *Server) Serve(listener net.Listener) error {
if srv.ListenLimit != 0 {
listener = LimitListener(listener, srv.ListenLimit)
}
// Make our stopchan
srv.StopChan()
// Track connection state
add := make(chan net.Conn)
idle := make(chan net.Conn)
active := make(chan net.Conn)
remove := make(chan net.Conn)
srv.Server.ConnState = func(conn net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
add <- conn
case http.StateActive:
active <- conn
case http.StateIdle:
idle <- conn
case http.StateClosed, http.StateHijacked:
remove <- conn
}
srv.stopLock.Lock()
defer srv.stopLock.Unlock()
if srv.ConnState != nil {
srv.ConnState(conn, state)
}
}
// Manage open connections
shutdown := make(chan chan struct{})
kill := make(chan struct{})
go srv.manageConnections(add, idle, active, remove, shutdown, kill)
interrupt := srv.interruptChan()
// Set up the interrupt handler
if !srv.NoSignalHandling {
signalNotify(interrupt)
}
quitting := make(chan struct{})
go srv.handleInterrupt(interrupt, quitting, listener)
// Serve with graceful listener.
// Execution blocks here until listener.Close() is called, above.
err := srv.Server.Serve(listener)
if err != nil {
// If the underlying listening is closed, Serve returns an error
// complaining about listening on a closed socket. This is expected, so
// let's ignore the error if we are the ones who explicitly closed the
// socket.
select {
case <-quitting:
err = nil
default:
}
}
srv.shutdown(shutdown, kill)
return err
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"Serve",
"(",
"listener",
"net",
".",
"Listener",
")",
"error",
"{",
"if",
"srv",
".",
"ListenLimit",
"!=",
"0",
"{",
"listener",
"=",
"LimitListener",
"(",
"listener",
",",
"srv",
".",
"ListenLimit",
")",
"\n",
"}",
"\n\n",
"// Make our stopchan",
"srv",
".",
"StopChan",
"(",
")",
"\n\n",
"// Track connection state",
"add",
":=",
"make",
"(",
"chan",
"net",
".",
"Conn",
")",
"\n",
"idle",
":=",
"make",
"(",
"chan",
"net",
".",
"Conn",
")",
"\n",
"active",
":=",
"make",
"(",
"chan",
"net",
".",
"Conn",
")",
"\n",
"remove",
":=",
"make",
"(",
"chan",
"net",
".",
"Conn",
")",
"\n\n",
"srv",
".",
"Server",
".",
"ConnState",
"=",
"func",
"(",
"conn",
"net",
".",
"Conn",
",",
"state",
"http",
".",
"ConnState",
")",
"{",
"switch",
"state",
"{",
"case",
"http",
".",
"StateNew",
":",
"add",
"<-",
"conn",
"\n",
"case",
"http",
".",
"StateActive",
":",
"active",
"<-",
"conn",
"\n",
"case",
"http",
".",
"StateIdle",
":",
"idle",
"<-",
"conn",
"\n",
"case",
"http",
".",
"StateClosed",
",",
"http",
".",
"StateHijacked",
":",
"remove",
"<-",
"conn",
"\n",
"}",
"\n\n",
"srv",
".",
"stopLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"srv",
".",
"stopLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"srv",
".",
"ConnState",
"!=",
"nil",
"{",
"srv",
".",
"ConnState",
"(",
"conn",
",",
"state",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Manage open connections",
"shutdown",
":=",
"make",
"(",
"chan",
"chan",
"struct",
"{",
"}",
")",
"\n",
"kill",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"srv",
".",
"manageConnections",
"(",
"add",
",",
"idle",
",",
"active",
",",
"remove",
",",
"shutdown",
",",
"kill",
")",
"\n\n",
"interrupt",
":=",
"srv",
".",
"interruptChan",
"(",
")",
"\n",
"// Set up the interrupt handler",
"if",
"!",
"srv",
".",
"NoSignalHandling",
"{",
"signalNotify",
"(",
"interrupt",
")",
"\n",
"}",
"\n",
"quitting",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"srv",
".",
"handleInterrupt",
"(",
"interrupt",
",",
"quitting",
",",
"listener",
")",
"\n\n",
"// Serve with graceful listener.",
"// Execution blocks here until listener.Close() is called, above.",
"err",
":=",
"srv",
".",
"Server",
".",
"Serve",
"(",
"listener",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// If the underlying listening is closed, Serve returns an error",
"// complaining about listening on a closed socket. This is expected, so",
"// let's ignore the error if we are the ones who explicitly closed the",
"// socket.",
"select",
"{",
"case",
"<-",
"quitting",
":",
"err",
"=",
"nil",
"\n",
"default",
":",
"}",
"\n",
"}",
"\n\n",
"srv",
".",
"shutdown",
"(",
"shutdown",
",",
"kill",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Serve is equivalent to http.Server.Serve with graceful shutdown enabled. | [
"Serve",
"is",
"equivalent",
"to",
"http",
".",
"Server",
".",
"Serve",
"with",
"graceful",
"shutdown",
"enabled",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L259-L325 | train |
tylerb/graceful | graceful.go | Stop | func (srv *Server) Stop(timeout time.Duration) {
srv.stopLock.Lock()
defer srv.stopLock.Unlock()
srv.Timeout = timeout
sendSignalInt(srv.interruptChan())
} | go | func (srv *Server) Stop(timeout time.Duration) {
srv.stopLock.Lock()
defer srv.stopLock.Unlock()
srv.Timeout = timeout
sendSignalInt(srv.interruptChan())
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"Stop",
"(",
"timeout",
"time",
".",
"Duration",
")",
"{",
"srv",
".",
"stopLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"srv",
".",
"stopLock",
".",
"Unlock",
"(",
")",
"\n\n",
"srv",
".",
"Timeout",
"=",
"timeout",
"\n",
"sendSignalInt",
"(",
"srv",
".",
"interruptChan",
"(",
")",
")",
"\n",
"}"
] | // Stop instructs the type to halt operations and close
// the stop channel when it is finished.
//
// timeout is grace period for which to wait before shutting
// down the server. The timeout value passed here will override the
// timeout given when constructing the server, as this is an explicit
// command to stop the server. | [
"Stop",
"instructs",
"the",
"type",
"to",
"halt",
"operations",
"and",
"close",
"the",
"stop",
"channel",
"when",
"it",
"is",
"finished",
".",
"timeout",
"is",
"grace",
"period",
"for",
"which",
"to",
"wait",
"before",
"shutting",
"down",
"the",
"server",
".",
"The",
"timeout",
"value",
"passed",
"here",
"will",
"override",
"the",
"timeout",
"given",
"when",
"constructing",
"the",
"server",
"as",
"this",
"is",
"an",
"explicit",
"command",
"to",
"stop",
"the",
"server",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L334-L340 | train |
tylerb/graceful | graceful.go | StopChan | func (srv *Server) StopChan() <-chan struct{} {
srv.chanLock.Lock()
defer srv.chanLock.Unlock()
if srv.stopChan == nil {
srv.stopChan = make(chan struct{})
}
return srv.stopChan
} | go | func (srv *Server) StopChan() <-chan struct{} {
srv.chanLock.Lock()
defer srv.chanLock.Unlock()
if srv.stopChan == nil {
srv.stopChan = make(chan struct{})
}
return srv.stopChan
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"StopChan",
"(",
")",
"<-",
"chan",
"struct",
"{",
"}",
"{",
"srv",
".",
"chanLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"srv",
".",
"chanLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"srv",
".",
"stopChan",
"==",
"nil",
"{",
"srv",
".",
"stopChan",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"return",
"srv",
".",
"stopChan",
"\n",
"}"
] | // StopChan gets the stop channel which will block until
// stopping has completed, at which point it is closed.
// Callers should never close the stop channel. | [
"StopChan",
"gets",
"the",
"stop",
"channel",
"which",
"will",
"block",
"until",
"stopping",
"has",
"completed",
"at",
"which",
"point",
"it",
"is",
"closed",
".",
"Callers",
"should",
"never",
"close",
"the",
"stop",
"channel",
"."
] | d72b0151351a13d0421b763b88f791469c4f5dc7 | https://github.com/tylerb/graceful/blob/d72b0151351a13d0421b763b88f791469c4f5dc7/graceful.go#L345-L353 | train |
hashicorp/go-multierror | multierror.go | ErrorOrNil | func (e *Error) ErrorOrNil() error {
if e == nil {
return nil
}
if len(e.Errors) == 0 {
return nil
}
return e
} | go | func (e *Error) ErrorOrNil() error {
if e == nil {
return nil
}
if len(e.Errors) == 0 {
return nil
}
return e
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"ErrorOrNil",
"(",
")",
"error",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"e",
".",
"Errors",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"e",
"\n",
"}"
] | // ErrorOrNil returns an error interface if this Error represents
// a list of errors, or returns nil if the list of errors is empty. This
// function is useful at the end of accumulation to make sure that the value
// returned represents the existence of errors. | [
"ErrorOrNil",
"returns",
"an",
"error",
"interface",
"if",
"this",
"Error",
"represents",
"a",
"list",
"of",
"errors",
"or",
"returns",
"nil",
"if",
"the",
"list",
"of",
"errors",
"is",
"empty",
".",
"This",
"function",
"is",
"useful",
"at",
"the",
"end",
"of",
"accumulation",
"to",
"make",
"sure",
"that",
"the",
"value",
"returned",
"represents",
"the",
"existence",
"of",
"errors",
"."
] | 886a7fbe3eb1c874d46f623bfa70af45f425b3d1 | https://github.com/hashicorp/go-multierror/blob/886a7fbe3eb1c874d46f623bfa70af45f425b3d1/multierror.go#L27-L36 | train |
hashicorp/go-multierror | prefix.go | Prefix | func Prefix(err error, prefix string) error {
if err == nil {
return nil
}
format := fmt.Sprintf("%s {{err}}", prefix)
switch err := err.(type) {
case *Error:
// Typed nils can reach here, so initialize if we are nil
if err == nil {
err = new(Error)
}
// Wrap each of the errors
for i, e := range err.Errors {
err.Errors[i] = errwrap.Wrapf(format, e)
}
return err
default:
return errwrap.Wrapf(format, err)
}
} | go | func Prefix(err error, prefix string) error {
if err == nil {
return nil
}
format := fmt.Sprintf("%s {{err}}", prefix)
switch err := err.(type) {
case *Error:
// Typed nils can reach here, so initialize if we are nil
if err == nil {
err = new(Error)
}
// Wrap each of the errors
for i, e := range err.Errors {
err.Errors[i] = errwrap.Wrapf(format, e)
}
return err
default:
return errwrap.Wrapf(format, err)
}
} | [
"func",
"Prefix",
"(",
"err",
"error",
",",
"prefix",
"string",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"format",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"prefix",
")",
"\n",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Error",
":",
"// Typed nils can reach here, so initialize if we are nil",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"new",
"(",
"Error",
")",
"\n",
"}",
"\n\n",
"// Wrap each of the errors",
"for",
"i",
",",
"e",
":=",
"range",
"err",
".",
"Errors",
"{",
"err",
".",
"Errors",
"[",
"i",
"]",
"=",
"errwrap",
".",
"Wrapf",
"(",
"format",
",",
"e",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"default",
":",
"return",
"errwrap",
".",
"Wrapf",
"(",
"format",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // Prefix is a helper function that will prefix some text
// to the given error. If the error is a multierror.Error, then
// it will be prefixed to each wrapped error.
//
// This is useful to use when appending multiple multierrors
// together in order to give better scoping. | [
"Prefix",
"is",
"a",
"helper",
"function",
"that",
"will",
"prefix",
"some",
"text",
"to",
"the",
"given",
"error",
".",
"If",
"the",
"error",
"is",
"a",
"multierror",
".",
"Error",
"then",
"it",
"will",
"be",
"prefixed",
"to",
"each",
"wrapped",
"error",
".",
"This",
"is",
"useful",
"to",
"use",
"when",
"appending",
"multiple",
"multierrors",
"together",
"in",
"order",
"to",
"give",
"better",
"scoping",
"."
] | 886a7fbe3eb1c874d46f623bfa70af45f425b3d1 | https://github.com/hashicorp/go-multierror/blob/886a7fbe3eb1c874d46f623bfa70af45f425b3d1/prefix.go#L15-L37 | train |
hashicorp/go-multierror | append.go | Append | func Append(err error, errs ...error) *Error {
switch err := err.(type) {
case *Error:
// Typed nils can reach here, so initialize if we are nil
if err == nil {
err = new(Error)
}
// Go through each error and flatten
for _, e := range errs {
switch e := e.(type) {
case *Error:
if e != nil {
err.Errors = append(err.Errors, e.Errors...)
}
default:
if e != nil {
err.Errors = append(err.Errors, e)
}
}
}
return err
default:
newErrs := make([]error, 0, len(errs)+1)
if err != nil {
newErrs = append(newErrs, err)
}
newErrs = append(newErrs, errs...)
return Append(&Error{}, newErrs...)
}
} | go | func Append(err error, errs ...error) *Error {
switch err := err.(type) {
case *Error:
// Typed nils can reach here, so initialize if we are nil
if err == nil {
err = new(Error)
}
// Go through each error and flatten
for _, e := range errs {
switch e := e.(type) {
case *Error:
if e != nil {
err.Errors = append(err.Errors, e.Errors...)
}
default:
if e != nil {
err.Errors = append(err.Errors, e)
}
}
}
return err
default:
newErrs := make([]error, 0, len(errs)+1)
if err != nil {
newErrs = append(newErrs, err)
}
newErrs = append(newErrs, errs...)
return Append(&Error{}, newErrs...)
}
} | [
"func",
"Append",
"(",
"err",
"error",
",",
"errs",
"...",
"error",
")",
"*",
"Error",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Error",
":",
"// Typed nils can reach here, so initialize if we are nil",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"new",
"(",
"Error",
")",
"\n",
"}",
"\n\n",
"// Go through each error and flatten",
"for",
"_",
",",
"e",
":=",
"range",
"errs",
"{",
"switch",
"e",
":=",
"e",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Error",
":",
"if",
"e",
"!=",
"nil",
"{",
"err",
".",
"Errors",
"=",
"append",
"(",
"err",
".",
"Errors",
",",
"e",
".",
"Errors",
"...",
")",
"\n",
"}",
"\n",
"default",
":",
"if",
"e",
"!=",
"nil",
"{",
"err",
".",
"Errors",
"=",
"append",
"(",
"err",
".",
"Errors",
",",
"e",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"default",
":",
"newErrs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
",",
"len",
"(",
"errs",
")",
"+",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"newErrs",
"=",
"append",
"(",
"newErrs",
",",
"err",
")",
"\n",
"}",
"\n",
"newErrs",
"=",
"append",
"(",
"newErrs",
",",
"errs",
"...",
")",
"\n\n",
"return",
"Append",
"(",
"&",
"Error",
"{",
"}",
",",
"newErrs",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // Append is a helper function that will append more errors
// onto an Error in order to create a larger multi-error.
//
// If err is not a multierror.Error, then it will be turned into
// one. If any of the errs are multierr.Error, they will be flattened
// one level into err. | [
"Append",
"is",
"a",
"helper",
"function",
"that",
"will",
"append",
"more",
"errors",
"onto",
"an",
"Error",
"in",
"order",
"to",
"create",
"a",
"larger",
"multi",
"-",
"error",
".",
"If",
"err",
"is",
"not",
"a",
"multierror",
".",
"Error",
"then",
"it",
"will",
"be",
"turned",
"into",
"one",
".",
"If",
"any",
"of",
"the",
"errs",
"are",
"multierr",
".",
"Error",
"they",
"will",
"be",
"flattened",
"one",
"level",
"into",
"err",
"."
] | 886a7fbe3eb1c874d46f623bfa70af45f425b3d1 | https://github.com/hashicorp/go-multierror/blob/886a7fbe3eb1c874d46f623bfa70af45f425b3d1/append.go#L9-L41 | train |
hashicorp/go-multierror | sort.go | Swap | func (err Error) Swap(i, j int) {
err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i]
} | go | func (err Error) Swap(i, j int) {
err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i]
} | [
"func",
"(",
"err",
"Error",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"err",
".",
"Errors",
"[",
"i",
"]",
",",
"err",
".",
"Errors",
"[",
"j",
"]",
"=",
"err",
".",
"Errors",
"[",
"j",
"]",
",",
"err",
".",
"Errors",
"[",
"i",
"]",
"\n",
"}"
] | // Swap implements sort.Interface function for swapping elements | [
"Swap",
"implements",
"sort",
".",
"Interface",
"function",
"for",
"swapping",
"elements"
] | 886a7fbe3eb1c874d46f623bfa70af45f425b3d1 | https://github.com/hashicorp/go-multierror/blob/886a7fbe3eb1c874d46f623bfa70af45f425b3d1/sort.go#L9-L11 | train |
hashicorp/go-multierror | sort.go | Less | func (err Error) Less(i, j int) bool {
return err.Errors[i].Error() < err.Errors[j].Error()
} | go | func (err Error) Less(i, j int) bool {
return err.Errors[i].Error() < err.Errors[j].Error()
} | [
"func",
"(",
"err",
"Error",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"err",
".",
"Errors",
"[",
"i",
"]",
".",
"Error",
"(",
")",
"<",
"err",
".",
"Errors",
"[",
"j",
"]",
".",
"Error",
"(",
")",
"\n",
"}"
] | // Less implements sort.Interface function for determining order | [
"Less",
"implements",
"sort",
".",
"Interface",
"function",
"for",
"determining",
"order"
] | 886a7fbe3eb1c874d46f623bfa70af45f425b3d1 | https://github.com/hashicorp/go-multierror/blob/886a7fbe3eb1c874d46f623bfa70af45f425b3d1/sort.go#L14-L16 | train |
deis/deis | deisctl/backend/fleet/journal.go | runJournal | func (c *FleetClient) runJournal(name string) (exit int) {
u, err := c.Fleet.Unit(name)
if suToGlobal(*u) {
fmt.Fprintf(c.errWriter, "Unable to get journal for global unit %s. Check on a host directly using journalctl.\n", name)
return 1
}
machineID, err := c.findUnit(name)
if err != nil {
return 1
}
command := fmt.Sprintf("journalctl --unit %s --no-pager -n 40 -f", name)
return c.runCommand(command, machineID)
} | go | func (c *FleetClient) runJournal(name string) (exit int) {
u, err := c.Fleet.Unit(name)
if suToGlobal(*u) {
fmt.Fprintf(c.errWriter, "Unable to get journal for global unit %s. Check on a host directly using journalctl.\n", name)
return 1
}
machineID, err := c.findUnit(name)
if err != nil {
return 1
}
command := fmt.Sprintf("journalctl --unit %s --no-pager -n 40 -f", name)
return c.runCommand(command, machineID)
} | [
"func",
"(",
"c",
"*",
"FleetClient",
")",
"runJournal",
"(",
"name",
"string",
")",
"(",
"exit",
"int",
")",
"{",
"u",
",",
"err",
":=",
"c",
".",
"Fleet",
".",
"Unit",
"(",
"name",
")",
"\n",
"if",
"suToGlobal",
"(",
"*",
"u",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"errWriter",
",",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n\n",
"machineID",
",",
"err",
":=",
"c",
".",
"findUnit",
"(",
"name",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"1",
"\n",
"}",
"\n\n",
"command",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"return",
"c",
".",
"runCommand",
"(",
"command",
",",
"machineID",
")",
"\n",
"}"
] | // runJournal tails the systemd journal for a given unit | [
"runJournal",
"tails",
"the",
"systemd",
"journal",
"for",
"a",
"given",
"unit"
] | 1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410 | https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/deisctl/backend/fleet/journal.go#L20-L35 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.