id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
0 | jessevdk/go-assets | file.go | Close | func (f *File) Close() error {
f.buf = nil
f.dirIndex = 0
return nil
} | go | func (f *File) Close() error {
f.buf = nil
f.dirIndex = 0
return nil
} | [
"func",
"(",
"f",
"*",
"File",
")",
"Close",
"(",
")",
"error",
"{",
"f",
".",
"buf",
"=",
"nil",
"\n",
"f",
".",
"dirIndex",
"=",
"0",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Implementation of http.File | [
"Implementation",
"of",
"http",
".",
"File"
] | 4f4301a06e153ff90e17793577ab6bf79f8dc5c5 | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/file.go#L57-L62 |
1 | jessevdk/go-assets | filesystem.go | Open | func (f *FileSystem) Open(p string) (http.File, error) {
p = path.Clean(p)
if len(f.LocalPath) != 0 {
return http.Dir(f.LocalPath).Open(p)
}
if fi, ok := f.Files[p]; ok {
if !fi.IsDir() {
// Make a copy for reading
ret := fi
ret.buf = bytes.NewReader(ret.Data)
return ret, nil
}
return fi, nil
}
return nil, os.ErrNotExist
} | go | func (f *FileSystem) Open(p string) (http.File, error) {
p = path.Clean(p)
if len(f.LocalPath) != 0 {
return http.Dir(f.LocalPath).Open(p)
}
if fi, ok := f.Files[p]; ok {
if !fi.IsDir() {
// Make a copy for reading
ret := fi
ret.buf = bytes.NewReader(ret.Data)
return ret, nil
}
return fi, nil
}
return nil, os.ErrNotExist
} | [
"func",
"(",
"f",
"*",
"FileSystem",
")",
"Open",
"(",
"p",
"string",
")",
"(",
"http",
".",
"File",
",",
"error",
")",
"{",
"p",
"=",
"path",
".",
"Clean",
"(",
"p",
")",
"\n\n",
"if",
"len",
"(",
"f",
".",
"LocalPath",
")",
"!=",
"0",
"{",
"return",
"http",
".",
"Dir",
"(",
"f",
".",
"LocalPath",
")",
".",
"Open",
"(",
"p",
")",
"\n",
"}",
"\n\n",
"if",
"fi",
",",
"ok",
":=",
"f",
".",
"Files",
"[",
"p",
"]",
";",
"ok",
"{",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"// Make a copy for reading",
"ret",
":=",
"fi",
"\n",
"ret",
".",
"buf",
"=",
"bytes",
".",
"NewReader",
"(",
"ret",
".",
"Data",
")",
"\n\n",
"return",
"ret",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"fi",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"os",
".",
"ErrNotExist",
"\n",
"}"
] | // Implementation of http.FileSystem | [
"Implementation",
"of",
"http",
".",
"FileSystem"
] | 4f4301a06e153ff90e17793577ab6bf79f8dc5c5 | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/filesystem.go#L50-L70 |
2 | jessevdk/go-assets | generate.go | Add | func (x *Generator) Add(p string) error {
if x.fsFilesMap == nil {
x.fsFilesMap = make(map[string]file)
}
if x.fsDirsMap == nil {
x.fsDirsMap = make(map[string][]string)
}
p = path.Clean(p)
info, err := os.Stat(p)
if err != nil {
return err
}
prefix, p := x.splitRelPrefix(p)
if err := x.addParents(p, prefix); err != nil {
return err
}
return x.addPath(path.Dir(p), prefix, info)
} | go | func (x *Generator) Add(p string) error {
if x.fsFilesMap == nil {
x.fsFilesMap = make(map[string]file)
}
if x.fsDirsMap == nil {
x.fsDirsMap = make(map[string][]string)
}
p = path.Clean(p)
info, err := os.Stat(p)
if err != nil {
return err
}
prefix, p := x.splitRelPrefix(p)
if err := x.addParents(p, prefix); err != nil {
return err
}
return x.addPath(path.Dir(p), prefix, info)
} | [
"func",
"(",
"x",
"*",
"Generator",
")",
"Add",
"(",
"p",
"string",
")",
"error",
"{",
"if",
"x",
".",
"fsFilesMap",
"==",
"nil",
"{",
"x",
".",
"fsFilesMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"file",
")",
"\n",
"}",
"\n\n",
"if",
"x",
".",
"fsDirsMap",
"==",
"nil",
"{",
"x",
".",
"fsDirsMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"}",
"\n\n",
"p",
"=",
"path",
".",
"Clean",
"(",
"p",
")",
"\n\n",
"info",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"p",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"prefix",
",",
"p",
":=",
"x",
".",
"splitRelPrefix",
"(",
"p",
")",
"\n\n",
"if",
"err",
":=",
"x",
".",
"addParents",
"(",
"p",
",",
"prefix",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"x",
".",
"addPath",
"(",
"path",
".",
"Dir",
"(",
"p",
")",
",",
"prefix",
",",
"info",
")",
"\n",
"}"
] | // Add a file or directory asset to the generator. Added directories will be
// recursed automatically. | [
"Add",
"a",
"file",
"or",
"directory",
"asset",
"to",
"the",
"generator",
".",
"Added",
"directories",
"will",
"be",
"recursed",
"automatically",
"."
] | 4f4301a06e153ff90e17793577ab6bf79f8dc5c5 | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/generate.go#L129-L153 |
3 | jessevdk/go-assets | generate.go | Write | func (x *Generator) Write(wr io.Writer) error {
p := x.PackageName
if len(p) == 0 {
p = "main"
}
variableName := x.VariableName
if len(variableName) == 0 {
variableName = "Assets"
}
writer := &bytes.Buffer{}
// Write package and import
fmt.Fprintf(writer, "package %s\n\n", p)
fmt.Fprintln(writer, "import (")
fmt.Fprintln(writer, "\t\"time\"")
fmt.Fprintln(writer)
fmt.Fprintln(writer, "\t\"github.com/jessevdk/go-assets\"")
fmt.Fprintln(writer, ")")
fmt.Fprintln(writer)
vnames := make(map[string]string)
// Write file contents as const strings
if x.fsFilesMap != nil {
// Create mapping from full file path to asset variable name.
// This also reads the file and writes the contents as a const
// string
for k, v := range x.fsFilesMap {
if v.info.IsDir() {
continue
}
f, err := os.Open(v.path)
if err != nil {
return err
}
data, err := ioutil.ReadAll(f)
f.Close()
if err != nil {
return err
}
s := sha1.New()
io.WriteString(s, k)
vname := fmt.Sprintf("_%s%x", variableName, s.Sum(nil))
vnames[k] = vname
fmt.Fprintf(writer, "var %s = %#v\n", vname, string(data))
}
fmt.Fprintln(writer)
}
fmt.Fprintf(writer, "// %s returns go-assets FileSystem\n", variableName)
fmt.Fprintf(writer, "var %s = assets.NewFileSystem(", variableName)
if x.fsDirsMap == nil {
x.fsDirsMap = make(map[string][]string)
}
if x.fsFilesMap == nil {
x.fsFilesMap = make(map[string]file)
}
dirmap := make(map[string][]string)
for k, v := range x.fsDirsMap {
if kk, ok := x.stripPrefix(k); ok {
if len(kk) == 0 {
kk = "/"
}
dirmap[kk] = v
}
}
fmt.Fprintf(writer, "%#v, ", dirmap)
fmt.Fprintf(writer, "map[string]*assets.File{\n")
// Write files
for k, v := range x.fsFilesMap {
kk, ok := x.stripPrefix(k)
if !ok {
continue
}
if len(kk) == 0 {
kk = "/"
}
mt := v.info.ModTime()
var dt string
if !v.info.IsDir() {
dt = "[]byte(" + vnames[k] + ")"
} else {
dt = "nil"
}
fmt.Fprintf(writer, "\t\t%#v: &assets.File{\n", kk)
fmt.Fprintf(writer, "\t\t\tPath: %#v,\n", kk)
fmt.Fprintf(writer, "\t\t\tFileMode: %#v,\n", v.info.Mode())
fmt.Fprintf(writer, "\t\t\tMtime: time.Unix(%#v, %#v),\n", mt.Unix(), mt.UnixNano())
fmt.Fprintf(writer, "\t\t\tData: %s,\n", dt)
fmt.Fprintf(writer, "\t\t},")
}
fmt.Fprintln(writer, "\t}, \"\")")
ret, err := format.Source(writer.Bytes())
if err != nil {
return err
}
wr.Write(ret)
return nil
} | go | func (x *Generator) Write(wr io.Writer) error {
p := x.PackageName
if len(p) == 0 {
p = "main"
}
variableName := x.VariableName
if len(variableName) == 0 {
variableName = "Assets"
}
writer := &bytes.Buffer{}
// Write package and import
fmt.Fprintf(writer, "package %s\n\n", p)
fmt.Fprintln(writer, "import (")
fmt.Fprintln(writer, "\t\"time\"")
fmt.Fprintln(writer)
fmt.Fprintln(writer, "\t\"github.com/jessevdk/go-assets\"")
fmt.Fprintln(writer, ")")
fmt.Fprintln(writer)
vnames := make(map[string]string)
// Write file contents as const strings
if x.fsFilesMap != nil {
// Create mapping from full file path to asset variable name.
// This also reads the file and writes the contents as a const
// string
for k, v := range x.fsFilesMap {
if v.info.IsDir() {
continue
}
f, err := os.Open(v.path)
if err != nil {
return err
}
data, err := ioutil.ReadAll(f)
f.Close()
if err != nil {
return err
}
s := sha1.New()
io.WriteString(s, k)
vname := fmt.Sprintf("_%s%x", variableName, s.Sum(nil))
vnames[k] = vname
fmt.Fprintf(writer, "var %s = %#v\n", vname, string(data))
}
fmt.Fprintln(writer)
}
fmt.Fprintf(writer, "// %s returns go-assets FileSystem\n", variableName)
fmt.Fprintf(writer, "var %s = assets.NewFileSystem(", variableName)
if x.fsDirsMap == nil {
x.fsDirsMap = make(map[string][]string)
}
if x.fsFilesMap == nil {
x.fsFilesMap = make(map[string]file)
}
dirmap := make(map[string][]string)
for k, v := range x.fsDirsMap {
if kk, ok := x.stripPrefix(k); ok {
if len(kk) == 0 {
kk = "/"
}
dirmap[kk] = v
}
}
fmt.Fprintf(writer, "%#v, ", dirmap)
fmt.Fprintf(writer, "map[string]*assets.File{\n")
// Write files
for k, v := range x.fsFilesMap {
kk, ok := x.stripPrefix(k)
if !ok {
continue
}
if len(kk) == 0 {
kk = "/"
}
mt := v.info.ModTime()
var dt string
if !v.info.IsDir() {
dt = "[]byte(" + vnames[k] + ")"
} else {
dt = "nil"
}
fmt.Fprintf(writer, "\t\t%#v: &assets.File{\n", kk)
fmt.Fprintf(writer, "\t\t\tPath: %#v,\n", kk)
fmt.Fprintf(writer, "\t\t\tFileMode: %#v,\n", v.info.Mode())
fmt.Fprintf(writer, "\t\t\tMtime: time.Unix(%#v, %#v),\n", mt.Unix(), mt.UnixNano())
fmt.Fprintf(writer, "\t\t\tData: %s,\n", dt)
fmt.Fprintf(writer, "\t\t},")
}
fmt.Fprintln(writer, "\t}, \"\")")
ret, err := format.Source(writer.Bytes())
if err != nil {
return err
}
wr.Write(ret)
return nil
} | [
"func",
"(",
"x",
"*",
"Generator",
")",
"Write",
"(",
"wr",
"io",
".",
"Writer",
")",
"error",
"{",
"p",
":=",
"x",
".",
"PackageName",
"\n\n",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"p",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"variableName",
":=",
"x",
".",
"VariableName",
"\n\n",
"if",
"len",
"(",
"variableName",
")",
"==",
"0",
"{",
"variableName",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"writer",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"// Write package and import",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"p",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
")",
"\n\n",
"vnames",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n\n",
"// Write file contents as const strings",
"if",
"x",
".",
"fsFilesMap",
"!=",
"nil",
"{",
"// Create mapping from full file path to asset variable name.",
"// This also reads the file and writes the contents as a const",
"// string",
"for",
"k",
",",
"v",
":=",
"range",
"x",
".",
"fsFilesMap",
"{",
"if",
"v",
".",
"info",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"v",
".",
"path",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n\n",
"f",
".",
"Close",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"io",
".",
"WriteString",
"(",
"s",
",",
"k",
")",
"\n\n",
"vname",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"variableName",
",",
"s",
".",
"Sum",
"(",
"nil",
")",
")",
"\n",
"vnames",
"[",
"k",
"]",
"=",
"vname",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\n",
"\"",
",",
"vname",
",",
"string",
"(",
"data",
")",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\n",
"\"",
",",
"variableName",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\"",
",",
"variableName",
")",
"\n\n",
"if",
"x",
".",
"fsDirsMap",
"==",
"nil",
"{",
"x",
".",
"fsDirsMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"}",
"\n\n",
"if",
"x",
".",
"fsFilesMap",
"==",
"nil",
"{",
"x",
".",
"fsFilesMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"file",
")",
"\n",
"}",
"\n\n",
"dirmap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"x",
".",
"fsDirsMap",
"{",
"if",
"kk",
",",
"ok",
":=",
"x",
".",
"stripPrefix",
"(",
"k",
")",
";",
"ok",
"{",
"if",
"len",
"(",
"kk",
")",
"==",
"0",
"{",
"kk",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"dirmap",
"[",
"kk",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\"",
",",
"dirmap",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\n",
"\"",
")",
"\n\n",
"// Write files",
"for",
"k",
",",
"v",
":=",
"range",
"x",
".",
"fsFilesMap",
"{",
"kk",
",",
"ok",
":=",
"x",
".",
"stripPrefix",
"(",
"k",
")",
"\n\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"kk",
")",
"==",
"0",
"{",
"kk",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"mt",
":=",
"v",
".",
"info",
".",
"ModTime",
"(",
")",
"\n\n",
"var",
"dt",
"string",
"\n\n",
"if",
"!",
"v",
".",
"info",
".",
"IsDir",
"(",
")",
"{",
"dt",
"=",
"\"",
"\"",
"+",
"vnames",
"[",
"k",
"]",
"+",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"dt",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\t",
"\\t",
"\\n",
"\"",
",",
"kk",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\t",
"\\t",
"\\t",
"\\n",
"\"",
",",
"kk",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\t",
"\\t",
"\\t",
"\\n",
"\"",
",",
"v",
".",
"info",
".",
"Mode",
"(",
")",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\t",
"\\t",
"\\t",
"\\n",
"\"",
",",
"mt",
".",
"Unix",
"(",
")",
",",
"mt",
".",
"UnixNano",
"(",
")",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\t",
"\\t",
"\\t",
"\\n",
"\"",
",",
"dt",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"writer",
",",
"\"",
"\\t",
"\\t",
"\"",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"writer",
",",
"\"",
"\\t",
"\\\"",
"\\\"",
"\"",
")",
"\n\n",
"ret",
",",
"err",
":=",
"format",
".",
"Source",
"(",
"writer",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"wr",
".",
"Write",
"(",
"ret",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Write the asset tree specified in the generator to the given writer. The
// written asset tree is a valid, standalone go file with the assets
// embedded into it. | [
"Write",
"the",
"asset",
"tree",
"specified",
"in",
"the",
"generator",
"to",
"the",
"given",
"writer",
".",
"The",
"written",
"asset",
"tree",
"is",
"a",
"valid",
"standalone",
"go",
"file",
"with",
"the",
"assets",
"embedded",
"into",
"it",
"."
] | 4f4301a06e153ff90e17793577ab6bf79f8dc5c5 | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/generate.go#L170-L298 |
4 | ttacon/libphonenumber | phonenumberutil.go | isViablePhoneNumber | func isViablePhoneNumber(number string) bool {
if len(number) < MIN_LENGTH_FOR_NSN {
return false
}
return VALID_PHONE_NUMBER_PATTERN.MatchString(number)
} | go | func isViablePhoneNumber(number string) bool {
if len(number) < MIN_LENGTH_FOR_NSN {
return false
}
return VALID_PHONE_NUMBER_PATTERN.MatchString(number)
} | [
"func",
"isViablePhoneNumber",
"(",
"number",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"number",
")",
"<",
"MIN_LENGTH_FOR_NSN",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"VALID_PHONE_NUMBER_PATTERN",
".",
"MatchString",
"(",
"number",
")",
"\n",
"}"
] | // Checks to see if the string of characters could possibly be a phone
// number at all. At the moment, checks to see that the string begins
// with at least 2 digits, ignoring any punctuation commonly found in
// phone numbers. This method does not require the number to be
// normalized in advance - but does assume that leading non-number symbols
// have been removed, such as by the method extractPossibleNumber.
// @VisibleForTesting | [
"Checks",
"to",
"see",
"if",
"the",
"string",
"of",
"characters",
"could",
"possibly",
"be",
"a",
"phone",
"number",
"at",
"all",
".",
"At",
"the",
"moment",
"checks",
"to",
"see",
"that",
"the",
"string",
"begins",
"with",
"at",
"least",
"2",
"digits",
"ignoring",
"any",
"punctuation",
"commonly",
"found",
"in",
"phone",
"numbers",
".",
"This",
"method",
"does",
"not",
"require",
"the",
"number",
"to",
"be",
"normalized",
"in",
"advance",
"-",
"but",
"does",
"assume",
"that",
"leading",
"non",
"-",
"number",
"symbols",
"have",
"been",
"removed",
"such",
"as",
"by",
"the",
"method",
"extractPossibleNumber",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L725-L730 |
5 | ttacon/libphonenumber | phonenumberutil.go | GetCountryMobileToken | func GetCountryMobileToken(countryCallingCode int) string {
if val, ok := MOBILE_TOKEN_MAPPINGS[countryCallingCode]; ok {
return val
}
return ""
} | go | func GetCountryMobileToken(countryCallingCode int) string {
if val, ok := MOBILE_TOKEN_MAPPINGS[countryCallingCode]; ok {
return val
}
return ""
} | [
"func",
"GetCountryMobileToken",
"(",
"countryCallingCode",
"int",
")",
"string",
"{",
"if",
"val",
",",
"ok",
":=",
"MOBILE_TOKEN_MAPPINGS",
"[",
"countryCallingCode",
"]",
";",
"ok",
"{",
"return",
"val",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Returns the mobile token for the provided country calling code if it
// has one, otherwise returns an empty string. A mobile token is a number
// inserted before the area code when dialing a mobile number from that
// country from abroad. | [
"Returns",
"the",
"mobile",
"token",
"for",
"the",
"provided",
"country",
"calling",
"code",
"if",
"it",
"has",
"one",
"otherwise",
"returns",
"an",
"empty",
"string",
".",
"A",
"mobile",
"token",
"is",
"a",
"number",
"inserted",
"before",
"the",
"area",
"code",
"when",
"dialing",
"a",
"mobile",
"number",
"from",
"that",
"country",
"from",
"abroad",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L958-L963 |
6 | ttacon/libphonenumber | phonenumberutil.go | normalizeHelper | func normalizeHelper(number string,
normalizationReplacements map[rune]rune,
removeNonMatches bool) string {
var normalizedNumber = builder.NewBuilder(nil)
for _, character := range number {
newDigit, ok := normalizationReplacements[unicode.ToUpper(character)]
if ok {
normalizedNumber.WriteRune(newDigit)
} else if !removeNonMatches {
normalizedNumber.WriteRune(character)
}
// If neither of the above are true, we remove this character.
}
return normalizedNumber.String()
} | go | func normalizeHelper(number string,
normalizationReplacements map[rune]rune,
removeNonMatches bool) string {
var normalizedNumber = builder.NewBuilder(nil)
for _, character := range number {
newDigit, ok := normalizationReplacements[unicode.ToUpper(character)]
if ok {
normalizedNumber.WriteRune(newDigit)
} else if !removeNonMatches {
normalizedNumber.WriteRune(character)
}
// If neither of the above are true, we remove this character.
}
return normalizedNumber.String()
} | [
"func",
"normalizeHelper",
"(",
"number",
"string",
",",
"normalizationReplacements",
"map",
"[",
"rune",
"]",
"rune",
",",
"removeNonMatches",
"bool",
")",
"string",
"{",
"var",
"normalizedNumber",
"=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"for",
"_",
",",
"character",
":=",
"range",
"number",
"{",
"newDigit",
",",
"ok",
":=",
"normalizationReplacements",
"[",
"unicode",
".",
"ToUpper",
"(",
"character",
")",
"]",
"\n",
"if",
"ok",
"{",
"normalizedNumber",
".",
"WriteRune",
"(",
"newDigit",
")",
"\n",
"}",
"else",
"if",
"!",
"removeNonMatches",
"{",
"normalizedNumber",
".",
"WriteRune",
"(",
"character",
")",
"\n",
"}",
"\n",
"// If neither of the above are true, we remove this character.",
"}",
"\n",
"return",
"normalizedNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Normalizes a string of characters representing a phone number by replacing
// all characters found in the accompanying map with the values therein,
// and stripping all other characters if removeNonMatches is true. | [
"Normalizes",
"a",
"string",
"of",
"characters",
"representing",
"a",
"phone",
"number",
"by",
"replacing",
"all",
"characters",
"found",
"in",
"the",
"accompanying",
"map",
"with",
"the",
"values",
"therein",
"and",
"stripping",
"all",
"other",
"characters",
"if",
"removeNonMatches",
"is",
"true",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L968-L983 |
7 | ttacon/libphonenumber | phonenumberutil.go | isNumberGeographical | func isNumberGeographical(phoneNumber *PhoneNumber) bool {
numberType := GetNumberType(phoneNumber)
// TODO: Include mobile phone numbers from countries like Indonesia,
// which has some mobile numbers that are geographical.
return numberType == FIXED_LINE ||
numberType == FIXED_LINE_OR_MOBILE
} | go | func isNumberGeographical(phoneNumber *PhoneNumber) bool {
numberType := GetNumberType(phoneNumber)
// TODO: Include mobile phone numbers from countries like Indonesia,
// which has some mobile numbers that are geographical.
return numberType == FIXED_LINE ||
numberType == FIXED_LINE_OR_MOBILE
} | [
"func",
"isNumberGeographical",
"(",
"phoneNumber",
"*",
"PhoneNumber",
")",
"bool",
"{",
"numberType",
":=",
"GetNumberType",
"(",
"phoneNumber",
")",
"\n",
"// TODO: Include mobile phone numbers from countries like Indonesia,",
"// which has some mobile numbers that are geographical.",
"return",
"numberType",
"==",
"FIXED_LINE",
"||",
"numberType",
"==",
"FIXED_LINE_OR_MOBILE",
"\n",
"}"
] | // Tests whether a phone number has a geographical association. It checks
// if the number is associated to a certain region in the country where it
// belongs to. Note that this doesn't verify if the number is actually in use.
//
// A similar method is implemented as PhoneNumberOfflineGeocoder.canBeGeocoded,
// which performs a looser check, since it only prevents cases where prefixes
// overlap for geocodable and non-geocodable numbers. Also, if new phone
// number types were added, we should check if this other method should be
// updated too. | [
"Tests",
"whether",
"a",
"phone",
"number",
"has",
"a",
"geographical",
"association",
".",
"It",
"checks",
"if",
"the",
"number",
"is",
"associated",
"to",
"a",
"certain",
"region",
"in",
"the",
"country",
"where",
"it",
"belongs",
"to",
".",
"Note",
"that",
"this",
"doesn",
"t",
"verify",
"if",
"the",
"number",
"is",
"actually",
"in",
"use",
".",
"A",
"similar",
"method",
"is",
"implemented",
"as",
"PhoneNumberOfflineGeocoder",
".",
"canBeGeocoded",
"which",
"performs",
"a",
"looser",
"check",
"since",
"it",
"only",
"prevents",
"cases",
"where",
"prefixes",
"overlap",
"for",
"geocodable",
"and",
"non",
"-",
"geocodable",
"numbers",
".",
"Also",
"if",
"new",
"phone",
"number",
"types",
"were",
"added",
"we",
"should",
"check",
"if",
"this",
"other",
"method",
"should",
"be",
"updated",
"too",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1012-L1018 |
8 | ttacon/libphonenumber | phonenumberutil.go | isValidRegionCode | func isValidRegionCode(regionCode string) bool {
_, contains := readFromSupportedRegions(regionCode)
return len(regionCode) != 0 && contains
} | go | func isValidRegionCode(regionCode string) bool {
_, contains := readFromSupportedRegions(regionCode)
return len(regionCode) != 0 && contains
} | [
"func",
"isValidRegionCode",
"(",
"regionCode",
"string",
")",
"bool",
"{",
"_",
",",
"contains",
":=",
"readFromSupportedRegions",
"(",
"regionCode",
")",
"\n",
"return",
"len",
"(",
"regionCode",
")",
"!=",
"0",
"&&",
"contains",
"\n",
"}"
] | // Helper function to check region code is not unknown or null. | [
"Helper",
"function",
"to",
"check",
"region",
"code",
"is",
"not",
"unknown",
"or",
"null",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1021-L1024 |
9 | ttacon/libphonenumber | phonenumberutil.go | Format | func Format(number *PhoneNumber, numberFormat PhoneNumberFormat) string {
if number.GetNationalNumber() == 0 && len(number.GetRawInput()) > 0 {
// Unparseable numbers that kept their raw input just use that.
// This is the only case where a number can be formatted as E164
// without a leading '+' symbol (but the original number wasn't
// parseable anyway).
// TODO: Consider removing the 'if' above so that unparseable
// strings without raw input format to the empty string instead of "+00"
rawInput := number.GetRawInput()
if len(rawInput) > 0 {
return rawInput
}
}
var formattedNumber = builder.NewBuilder(nil)
FormatWithBuf(number, numberFormat, formattedNumber)
return formattedNumber.String()
} | go | func Format(number *PhoneNumber, numberFormat PhoneNumberFormat) string {
if number.GetNationalNumber() == 0 && len(number.GetRawInput()) > 0 {
// Unparseable numbers that kept their raw input just use that.
// This is the only case where a number can be formatted as E164
// without a leading '+' symbol (but the original number wasn't
// parseable anyway).
// TODO: Consider removing the 'if' above so that unparseable
// strings without raw input format to the empty string instead of "+00"
rawInput := number.GetRawInput()
if len(rawInput) > 0 {
return rawInput
}
}
var formattedNumber = builder.NewBuilder(nil)
FormatWithBuf(number, numberFormat, formattedNumber)
return formattedNumber.String()
} | [
"func",
"Format",
"(",
"number",
"*",
"PhoneNumber",
",",
"numberFormat",
"PhoneNumberFormat",
")",
"string",
"{",
"if",
"number",
".",
"GetNationalNumber",
"(",
")",
"==",
"0",
"&&",
"len",
"(",
"number",
".",
"GetRawInput",
"(",
")",
")",
">",
"0",
"{",
"// Unparseable numbers that kept their raw input just use that.",
"// This is the only case where a number can be formatted as E164",
"// without a leading '+' symbol (but the original number wasn't",
"// parseable anyway).",
"// TODO: Consider removing the 'if' above so that unparseable",
"// strings without raw input format to the empty string instead of \"+00\"",
"rawInput",
":=",
"number",
".",
"GetRawInput",
"(",
")",
"\n",
"if",
"len",
"(",
"rawInput",
")",
">",
"0",
"{",
"return",
"rawInput",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"formattedNumber",
"=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"FormatWithBuf",
"(",
"number",
",",
"numberFormat",
",",
"formattedNumber",
")",
"\n",
"return",
"formattedNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Formats a phone number in the specified format using default rules. Note
// that this does not promise to produce a phone number that the user can
// dial from where they are - although we do format in either 'national' or
// 'international' format depending on what the client asks for, we do not
// currently support a more abbreviated format, such as for users in the
// same "area" who could potentially dial the number without area code.
// Note that if the phone number has a country calling code of 0 or an
// otherwise invalid country calling code, we cannot work out which
// formatting rules to apply so we return the national significant number
// with no formatting applied. | [
"Formats",
"a",
"phone",
"number",
"in",
"the",
"specified",
"format",
"using",
"default",
"rules",
".",
"Note",
"that",
"this",
"does",
"not",
"promise",
"to",
"produce",
"a",
"phone",
"number",
"that",
"the",
"user",
"can",
"dial",
"from",
"where",
"they",
"are",
"-",
"although",
"we",
"do",
"format",
"in",
"either",
"national",
"or",
"international",
"format",
"depending",
"on",
"what",
"the",
"client",
"asks",
"for",
"we",
"do",
"not",
"currently",
"support",
"a",
"more",
"abbreviated",
"format",
"such",
"as",
"for",
"users",
"in",
"the",
"same",
"area",
"who",
"could",
"potentially",
"dial",
"the",
"number",
"without",
"area",
"code",
".",
"Note",
"that",
"if",
"the",
"phone",
"number",
"has",
"a",
"country",
"calling",
"code",
"of",
"0",
"or",
"an",
"otherwise",
"invalid",
"country",
"calling",
"code",
"we",
"cannot",
"work",
"out",
"which",
"formatting",
"rules",
"to",
"apply",
"so",
"we",
"return",
"the",
"national",
"significant",
"number",
"with",
"no",
"formatting",
"applied",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1042-L1058 |
10 | ttacon/libphonenumber | phonenumberutil.go | FormatByPattern | func FormatByPattern(number *PhoneNumber,
numberFormat PhoneNumberFormat,
userDefinedFormats []*NumberFormat) string {
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
// Note GetRegionCodeForCountryCode() is used because formatting
// information for regions which share a country calling code is
// contained by only one region for performance reasons. For example,
// for NANPA regions it will be contained in the metadata for US.
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid
metadata := getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNumber := builder.NewBuilder(nil)
formattingPattern := chooseFormattingPatternForNumber(
userDefinedFormats, nationalSignificantNumber)
if formattingPattern == nil {
// If no pattern above is matched, we format the number as a whole.
formattedNumber.WriteString(nationalSignificantNumber)
} else {
var numFormatCopy *NumberFormat
// Before we do a replacement of the national prefix pattern
// $NP with the national prefix, we need to copy the rule so
// that subsequent replacements for different numbers have the
// appropriate national prefix.
proto.Merge(numFormatCopy, formattingPattern)
nationalPrefixFormattingRule := formattingPattern.GetNationalPrefixFormattingRule()
if len(nationalPrefixFormattingRule) > 0 {
nationalPrefix := metadata.GetNationalPrefix()
if len(nationalPrefix) > 0 {
// Replace $NP with national prefix and $FG with the
// first group ($1).
nationalPrefixFormattingRule =
NP_PATTERN.ReplaceAllString(
nationalPrefixFormattingRule, nationalPrefix)
nationalPrefixFormattingRule =
FG_PATTERN.ReplaceAllString(
nationalPrefixFormattingRule, "\\$1")
numFormatCopy.NationalPrefixFormattingRule =
&nationalPrefixFormattingRule
} else {
// We don't want to have a rule for how to format the
// national prefix if there isn't one.
numFormatCopy.NationalPrefixFormattingRule = nil
}
}
formattedNumber.WriteString(
formatNsnUsingPattern(
nationalSignificantNumber, numFormatCopy, numberFormat))
}
maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber)
prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber)
return formattedNumber.String()
} | go | func FormatByPattern(number *PhoneNumber,
numberFormat PhoneNumberFormat,
userDefinedFormats []*NumberFormat) string {
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
// Note GetRegionCodeForCountryCode() is used because formatting
// information for regions which share a country calling code is
// contained by only one region for performance reasons. For example,
// for NANPA regions it will be contained in the metadata for US.
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid
metadata := getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNumber := builder.NewBuilder(nil)
formattingPattern := chooseFormattingPatternForNumber(
userDefinedFormats, nationalSignificantNumber)
if formattingPattern == nil {
// If no pattern above is matched, we format the number as a whole.
formattedNumber.WriteString(nationalSignificantNumber)
} else {
var numFormatCopy *NumberFormat
// Before we do a replacement of the national prefix pattern
// $NP with the national prefix, we need to copy the rule so
// that subsequent replacements for different numbers have the
// appropriate national prefix.
proto.Merge(numFormatCopy, formattingPattern)
nationalPrefixFormattingRule := formattingPattern.GetNationalPrefixFormattingRule()
if len(nationalPrefixFormattingRule) > 0 {
nationalPrefix := metadata.GetNationalPrefix()
if len(nationalPrefix) > 0 {
// Replace $NP with national prefix and $FG with the
// first group ($1).
nationalPrefixFormattingRule =
NP_PATTERN.ReplaceAllString(
nationalPrefixFormattingRule, nationalPrefix)
nationalPrefixFormattingRule =
FG_PATTERN.ReplaceAllString(
nationalPrefixFormattingRule, "\\$1")
numFormatCopy.NationalPrefixFormattingRule =
&nationalPrefixFormattingRule
} else {
// We don't want to have a rule for how to format the
// national prefix if there isn't one.
numFormatCopy.NationalPrefixFormattingRule = nil
}
}
formattedNumber.WriteString(
formatNsnUsingPattern(
nationalSignificantNumber, numFormatCopy, numberFormat))
}
maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber)
prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber)
return formattedNumber.String()
} | [
"func",
"FormatByPattern",
"(",
"number",
"*",
"PhoneNumber",
",",
"numberFormat",
"PhoneNumberFormat",
",",
"userDefinedFormats",
"[",
"]",
"*",
"NumberFormat",
")",
"string",
"{",
"countryCallingCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"nationalSignificantNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCallingCode",
")",
"{",
"return",
"nationalSignificantNumber",
"\n",
"}",
"\n",
"// Note GetRegionCodeForCountryCode() is used because formatting",
"// information for regions which share a country calling code is",
"// contained by only one region for performance reasons. For example,",
"// for NANPA regions it will be contained in the metadata for US.",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCallingCode",
")",
"\n",
"// Metadata cannot be null because the country calling code is valid",
"metadata",
":=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCallingCode",
",",
"regionCode",
")",
"\n\n",
"formattedNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n\n",
"formattingPattern",
":=",
"chooseFormattingPatternForNumber",
"(",
"userDefinedFormats",
",",
"nationalSignificantNumber",
")",
"\n",
"if",
"formattingPattern",
"==",
"nil",
"{",
"// If no pattern above is matched, we format the number as a whole.",
"formattedNumber",
".",
"WriteString",
"(",
"nationalSignificantNumber",
")",
"\n",
"}",
"else",
"{",
"var",
"numFormatCopy",
"*",
"NumberFormat",
"\n",
"// Before we do a replacement of the national prefix pattern",
"// $NP with the national prefix, we need to copy the rule so",
"// that subsequent replacements for different numbers have the",
"// appropriate national prefix.",
"proto",
".",
"Merge",
"(",
"numFormatCopy",
",",
"formattingPattern",
")",
"\n",
"nationalPrefixFormattingRule",
":=",
"formattingPattern",
".",
"GetNationalPrefixFormattingRule",
"(",
")",
"\n",
"if",
"len",
"(",
"nationalPrefixFormattingRule",
")",
">",
"0",
"{",
"nationalPrefix",
":=",
"metadata",
".",
"GetNationalPrefix",
"(",
")",
"\n",
"if",
"len",
"(",
"nationalPrefix",
")",
">",
"0",
"{",
"// Replace $NP with national prefix and $FG with the",
"// first group ($1).",
"nationalPrefixFormattingRule",
"=",
"NP_PATTERN",
".",
"ReplaceAllString",
"(",
"nationalPrefixFormattingRule",
",",
"nationalPrefix",
")",
"\n",
"nationalPrefixFormattingRule",
"=",
"FG_PATTERN",
".",
"ReplaceAllString",
"(",
"nationalPrefixFormattingRule",
",",
"\"",
"\\\\",
"\"",
")",
"\n",
"numFormatCopy",
".",
"NationalPrefixFormattingRule",
"=",
"&",
"nationalPrefixFormattingRule",
"\n",
"}",
"else",
"{",
"// We don't want to have a rule for how to format the",
"// national prefix if there isn't one.",
"numFormatCopy",
".",
"NationalPrefixFormattingRule",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"formattedNumber",
".",
"WriteString",
"(",
"formatNsnUsingPattern",
"(",
"nationalSignificantNumber",
",",
"numFormatCopy",
",",
"numberFormat",
")",
")",
"\n",
"}",
"\n",
"maybeAppendFormattedExtension",
"(",
"number",
",",
"metadata",
",",
"numberFormat",
",",
"formattedNumber",
")",
"\n",
"prefixNumberWithCountryCallingCode",
"(",
"countryCallingCode",
",",
"numberFormat",
",",
"formattedNumber",
")",
"\n",
"return",
"formattedNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Formats a phone number in the specified format using client-defined
// formatting rules. Note that if the phone number has a country calling
// code of zero or an otherwise invalid country calling code, we cannot
// work out things like whether there should be a national prefix applied,
// or how to format extensions, so we return the national significant
// number with no formatting applied. | [
"Formats",
"a",
"phone",
"number",
"in",
"the",
"specified",
"format",
"using",
"client",
"-",
"defined",
"formatting",
"rules",
".",
"Note",
"that",
"if",
"the",
"phone",
"number",
"has",
"a",
"country",
"calling",
"code",
"of",
"zero",
"or",
"an",
"otherwise",
"invalid",
"country",
"calling",
"code",
"we",
"cannot",
"work",
"out",
"things",
"like",
"whether",
"there",
"should",
"be",
"a",
"national",
"prefix",
"applied",
"or",
"how",
"to",
"format",
"extensions",
"so",
"we",
"return",
"the",
"national",
"significant",
"number",
"with",
"no",
"formatting",
"applied",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1109-L1167 |
11 | ttacon/libphonenumber | phonenumberutil.go | FormatNationalNumberWithCarrierCode | func FormatNationalNumberWithCarrierCode(number *PhoneNumber, carrierCode string) string {
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
// Note GetRegionCodeForCountryCode() is used because formatting
// information for regions which share a country calling code is
// contained by only one region for performance reasons. For
// example, for NANPA regions it will be contained in the metadata for US.
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid.
metadata := getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNumber := builder.NewBuilder(nil)
formattedNumber.WriteString(
formatNsnWithCarrier(
nationalSignificantNumber,
metadata,
NATIONAL,
carrierCode))
maybeAppendFormattedExtension(number, metadata, NATIONAL, formattedNumber)
prefixNumberWithCountryCallingCode(
countryCallingCode,
NATIONAL,
formattedNumber)
return formattedNumber.String()
} | go | func FormatNationalNumberWithCarrierCode(number *PhoneNumber, carrierCode string) string {
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
// Note GetRegionCodeForCountryCode() is used because formatting
// information for regions which share a country calling code is
// contained by only one region for performance reasons. For
// example, for NANPA regions it will be contained in the metadata for US.
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid.
metadata := getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNumber := builder.NewBuilder(nil)
formattedNumber.WriteString(
formatNsnWithCarrier(
nationalSignificantNumber,
metadata,
NATIONAL,
carrierCode))
maybeAppendFormattedExtension(number, metadata, NATIONAL, formattedNumber)
prefixNumberWithCountryCallingCode(
countryCallingCode,
NATIONAL,
formattedNumber)
return formattedNumber.String()
} | [
"func",
"FormatNationalNumberWithCarrierCode",
"(",
"number",
"*",
"PhoneNumber",
",",
"carrierCode",
"string",
")",
"string",
"{",
"countryCallingCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"nationalSignificantNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCallingCode",
")",
"{",
"return",
"nationalSignificantNumber",
"\n",
"}",
"\n",
"// Note GetRegionCodeForCountryCode() is used because formatting",
"// information for regions which share a country calling code is",
"// contained by only one region for performance reasons. For",
"// example, for NANPA regions it will be contained in the metadata for US.",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCallingCode",
")",
"\n",
"// Metadata cannot be null because the country calling code is valid.",
"metadata",
":=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCallingCode",
",",
"regionCode",
")",
"\n\n",
"formattedNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"formattedNumber",
".",
"WriteString",
"(",
"formatNsnWithCarrier",
"(",
"nationalSignificantNumber",
",",
"metadata",
",",
"NATIONAL",
",",
"carrierCode",
")",
")",
"\n",
"maybeAppendFormattedExtension",
"(",
"number",
",",
"metadata",
",",
"NATIONAL",
",",
"formattedNumber",
")",
"\n",
"prefixNumberWithCountryCallingCode",
"(",
"countryCallingCode",
",",
"NATIONAL",
",",
"formattedNumber",
")",
"\n",
"return",
"formattedNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Formats a phone number in national format for dialing using the carrier
// as specified in the carrierCode. The carrierCode will always be used
// regardless of whether the phone number already has a preferred domestic
// carrier code stored. If carrierCode contains an empty string, returns
// the number in national format without any carrier code. | [
"Formats",
"a",
"phone",
"number",
"in",
"national",
"format",
"for",
"dialing",
"using",
"the",
"carrier",
"as",
"specified",
"in",
"the",
"carrierCode",
".",
"The",
"carrierCode",
"will",
"always",
"be",
"used",
"regardless",
"of",
"whether",
"the",
"phone",
"number",
"already",
"has",
"a",
"preferred",
"domestic",
"carrier",
"code",
"stored",
".",
"If",
"carrierCode",
"contains",
"an",
"empty",
"string",
"returns",
"the",
"number",
"in",
"national",
"format",
"without",
"any",
"carrier",
"code",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1174-L1201 |
12 | ttacon/libphonenumber | phonenumberutil.go | FormatNationalNumberWithPreferredCarrierCode | func FormatNationalNumberWithPreferredCarrierCode(
number *PhoneNumber,
fallbackCarrierCode string) string {
pref := number.GetPreferredDomesticCarrierCode()
if number.GetPreferredDomesticCarrierCode() == "" {
pref = fallbackCarrierCode
}
return FormatNationalNumberWithCarrierCode(number, pref)
} | go | func FormatNationalNumberWithPreferredCarrierCode(
number *PhoneNumber,
fallbackCarrierCode string) string {
pref := number.GetPreferredDomesticCarrierCode()
if number.GetPreferredDomesticCarrierCode() == "" {
pref = fallbackCarrierCode
}
return FormatNationalNumberWithCarrierCode(number, pref)
} | [
"func",
"FormatNationalNumberWithPreferredCarrierCode",
"(",
"number",
"*",
"PhoneNumber",
",",
"fallbackCarrierCode",
"string",
")",
"string",
"{",
"pref",
":=",
"number",
".",
"GetPreferredDomesticCarrierCode",
"(",
")",
"\n",
"if",
"number",
".",
"GetPreferredDomesticCarrierCode",
"(",
")",
"==",
"\"",
"\"",
"{",
"pref",
"=",
"fallbackCarrierCode",
"\n",
"}",
"\n",
"return",
"FormatNationalNumberWithCarrierCode",
"(",
"number",
",",
"pref",
")",
"\n",
"}"
] | // Formats a phone number in national format for dialing using the carrier
// as specified in the preferredDomesticCarrierCode field of the PhoneNumber
// object passed in. If that is missing, use the fallbackCarrierCode passed
// in instead. If there is no preferredDomesticCarrierCode, and the
// fallbackCarrierCode contains an empty string, return the number in
// national format without any carrier code.
//
// Use formatNationalNumberWithCarrierCode instead if the carrier code
// passed in should take precedence over the number's
// preferredDomesticCarrierCode when formatting. | [
"Formats",
"a",
"phone",
"number",
"in",
"national",
"format",
"for",
"dialing",
"using",
"the",
"carrier",
"as",
"specified",
"in",
"the",
"preferredDomesticCarrierCode",
"field",
"of",
"the",
"PhoneNumber",
"object",
"passed",
"in",
".",
"If",
"that",
"is",
"missing",
"use",
"the",
"fallbackCarrierCode",
"passed",
"in",
"instead",
".",
"If",
"there",
"is",
"no",
"preferredDomesticCarrierCode",
"and",
"the",
"fallbackCarrierCode",
"contains",
"an",
"empty",
"string",
"return",
"the",
"number",
"in",
"national",
"format",
"without",
"any",
"carrier",
"code",
".",
"Use",
"formatNationalNumberWithCarrierCode",
"instead",
"if",
"the",
"carrier",
"code",
"passed",
"in",
"should",
"take",
"precedence",
"over",
"the",
"number",
"s",
"preferredDomesticCarrierCode",
"when",
"formatting",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1221-L1230 |
13 | ttacon/libphonenumber | phonenumberutil.go | FormatInOriginalFormat | func FormatInOriginalFormat(number *PhoneNumber, regionCallingFrom string) string {
rawInput := number.GetRawInput()
if len(rawInput) == 0 &&
(hasUnexpectedItalianLeadingZero(number) ||
!hasFormattingPatternForNumber(number)) {
// We check if we have the formatting pattern because without that, we might format the number
// as a group without national prefix.
return rawInput
}
if number.GetCountryCodeSource() == 0 {
return Format(number, NATIONAL)
}
var formattedNumber string
switch number.GetCountryCodeSource() {
case PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN:
formattedNumber = Format(number, INTERNATIONAL)
case PhoneNumber_FROM_NUMBER_WITH_IDD:
formattedNumber = FormatOutOfCountryCallingNumber(number, regionCallingFrom)
case PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN:
formattedNumber = Format(number, INTERNATIONAL)[1:]
case PhoneNumber_FROM_DEFAULT_COUNTRY:
// Fall-through to default case.
fallthrough
default:
regionCode := GetRegionCodeForCountryCode(int(number.GetCountryCode()))
// We strip non-digits from the NDD here, and from the raw
// input later, so that we can compare them easily.
nationalPrefix := GetNddPrefixForRegion(
regionCode, true /* strip non-digits */)
nationalFormat := Format(number, NATIONAL)
if len(nationalPrefix) == 0 {
// If the region doesn't have a national prefix at all,
// we can safely return the national format without worrying
// about a national prefix being added.
formattedNumber = nationalFormat
break
}
// Otherwise, we check if the original number was entered with
// a national prefix.
if rawInputContainsNationalPrefix(rawInput, nationalPrefix, regionCode) {
// If so, we can safely return the national format.
formattedNumber = nationalFormat
}
// Metadata cannot be null here because GetNddPrefixForRegion()
// (above) returns null if there is no metadata for the region.
metadata := getMetadataForRegion(regionCode)
nationalNumber := GetNationalSignificantNumber(number)
formatRule :=
chooseFormattingPatternForNumber(metadata.GetNumberFormat(), nationalNumber)
// The format rule could still be null here if the national
// number was 0 and there was no raw input (this should not
// be possible for numbers generated by the phonenumber library
// as they would also not have a country calling code and we
// would have exited earlier).
if formatRule == nil {
formattedNumber = nationalFormat
break
}
// When the format we apply to this number doesn't contain
// national prefix, we can just return the national format.
// TODO: Refactor the code below with the code in
// isNationalPrefixPresentIfRequired.
candidateNationalPrefixRule := formatRule.GetNationalPrefixFormattingRule()
// We assume that the first-group symbol will never be _before_
// the national prefix.
indexOfFirstGroup := strings.Index(candidateNationalPrefixRule, "$1")
if indexOfFirstGroup <= 0 {
formattedNumber = nationalFormat
break
}
candidateNationalPrefixRule =
candidateNationalPrefixRule[0:indexOfFirstGroup]
candidateNationalPrefixRule = NormalizeDigitsOnly(candidateNationalPrefixRule)
if len(candidateNationalPrefixRule) == 0 {
// National prefix not used when formatting this number.
formattedNumber = nationalFormat
break
}
// Otherwise, we need to remove the national prefix from our output.
var numFormatCopy *NumberFormat
proto.Merge(numFormatCopy, formatRule)
numFormatCopy.NationalPrefixFormattingRule = nil
var numberFormats = []*NumberFormat{numFormatCopy}
formattedNumber = FormatByPattern(number, NATIONAL, numberFormats)
break
}
rawInput = number.GetRawInput()
// If no digit is inserted/removed/modified as a result of our
// formatting, we return the formatted phone number; otherwise we
// return the raw input the user entered.
if len(formattedNumber) != 0 && len(rawInput) > 0 {
normalizedFormattedNumber := normalizeDiallableCharsOnly(formattedNumber)
normalizedRawInput := normalizeDiallableCharsOnly(rawInput)
if normalizedFormattedNumber != normalizedRawInput {
formattedNumber = rawInput
}
}
return formattedNumber
} | go | func FormatInOriginalFormat(number *PhoneNumber, regionCallingFrom string) string {
rawInput := number.GetRawInput()
if len(rawInput) == 0 &&
(hasUnexpectedItalianLeadingZero(number) ||
!hasFormattingPatternForNumber(number)) {
// We check if we have the formatting pattern because without that, we might format the number
// as a group without national prefix.
return rawInput
}
if number.GetCountryCodeSource() == 0 {
return Format(number, NATIONAL)
}
var formattedNumber string
switch number.GetCountryCodeSource() {
case PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN:
formattedNumber = Format(number, INTERNATIONAL)
case PhoneNumber_FROM_NUMBER_WITH_IDD:
formattedNumber = FormatOutOfCountryCallingNumber(number, regionCallingFrom)
case PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN:
formattedNumber = Format(number, INTERNATIONAL)[1:]
case PhoneNumber_FROM_DEFAULT_COUNTRY:
// Fall-through to default case.
fallthrough
default:
regionCode := GetRegionCodeForCountryCode(int(number.GetCountryCode()))
// We strip non-digits from the NDD here, and from the raw
// input later, so that we can compare them easily.
nationalPrefix := GetNddPrefixForRegion(
regionCode, true /* strip non-digits */)
nationalFormat := Format(number, NATIONAL)
if len(nationalPrefix) == 0 {
// If the region doesn't have a national prefix at all,
// we can safely return the national format without worrying
// about a national prefix being added.
formattedNumber = nationalFormat
break
}
// Otherwise, we check if the original number was entered with
// a national prefix.
if rawInputContainsNationalPrefix(rawInput, nationalPrefix, regionCode) {
// If so, we can safely return the national format.
formattedNumber = nationalFormat
}
// Metadata cannot be null here because GetNddPrefixForRegion()
// (above) returns null if there is no metadata for the region.
metadata := getMetadataForRegion(regionCode)
nationalNumber := GetNationalSignificantNumber(number)
formatRule :=
chooseFormattingPatternForNumber(metadata.GetNumberFormat(), nationalNumber)
// The format rule could still be null here if the national
// number was 0 and there was no raw input (this should not
// be possible for numbers generated by the phonenumber library
// as they would also not have a country calling code and we
// would have exited earlier).
if formatRule == nil {
formattedNumber = nationalFormat
break
}
// When the format we apply to this number doesn't contain
// national prefix, we can just return the national format.
// TODO: Refactor the code below with the code in
// isNationalPrefixPresentIfRequired.
candidateNationalPrefixRule := formatRule.GetNationalPrefixFormattingRule()
// We assume that the first-group symbol will never be _before_
// the national prefix.
indexOfFirstGroup := strings.Index(candidateNationalPrefixRule, "$1")
if indexOfFirstGroup <= 0 {
formattedNumber = nationalFormat
break
}
candidateNationalPrefixRule =
candidateNationalPrefixRule[0:indexOfFirstGroup]
candidateNationalPrefixRule = NormalizeDigitsOnly(candidateNationalPrefixRule)
if len(candidateNationalPrefixRule) == 0 {
// National prefix not used when formatting this number.
formattedNumber = nationalFormat
break
}
// Otherwise, we need to remove the national prefix from our output.
var numFormatCopy *NumberFormat
proto.Merge(numFormatCopy, formatRule)
numFormatCopy.NationalPrefixFormattingRule = nil
var numberFormats = []*NumberFormat{numFormatCopy}
formattedNumber = FormatByPattern(number, NATIONAL, numberFormats)
break
}
rawInput = number.GetRawInput()
// If no digit is inserted/removed/modified as a result of our
// formatting, we return the formatted phone number; otherwise we
// return the raw input the user entered.
if len(formattedNumber) != 0 && len(rawInput) > 0 {
normalizedFormattedNumber := normalizeDiallableCharsOnly(formattedNumber)
normalizedRawInput := normalizeDiallableCharsOnly(rawInput)
if normalizedFormattedNumber != normalizedRawInput {
formattedNumber = rawInput
}
}
return formattedNumber
} | [
"func",
"FormatInOriginalFormat",
"(",
"number",
"*",
"PhoneNumber",
",",
"regionCallingFrom",
"string",
")",
"string",
"{",
"rawInput",
":=",
"number",
".",
"GetRawInput",
"(",
")",
"\n",
"if",
"len",
"(",
"rawInput",
")",
"==",
"0",
"&&",
"(",
"hasUnexpectedItalianLeadingZero",
"(",
"number",
")",
"||",
"!",
"hasFormattingPatternForNumber",
"(",
"number",
")",
")",
"{",
"// We check if we have the formatting pattern because without that, we might format the number",
"// as a group without national prefix.",
"return",
"rawInput",
"\n",
"}",
"\n",
"if",
"number",
".",
"GetCountryCodeSource",
"(",
")",
"==",
"0",
"{",
"return",
"Format",
"(",
"number",
",",
"NATIONAL",
")",
"\n",
"}",
"\n",
"var",
"formattedNumber",
"string",
"\n",
"switch",
"number",
".",
"GetCountryCodeSource",
"(",
")",
"{",
"case",
"PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN",
":",
"formattedNumber",
"=",
"Format",
"(",
"number",
",",
"INTERNATIONAL",
")",
"\n",
"case",
"PhoneNumber_FROM_NUMBER_WITH_IDD",
":",
"formattedNumber",
"=",
"FormatOutOfCountryCallingNumber",
"(",
"number",
",",
"regionCallingFrom",
")",
"\n",
"case",
"PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN",
":",
"formattedNumber",
"=",
"Format",
"(",
"number",
",",
"INTERNATIONAL",
")",
"[",
"1",
":",
"]",
"\n",
"case",
"PhoneNumber_FROM_DEFAULT_COUNTRY",
":",
"// Fall-through to default case.",
"fallthrough",
"\n",
"default",
":",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
")",
"\n",
"// We strip non-digits from the NDD here, and from the raw",
"// input later, so that we can compare them easily.",
"nationalPrefix",
":=",
"GetNddPrefixForRegion",
"(",
"regionCode",
",",
"true",
"/* strip non-digits */",
")",
"\n",
"nationalFormat",
":=",
"Format",
"(",
"number",
",",
"NATIONAL",
")",
"\n",
"if",
"len",
"(",
"nationalPrefix",
")",
"==",
"0",
"{",
"// If the region doesn't have a national prefix at all,",
"// we can safely return the national format without worrying",
"// about a national prefix being added.",
"formattedNumber",
"=",
"nationalFormat",
"\n",
"break",
"\n",
"}",
"\n",
"// Otherwise, we check if the original number was entered with",
"// a national prefix.",
"if",
"rawInputContainsNationalPrefix",
"(",
"rawInput",
",",
"nationalPrefix",
",",
"regionCode",
")",
"{",
"// If so, we can safely return the national format.",
"formattedNumber",
"=",
"nationalFormat",
"\n",
"}",
"\n",
"// Metadata cannot be null here because GetNddPrefixForRegion()",
"// (above) returns null if there is no metadata for the region.",
"metadata",
":=",
"getMetadataForRegion",
"(",
"regionCode",
")",
"\n",
"nationalNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"formatRule",
":=",
"chooseFormattingPatternForNumber",
"(",
"metadata",
".",
"GetNumberFormat",
"(",
")",
",",
"nationalNumber",
")",
"\n",
"// The format rule could still be null here if the national",
"// number was 0 and there was no raw input (this should not",
"// be possible for numbers generated by the phonenumber library",
"// as they would also not have a country calling code and we",
"// would have exited earlier).",
"if",
"formatRule",
"==",
"nil",
"{",
"formattedNumber",
"=",
"nationalFormat",
"\n",
"break",
"\n",
"}",
"\n",
"// When the format we apply to this number doesn't contain",
"// national prefix, we can just return the national format.",
"// TODO: Refactor the code below with the code in",
"// isNationalPrefixPresentIfRequired.",
"candidateNationalPrefixRule",
":=",
"formatRule",
".",
"GetNationalPrefixFormattingRule",
"(",
")",
"\n",
"// We assume that the first-group symbol will never be _before_",
"// the national prefix.",
"indexOfFirstGroup",
":=",
"strings",
".",
"Index",
"(",
"candidateNationalPrefixRule",
",",
"\"",
"\"",
")",
"\n",
"if",
"indexOfFirstGroup",
"<=",
"0",
"{",
"formattedNumber",
"=",
"nationalFormat",
"\n",
"break",
"\n",
"}",
"\n",
"candidateNationalPrefixRule",
"=",
"candidateNationalPrefixRule",
"[",
"0",
":",
"indexOfFirstGroup",
"]",
"\n",
"candidateNationalPrefixRule",
"=",
"NormalizeDigitsOnly",
"(",
"candidateNationalPrefixRule",
")",
"\n",
"if",
"len",
"(",
"candidateNationalPrefixRule",
")",
"==",
"0",
"{",
"// National prefix not used when formatting this number.",
"formattedNumber",
"=",
"nationalFormat",
"\n",
"break",
"\n",
"}",
"\n",
"// Otherwise, we need to remove the national prefix from our output.",
"var",
"numFormatCopy",
"*",
"NumberFormat",
"\n",
"proto",
".",
"Merge",
"(",
"numFormatCopy",
",",
"formatRule",
")",
"\n",
"numFormatCopy",
".",
"NationalPrefixFormattingRule",
"=",
"nil",
"\n",
"var",
"numberFormats",
"=",
"[",
"]",
"*",
"NumberFormat",
"{",
"numFormatCopy",
"}",
"\n",
"formattedNumber",
"=",
"FormatByPattern",
"(",
"number",
",",
"NATIONAL",
",",
"numberFormats",
")",
"\n",
"break",
"\n",
"}",
"\n",
"rawInput",
"=",
"number",
".",
"GetRawInput",
"(",
")",
"\n",
"// If no digit is inserted/removed/modified as a result of our",
"// formatting, we return the formatted phone number; otherwise we",
"// return the raw input the user entered.",
"if",
"len",
"(",
"formattedNumber",
")",
"!=",
"0",
"&&",
"len",
"(",
"rawInput",
")",
">",
"0",
"{",
"normalizedFormattedNumber",
":=",
"normalizeDiallableCharsOnly",
"(",
"formattedNumber",
")",
"\n",
"normalizedRawInput",
":=",
"normalizeDiallableCharsOnly",
"(",
"rawInput",
")",
"\n",
"if",
"normalizedFormattedNumber",
"!=",
"normalizedRawInput",
"{",
"formattedNumber",
"=",
"rawInput",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"formattedNumber",
"\n",
"}"
] | // Formats a phone number using the original phone number format that the
// number is parsed from. The original format is embedded in the
// country_code_source field of the PhoneNumber object passed in. If such
// information is missing, the number will be formatted into the NATIONAL
// format by default. When the number contains a leading zero and this is
// unexpected for this country, or we don't have a formatting pattern for
// the number, the method returns the raw input when it is available.
//
// Note this method guarantees no digit will be inserted, removed or
// modified as a result of formatting. | [
"Formats",
"a",
"phone",
"number",
"using",
"the",
"original",
"phone",
"number",
"format",
"that",
"the",
"number",
"is",
"parsed",
"from",
".",
"The",
"original",
"format",
"is",
"embedded",
"in",
"the",
"country_code_source",
"field",
"of",
"the",
"PhoneNumber",
"object",
"passed",
"in",
".",
"If",
"such",
"information",
"is",
"missing",
"the",
"number",
"will",
"be",
"formatted",
"into",
"the",
"NATIONAL",
"format",
"by",
"default",
".",
"When",
"the",
"number",
"contains",
"a",
"leading",
"zero",
"and",
"this",
"is",
"unexpected",
"for",
"this",
"country",
"or",
"we",
"don",
"t",
"have",
"a",
"formatting",
"pattern",
"for",
"the",
"number",
"the",
"method",
"returns",
"the",
"raw",
"input",
"when",
"it",
"is",
"available",
".",
"Note",
"this",
"method",
"guarantees",
"no",
"digit",
"will",
"be",
"inserted",
"removed",
"or",
"modified",
"as",
"a",
"result",
"of",
"formatting",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1444-L1542 |
14 | ttacon/libphonenumber | phonenumberutil.go | rawInputContainsNationalPrefix | func rawInputContainsNationalPrefix(rawInput, nationalPrefix, regionCode string) bool {
normalizedNationalNumber := NormalizeDigitsOnly(rawInput)
if strings.HasPrefix(normalizedNationalNumber, nationalPrefix) {
// Some Japanese numbers (e.g. 00777123) might be mistaken to
// contain the national prefix when written without it
// (e.g. 0777123) if we just do prefix matching. To tackle that,
// we check the validity of the number if the assumed national
// prefix is removed (777123 won't be valid in Japan).
num, err := Parse(normalizedNationalNumber[len(nationalPrefix):], regionCode)
if err != nil {
return false
}
return IsValidNumber(num)
}
return false
} | go | func rawInputContainsNationalPrefix(rawInput, nationalPrefix, regionCode string) bool {
normalizedNationalNumber := NormalizeDigitsOnly(rawInput)
if strings.HasPrefix(normalizedNationalNumber, nationalPrefix) {
// Some Japanese numbers (e.g. 00777123) might be mistaken to
// contain the national prefix when written without it
// (e.g. 0777123) if we just do prefix matching. To tackle that,
// we check the validity of the number if the assumed national
// prefix is removed (777123 won't be valid in Japan).
num, err := Parse(normalizedNationalNumber[len(nationalPrefix):], regionCode)
if err != nil {
return false
}
return IsValidNumber(num)
}
return false
} | [
"func",
"rawInputContainsNationalPrefix",
"(",
"rawInput",
",",
"nationalPrefix",
",",
"regionCode",
"string",
")",
"bool",
"{",
"normalizedNationalNumber",
":=",
"NormalizeDigitsOnly",
"(",
"rawInput",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"normalizedNationalNumber",
",",
"nationalPrefix",
")",
"{",
"// Some Japanese numbers (e.g. 00777123) might be mistaken to",
"// contain the national prefix when written without it",
"// (e.g. 0777123) if we just do prefix matching. To tackle that,",
"// we check the validity of the number if the assumed national",
"// prefix is removed (777123 won't be valid in Japan).",
"num",
",",
"err",
":=",
"Parse",
"(",
"normalizedNationalNumber",
"[",
"len",
"(",
"nationalPrefix",
")",
":",
"]",
",",
"regionCode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"IsValidNumber",
"(",
"num",
")",
"\n\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Check if rawInput, which is assumed to be in the national format, has
// a national prefix. The national prefix is assumed to be in digits-only
// form. | [
"Check",
"if",
"rawInput",
"which",
"is",
"assumed",
"to",
"be",
"in",
"the",
"national",
"format",
"has",
"a",
"national",
"prefix",
".",
"The",
"national",
"prefix",
"is",
"assumed",
"to",
"be",
"in",
"digits",
"-",
"only",
"form",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1547-L1563 |
15 | ttacon/libphonenumber | phonenumberutil.go | hasUnexpectedItalianLeadingZero | func hasUnexpectedItalianLeadingZero(number *PhoneNumber) bool {
return number.GetItalianLeadingZero() &&
!isLeadingZeroPossible(int(number.GetCountryCode()))
} | go | func hasUnexpectedItalianLeadingZero(number *PhoneNumber) bool {
return number.GetItalianLeadingZero() &&
!isLeadingZeroPossible(int(number.GetCountryCode()))
} | [
"func",
"hasUnexpectedItalianLeadingZero",
"(",
"number",
"*",
"PhoneNumber",
")",
"bool",
"{",
"return",
"number",
".",
"GetItalianLeadingZero",
"(",
")",
"&&",
"!",
"isLeadingZeroPossible",
"(",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
")",
"\n",
"}"
] | // Returns true if a number is from a region whose national significant
// number couldn't contain a leading zero, but has the italian_leading_zero
// field set to true. | [
"Returns",
"true",
"if",
"a",
"number",
"is",
"from",
"a",
"region",
"whose",
"national",
"significant",
"number",
"couldn",
"t",
"contain",
"a",
"leading",
"zero",
"but",
"has",
"the",
"italian_leading_zero",
"field",
"set",
"to",
"true",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1568-L1571 |
16 | ttacon/libphonenumber | phonenumberutil.go | GetNationalSignificantNumber | func GetNationalSignificantNumber(number *PhoneNumber) string {
// If leading zero(s) have been set, we prefix this now. Note this
// is not a national prefix.
nationalNumber := builder.NewBuilder(nil)
if number.GetItalianLeadingZero() {
zeros := make([]byte, number.GetNumberOfLeadingZeros())
for i := range zeros {
zeros[i] = '0'
}
nationalNumber.Write(zeros)
}
asStr := strconv.FormatUint(number.GetNationalNumber(), 10)
nationalNumber.WriteString(asStr)
return nationalNumber.String()
} | go | func GetNationalSignificantNumber(number *PhoneNumber) string {
// If leading zero(s) have been set, we prefix this now. Note this
// is not a national prefix.
nationalNumber := builder.NewBuilder(nil)
if number.GetItalianLeadingZero() {
zeros := make([]byte, number.GetNumberOfLeadingZeros())
for i := range zeros {
zeros[i] = '0'
}
nationalNumber.Write(zeros)
}
asStr := strconv.FormatUint(number.GetNationalNumber(), 10)
nationalNumber.WriteString(asStr)
return nationalNumber.String()
} | [
"func",
"GetNationalSignificantNumber",
"(",
"number",
"*",
"PhoneNumber",
")",
"string",
"{",
"// If leading zero(s) have been set, we prefix this now. Note this",
"// is not a national prefix.",
"nationalNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"if",
"number",
".",
"GetItalianLeadingZero",
"(",
")",
"{",
"zeros",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"number",
".",
"GetNumberOfLeadingZeros",
"(",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"zeros",
"{",
"zeros",
"[",
"i",
"]",
"=",
"'0'",
"\n",
"}",
"\n",
"nationalNumber",
".",
"Write",
"(",
"zeros",
")",
"\n",
"}",
"\n",
"asStr",
":=",
"strconv",
".",
"FormatUint",
"(",
"number",
".",
"GetNationalNumber",
"(",
")",
",",
"10",
")",
"\n",
"nationalNumber",
".",
"WriteString",
"(",
"asStr",
")",
"\n\n",
"return",
"nationalNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Gets the national significant number of the a phone number. Note a
// national significant number doesn't contain a national prefix or
// any formatting. | [
"Gets",
"the",
"national",
"significant",
"number",
"of",
"the",
"a",
"phone",
"number",
".",
"Note",
"a",
"national",
"significant",
"number",
"doesn",
"t",
"contain",
"a",
"national",
"prefix",
"or",
"any",
"formatting",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1718-L1733 |
17 | ttacon/libphonenumber | phonenumberutil.go | prefixNumberWithCountryCallingCode | func prefixNumberWithCountryCallingCode(
countryCallingCode int,
numberFormat PhoneNumberFormat,
formattedNumber *builder.Builder) {
// TODO(ttacon): add some sort of BulkWrite builder to builder.Builder
// also that name isn't too awesome...:)
newBuf := builder.NewBuilder(nil)
switch numberFormat {
case E164:
newBuf.WriteString(string(PLUS_SIGN))
newBuf.Write(strconv.AppendInt([]byte{}, int64(countryCallingCode), 10))
newBuf.Write(formattedNumber.Bytes())
case INTERNATIONAL:
newBuf.WriteString(string(PLUS_SIGN))
newBuf.Write(strconv.AppendInt([]byte{}, int64(countryCallingCode), 10))
newBuf.WriteString(" ")
newBuf.Write(formattedNumber.Bytes())
case RFC3966:
newBuf.WriteString(RFC3966_PREFIX)
newBuf.WriteString(string(PLUS_SIGN))
newBuf.Write(strconv.AppendInt([]byte{}, int64(countryCallingCode), 10))
newBuf.WriteString("-")
newBuf.Write(formattedNumber.Bytes())
case NATIONAL:
fallthrough
default:
newBuf.Write(formattedNumber.Bytes())
}
formattedNumber.ResetWith(newBuf.Bytes())
} | go | func prefixNumberWithCountryCallingCode(
countryCallingCode int,
numberFormat PhoneNumberFormat,
formattedNumber *builder.Builder) {
// TODO(ttacon): add some sort of BulkWrite builder to builder.Builder
// also that name isn't too awesome...:)
newBuf := builder.NewBuilder(nil)
switch numberFormat {
case E164:
newBuf.WriteString(string(PLUS_SIGN))
newBuf.Write(strconv.AppendInt([]byte{}, int64(countryCallingCode), 10))
newBuf.Write(formattedNumber.Bytes())
case INTERNATIONAL:
newBuf.WriteString(string(PLUS_SIGN))
newBuf.Write(strconv.AppendInt([]byte{}, int64(countryCallingCode), 10))
newBuf.WriteString(" ")
newBuf.Write(formattedNumber.Bytes())
case RFC3966:
newBuf.WriteString(RFC3966_PREFIX)
newBuf.WriteString(string(PLUS_SIGN))
newBuf.Write(strconv.AppendInt([]byte{}, int64(countryCallingCode), 10))
newBuf.WriteString("-")
newBuf.Write(formattedNumber.Bytes())
case NATIONAL:
fallthrough
default:
newBuf.Write(formattedNumber.Bytes())
}
formattedNumber.ResetWith(newBuf.Bytes())
} | [
"func",
"prefixNumberWithCountryCallingCode",
"(",
"countryCallingCode",
"int",
",",
"numberFormat",
"PhoneNumberFormat",
",",
"formattedNumber",
"*",
"builder",
".",
"Builder",
")",
"{",
"// TODO(ttacon): add some sort of BulkWrite builder to builder.Builder",
"// also that name isn't too awesome...:)",
"newBuf",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"switch",
"numberFormat",
"{",
"case",
"E164",
":",
"newBuf",
".",
"WriteString",
"(",
"string",
"(",
"PLUS_SIGN",
")",
")",
"\n",
"newBuf",
".",
"Write",
"(",
"strconv",
".",
"AppendInt",
"(",
"[",
"]",
"byte",
"{",
"}",
",",
"int64",
"(",
"countryCallingCode",
")",
",",
"10",
")",
")",
"\n",
"newBuf",
".",
"Write",
"(",
"formattedNumber",
".",
"Bytes",
"(",
")",
")",
"\n",
"case",
"INTERNATIONAL",
":",
"newBuf",
".",
"WriteString",
"(",
"string",
"(",
"PLUS_SIGN",
")",
")",
"\n",
"newBuf",
".",
"Write",
"(",
"strconv",
".",
"AppendInt",
"(",
"[",
"]",
"byte",
"{",
"}",
",",
"int64",
"(",
"countryCallingCode",
")",
",",
"10",
")",
")",
"\n",
"newBuf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"newBuf",
".",
"Write",
"(",
"formattedNumber",
".",
"Bytes",
"(",
")",
")",
"\n",
"case",
"RFC3966",
":",
"newBuf",
".",
"WriteString",
"(",
"RFC3966_PREFIX",
")",
"\n",
"newBuf",
".",
"WriteString",
"(",
"string",
"(",
"PLUS_SIGN",
")",
")",
"\n",
"newBuf",
".",
"Write",
"(",
"strconv",
".",
"AppendInt",
"(",
"[",
"]",
"byte",
"{",
"}",
",",
"int64",
"(",
"countryCallingCode",
")",
",",
"10",
")",
")",
"\n",
"newBuf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"newBuf",
".",
"Write",
"(",
"formattedNumber",
".",
"Bytes",
"(",
")",
")",
"\n",
"case",
"NATIONAL",
":",
"fallthrough",
"\n",
"default",
":",
"newBuf",
".",
"Write",
"(",
"formattedNumber",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"\n",
"formattedNumber",
".",
"ResetWith",
"(",
"newBuf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // A helper function that is used by format and formatByPattern. | [
"A",
"helper",
"function",
"that",
"is",
"used",
"by",
"format",
"and",
"formatByPattern",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1736-L1766 |
18 | ttacon/libphonenumber | phonenumberutil.go | formatNsn | func formatNsn(
number string, metadata *PhoneMetadata, numberFormat PhoneNumberFormat) string {
return formatNsnWithCarrier(number, metadata, numberFormat, "")
} | go | func formatNsn(
number string, metadata *PhoneMetadata, numberFormat PhoneNumberFormat) string {
return formatNsnWithCarrier(number, metadata, numberFormat, "")
} | [
"func",
"formatNsn",
"(",
"number",
"string",
",",
"metadata",
"*",
"PhoneMetadata",
",",
"numberFormat",
"PhoneNumberFormat",
")",
"string",
"{",
"return",
"formatNsnWithCarrier",
"(",
"number",
",",
"metadata",
",",
"numberFormat",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Simple wrapper of formatNsn for the common case of no carrier code. | [
"Simple",
"wrapper",
"of",
"formatNsn",
"for",
"the",
"common",
"case",
"of",
"no",
"carrier",
"code",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1769-L1772 |
19 | ttacon/libphonenumber | phonenumberutil.go | formatNsnUsingPattern | func formatNsnUsingPattern(
nationalNumber string,
formattingPattern *NumberFormat,
numberFormat PhoneNumberFormat) string {
return formatNsnUsingPatternWithCarrier(
nationalNumber, formattingPattern, numberFormat, "")
} | go | func formatNsnUsingPattern(
nationalNumber string,
formattingPattern *NumberFormat,
numberFormat PhoneNumberFormat) string {
return formatNsnUsingPatternWithCarrier(
nationalNumber, formattingPattern, numberFormat, "")
} | [
"func",
"formatNsnUsingPattern",
"(",
"nationalNumber",
"string",
",",
"formattingPattern",
"*",
"NumberFormat",
",",
"numberFormat",
"PhoneNumberFormat",
")",
"string",
"{",
"return",
"formatNsnUsingPatternWithCarrier",
"(",
"nationalNumber",
",",
"formattingPattern",
",",
"numberFormat",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code. | [
"Simple",
"wrapper",
"of",
"formatNsnUsingPattern",
"for",
"the",
"common",
"case",
"of",
"no",
"carrier",
"code",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1844-L1850 |
20 | ttacon/libphonenumber | phonenumberutil.go | formatNsnUsingPatternWithCarrier | func formatNsnUsingPatternWithCarrier(
nationalNumber string,
formattingPattern *NumberFormat,
numberFormat PhoneNumberFormat,
carrierCode string) string {
numberFormatRule := formattingPattern.GetFormat()
m, ok := readFromRegexCache(formattingPattern.GetPattern())
if !ok {
pat := formattingPattern.GetPattern()
m = regexp.MustCompile(pat)
writeToRegexCache(pat, m)
}
formattedNationalNumber := ""
if numberFormat == NATIONAL &&
len(carrierCode) > 0 &&
len(formattingPattern.GetDomesticCarrierCodeFormattingRule()) > 0 {
// Replace the $CC in the formatting rule with the desired carrier code.
carrierCodeFormattingRule := formattingPattern.GetDomesticCarrierCodeFormattingRule()
i := 1
carrierCodeFormattingRule =
CC_PATTERN.ReplaceAllStringFunc(carrierCodeFormattingRule,
func(s string) string {
if i > 0 {
i -= 1
return carrierCode
}
return s
})
// Now replace the $FG in the formatting rule with the first group
// and the carrier code combined in the appropriate way.
i = 1
numberFormatRule = FIRST_GROUP_PATTERN.ReplaceAllStringFunc(
numberFormatRule,
func(s string) string {
if i > 0 {
i -= 1
return carrierCodeFormattingRule
}
return s
})
formattedNationalNumber = m.ReplaceAllString(numberFormatRule, nationalNumber)
} else {
// Use the national prefix formatting rule instead.
nationalPrefixFormattingRule :=
formattingPattern.GetNationalPrefixFormattingRule()
if numberFormat == NATIONAL &&
len(nationalPrefixFormattingRule) > 0 {
i := 1
fgp := FIRST_GROUP_PATTERN.ReplaceAllStringFunc(numberFormatRule,
func(s string) string {
if i > 0 {
i -= 1
return nationalPrefixFormattingRule
}
return s
})
formattedNationalNumber = m.ReplaceAllString(nationalNumber, fgp)
} else {
formattedNationalNumber = m.ReplaceAllString(
nationalNumber,
numberFormatRule,
)
}
}
if numberFormat == RFC3966 {
// Strip any leading punctuation.
inds := SEPARATOR_PATTERN.FindStringIndex(formattedNationalNumber)
if len(inds) > 0 && inds[0] == 0 {
formattedNationalNumber = formattedNationalNumber[inds[1]:]
}
allStr := NOT_SEPARATOR_PATTERN.FindAllString(formattedNationalNumber, -1)
formattedNationalNumber = strings.Join(allStr, "-")
}
return formattedNationalNumber
} | go | func formatNsnUsingPatternWithCarrier(
nationalNumber string,
formattingPattern *NumberFormat,
numberFormat PhoneNumberFormat,
carrierCode string) string {
numberFormatRule := formattingPattern.GetFormat()
m, ok := readFromRegexCache(formattingPattern.GetPattern())
if !ok {
pat := formattingPattern.GetPattern()
m = regexp.MustCompile(pat)
writeToRegexCache(pat, m)
}
formattedNationalNumber := ""
if numberFormat == NATIONAL &&
len(carrierCode) > 0 &&
len(formattingPattern.GetDomesticCarrierCodeFormattingRule()) > 0 {
// Replace the $CC in the formatting rule with the desired carrier code.
carrierCodeFormattingRule := formattingPattern.GetDomesticCarrierCodeFormattingRule()
i := 1
carrierCodeFormattingRule =
CC_PATTERN.ReplaceAllStringFunc(carrierCodeFormattingRule,
func(s string) string {
if i > 0 {
i -= 1
return carrierCode
}
return s
})
// Now replace the $FG in the formatting rule with the first group
// and the carrier code combined in the appropriate way.
i = 1
numberFormatRule = FIRST_GROUP_PATTERN.ReplaceAllStringFunc(
numberFormatRule,
func(s string) string {
if i > 0 {
i -= 1
return carrierCodeFormattingRule
}
return s
})
formattedNationalNumber = m.ReplaceAllString(numberFormatRule, nationalNumber)
} else {
// Use the national prefix formatting rule instead.
nationalPrefixFormattingRule :=
formattingPattern.GetNationalPrefixFormattingRule()
if numberFormat == NATIONAL &&
len(nationalPrefixFormattingRule) > 0 {
i := 1
fgp := FIRST_GROUP_PATTERN.ReplaceAllStringFunc(numberFormatRule,
func(s string) string {
if i > 0 {
i -= 1
return nationalPrefixFormattingRule
}
return s
})
formattedNationalNumber = m.ReplaceAllString(nationalNumber, fgp)
} else {
formattedNationalNumber = m.ReplaceAllString(
nationalNumber,
numberFormatRule,
)
}
}
if numberFormat == RFC3966 {
// Strip any leading punctuation.
inds := SEPARATOR_PATTERN.FindStringIndex(formattedNationalNumber)
if len(inds) > 0 && inds[0] == 0 {
formattedNationalNumber = formattedNationalNumber[inds[1]:]
}
allStr := NOT_SEPARATOR_PATTERN.FindAllString(formattedNationalNumber, -1)
formattedNationalNumber = strings.Join(allStr, "-")
}
return formattedNationalNumber
} | [
"func",
"formatNsnUsingPatternWithCarrier",
"(",
"nationalNumber",
"string",
",",
"formattingPattern",
"*",
"NumberFormat",
",",
"numberFormat",
"PhoneNumberFormat",
",",
"carrierCode",
"string",
")",
"string",
"{",
"numberFormatRule",
":=",
"formattingPattern",
".",
"GetFormat",
"(",
")",
"\n",
"m",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"formattingPattern",
".",
"GetPattern",
"(",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"pat",
":=",
"formattingPattern",
".",
"GetPattern",
"(",
")",
"\n",
"m",
"=",
"regexp",
".",
"MustCompile",
"(",
"pat",
")",
"\n",
"writeToRegexCache",
"(",
"pat",
",",
"m",
")",
"\n",
"}",
"\n\n",
"formattedNationalNumber",
":=",
"\"",
"\"",
"\n",
"if",
"numberFormat",
"==",
"NATIONAL",
"&&",
"len",
"(",
"carrierCode",
")",
">",
"0",
"&&",
"len",
"(",
"formattingPattern",
".",
"GetDomesticCarrierCodeFormattingRule",
"(",
")",
")",
">",
"0",
"{",
"// Replace the $CC in the formatting rule with the desired carrier code.",
"carrierCodeFormattingRule",
":=",
"formattingPattern",
".",
"GetDomesticCarrierCodeFormattingRule",
"(",
")",
"\n",
"i",
":=",
"1",
"\n",
"carrierCodeFormattingRule",
"=",
"CC_PATTERN",
".",
"ReplaceAllStringFunc",
"(",
"carrierCodeFormattingRule",
",",
"func",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"i",
">",
"0",
"{",
"i",
"-=",
"1",
"\n",
"return",
"carrierCode",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}",
")",
"\n",
"// Now replace the $FG in the formatting rule with the first group",
"// and the carrier code combined in the appropriate way.",
"i",
"=",
"1",
"\n",
"numberFormatRule",
"=",
"FIRST_GROUP_PATTERN",
".",
"ReplaceAllStringFunc",
"(",
"numberFormatRule",
",",
"func",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"i",
">",
"0",
"{",
"i",
"-=",
"1",
"\n",
"return",
"carrierCodeFormattingRule",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}",
")",
"\n",
"formattedNationalNumber",
"=",
"m",
".",
"ReplaceAllString",
"(",
"numberFormatRule",
",",
"nationalNumber",
")",
"\n",
"}",
"else",
"{",
"// Use the national prefix formatting rule instead.",
"nationalPrefixFormattingRule",
":=",
"formattingPattern",
".",
"GetNationalPrefixFormattingRule",
"(",
")",
"\n",
"if",
"numberFormat",
"==",
"NATIONAL",
"&&",
"len",
"(",
"nationalPrefixFormattingRule",
")",
">",
"0",
"{",
"i",
":=",
"1",
"\n",
"fgp",
":=",
"FIRST_GROUP_PATTERN",
".",
"ReplaceAllStringFunc",
"(",
"numberFormatRule",
",",
"func",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"i",
">",
"0",
"{",
"i",
"-=",
"1",
"\n",
"return",
"nationalPrefixFormattingRule",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}",
")",
"\n",
"formattedNationalNumber",
"=",
"m",
".",
"ReplaceAllString",
"(",
"nationalNumber",
",",
"fgp",
")",
"\n",
"}",
"else",
"{",
"formattedNationalNumber",
"=",
"m",
".",
"ReplaceAllString",
"(",
"nationalNumber",
",",
"numberFormatRule",
",",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"numberFormat",
"==",
"RFC3966",
"{",
"// Strip any leading punctuation.",
"inds",
":=",
"SEPARATOR_PATTERN",
".",
"FindStringIndex",
"(",
"formattedNationalNumber",
")",
"\n",
"if",
"len",
"(",
"inds",
")",
">",
"0",
"&&",
"inds",
"[",
"0",
"]",
"==",
"0",
"{",
"formattedNationalNumber",
"=",
"formattedNationalNumber",
"[",
"inds",
"[",
"1",
"]",
":",
"]",
"\n",
"}",
"\n",
"allStr",
":=",
"NOT_SEPARATOR_PATTERN",
".",
"FindAllString",
"(",
"formattedNationalNumber",
",",
"-",
"1",
")",
"\n",
"formattedNationalNumber",
"=",
"strings",
".",
"Join",
"(",
"allStr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"formattedNationalNumber",
"\n",
"}"
] | // Note that carrierCode is optional - if null or an empty string, no
// carrier code replacement will take place. | [
"Note",
"that",
"carrierCode",
"is",
"optional",
"-",
"if",
"null",
"or",
"an",
"empty",
"string",
"no",
"carrier",
"code",
"replacement",
"will",
"take",
"place",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1854-L1930 |
21 | ttacon/libphonenumber | phonenumberutil.go | GetExampleNumberForType | func GetExampleNumberForType(regionCode string, typ PhoneNumberType) *PhoneNumber {
// Check the region code is valid.
if !isValidRegionCode(regionCode) {
return nil
}
//PhoneNumberDesc (pointer?)
var desc = getNumberDescByType(getMetadataForRegion(regionCode), typ)
exNum := desc.GetExampleNumber()
if len(exNum) > 0 {
num, err := Parse(exNum, regionCode)
if err != nil {
return nil
}
return num
}
return nil
} | go | func GetExampleNumberForType(regionCode string, typ PhoneNumberType) *PhoneNumber {
// Check the region code is valid.
if !isValidRegionCode(regionCode) {
return nil
}
//PhoneNumberDesc (pointer?)
var desc = getNumberDescByType(getMetadataForRegion(regionCode), typ)
exNum := desc.GetExampleNumber()
if len(exNum) > 0 {
num, err := Parse(exNum, regionCode)
if err != nil {
return nil
}
return num
}
return nil
} | [
"func",
"GetExampleNumberForType",
"(",
"regionCode",
"string",
",",
"typ",
"PhoneNumberType",
")",
"*",
"PhoneNumber",
"{",
"// Check the region code is valid.",
"if",
"!",
"isValidRegionCode",
"(",
"regionCode",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"//PhoneNumberDesc (pointer?)",
"var",
"desc",
"=",
"getNumberDescByType",
"(",
"getMetadataForRegion",
"(",
"regionCode",
")",
",",
"typ",
")",
"\n",
"exNum",
":=",
"desc",
".",
"GetExampleNumber",
"(",
")",
"\n",
"if",
"len",
"(",
"exNum",
")",
">",
"0",
"{",
"num",
",",
"err",
":=",
"Parse",
"(",
"exNum",
",",
"regionCode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"num",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Gets a valid number for the specified region and number type. | [
"Gets",
"a",
"valid",
"number",
"for",
"the",
"specified",
"region",
"and",
"number",
"type",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1938-L1954 |
22 | ttacon/libphonenumber | phonenumberutil.go | GetExampleNumberForNonGeoEntity | func GetExampleNumberForNonGeoEntity(countryCallingCode int) *PhoneNumber {
var metadata *PhoneMetadata = getMetadataForNonGeographicalRegion(countryCallingCode)
if metadata == nil {
return nil
}
var desc *PhoneNumberDesc = metadata.GetTollFree()
if countryCallingCode == 979 {
desc = metadata.GetPremiumRate()
}
exNum := desc.GetExampleNumber()
if len(exNum) > 0 {
num, err := Parse("+"+strconv.Itoa(countryCallingCode)+exNum, "ZZ")
if err != nil {
return nil
}
return num
}
return nil
} | go | func GetExampleNumberForNonGeoEntity(countryCallingCode int) *PhoneNumber {
var metadata *PhoneMetadata = getMetadataForNonGeographicalRegion(countryCallingCode)
if metadata == nil {
return nil
}
var desc *PhoneNumberDesc = metadata.GetTollFree()
if countryCallingCode == 979 {
desc = metadata.GetPremiumRate()
}
exNum := desc.GetExampleNumber()
if len(exNum) > 0 {
num, err := Parse("+"+strconv.Itoa(countryCallingCode)+exNum, "ZZ")
if err != nil {
return nil
}
return num
}
return nil
} | [
"func",
"GetExampleNumberForNonGeoEntity",
"(",
"countryCallingCode",
"int",
")",
"*",
"PhoneNumber",
"{",
"var",
"metadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForNonGeographicalRegion",
"(",
"countryCallingCode",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"desc",
"*",
"PhoneNumberDesc",
"=",
"metadata",
".",
"GetTollFree",
"(",
")",
"\n\n",
"if",
"countryCallingCode",
"==",
"979",
"{",
"desc",
"=",
"metadata",
".",
"GetPremiumRate",
"(",
")",
"\n",
"}",
"\n\n",
"exNum",
":=",
"desc",
".",
"GetExampleNumber",
"(",
")",
"\n",
"if",
"len",
"(",
"exNum",
")",
">",
"0",
"{",
"num",
",",
"err",
":=",
"Parse",
"(",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"countryCallingCode",
")",
"+",
"exNum",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"num",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Gets a valid number for the specified country calling code for a
// non-geographical entity. | [
"Gets",
"a",
"valid",
"number",
"for",
"the",
"specified",
"country",
"calling",
"code",
"for",
"a",
"non",
"-",
"geographical",
"entity",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1958-L1978 |
23 | ttacon/libphonenumber | phonenumberutil.go | maybeAppendFormattedExtension | func maybeAppendFormattedExtension(
number *PhoneNumber,
metadata *PhoneMetadata,
numberFormat PhoneNumberFormat,
formattedNumber *builder.Builder) {
extension := number.GetExtension()
if len(extension) == 0 {
return
}
prefExtn := metadata.GetPreferredExtnPrefix()
if numberFormat == RFC3966 {
formattedNumber.WriteString(RFC3966_EXTN_PREFIX)
} else if len(prefExtn) > 0 {
formattedNumber.WriteString(prefExtn)
} else {
formattedNumber.WriteString(DEFAULT_EXTN_PREFIX)
}
formattedNumber.WriteString(extension)
} | go | func maybeAppendFormattedExtension(
number *PhoneNumber,
metadata *PhoneMetadata,
numberFormat PhoneNumberFormat,
formattedNumber *builder.Builder) {
extension := number.GetExtension()
if len(extension) == 0 {
return
}
prefExtn := metadata.GetPreferredExtnPrefix()
if numberFormat == RFC3966 {
formattedNumber.WriteString(RFC3966_EXTN_PREFIX)
} else if len(prefExtn) > 0 {
formattedNumber.WriteString(prefExtn)
} else {
formattedNumber.WriteString(DEFAULT_EXTN_PREFIX)
}
formattedNumber.WriteString(extension)
} | [
"func",
"maybeAppendFormattedExtension",
"(",
"number",
"*",
"PhoneNumber",
",",
"metadata",
"*",
"PhoneMetadata",
",",
"numberFormat",
"PhoneNumberFormat",
",",
"formattedNumber",
"*",
"builder",
".",
"Builder",
")",
"{",
"extension",
":=",
"number",
".",
"GetExtension",
"(",
")",
"\n",
"if",
"len",
"(",
"extension",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"prefExtn",
":=",
"metadata",
".",
"GetPreferredExtnPrefix",
"(",
")",
"\n",
"if",
"numberFormat",
"==",
"RFC3966",
"{",
"formattedNumber",
".",
"WriteString",
"(",
"RFC3966_EXTN_PREFIX",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"prefExtn",
")",
">",
"0",
"{",
"formattedNumber",
".",
"WriteString",
"(",
"prefExtn",
")",
"\n",
"}",
"else",
"{",
"formattedNumber",
".",
"WriteString",
"(",
"DEFAULT_EXTN_PREFIX",
")",
"\n",
"}",
"\n",
"formattedNumber",
".",
"WriteString",
"(",
"extension",
")",
"\n",
"}"
] | // Appends the formatted extension of a phone number to formattedNumber,
// if the phone number had an extension specified. | [
"Appends",
"the",
"formatted",
"extension",
"of",
"a",
"phone",
"number",
"to",
"formattedNumber",
"if",
"the",
"phone",
"number",
"had",
"an",
"extension",
"specified",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1982-L2002 |
24 | ttacon/libphonenumber | phonenumberutil.go | GetNumberType | func GetNumberType(number *PhoneNumber) PhoneNumberType {
var regionCode string = GetRegionCodeForNumber(number)
var metadata *PhoneMetadata = getMetadataForRegionOrCallingCode(
int(number.GetCountryCode()), regionCode)
if metadata == nil {
return UNKNOWN
}
var nationalSignificantNumber = GetNationalSignificantNumber(number)
return getNumberTypeHelper(nationalSignificantNumber, metadata)
} | go | func GetNumberType(number *PhoneNumber) PhoneNumberType {
var regionCode string = GetRegionCodeForNumber(number)
var metadata *PhoneMetadata = getMetadataForRegionOrCallingCode(
int(number.GetCountryCode()), regionCode)
if metadata == nil {
return UNKNOWN
}
var nationalSignificantNumber = GetNationalSignificantNumber(number)
return getNumberTypeHelper(nationalSignificantNumber, metadata)
} | [
"func",
"GetNumberType",
"(",
"number",
"*",
"PhoneNumber",
")",
"PhoneNumberType",
"{",
"var",
"regionCode",
"string",
"=",
"GetRegionCodeForNumber",
"(",
"number",
")",
"\n",
"var",
"metadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegionOrCallingCode",
"(",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
",",
"regionCode",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"{",
"return",
"UNKNOWN",
"\n",
"}",
"\n",
"var",
"nationalSignificantNumber",
"=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"return",
"getNumberTypeHelper",
"(",
"nationalSignificantNumber",
",",
"metadata",
")",
"\n",
"}"
] | // Gets the type of a phone number. | [
"Gets",
"the",
"type",
"of",
"a",
"phone",
"number",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2037-L2046 |
25 | ttacon/libphonenumber | phonenumberutil.go | getMetadataForRegion | func getMetadataForRegion(regionCode string) *PhoneMetadata {
if !isValidRegionCode(regionCode) {
return nil
}
val, _ := readFromRegionToMetadataMap(regionCode)
return val
} | go | func getMetadataForRegion(regionCode string) *PhoneMetadata {
if !isValidRegionCode(regionCode) {
return nil
}
val, _ := readFromRegionToMetadataMap(regionCode)
return val
} | [
"func",
"getMetadataForRegion",
"(",
"regionCode",
"string",
")",
"*",
"PhoneMetadata",
"{",
"if",
"!",
"isValidRegionCode",
"(",
"regionCode",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"val",
",",
"_",
":=",
"readFromRegionToMetadataMap",
"(",
"regionCode",
")",
"\n",
"return",
"val",
"\n",
"}"
] | // Returns the metadata for the given region code or nil if the region
// code is invalid or unknown. | [
"Returns",
"the",
"metadata",
"for",
"the",
"given",
"region",
"code",
"or",
"nil",
"if",
"the",
"region",
"code",
"is",
"invalid",
"or",
"unknown",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2106-L2112 |
26 | ttacon/libphonenumber | phonenumberutil.go | IsValidNumber | func IsValidNumber(number *PhoneNumber) bool {
var regionCode string = GetRegionCodeForNumber(number)
return IsValidNumberForRegion(number, regionCode)
} | go | func IsValidNumber(number *PhoneNumber) bool {
var regionCode string = GetRegionCodeForNumber(number)
return IsValidNumberForRegion(number, regionCode)
} | [
"func",
"IsValidNumber",
"(",
"number",
"*",
"PhoneNumber",
")",
"bool",
"{",
"var",
"regionCode",
"string",
"=",
"GetRegionCodeForNumber",
"(",
"number",
")",
"\n",
"return",
"IsValidNumberForRegion",
"(",
"number",
",",
"regionCode",
")",
"\n",
"}"
] | // Tests whether a phone number matches a valid pattern. Note this doesn't
// verify the number is actually in use, which is impossible to tell by
// just looking at a number itself. | [
"Tests",
"whether",
"a",
"phone",
"number",
"matches",
"a",
"valid",
"pattern",
".",
"Note",
"this",
"doesn",
"t",
"verify",
"the",
"number",
"is",
"actually",
"in",
"use",
"which",
"is",
"impossible",
"to",
"tell",
"by",
"just",
"looking",
"at",
"a",
"number",
"itself",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2154-L2157 |
27 | ttacon/libphonenumber | phonenumberutil.go | GetRegionCodeForNumber | func GetRegionCodeForNumber(number *PhoneNumber) string {
var countryCode int = int(number.GetCountryCode())
var regions []string = CountryCodeToRegion[countryCode]
if len(regions) == 0 {
return ""
}
if len(regions) == 1 {
return regions[0]
}
return getRegionCodeForNumberFromRegionList(number, regions)
} | go | func GetRegionCodeForNumber(number *PhoneNumber) string {
var countryCode int = int(number.GetCountryCode())
var regions []string = CountryCodeToRegion[countryCode]
if len(regions) == 0 {
return ""
}
if len(regions) == 1 {
return regions[0]
}
return getRegionCodeForNumberFromRegionList(number, regions)
} | [
"func",
"GetRegionCodeForNumber",
"(",
"number",
"*",
"PhoneNumber",
")",
"string",
"{",
"var",
"countryCode",
"int",
"=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"var",
"regions",
"[",
"]",
"string",
"=",
"CountryCodeToRegion",
"[",
"countryCode",
"]",
"\n",
"if",
"len",
"(",
"regions",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"len",
"(",
"regions",
")",
"==",
"1",
"{",
"return",
"regions",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"getRegionCodeForNumberFromRegionList",
"(",
"number",
",",
"regions",
")",
"\n",
"}"
] | // Returns the region where a phone number is from. This could be used for
// geocoding at the region level. | [
"Returns",
"the",
"region",
"where",
"a",
"phone",
"number",
"is",
"from",
".",
"This",
"could",
"be",
"used",
"for",
"geocoding",
"at",
"the",
"region",
"level",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2198-L2208 |
28 | ttacon/libphonenumber | phonenumberutil.go | getCountryCodeForValidRegion | func getCountryCodeForValidRegion(regionCode string) int {
var metadata *PhoneMetadata = getMetadataForRegion(regionCode)
return int(metadata.GetCountryCode())
} | go | func getCountryCodeForValidRegion(regionCode string) int {
var metadata *PhoneMetadata = getMetadataForRegion(regionCode)
return int(metadata.GetCountryCode())
} | [
"func",
"getCountryCodeForValidRegion",
"(",
"regionCode",
"string",
")",
"int",
"{",
"var",
"metadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegion",
"(",
"regionCode",
")",
"\n",
"return",
"int",
"(",
"metadata",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"}"
] | // Returns the country calling code for a specific region. For example,
// this would be 1 for the United States, and 64 for New Zealand. Assumes
// the region is already valid. | [
"Returns",
"the",
"country",
"calling",
"code",
"for",
"a",
"specific",
"region",
".",
"For",
"example",
"this",
"would",
"be",
"1",
"for",
"the",
"United",
"States",
"and",
"64",
"for",
"New",
"Zealand",
".",
"Assumes",
"the",
"region",
"is",
"already",
"valid",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2274-L2277 |
29 | ttacon/libphonenumber | phonenumberutil.go | isLeadingZeroPossible | func isLeadingZeroPossible(countryCallingCode int) bool {
var mainMetadataForCallingCode *PhoneMetadata = getMetadataForRegionOrCallingCode(
countryCallingCode,
GetRegionCodeForCountryCode(countryCallingCode),
)
return mainMetadataForCallingCode.GetLeadingZeroPossible()
} | go | func isLeadingZeroPossible(countryCallingCode int) bool {
var mainMetadataForCallingCode *PhoneMetadata = getMetadataForRegionOrCallingCode(
countryCallingCode,
GetRegionCodeForCountryCode(countryCallingCode),
)
return mainMetadataForCallingCode.GetLeadingZeroPossible()
} | [
"func",
"isLeadingZeroPossible",
"(",
"countryCallingCode",
"int",
")",
"bool",
"{",
"var",
"mainMetadataForCallingCode",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCallingCode",
",",
"GetRegionCodeForCountryCode",
"(",
"countryCallingCode",
")",
",",
")",
"\n",
"return",
"mainMetadataForCallingCode",
".",
"GetLeadingZeroPossible",
"(",
")",
"\n",
"}"
] | // Checks whether the country calling code is from a region whose national
// significant number could contain a leading zero. An example of such a
// region is Italy. Returns false if no metadata for the country is found. | [
"Checks",
"whether",
"the",
"country",
"calling",
"code",
"is",
"from",
"a",
"region",
"whose",
"national",
"significant",
"number",
"could",
"contain",
"a",
"leading",
"zero",
".",
"An",
"example",
"of",
"such",
"a",
"region",
"is",
"Italy",
".",
"Returns",
"false",
"if",
"no",
"metadata",
"for",
"the",
"country",
"is",
"found",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2317-L2323 |
30 | ttacon/libphonenumber | phonenumberutil.go | isShorterThanPossibleNormalNumber | func isShorterThanPossibleNormalNumber(
regionMetadata *PhoneMetadata,
number string) bool {
pat, ok := readFromRegexCache(regionMetadata.GetGeneralDesc().GetNationalNumberPattern())
if !ok {
patP := regionMetadata.GetGeneralDesc().GetNationalNumberPattern()
pat = regexp.MustCompile(patP)
writeToRegexCache(patP, pat)
}
return testNumberLengthAgainstPattern(pat, number) == TOO_SHORT
} | go | func isShorterThanPossibleNormalNumber(
regionMetadata *PhoneMetadata,
number string) bool {
pat, ok := readFromRegexCache(regionMetadata.GetGeneralDesc().GetNationalNumberPattern())
if !ok {
patP := regionMetadata.GetGeneralDesc().GetNationalNumberPattern()
pat = regexp.MustCompile(patP)
writeToRegexCache(patP, pat)
}
return testNumberLengthAgainstPattern(pat, number) == TOO_SHORT
} | [
"func",
"isShorterThanPossibleNormalNumber",
"(",
"regionMetadata",
"*",
"PhoneMetadata",
",",
"number",
"string",
")",
"bool",
"{",
"pat",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"regionMetadata",
".",
"GetGeneralDesc",
"(",
")",
".",
"GetNationalNumberPattern",
"(",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"patP",
":=",
"regionMetadata",
".",
"GetGeneralDesc",
"(",
")",
".",
"GetNationalNumberPattern",
"(",
")",
"\n",
"pat",
"=",
"regexp",
".",
"MustCompile",
"(",
"patP",
")",
"\n",
"writeToRegexCache",
"(",
"patP",
",",
"pat",
")",
"\n",
"}",
"\n",
"return",
"testNumberLengthAgainstPattern",
"(",
"pat",
",",
"number",
")",
"==",
"TOO_SHORT",
"\n",
"}"
] | // Helper method to check whether a number is too short to be a regular
// length phone number in a region. | [
"Helper",
"method",
"to",
"check",
"whether",
"a",
"number",
"is",
"too",
"short",
"to",
"be",
"a",
"regular",
"length",
"phone",
"number",
"in",
"a",
"region",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2370-L2381 |
31 | ttacon/libphonenumber | phonenumberutil.go | TruncateTooLongNumber | func TruncateTooLongNumber(number *PhoneNumber) bool {
if IsValidNumber(number) {
return true
}
var numberCopy *PhoneNumber
proto.Merge(numberCopy, number)
nationalNumber := number.GetNationalNumber()
nationalNumber /= 10
numberCopy.NationalNumber = proto.Uint64(nationalNumber)
if IsPossibleNumberWithReason(numberCopy) == TOO_SHORT || nationalNumber == 0 {
return false
}
for !IsValidNumber(numberCopy) {
nationalNumber /= 10
numberCopy.NationalNumber = proto.Uint64(nationalNumber)
if IsPossibleNumberWithReason(numberCopy) == TOO_SHORT ||
nationalNumber == 0 {
return false
}
}
number.NationalNumber = proto.Uint64(nationalNumber)
return true
} | go | func TruncateTooLongNumber(number *PhoneNumber) bool {
if IsValidNumber(number) {
return true
}
var numberCopy *PhoneNumber
proto.Merge(numberCopy, number)
nationalNumber := number.GetNationalNumber()
nationalNumber /= 10
numberCopy.NationalNumber = proto.Uint64(nationalNumber)
if IsPossibleNumberWithReason(numberCopy) == TOO_SHORT || nationalNumber == 0 {
return false
}
for !IsValidNumber(numberCopy) {
nationalNumber /= 10
numberCopy.NationalNumber = proto.Uint64(nationalNumber)
if IsPossibleNumberWithReason(numberCopy) == TOO_SHORT ||
nationalNumber == 0 {
return false
}
}
number.NationalNumber = proto.Uint64(nationalNumber)
return true
} | [
"func",
"TruncateTooLongNumber",
"(",
"number",
"*",
"PhoneNumber",
")",
"bool",
"{",
"if",
"IsValidNumber",
"(",
"number",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"var",
"numberCopy",
"*",
"PhoneNumber",
"\n",
"proto",
".",
"Merge",
"(",
"numberCopy",
",",
"number",
")",
"\n",
"nationalNumber",
":=",
"number",
".",
"GetNationalNumber",
"(",
")",
"\n",
"nationalNumber",
"/=",
"10",
"\n",
"numberCopy",
".",
"NationalNumber",
"=",
"proto",
".",
"Uint64",
"(",
"nationalNumber",
")",
"\n",
"if",
"IsPossibleNumberWithReason",
"(",
"numberCopy",
")",
"==",
"TOO_SHORT",
"||",
"nationalNumber",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"!",
"IsValidNumber",
"(",
"numberCopy",
")",
"{",
"nationalNumber",
"/=",
"10",
"\n",
"numberCopy",
".",
"NationalNumber",
"=",
"proto",
".",
"Uint64",
"(",
"nationalNumber",
")",
"\n",
"if",
"IsPossibleNumberWithReason",
"(",
"numberCopy",
")",
"==",
"TOO_SHORT",
"||",
"nationalNumber",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"number",
".",
"NationalNumber",
"=",
"proto",
".",
"Uint64",
"(",
"nationalNumber",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // Attempts to extract a valid number from a phone number that is too long
// to be valid, and resets the PhoneNumber object passed in to that valid
// version. If no valid number could be extracted, the PhoneNumber object
// passed in will not be modified. | [
"Attempts",
"to",
"extract",
"a",
"valid",
"number",
"from",
"a",
"phone",
"number",
"that",
"is",
"too",
"long",
"to",
"be",
"valid",
"and",
"resets",
"the",
"PhoneNumber",
"object",
"passed",
"in",
"to",
"that",
"valid",
"version",
".",
"If",
"no",
"valid",
"number",
"could",
"be",
"extracted",
"the",
"PhoneNumber",
"object",
"passed",
"in",
"will",
"not",
"be",
"modified",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2457-L2480 |
32 | ttacon/libphonenumber | phonenumberutil.go | parsePrefixAsIdd | func parsePrefixAsIdd(iddPattern *regexp.Regexp, number *builder.Builder) bool {
numStr := number.String()
ind := iddPattern.FindStringIndex(numStr)
if len(ind) == 0 || ind[0] != 0 {
return false
}
matchEnd := ind[1] // ind is a two element slice
// Only strip this if the first digit after the match is not
// a 0, since country calling codes cannot begin with 0.
find := CAPTURING_DIGIT_PATTERN.FindAllString(numStr[matchEnd:], -1)
if len(find) > 0 {
if NormalizeDigitsOnly(find[0]) == "0" {
return false
}
}
numBytes := []byte(numStr)
number.ResetWith(numBytes[matchEnd:])
return true
} | go | func parsePrefixAsIdd(iddPattern *regexp.Regexp, number *builder.Builder) bool {
numStr := number.String()
ind := iddPattern.FindStringIndex(numStr)
if len(ind) == 0 || ind[0] != 0 {
return false
}
matchEnd := ind[1] // ind is a two element slice
// Only strip this if the first digit after the match is not
// a 0, since country calling codes cannot begin with 0.
find := CAPTURING_DIGIT_PATTERN.FindAllString(numStr[matchEnd:], -1)
if len(find) > 0 {
if NormalizeDigitsOnly(find[0]) == "0" {
return false
}
}
numBytes := []byte(numStr)
number.ResetWith(numBytes[matchEnd:])
return true
} | [
"func",
"parsePrefixAsIdd",
"(",
"iddPattern",
"*",
"regexp",
".",
"Regexp",
",",
"number",
"*",
"builder",
".",
"Builder",
")",
"bool",
"{",
"numStr",
":=",
"number",
".",
"String",
"(",
")",
"\n",
"ind",
":=",
"iddPattern",
".",
"FindStringIndex",
"(",
"numStr",
")",
"\n",
"if",
"len",
"(",
"ind",
")",
"==",
"0",
"||",
"ind",
"[",
"0",
"]",
"!=",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"matchEnd",
":=",
"ind",
"[",
"1",
"]",
"// ind is a two element slice",
"\n",
"// Only strip this if the first digit after the match is not",
"// a 0, since country calling codes cannot begin with 0.",
"find",
":=",
"CAPTURING_DIGIT_PATTERN",
".",
"FindAllString",
"(",
"numStr",
"[",
"matchEnd",
":",
"]",
",",
"-",
"1",
")",
"\n",
"if",
"len",
"(",
"find",
")",
">",
"0",
"{",
"if",
"NormalizeDigitsOnly",
"(",
"find",
"[",
"0",
"]",
")",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"numBytes",
":=",
"[",
"]",
"byte",
"(",
"numStr",
")",
"\n",
"number",
".",
"ResetWith",
"(",
"numBytes",
"[",
"matchEnd",
":",
"]",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // Strips the IDD from the start of the number if present. Helper function
// used by maybeStripInternationalPrefixAndNormalize. | [
"Strips",
"the",
"IDD",
"from",
"the",
"start",
"of",
"the",
"number",
"if",
"present",
".",
"Helper",
"function",
"used",
"by",
"maybeStripInternationalPrefixAndNormalize",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2625-L2644 |
33 | ttacon/libphonenumber | phonenumberutil.go | checkRegionForParsing | func checkRegionForParsing(numberToParse, defaultRegion string) bool {
if !isValidRegionCode(defaultRegion) {
// If the number is null or empty, we can't infer the region.
if len(numberToParse) == 0 ||
!PLUS_CHARS_PATTERN.MatchString(numberToParse) {
return false
}
}
return true
} | go | func checkRegionForParsing(numberToParse, defaultRegion string) bool {
if !isValidRegionCode(defaultRegion) {
// If the number is null or empty, we can't infer the region.
if len(numberToParse) == 0 ||
!PLUS_CHARS_PATTERN.MatchString(numberToParse) {
return false
}
}
return true
} | [
"func",
"checkRegionForParsing",
"(",
"numberToParse",
",",
"defaultRegion",
"string",
")",
"bool",
"{",
"if",
"!",
"isValidRegionCode",
"(",
"defaultRegion",
")",
"{",
"// If the number is null or empty, we can't infer the region.",
"if",
"len",
"(",
"numberToParse",
")",
"==",
"0",
"||",
"!",
"PLUS_CHARS_PATTERN",
".",
"MatchString",
"(",
"numberToParse",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Checks to see that the region code used is valid, or if it is not valid,
// that the number to parse starts with a + symbol so that we can attempt
// to infer the region from the number. Returns false if it cannot use the
// region provided and the region cannot be inferred. | [
"Checks",
"to",
"see",
"that",
"the",
"region",
"code",
"used",
"is",
"valid",
"or",
"if",
"it",
"is",
"not",
"valid",
"that",
"the",
"number",
"to",
"parse",
"starts",
"with",
"a",
"+",
"symbol",
"so",
"that",
"we",
"can",
"attempt",
"to",
"infer",
"the",
"region",
"from",
"the",
"number",
".",
"Returns",
"false",
"if",
"it",
"cannot",
"use",
"the",
"region",
"provided",
"and",
"the",
"region",
"cannot",
"be",
"inferred",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2786-L2795 |
34 | ttacon/libphonenumber | phonenumberutil.go | buildNationalNumberForParsing | func buildNationalNumberForParsing(
numberToParse string,
nationalNumber *builder.Builder) {
indexOfPhoneContext := strings.Index(numberToParse, RFC3966_PHONE_CONTEXT)
if indexOfPhoneContext > 0 {
phoneContextStart := indexOfPhoneContext + len(RFC3966_PHONE_CONTEXT)
// If the phone context contains a phone number prefix, we need
// to capture it, whereas domains will be ignored.
if numberToParse[phoneContextStart] == PLUS_SIGN {
// Additional parameters might follow the phone context. If so,
// we will remove them here because the parameters after phone
// context are not important for parsing the phone number.
phoneContextEnd := strings.Index(numberToParse[phoneContextStart:], ";")
if phoneContextEnd > 0 {
nationalNumber.WriteString(
numberToParse[phoneContextStart:phoneContextEnd])
} else {
nationalNumber.WriteString(numberToParse[phoneContextStart:])
}
}
// Now append everything between the "tel:" prefix and the
// phone-context. This should include the national number, an
// optional extension or isdn-subaddress component. Note we also
// handle the case when "tel:" is missing, as we have seen in some
// of the phone number inputs. In that case, we append everything
// from the beginning.
indexOfRfc3966Prefix := strings.Index(numberToParse, RFC3966_PREFIX)
indexOfNationalNumber := 0
if indexOfRfc3966Prefix >= 0 {
indexOfNationalNumber = indexOfRfc3966Prefix + len(RFC3966_PREFIX)
}
nationalNumber.WriteString(
numberToParse[indexOfNationalNumber:indexOfPhoneContext])
} else {
// Extract a possible number from the string passed in (this
// strips leading characters that could not be the start of a
// phone number.)
nationalNumber.WriteString(extractPossibleNumber(numberToParse))
}
// Delete the isdn-subaddress and everything after it if it is present.
// Note extension won't appear at the same time with isdn-subaddress
// according to paragraph 5.3 of the RFC3966 spec,
indexOfIsdn := strings.Index(nationalNumber.String(), RFC3966_ISDN_SUBADDRESS)
if indexOfIsdn > 0 {
natNumBytes := nationalNumber.Bytes()
nationalNumber.ResetWith(natNumBytes[:indexOfIsdn])
}
// If both phone context and isdn-subaddress are absent but other
// parameters are present, the parameters are left in nationalNumber.
// This is because we are concerned about deleting content from a
// potential number string when there is no strong evidence that the
// number is actually written in RFC3966.
} | go | func buildNationalNumberForParsing(
numberToParse string,
nationalNumber *builder.Builder) {
indexOfPhoneContext := strings.Index(numberToParse, RFC3966_PHONE_CONTEXT)
if indexOfPhoneContext > 0 {
phoneContextStart := indexOfPhoneContext + len(RFC3966_PHONE_CONTEXT)
// If the phone context contains a phone number prefix, we need
// to capture it, whereas domains will be ignored.
if numberToParse[phoneContextStart] == PLUS_SIGN {
// Additional parameters might follow the phone context. If so,
// we will remove them here because the parameters after phone
// context are not important for parsing the phone number.
phoneContextEnd := strings.Index(numberToParse[phoneContextStart:], ";")
if phoneContextEnd > 0 {
nationalNumber.WriteString(
numberToParse[phoneContextStart:phoneContextEnd])
} else {
nationalNumber.WriteString(numberToParse[phoneContextStart:])
}
}
// Now append everything between the "tel:" prefix and the
// phone-context. This should include the national number, an
// optional extension or isdn-subaddress component. Note we also
// handle the case when "tel:" is missing, as we have seen in some
// of the phone number inputs. In that case, we append everything
// from the beginning.
indexOfRfc3966Prefix := strings.Index(numberToParse, RFC3966_PREFIX)
indexOfNationalNumber := 0
if indexOfRfc3966Prefix >= 0 {
indexOfNationalNumber = indexOfRfc3966Prefix + len(RFC3966_PREFIX)
}
nationalNumber.WriteString(
numberToParse[indexOfNationalNumber:indexOfPhoneContext])
} else {
// Extract a possible number from the string passed in (this
// strips leading characters that could not be the start of a
// phone number.)
nationalNumber.WriteString(extractPossibleNumber(numberToParse))
}
// Delete the isdn-subaddress and everything after it if it is present.
// Note extension won't appear at the same time with isdn-subaddress
// according to paragraph 5.3 of the RFC3966 spec,
indexOfIsdn := strings.Index(nationalNumber.String(), RFC3966_ISDN_SUBADDRESS)
if indexOfIsdn > 0 {
natNumBytes := nationalNumber.Bytes()
nationalNumber.ResetWith(natNumBytes[:indexOfIsdn])
}
// If both phone context and isdn-subaddress are absent but other
// parameters are present, the parameters are left in nationalNumber.
// This is because we are concerned about deleting content from a
// potential number string when there is no strong evidence that the
// number is actually written in RFC3966.
} | [
"func",
"buildNationalNumberForParsing",
"(",
"numberToParse",
"string",
",",
"nationalNumber",
"*",
"builder",
".",
"Builder",
")",
"{",
"indexOfPhoneContext",
":=",
"strings",
".",
"Index",
"(",
"numberToParse",
",",
"RFC3966_PHONE_CONTEXT",
")",
"\n",
"if",
"indexOfPhoneContext",
">",
"0",
"{",
"phoneContextStart",
":=",
"indexOfPhoneContext",
"+",
"len",
"(",
"RFC3966_PHONE_CONTEXT",
")",
"\n",
"// If the phone context contains a phone number prefix, we need",
"// to capture it, whereas domains will be ignored.",
"if",
"numberToParse",
"[",
"phoneContextStart",
"]",
"==",
"PLUS_SIGN",
"{",
"// Additional parameters might follow the phone context. If so,",
"// we will remove them here because the parameters after phone",
"// context are not important for parsing the phone number.",
"phoneContextEnd",
":=",
"strings",
".",
"Index",
"(",
"numberToParse",
"[",
"phoneContextStart",
":",
"]",
",",
"\"",
"\"",
")",
"\n",
"if",
"phoneContextEnd",
">",
"0",
"{",
"nationalNumber",
".",
"WriteString",
"(",
"numberToParse",
"[",
"phoneContextStart",
":",
"phoneContextEnd",
"]",
")",
"\n",
"}",
"else",
"{",
"nationalNumber",
".",
"WriteString",
"(",
"numberToParse",
"[",
"phoneContextStart",
":",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Now append everything between the \"tel:\" prefix and the",
"// phone-context. This should include the national number, an",
"// optional extension or isdn-subaddress component. Note we also",
"// handle the case when \"tel:\" is missing, as we have seen in some",
"// of the phone number inputs. In that case, we append everything",
"// from the beginning.",
"indexOfRfc3966Prefix",
":=",
"strings",
".",
"Index",
"(",
"numberToParse",
",",
"RFC3966_PREFIX",
")",
"\n",
"indexOfNationalNumber",
":=",
"0",
"\n",
"if",
"indexOfRfc3966Prefix",
">=",
"0",
"{",
"indexOfNationalNumber",
"=",
"indexOfRfc3966Prefix",
"+",
"len",
"(",
"RFC3966_PREFIX",
")",
"\n",
"}",
"\n",
"nationalNumber",
".",
"WriteString",
"(",
"numberToParse",
"[",
"indexOfNationalNumber",
":",
"indexOfPhoneContext",
"]",
")",
"\n",
"}",
"else",
"{",
"// Extract a possible number from the string passed in (this",
"// strips leading characters that could not be the start of a",
"// phone number.)",
"nationalNumber",
".",
"WriteString",
"(",
"extractPossibleNumber",
"(",
"numberToParse",
")",
")",
"\n",
"}",
"\n\n",
"// Delete the isdn-subaddress and everything after it if it is present.",
"// Note extension won't appear at the same time with isdn-subaddress",
"// according to paragraph 5.3 of the RFC3966 spec,",
"indexOfIsdn",
":=",
"strings",
".",
"Index",
"(",
"nationalNumber",
".",
"String",
"(",
")",
",",
"RFC3966_ISDN_SUBADDRESS",
")",
"\n",
"if",
"indexOfIsdn",
">",
"0",
"{",
"natNumBytes",
":=",
"nationalNumber",
".",
"Bytes",
"(",
")",
"\n",
"nationalNumber",
".",
"ResetWith",
"(",
"natNumBytes",
"[",
":",
"indexOfIsdn",
"]",
")",
"\n",
"}",
"\n",
"// If both phone context and isdn-subaddress are absent but other",
"// parameters are present, the parameters are left in nationalNumber.",
"// This is because we are concerned about deleting content from a",
"// potential number string when there is no strong evidence that the",
"// number is actually written in RFC3966.",
"}"
] | // Converts numberToParse to a form that we can parse and write it to
// nationalNumber if it is written in RFC3966; otherwise extract a possible
// number out of it and write to nationalNumber. | [
"Converts",
"numberToParse",
"to",
"a",
"form",
"that",
"we",
"can",
"parse",
"and",
"write",
"it",
"to",
"nationalNumber",
"if",
"it",
"is",
"written",
"in",
"RFC3966",
";",
"otherwise",
"extract",
"a",
"possible",
"number",
"out",
"of",
"it",
"and",
"write",
"to",
"nationalNumber",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3009-L3063 |
35 | ttacon/libphonenumber | phonenumberutil.go | isNumberMatchWithNumbers | func isNumberMatchWithNumbers(firstNumberIn, secondNumberIn *PhoneNumber) MatchType {
// Make copies of the phone number so that the numbers passed in are not edited.
var firstNumber, secondNumber *PhoneNumber
firstNumber = &PhoneNumber{}
secondNumber = &PhoneNumber{}
proto.Merge(firstNumber, firstNumberIn)
proto.Merge(secondNumber, secondNumberIn)
// First clear raw_input, country_code_source and
// preferred_domestic_carrier_code fields and any empty-string
// extensions so that we can use the proto-buffer equality method.
firstNumber.RawInput = nil
firstNumber.CountryCodeSource = nil
firstNumber.PreferredDomesticCarrierCode = nil
secondNumber.RawInput = nil
secondNumber.CountryCodeSource = nil
secondNumber.PreferredDomesticCarrierCode = nil
firstNumExt := firstNumber.GetExtension()
secondNumExt := secondNumber.GetExtension()
// NOTE(ttacon): don't think we need this in go land...
if len(firstNumExt) == 0 {
firstNumber.Extension = nil
}
if len(secondNumExt) == 0 {
secondNumber.Extension = nil
}
// Early exit if both had extensions and these are different.
if len(firstNumExt) > 0 && len(secondNumExt) > 0 &&
firstNumExt != secondNumExt {
return NO_MATCH
}
var (
firstNumberCountryCode = firstNumber.GetCountryCode()
secondNumberCountryCode = secondNumber.GetCountryCode()
)
// Both had country_code specified.
if firstNumberCountryCode != 0 && secondNumberCountryCode != 0 {
// TODO(ttacon): remove when make gen-equals
if reflect.DeepEqual(firstNumber, secondNumber) {
return EXACT_MATCH
} else if firstNumberCountryCode == secondNumberCountryCode &&
isNationalNumberSuffixOfTheOther(firstNumber, secondNumber) {
// A SHORT_NSN_MATCH occurs if there is a difference because of
// the presence or absence of an 'Italian leading zero', the
// presence or absence of an extension, or one NSN being a
// shorter variant of the other.
return SHORT_NSN_MATCH
}
// This is not a match.
return NO_MATCH
}
// Checks cases where one or both country_code fields were not
// specified. To make equality checks easier, we first set the
// country_code fields to be equal.
firstNumber.CountryCode = proto.Int(int(secondNumberCountryCode))
// If all else was the same, then this is an NSN_MATCH.
// TODO(ttacon): remove when make gen-equals
if reflect.DeepEqual(firstNumber, secondNumber) {
return NSN_MATCH
}
if isNationalNumberSuffixOfTheOther(firstNumber, secondNumber) {
return SHORT_NSN_MATCH
}
return NO_MATCH
} | go | func isNumberMatchWithNumbers(firstNumberIn, secondNumberIn *PhoneNumber) MatchType {
// Make copies of the phone number so that the numbers passed in are not edited.
var firstNumber, secondNumber *PhoneNumber
firstNumber = &PhoneNumber{}
secondNumber = &PhoneNumber{}
proto.Merge(firstNumber, firstNumberIn)
proto.Merge(secondNumber, secondNumberIn)
// First clear raw_input, country_code_source and
// preferred_domestic_carrier_code fields and any empty-string
// extensions so that we can use the proto-buffer equality method.
firstNumber.RawInput = nil
firstNumber.CountryCodeSource = nil
firstNumber.PreferredDomesticCarrierCode = nil
secondNumber.RawInput = nil
secondNumber.CountryCodeSource = nil
secondNumber.PreferredDomesticCarrierCode = nil
firstNumExt := firstNumber.GetExtension()
secondNumExt := secondNumber.GetExtension()
// NOTE(ttacon): don't think we need this in go land...
if len(firstNumExt) == 0 {
firstNumber.Extension = nil
}
if len(secondNumExt) == 0 {
secondNumber.Extension = nil
}
// Early exit if both had extensions and these are different.
if len(firstNumExt) > 0 && len(secondNumExt) > 0 &&
firstNumExt != secondNumExt {
return NO_MATCH
}
var (
firstNumberCountryCode = firstNumber.GetCountryCode()
secondNumberCountryCode = secondNumber.GetCountryCode()
)
// Both had country_code specified.
if firstNumberCountryCode != 0 && secondNumberCountryCode != 0 {
// TODO(ttacon): remove when make gen-equals
if reflect.DeepEqual(firstNumber, secondNumber) {
return EXACT_MATCH
} else if firstNumberCountryCode == secondNumberCountryCode &&
isNationalNumberSuffixOfTheOther(firstNumber, secondNumber) {
// A SHORT_NSN_MATCH occurs if there is a difference because of
// the presence or absence of an 'Italian leading zero', the
// presence or absence of an extension, or one NSN being a
// shorter variant of the other.
return SHORT_NSN_MATCH
}
// This is not a match.
return NO_MATCH
}
// Checks cases where one or both country_code fields were not
// specified. To make equality checks easier, we first set the
// country_code fields to be equal.
firstNumber.CountryCode = proto.Int(int(secondNumberCountryCode))
// If all else was the same, then this is an NSN_MATCH.
// TODO(ttacon): remove when make gen-equals
if reflect.DeepEqual(firstNumber, secondNumber) {
return NSN_MATCH
}
if isNationalNumberSuffixOfTheOther(firstNumber, secondNumber) {
return SHORT_NSN_MATCH
}
return NO_MATCH
} | [
"func",
"isNumberMatchWithNumbers",
"(",
"firstNumberIn",
",",
"secondNumberIn",
"*",
"PhoneNumber",
")",
"MatchType",
"{",
"// Make copies of the phone number so that the numbers passed in are not edited.",
"var",
"firstNumber",
",",
"secondNumber",
"*",
"PhoneNumber",
"\n",
"firstNumber",
"=",
"&",
"PhoneNumber",
"{",
"}",
"\n",
"secondNumber",
"=",
"&",
"PhoneNumber",
"{",
"}",
"\n",
"proto",
".",
"Merge",
"(",
"firstNumber",
",",
"firstNumberIn",
")",
"\n",
"proto",
".",
"Merge",
"(",
"secondNumber",
",",
"secondNumberIn",
")",
"\n",
"// First clear raw_input, country_code_source and",
"// preferred_domestic_carrier_code fields and any empty-string",
"// extensions so that we can use the proto-buffer equality method.",
"firstNumber",
".",
"RawInput",
"=",
"nil",
"\n",
"firstNumber",
".",
"CountryCodeSource",
"=",
"nil",
"\n",
"firstNumber",
".",
"PreferredDomesticCarrierCode",
"=",
"nil",
"\n",
"secondNumber",
".",
"RawInput",
"=",
"nil",
"\n",
"secondNumber",
".",
"CountryCodeSource",
"=",
"nil",
"\n",
"secondNumber",
".",
"PreferredDomesticCarrierCode",
"=",
"nil",
"\n\n",
"firstNumExt",
":=",
"firstNumber",
".",
"GetExtension",
"(",
")",
"\n",
"secondNumExt",
":=",
"secondNumber",
".",
"GetExtension",
"(",
")",
"\n",
"// NOTE(ttacon): don't think we need this in go land...",
"if",
"len",
"(",
"firstNumExt",
")",
"==",
"0",
"{",
"firstNumber",
".",
"Extension",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"secondNumExt",
")",
"==",
"0",
"{",
"secondNumber",
".",
"Extension",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Early exit if both had extensions and these are different.",
"if",
"len",
"(",
"firstNumExt",
")",
">",
"0",
"&&",
"len",
"(",
"secondNumExt",
")",
">",
"0",
"&&",
"firstNumExt",
"!=",
"secondNumExt",
"{",
"return",
"NO_MATCH",
"\n",
"}",
"\n",
"var",
"(",
"firstNumberCountryCode",
"=",
"firstNumber",
".",
"GetCountryCode",
"(",
")",
"\n",
"secondNumberCountryCode",
"=",
"secondNumber",
".",
"GetCountryCode",
"(",
")",
"\n",
")",
"\n",
"// Both had country_code specified.",
"if",
"firstNumberCountryCode",
"!=",
"0",
"&&",
"secondNumberCountryCode",
"!=",
"0",
"{",
"// TODO(ttacon): remove when make gen-equals",
"if",
"reflect",
".",
"DeepEqual",
"(",
"firstNumber",
",",
"secondNumber",
")",
"{",
"return",
"EXACT_MATCH",
"\n",
"}",
"else",
"if",
"firstNumberCountryCode",
"==",
"secondNumberCountryCode",
"&&",
"isNationalNumberSuffixOfTheOther",
"(",
"firstNumber",
",",
"secondNumber",
")",
"{",
"// A SHORT_NSN_MATCH occurs if there is a difference because of",
"// the presence or absence of an 'Italian leading zero', the",
"// presence or absence of an extension, or one NSN being a",
"// shorter variant of the other.",
"return",
"SHORT_NSN_MATCH",
"\n",
"}",
"\n",
"// This is not a match.",
"return",
"NO_MATCH",
"\n",
"}",
"\n",
"// Checks cases where one or both country_code fields were not",
"// specified. To make equality checks easier, we first set the",
"// country_code fields to be equal.",
"firstNumber",
".",
"CountryCode",
"=",
"proto",
".",
"Int",
"(",
"int",
"(",
"secondNumberCountryCode",
")",
")",
"\n",
"// If all else was the same, then this is an NSN_MATCH.",
"// TODO(ttacon): remove when make gen-equals",
"if",
"reflect",
".",
"DeepEqual",
"(",
"firstNumber",
",",
"secondNumber",
")",
"{",
"return",
"NSN_MATCH",
"\n",
"}",
"\n",
"if",
"isNationalNumberSuffixOfTheOther",
"(",
"firstNumber",
",",
"secondNumber",
")",
"{",
"return",
"SHORT_NSN_MATCH",
"\n",
"}",
"\n",
"return",
"NO_MATCH",
"\n",
"}"
] | // Takes two phone numbers and compares them for equality.
//
// Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
// for Italian numbers and any extension present are the same.
// Returns NSN_MATCH if either or both has no region specified, and the NSNs
// and extensions are the same.
// Returns SHORT_NSN_MATCH if either or both has no region specified, or the
// region specified is the same, and one NSN could be a shorter version of
// the other number. This includes the case where one has an extension
// specified, and the other does not.
// Returns NO_MATCH otherwise.
// For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
// The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. | [
"Takes",
"two",
"phone",
"numbers",
"and",
"compares",
"them",
"for",
"equality",
".",
"Returns",
"EXACT_MATCH",
"if",
"the",
"country_code",
"NSN",
"presence",
"of",
"a",
"leading",
"zero",
"for",
"Italian",
"numbers",
"and",
"any",
"extension",
"present",
"are",
"the",
"same",
".",
"Returns",
"NSN_MATCH",
"if",
"either",
"or",
"both",
"has",
"no",
"region",
"specified",
"and",
"the",
"NSNs",
"and",
"extensions",
"are",
"the",
"same",
".",
"Returns",
"SHORT_NSN_MATCH",
"if",
"either",
"or",
"both",
"has",
"no",
"region",
"specified",
"or",
"the",
"region",
"specified",
"is",
"the",
"same",
"and",
"one",
"NSN",
"could",
"be",
"a",
"shorter",
"version",
"of",
"the",
"other",
"number",
".",
"This",
"includes",
"the",
"case",
"where",
"one",
"has",
"an",
"extension",
"specified",
"and",
"the",
"other",
"does",
"not",
".",
"Returns",
"NO_MATCH",
"otherwise",
".",
"For",
"example",
"the",
"numbers",
"+",
"1",
"345",
"657",
"1234",
"and",
"657",
"1234",
"are",
"a",
"SHORT_NSN_MATCH",
".",
"The",
"numbers",
"+",
"1",
"345",
"657",
"1234",
"and",
"345",
"657",
"are",
"a",
"NO_MATCH",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3078-L3143 |
36 | ttacon/libphonenumber | phonenumberutil.go | isNationalNumberSuffixOfTheOther | func isNationalNumberSuffixOfTheOther(firstNumber, secondNumber *PhoneNumber) bool {
var (
firstNumberNationalNumber = strconv.FormatUint(
firstNumber.GetNationalNumber(), 10)
secondNumberNationalNumber = strconv.FormatUint(
secondNumber.GetNationalNumber(), 10)
)
// Note that endsWith returns true if the numbers are equal.
return strings.HasSuffix(firstNumberNationalNumber, secondNumberNationalNumber) ||
strings.HasSuffix(secondNumberNationalNumber, firstNumberNationalNumber)
} | go | func isNationalNumberSuffixOfTheOther(firstNumber, secondNumber *PhoneNumber) bool {
var (
firstNumberNationalNumber = strconv.FormatUint(
firstNumber.GetNationalNumber(), 10)
secondNumberNationalNumber = strconv.FormatUint(
secondNumber.GetNationalNumber(), 10)
)
// Note that endsWith returns true if the numbers are equal.
return strings.HasSuffix(firstNumberNationalNumber, secondNumberNationalNumber) ||
strings.HasSuffix(secondNumberNationalNumber, firstNumberNationalNumber)
} | [
"func",
"isNationalNumberSuffixOfTheOther",
"(",
"firstNumber",
",",
"secondNumber",
"*",
"PhoneNumber",
")",
"bool",
"{",
"var",
"(",
"firstNumberNationalNumber",
"=",
"strconv",
".",
"FormatUint",
"(",
"firstNumber",
".",
"GetNationalNumber",
"(",
")",
",",
"10",
")",
"\n",
"secondNumberNationalNumber",
"=",
"strconv",
".",
"FormatUint",
"(",
"secondNumber",
".",
"GetNationalNumber",
"(",
")",
",",
"10",
")",
"\n",
")",
"\n",
"// Note that endsWith returns true if the numbers are equal.",
"return",
"strings",
".",
"HasSuffix",
"(",
"firstNumberNationalNumber",
",",
"secondNumberNationalNumber",
")",
"||",
"strings",
".",
"HasSuffix",
"(",
"secondNumberNationalNumber",
",",
"firstNumberNationalNumber",
")",
"\n",
"}"
] | // Returns true when one national number is the suffix of the other or both
// are the same. | [
"Returns",
"true",
"when",
"one",
"national",
"number",
"is",
"the",
"suffix",
"of",
"the",
"other",
"or",
"both",
"are",
"the",
"same",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3147-L3157 |
37 | ttacon/libphonenumber | phonenumberutil.go | IsMobileNumberPortableRegion | func IsMobileNumberPortableRegion(regionCode string) bool {
metadata := getMetadataForRegion(regionCode)
if metadata == nil {
return false
}
return metadata.GetMobileNumberPortableRegion()
} | go | func IsMobileNumberPortableRegion(regionCode string) bool {
metadata := getMetadataForRegion(regionCode)
if metadata == nil {
return false
}
return metadata.GetMobileNumberPortableRegion()
} | [
"func",
"IsMobileNumberPortableRegion",
"(",
"regionCode",
"string",
")",
"bool",
"{",
"metadata",
":=",
"getMetadataForRegion",
"(",
"regionCode",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"metadata",
".",
"GetMobileNumberPortableRegion",
"(",
")",
"\n",
"}"
] | // Returns true if the supplied region supports mobile number portability.
// Returns false for invalid, unknown or regions that don't support mobile
// number portability. | [
"Returns",
"true",
"if",
"the",
"supplied",
"region",
"supports",
"mobile",
"number",
"portability",
".",
"Returns",
"false",
"for",
"invalid",
"unknown",
"or",
"regions",
"that",
"don",
"t",
"support",
"mobile",
"number",
"portability",
"."
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3254-L3260 |
38 | ttacon/libphonenumber | countryCodeToTimeZones.go | GetTimeZonesForRegion | func GetTimeZonesForRegion(number string) ([]string, error) {
for i := MAX_REGION_CODE_LENGTH; i > 0; i-- {
index, err := strconv.Atoi(number[0:i])
if err != nil {
return nil, err
}
if CountryCodeToTimeZones[index] != nil {
return CountryCodeToTimeZones[index], nil
}
}
return []string{UNKNOWN_TIMEZONE}, nil
} | go | func GetTimeZonesForRegion(number string) ([]string, error) {
for i := MAX_REGION_CODE_LENGTH; i > 0; i-- {
index, err := strconv.Atoi(number[0:i])
if err != nil {
return nil, err
}
if CountryCodeToTimeZones[index] != nil {
return CountryCodeToTimeZones[index], nil
}
}
return []string{UNKNOWN_TIMEZONE}, nil
} | [
"func",
"GetTimeZonesForRegion",
"(",
"number",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"for",
"i",
":=",
"MAX_REGION_CODE_LENGTH",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"index",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"number",
"[",
"0",
":",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"CountryCodeToTimeZones",
"[",
"index",
"]",
"!=",
"nil",
"{",
"return",
"CountryCodeToTimeZones",
"[",
"index",
"]",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"[",
"]",
"string",
"{",
"UNKNOWN_TIMEZONE",
"}",
",",
"nil",
"\n",
"}"
] | // Returns a slice of Timezones corresponding to the number passed
// or error when it is impossible to convert the string to int
// The algorythm tries to match the timezones starting from the maximum
// number of phone number digits and decreasing until it finds one or reaches 0 | [
"Returns",
"a",
"slice",
"of",
"Timezones",
"corresponding",
"to",
"the",
"number",
"passed",
"or",
"error",
"when",
"it",
"is",
"impossible",
"to",
"convert",
"the",
"string",
"to",
"int",
"The",
"algorythm",
"tries",
"to",
"match",
"the",
"timezones",
"starting",
"from",
"the",
"maximum",
"number",
"of",
"phone",
"number",
"digits",
"and",
"decreasing",
"until",
"it",
"finds",
"one",
"or",
"reaches",
"0"
] | 23ddf903e8f8800d2857645eb155ffbe15cd02ee | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/countryCodeToTimeZones.go#L2253-L2264 |
39 | hajimehoshi/go-mp3 | decode.go | Read | func (d *Decoder) Read(buf []byte) (int, error) {
for len(d.buf) == 0 {
if err := d.readFrame(); err != nil {
return 0, err
}
}
n := copy(buf, d.buf)
d.buf = d.buf[n:]
d.pos += int64(n)
return n, nil
} | go | func (d *Decoder) Read(buf []byte) (int, error) {
for len(d.buf) == 0 {
if err := d.readFrame(); err != nil {
return 0, err
}
}
n := copy(buf, d.buf)
d.buf = d.buf[n:]
d.pos += int64(n)
return n, nil
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"for",
"len",
"(",
"d",
".",
"buf",
")",
"==",
"0",
"{",
"if",
"err",
":=",
"d",
".",
"readFrame",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"n",
":=",
"copy",
"(",
"buf",
",",
"d",
".",
"buf",
")",
"\n",
"d",
".",
"buf",
"=",
"d",
".",
"buf",
"[",
"n",
":",
"]",
"\n",
"d",
".",
"pos",
"+=",
"int64",
"(",
"n",
")",
"\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // Read is io.Reader's Read. | [
"Read",
"is",
"io",
".",
"Reader",
"s",
"Read",
"."
] | 14af46a99b16fe1e285e22e032579d8b075c71f4 | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/decode.go#L57-L67 |
40 | hajimehoshi/go-mp3 | decode.go | Seek | func (d *Decoder) Seek(offset int64, whence int) (int64, error) {
npos := int64(0)
switch whence {
case io.SeekStart:
npos = offset
case io.SeekCurrent:
npos = d.pos + offset
case io.SeekEnd:
npos = d.Length() + offset
default:
panic(fmt.Sprintf("mp3: invalid whence: %v", whence))
}
d.pos = npos
d.buf = nil
d.frame = nil
f := d.pos / consts.BytesPerFrame
// If the frame is not first, read the previous ahead of reading that
// because the previous frame can affect the targeted frame.
if f > 0 {
f--
if _, err := d.source.Seek(d.frameStarts[f], 0); err != nil {
return 0, err
}
if err := d.readFrame(); err != nil {
return 0, err
}
if err := d.readFrame(); err != nil {
return 0, err
}
d.buf = d.buf[consts.BytesPerFrame+(d.pos%consts.BytesPerFrame):]
} else {
if _, err := d.source.Seek(d.frameStarts[f], 0); err != nil {
return 0, err
}
if err := d.readFrame(); err != nil {
return 0, err
}
d.buf = d.buf[d.pos:]
}
return npos, nil
} | go | func (d *Decoder) Seek(offset int64, whence int) (int64, error) {
npos := int64(0)
switch whence {
case io.SeekStart:
npos = offset
case io.SeekCurrent:
npos = d.pos + offset
case io.SeekEnd:
npos = d.Length() + offset
default:
panic(fmt.Sprintf("mp3: invalid whence: %v", whence))
}
d.pos = npos
d.buf = nil
d.frame = nil
f := d.pos / consts.BytesPerFrame
// If the frame is not first, read the previous ahead of reading that
// because the previous frame can affect the targeted frame.
if f > 0 {
f--
if _, err := d.source.Seek(d.frameStarts[f], 0); err != nil {
return 0, err
}
if err := d.readFrame(); err != nil {
return 0, err
}
if err := d.readFrame(); err != nil {
return 0, err
}
d.buf = d.buf[consts.BytesPerFrame+(d.pos%consts.BytesPerFrame):]
} else {
if _, err := d.source.Seek(d.frameStarts[f], 0); err != nil {
return 0, err
}
if err := d.readFrame(); err != nil {
return 0, err
}
d.buf = d.buf[d.pos:]
}
return npos, nil
} | [
"func",
"(",
"d",
"*",
"Decoder",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"npos",
":=",
"int64",
"(",
"0",
")",
"\n",
"switch",
"whence",
"{",
"case",
"io",
".",
"SeekStart",
":",
"npos",
"=",
"offset",
"\n",
"case",
"io",
".",
"SeekCurrent",
":",
"npos",
"=",
"d",
".",
"pos",
"+",
"offset",
"\n",
"case",
"io",
".",
"SeekEnd",
":",
"npos",
"=",
"d",
".",
"Length",
"(",
")",
"+",
"offset",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"whence",
")",
")",
"\n",
"}",
"\n",
"d",
".",
"pos",
"=",
"npos",
"\n",
"d",
".",
"buf",
"=",
"nil",
"\n",
"d",
".",
"frame",
"=",
"nil",
"\n",
"f",
":=",
"d",
".",
"pos",
"/",
"consts",
".",
"BytesPerFrame",
"\n",
"// If the frame is not first, read the previous ahead of reading that",
"// because the previous frame can affect the targeted frame.",
"if",
"f",
">",
"0",
"{",
"f",
"--",
"\n",
"if",
"_",
",",
"err",
":=",
"d",
".",
"source",
".",
"Seek",
"(",
"d",
".",
"frameStarts",
"[",
"f",
"]",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"readFrame",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"readFrame",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"d",
".",
"buf",
"=",
"d",
".",
"buf",
"[",
"consts",
".",
"BytesPerFrame",
"+",
"(",
"d",
".",
"pos",
"%",
"consts",
".",
"BytesPerFrame",
")",
":",
"]",
"\n",
"}",
"else",
"{",
"if",
"_",
",",
"err",
":=",
"d",
".",
"source",
".",
"Seek",
"(",
"d",
".",
"frameStarts",
"[",
"f",
"]",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"readFrame",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"d",
".",
"buf",
"=",
"d",
".",
"buf",
"[",
"d",
".",
"pos",
":",
"]",
"\n",
"}",
"\n",
"return",
"npos",
",",
"nil",
"\n",
"}"
] | // Seek is io.Seeker's Seek.
//
// Seek panics when the underlying source is not io.Seeker. | [
"Seek",
"is",
"io",
".",
"Seeker",
"s",
"Seek",
".",
"Seek",
"panics",
"when",
"the",
"underlying",
"source",
"is",
"not",
"io",
".",
"Seeker",
"."
] | 14af46a99b16fe1e285e22e032579d8b075c71f4 | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/decode.go#L72-L112 |
41 | hajimehoshi/go-mp3 | internal/frameheader/frameheader.go | IsValid | func (f FrameHeader) IsValid() bool {
const sync = 0xffe00000
if (f & sync) != sync {
return false
}
if f.ID() == consts.VersionReserved {
return false
}
if f.BitrateIndex() == 15 {
return false
}
if f.SamplingFrequency() == consts.SamplingFrequencyReserved {
return false
}
if f.Layer() == consts.LayerReserved {
return false
}
if f.Emphasis() == 2 {
return false
}
return true
} | go | func (f FrameHeader) IsValid() bool {
const sync = 0xffe00000
if (f & sync) != sync {
return false
}
if f.ID() == consts.VersionReserved {
return false
}
if f.BitrateIndex() == 15 {
return false
}
if f.SamplingFrequency() == consts.SamplingFrequencyReserved {
return false
}
if f.Layer() == consts.LayerReserved {
return false
}
if f.Emphasis() == 2 {
return false
}
return true
} | [
"func",
"(",
"f",
"FrameHeader",
")",
"IsValid",
"(",
")",
"bool",
"{",
"const",
"sync",
"=",
"0xffe00000",
"\n",
"if",
"(",
"f",
"&",
"sync",
")",
"!=",
"sync",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"f",
".",
"ID",
"(",
")",
"==",
"consts",
".",
"VersionReserved",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"f",
".",
"BitrateIndex",
"(",
")",
"==",
"15",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"f",
".",
"SamplingFrequency",
"(",
")",
"==",
"consts",
".",
"SamplingFrequencyReserved",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"f",
".",
"Layer",
"(",
")",
"==",
"consts",
".",
"LayerReserved",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"f",
".",
"Emphasis",
"(",
")",
"==",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // IsValid returns a boolean value indicating whether the header is valid or not. | [
"IsValid",
"returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"the",
"header",
"is",
"valid",
"or",
"not",
"."
] | 14af46a99b16fe1e285e22e032579d8b075c71f4 | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/internal/frameheader/frameheader.go#L105-L126 |
42 | seiflotfy/cuckoofilter | cuckoofilter.go | NewFilter | func NewFilter(capacity uint) *Filter {
capacity = getNextPow2(uint64(capacity)) / bucketSize
if capacity == 0 {
capacity = 1
}
buckets := make([]bucket, capacity)
for i := range buckets {
buckets[i] = [bucketSize]byte{}
}
return &Filter{buckets, 0}
} | go | func NewFilter(capacity uint) *Filter {
capacity = getNextPow2(uint64(capacity)) / bucketSize
if capacity == 0 {
capacity = 1
}
buckets := make([]bucket, capacity)
for i := range buckets {
buckets[i] = [bucketSize]byte{}
}
return &Filter{buckets, 0}
} | [
"func",
"NewFilter",
"(",
"capacity",
"uint",
")",
"*",
"Filter",
"{",
"capacity",
"=",
"getNextPow2",
"(",
"uint64",
"(",
"capacity",
")",
")",
"/",
"bucketSize",
"\n",
"if",
"capacity",
"==",
"0",
"{",
"capacity",
"=",
"1",
"\n",
"}",
"\n",
"buckets",
":=",
"make",
"(",
"[",
"]",
"bucket",
",",
"capacity",
")",
"\n",
"for",
"i",
":=",
"range",
"buckets",
"{",
"buckets",
"[",
"i",
"]",
"=",
"[",
"bucketSize",
"]",
"byte",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Filter",
"{",
"buckets",
",",
"0",
"}",
"\n",
"}"
] | // NewFilter returns a new cuckoofilter with a given capacity.
// A capacity of 1000000 is a normal default, which allocates
// about ~1MB on 64-bit machines. | [
"NewFilter",
"returns",
"a",
"new",
"cuckoofilter",
"with",
"a",
"given",
"capacity",
".",
"A",
"capacity",
"of",
"1000000",
"is",
"a",
"normal",
"default",
"which",
"allocates",
"about",
"~1MB",
"on",
"64",
"-",
"bit",
"machines",
"."
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L19-L29 |
43 | seiflotfy/cuckoofilter | cuckoofilter.go | Lookup | func (cf *Filter) Lookup(data []byte) bool {
i1, i2, fp := getIndicesAndFingerprint(data, uint(len(cf.buckets)))
b1, b2 := cf.buckets[i1], cf.buckets[i2]
return b1.getFingerprintIndex(fp) > -1 || b2.getFingerprintIndex(fp) > -1
} | go | func (cf *Filter) Lookup(data []byte) bool {
i1, i2, fp := getIndicesAndFingerprint(data, uint(len(cf.buckets)))
b1, b2 := cf.buckets[i1], cf.buckets[i2]
return b1.getFingerprintIndex(fp) > -1 || b2.getFingerprintIndex(fp) > -1
} | [
"func",
"(",
"cf",
"*",
"Filter",
")",
"Lookup",
"(",
"data",
"[",
"]",
"byte",
")",
"bool",
"{",
"i1",
",",
"i2",
",",
"fp",
":=",
"getIndicesAndFingerprint",
"(",
"data",
",",
"uint",
"(",
"len",
"(",
"cf",
".",
"buckets",
")",
")",
")",
"\n",
"b1",
",",
"b2",
":=",
"cf",
".",
"buckets",
"[",
"i1",
"]",
",",
"cf",
".",
"buckets",
"[",
"i2",
"]",
"\n",
"return",
"b1",
".",
"getFingerprintIndex",
"(",
"fp",
")",
">",
"-",
"1",
"||",
"b2",
".",
"getFingerprintIndex",
"(",
"fp",
")",
">",
"-",
"1",
"\n",
"}"
] | // Lookup returns true if data is in the counter | [
"Lookup",
"returns",
"true",
"if",
"data",
"is",
"in",
"the",
"counter"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L32-L36 |
44 | seiflotfy/cuckoofilter | cuckoofilter.go | Insert | func (cf *Filter) Insert(data []byte) bool {
i1, i2, fp := getIndicesAndFingerprint(data, uint(len(cf.buckets)))
if cf.insert(fp, i1) || cf.insert(fp, i2) {
return true
}
return cf.reinsert(fp, randi(i1, i2))
} | go | func (cf *Filter) Insert(data []byte) bool {
i1, i2, fp := getIndicesAndFingerprint(data, uint(len(cf.buckets)))
if cf.insert(fp, i1) || cf.insert(fp, i2) {
return true
}
return cf.reinsert(fp, randi(i1, i2))
} | [
"func",
"(",
"cf",
"*",
"Filter",
")",
"Insert",
"(",
"data",
"[",
"]",
"byte",
")",
"bool",
"{",
"i1",
",",
"i2",
",",
"fp",
":=",
"getIndicesAndFingerprint",
"(",
"data",
",",
"uint",
"(",
"len",
"(",
"cf",
".",
"buckets",
")",
")",
")",
"\n",
"if",
"cf",
".",
"insert",
"(",
"fp",
",",
"i1",
")",
"||",
"cf",
".",
"insert",
"(",
"fp",
",",
"i2",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"cf",
".",
"reinsert",
"(",
"fp",
",",
"randi",
"(",
"i1",
",",
"i2",
")",
")",
"\n",
"}"
] | // Insert inserts data into the counter and returns true upon success | [
"Insert",
"inserts",
"data",
"into",
"the",
"counter",
"and",
"returns",
"true",
"upon",
"success"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L53-L59 |
45 | seiflotfy/cuckoofilter | cuckoofilter.go | InsertUnique | func (cf *Filter) InsertUnique(data []byte) bool {
if cf.Lookup(data) {
return false
}
return cf.Insert(data)
} | go | func (cf *Filter) InsertUnique(data []byte) bool {
if cf.Lookup(data) {
return false
}
return cf.Insert(data)
} | [
"func",
"(",
"cf",
"*",
"Filter",
")",
"InsertUnique",
"(",
"data",
"[",
"]",
"byte",
")",
"bool",
"{",
"if",
"cf",
".",
"Lookup",
"(",
"data",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"cf",
".",
"Insert",
"(",
"data",
")",
"\n",
"}"
] | // InsertUnique inserts data into the counter if not exists and returns true upon success | [
"InsertUnique",
"inserts",
"data",
"into",
"the",
"counter",
"if",
"not",
"exists",
"and",
"returns",
"true",
"upon",
"success"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L62-L67 |
46 | seiflotfy/cuckoofilter | cuckoofilter.go | Delete | func (cf *Filter) Delete(data []byte) bool {
i1, i2, fp := getIndicesAndFingerprint(data, uint(len(cf.buckets)))
return cf.delete(fp, i1) || cf.delete(fp, i2)
} | go | func (cf *Filter) Delete(data []byte) bool {
i1, i2, fp := getIndicesAndFingerprint(data, uint(len(cf.buckets)))
return cf.delete(fp, i1) || cf.delete(fp, i2)
} | [
"func",
"(",
"cf",
"*",
"Filter",
")",
"Delete",
"(",
"data",
"[",
"]",
"byte",
")",
"bool",
"{",
"i1",
",",
"i2",
",",
"fp",
":=",
"getIndicesAndFingerprint",
"(",
"data",
",",
"uint",
"(",
"len",
"(",
"cf",
".",
"buckets",
")",
")",
")",
"\n",
"return",
"cf",
".",
"delete",
"(",
"fp",
",",
"i1",
")",
"||",
"cf",
".",
"delete",
"(",
"fp",
",",
"i2",
")",
"\n",
"}"
] | // Delete data from counter if exists and return if deleted or not | [
"Delete",
"data",
"from",
"counter",
"if",
"exists",
"and",
"return",
"if",
"deleted",
"or",
"not"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L94-L97 |
47 | seiflotfy/cuckoofilter | cuckoofilter.go | Encode | func (cf *Filter) Encode() []byte {
bytes := make([]byte, len(cf.buckets)*bucketSize)
for i, b := range cf.buckets {
for j, f := range b {
index := (i * len(b)) + j
bytes[index] = f
}
}
return bytes
} | go | func (cf *Filter) Encode() []byte {
bytes := make([]byte, len(cf.buckets)*bucketSize)
for i, b := range cf.buckets {
for j, f := range b {
index := (i * len(b)) + j
bytes[index] = f
}
}
return bytes
} | [
"func",
"(",
"cf",
"*",
"Filter",
")",
"Encode",
"(",
")",
"[",
"]",
"byte",
"{",
"bytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"cf",
".",
"buckets",
")",
"*",
"bucketSize",
")",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"cf",
".",
"buckets",
"{",
"for",
"j",
",",
"f",
":=",
"range",
"b",
"{",
"index",
":=",
"(",
"i",
"*",
"len",
"(",
"b",
")",
")",
"+",
"j",
"\n",
"bytes",
"[",
"index",
"]",
"=",
"f",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"bytes",
"\n",
"}"
] | // Encode returns a byte slice representing a Cuckoofilter | [
"Encode",
"returns",
"a",
"byte",
"slice",
"representing",
"a",
"Cuckoofilter"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L113-L122 |
48 | seiflotfy/cuckoofilter | cuckoofilter.go | Decode | func Decode(bytes []byte) (*Filter, error) {
var count uint
if len(bytes)%bucketSize != 0 {
return nil, fmt.Errorf("expected bytes to be multiple of %d, got %d", bucketSize, len(bytes))
}
buckets := make([]bucket, len(bytes)/4)
for i, b := range buckets {
for j := range b {
index := (i * len(b)) + j
if bytes[index] != 0 {
buckets[i][j] = bytes[index]
count++
}
}
}
return &Filter{
buckets: buckets,
count: count,
}, nil
} | go | func Decode(bytes []byte) (*Filter, error) {
var count uint
if len(bytes)%bucketSize != 0 {
return nil, fmt.Errorf("expected bytes to be multiple of %d, got %d", bucketSize, len(bytes))
}
buckets := make([]bucket, len(bytes)/4)
for i, b := range buckets {
for j := range b {
index := (i * len(b)) + j
if bytes[index] != 0 {
buckets[i][j] = bytes[index]
count++
}
}
}
return &Filter{
buckets: buckets,
count: count,
}, nil
} | [
"func",
"Decode",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"*",
"Filter",
",",
"error",
")",
"{",
"var",
"count",
"uint",
"\n",
"if",
"len",
"(",
"bytes",
")",
"%",
"bucketSize",
"!=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"bucketSize",
",",
"len",
"(",
"bytes",
")",
")",
"\n",
"}",
"\n",
"buckets",
":=",
"make",
"(",
"[",
"]",
"bucket",
",",
"len",
"(",
"bytes",
")",
"/",
"4",
")",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"buckets",
"{",
"for",
"j",
":=",
"range",
"b",
"{",
"index",
":=",
"(",
"i",
"*",
"len",
"(",
"b",
")",
")",
"+",
"j",
"\n",
"if",
"bytes",
"[",
"index",
"]",
"!=",
"0",
"{",
"buckets",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"bytes",
"[",
"index",
"]",
"\n",
"count",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Filter",
"{",
"buckets",
":",
"buckets",
",",
"count",
":",
"count",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Decode returns a Cuckoofilter from a byte slice | [
"Decode",
"returns",
"a",
"Cuckoofilter",
"from",
"a",
"byte",
"slice"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L125-L144 |
49 | seiflotfy/cuckoofilter | util.go | getIndicesAndFingerprint | func getIndicesAndFingerprint(data []byte, numBuckets uint) (uint, uint, byte) {
hash := metro.Hash64(data, 1337)
f := getFingerprint(data)
i1 := uint(hash) % numBuckets
i2 := getAltIndex(f, i1, numBuckets)
return i1, i2, f
} | go | func getIndicesAndFingerprint(data []byte, numBuckets uint) (uint, uint, byte) {
hash := metro.Hash64(data, 1337)
f := getFingerprint(data)
i1 := uint(hash) % numBuckets
i2 := getAltIndex(f, i1, numBuckets)
return i1, i2, f
} | [
"func",
"getIndicesAndFingerprint",
"(",
"data",
"[",
"]",
"byte",
",",
"numBuckets",
"uint",
")",
"(",
"uint",
",",
"uint",
",",
"byte",
")",
"{",
"hash",
":=",
"metro",
".",
"Hash64",
"(",
"data",
",",
"1337",
")",
"\n",
"f",
":=",
"getFingerprint",
"(",
"data",
")",
"\n",
"i1",
":=",
"uint",
"(",
"hash",
")",
"%",
"numBuckets",
"\n",
"i2",
":=",
"getAltIndex",
"(",
"f",
",",
"i1",
",",
"numBuckets",
")",
"\n",
"return",
"i1",
",",
"i2",
",",
"f",
"\n",
"}"
] | // getIndicesAndFingerprint returns the 2 bucket indices and fingerprint to be used | [
"getIndicesAndFingerprint",
"returns",
"the",
"2",
"bucket",
"indices",
"and",
"fingerprint",
"to",
"be",
"used"
] | 764cb5258d9bcd276f2f809e74cfa206d8e8e054 | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/util.go#L18-L24 |
50 | markbates/grift | grift/grift.go | Namespace | func Namespace(name string, s func()) error {
defer func() {
namespace = ""
}()
namespace = applyNamespace(name)
s()
return nil
} | go | func Namespace(name string, s func()) error {
defer func() {
namespace = ""
}()
namespace = applyNamespace(name)
s()
return nil
} | [
"func",
"Namespace",
"(",
"name",
"string",
",",
"s",
"func",
"(",
")",
")",
"error",
"{",
"defer",
"func",
"(",
")",
"{",
"namespace",
"=",
"\"",
"\"",
"\n",
"}",
"(",
")",
"\n\n",
"namespace",
"=",
"applyNamespace",
"(",
"name",
")",
"\n",
"s",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Namespace will place all tasks within the given prefix. | [
"Namespace",
"will",
"place",
"all",
"tasks",
"within",
"the",
"given",
"prefix",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L24-L32 |
51 | markbates/grift | grift/grift.go | Add | func Add(name string, grift Grift) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
if griftList[name] != nil {
fn := griftList[name]
griftList[name] = func(c *Context) error {
err := fn(c)
if err != nil {
return err
}
return grift(c)
}
} else {
griftList[name] = grift
}
return nil
} | go | func Add(name string, grift Grift) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
if griftList[name] != nil {
fn := griftList[name]
griftList[name] = func(c *Context) error {
err := fn(c)
if err != nil {
return err
}
return grift(c)
}
} else {
griftList[name] = grift
}
return nil
} | [
"func",
"Add",
"(",
"name",
"string",
",",
"grift",
"Grift",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
"=",
"applyNamespace",
"(",
"name",
")",
"\n\n",
"if",
"griftList",
"[",
"name",
"]",
"!=",
"nil",
"{",
"fn",
":=",
"griftList",
"[",
"name",
"]",
"\n",
"griftList",
"[",
"name",
"]",
"=",
"func",
"(",
"c",
"*",
"Context",
")",
"error",
"{",
"err",
":=",
"fn",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"grift",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"griftList",
"[",
"name",
"]",
"=",
"grift",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Add a grift. If there is already a grift
// with the given name the two grifts will
// be bundled together. | [
"Add",
"a",
"grift",
".",
"If",
"there",
"is",
"already",
"a",
"grift",
"with",
"the",
"given",
"name",
"the",
"two",
"grifts",
"will",
"be",
"bundled",
"together",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L51-L70 |
52 | markbates/grift | grift/grift.go | Set | func Set(name string, grift Grift) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
griftList[name] = grift
return nil
} | go | func Set(name string, grift Grift) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
griftList[name] = grift
return nil
} | [
"func",
"Set",
"(",
"name",
"string",
",",
"grift",
"Grift",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"name",
"=",
"applyNamespace",
"(",
"name",
")",
"\n",
"griftList",
"[",
"name",
"]",
"=",
"grift",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set a grift. This is similar to `Add` but it will
// overwrite an existing grift with the same name. | [
"Set",
"a",
"grift",
".",
"This",
"is",
"similar",
"to",
"Add",
"but",
"it",
"will",
"overwrite",
"an",
"existing",
"grift",
"with",
"the",
"same",
"name",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L74-L80 |
53 | markbates/grift | grift/grift.go | Rename | func Rename(oldName string, newName string) error {
lock.Lock()
defer lock.Unlock()
oldName = applyNamespace(oldName)
newName = applyNamespace(newName)
if griftList[oldName] == nil {
return fmt.Errorf("No task named %s defined!", oldName)
}
griftList[newName] = griftList[oldName]
delete(griftList, oldName)
return nil
} | go | func Rename(oldName string, newName string) error {
lock.Lock()
defer lock.Unlock()
oldName = applyNamespace(oldName)
newName = applyNamespace(newName)
if griftList[oldName] == nil {
return fmt.Errorf("No task named %s defined!", oldName)
}
griftList[newName] = griftList[oldName]
delete(griftList, oldName)
return nil
} | [
"func",
"Rename",
"(",
"oldName",
"string",
",",
"newName",
"string",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"oldName",
"=",
"applyNamespace",
"(",
"oldName",
")",
"\n",
"newName",
"=",
"applyNamespace",
"(",
"newName",
")",
"\n\n",
"if",
"griftList",
"[",
"oldName",
"]",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"oldName",
")",
"\n",
"}",
"\n",
"griftList",
"[",
"newName",
"]",
"=",
"griftList",
"[",
"oldName",
"]",
"\n",
"delete",
"(",
"griftList",
",",
"oldName",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Rename a grift. Useful if you want to re-define
// an existing grift, but don't want to write over
// the original. | [
"Rename",
"a",
"grift",
".",
"Useful",
"if",
"you",
"want",
"to",
"re",
"-",
"define",
"an",
"existing",
"grift",
"but",
"don",
"t",
"want",
"to",
"write",
"over",
"the",
"original",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L85-L98 |
54 | markbates/grift | grift/grift.go | Remove | func Remove(name string) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
delete(griftList, name)
delete(descriptions, name)
return nil
} | go | func Remove(name string) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
delete(griftList, name)
delete(descriptions, name)
return nil
} | [
"func",
"Remove",
"(",
"name",
"string",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
"=",
"applyNamespace",
"(",
"name",
")",
"\n\n",
"delete",
"(",
"griftList",
",",
"name",
")",
"\n",
"delete",
"(",
"descriptions",
",",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Remove a grift. Not incredibly useful, but here for
// completeness. | [
"Remove",
"a",
"grift",
".",
"Not",
"incredibly",
"useful",
"but",
"here",
"for",
"completeness",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L102-L111 |
55 | markbates/grift | grift/grift.go | Desc | func Desc(name string, description string) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
descriptions[name] = description
return nil
} | go | func Desc(name string, description string) error {
lock.Lock()
defer lock.Unlock()
name = applyNamespace(name)
descriptions[name] = description
return nil
} | [
"func",
"Desc",
"(",
"name",
"string",
",",
"description",
"string",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
"=",
"applyNamespace",
"(",
"name",
")",
"\n\n",
"descriptions",
"[",
"name",
"]",
"=",
"description",
"\n",
"return",
"nil",
"\n",
"}"
] | // Desc sets a helpful descriptive text for a grift.
// This description will be shown when `grift list`
// is run. | [
"Desc",
"sets",
"a",
"helpful",
"descriptive",
"text",
"for",
"a",
"grift",
".",
"This",
"description",
"will",
"be",
"shown",
"when",
"grift",
"list",
"is",
"run",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L116-L124 |
56 | markbates/grift | grift/grift.go | Run | func Run(name string, c *Context) error {
name = applyNamespace(name)
if griftList[name] == nil {
if name == "list" {
PrintGrifts(os.Stdout)
return nil
}
return fmt.Errorf("No task named '%s' defined!", name)
}
if c.Verbose {
defer func(start time.Time) {
log.Printf("Completed task %s in %s\n", name, time.Now().Sub(start))
}(time.Now())
log.Printf("Starting task %s\n", name)
}
return griftList[name](c)
} | go | func Run(name string, c *Context) error {
name = applyNamespace(name)
if griftList[name] == nil {
if name == "list" {
PrintGrifts(os.Stdout)
return nil
}
return fmt.Errorf("No task named '%s' defined!", name)
}
if c.Verbose {
defer func(start time.Time) {
log.Printf("Completed task %s in %s\n", name, time.Now().Sub(start))
}(time.Now())
log.Printf("Starting task %s\n", name)
}
return griftList[name](c)
} | [
"func",
"Run",
"(",
"name",
"string",
",",
"c",
"*",
"Context",
")",
"error",
"{",
"name",
"=",
"applyNamespace",
"(",
"name",
")",
"\n\n",
"if",
"griftList",
"[",
"name",
"]",
"==",
"nil",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"PrintGrifts",
"(",
"os",
".",
"Stdout",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"Verbose",
"{",
"defer",
"func",
"(",
"start",
"time",
".",
"Time",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
",",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
")",
"\n",
"}",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"griftList",
"[",
"name",
"]",
"(",
"c",
")",
"\n",
"}"
] | // Run a grift. This allows for the chaining for grifts.
// One grift can Run another grift and so on. | [
"Run",
"a",
"grift",
".",
"This",
"allows",
"for",
"the",
"chaining",
"for",
"grifts",
".",
"One",
"grift",
"can",
"Run",
"another",
"grift",
"and",
"so",
"on",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L128-L145 |
57 | markbates/grift | grift/grift.go | List | func List() []string {
keys := []string{}
for k := range griftList {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
} | go | func List() []string {
keys := []string{}
for k := range griftList {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
} | [
"func",
"List",
"(",
")",
"[",
"]",
"string",
"{",
"keys",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"k",
":=",
"range",
"griftList",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"return",
"keys",
"\n",
"}"
] | // List of the names of the defined grifts. | [
"List",
"of",
"the",
"names",
"of",
"the",
"defined",
"grifts",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L148-L155 |
58 | markbates/grift | grift/grift.go | Exec | func Exec(args []string, verbose bool) error {
name := "list"
if len(args) >= 1 {
name = args[0]
}
switch name {
case "list":
PrintGrifts(os.Stdout)
default:
c := NewContext(name)
c.Verbose = verbose
if len(args) >= 1 {
c.Args = args[1:]
}
return Run(name, c)
}
return nil
} | go | func Exec(args []string, verbose bool) error {
name := "list"
if len(args) >= 1 {
name = args[0]
}
switch name {
case "list":
PrintGrifts(os.Stdout)
default:
c := NewContext(name)
c.Verbose = verbose
if len(args) >= 1 {
c.Args = args[1:]
}
return Run(name, c)
}
return nil
} | [
"func",
"Exec",
"(",
"args",
"[",
"]",
"string",
",",
"verbose",
"bool",
")",
"error",
"{",
"name",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"args",
")",
">=",
"1",
"{",
"name",
"=",
"args",
"[",
"0",
"]",
"\n",
"}",
"\n",
"switch",
"name",
"{",
"case",
"\"",
"\"",
":",
"PrintGrifts",
"(",
"os",
".",
"Stdout",
")",
"\n",
"default",
":",
"c",
":=",
"NewContext",
"(",
"name",
")",
"\n",
"c",
".",
"Verbose",
"=",
"verbose",
"\n",
"if",
"len",
"(",
"args",
")",
">=",
"1",
"{",
"c",
".",
"Args",
"=",
"args",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"Run",
"(",
"name",
",",
"c",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Exec the grift stack. This is the main "entry point" to
// the grift system. | [
"Exec",
"the",
"grift",
"stack",
".",
"This",
"is",
"the",
"main",
"entry",
"point",
"to",
"the",
"grift",
"system",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L159-L176 |
59 | markbates/grift | grift/grift.go | PrintGrifts | func PrintGrifts(w io.Writer) {
fmt.Fprint(w, "Available grifts\n================\n")
cnLen := len(CommandName)
maxLen := cnLen
l := List()
for _, k := range l {
if (len(k) + cnLen) > maxLen {
maxLen = len(k) + cnLen
}
}
for _, k := range l {
m := strings.Join([]string{CommandName, k}, " ")
suffix := strings.Repeat(" ", (maxLen+3)-len(m)) + " #"
fmt.Fprintln(w, strings.Join([]string{m, suffix, descriptions[k]}, " "))
}
} | go | func PrintGrifts(w io.Writer) {
fmt.Fprint(w, "Available grifts\n================\n")
cnLen := len(CommandName)
maxLen := cnLen
l := List()
for _, k := range l {
if (len(k) + cnLen) > maxLen {
maxLen = len(k) + cnLen
}
}
for _, k := range l {
m := strings.Join([]string{CommandName, k}, " ")
suffix := strings.Repeat(" ", (maxLen+3)-len(m)) + " #"
fmt.Fprintln(w, strings.Join([]string{m, suffix, descriptions[k]}, " "))
}
} | [
"func",
"PrintGrifts",
"(",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"cnLen",
":=",
"len",
"(",
"CommandName",
")",
"\n",
"maxLen",
":=",
"cnLen",
"\n",
"l",
":=",
"List",
"(",
")",
"\n\n",
"for",
"_",
",",
"k",
":=",
"range",
"l",
"{",
"if",
"(",
"len",
"(",
"k",
")",
"+",
"cnLen",
")",
">",
"maxLen",
"{",
"maxLen",
"=",
"len",
"(",
"k",
")",
"+",
"cnLen",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"k",
":=",
"range",
"l",
"{",
"m",
":=",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"CommandName",
",",
"k",
"}",
",",
"\"",
"\"",
")",
"\n",
"suffix",
":=",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"(",
"maxLen",
"+",
"3",
")",
"-",
"len",
"(",
"m",
")",
")",
"+",
"\"",
"\"",
"\n\n",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"m",
",",
"suffix",
",",
"descriptions",
"[",
"k",
"]",
"}",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"}"
] | // PrintGrifts to the screen, nice, sorted, and with descriptions,
// should they exist. | [
"PrintGrifts",
"to",
"the",
"screen",
"nice",
"sorted",
"and",
"with",
"descriptions",
"should",
"they",
"exist",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L180-L199 |
60 | markbates/grift | grift/context.go | Value | func (c *Context) Value(key interface{}) interface{} {
if s, ok := key.(string); ok {
if v, ok := c.data[s]; ok {
return v
}
}
return c.Context.Value(key)
} | go | func (c *Context) Value(key interface{}) interface{} {
if s, ok := key.(string); ok {
if v, ok := c.data[s]; ok {
return v
}
}
return c.Context.Value(key)
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"Value",
"(",
"key",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"if",
"s",
",",
"ok",
":=",
"key",
".",
"(",
"string",
")",
";",
"ok",
"{",
"if",
"v",
",",
"ok",
":=",
"c",
".",
"data",
"[",
"s",
"]",
";",
"ok",
"{",
"return",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"c",
".",
"Context",
".",
"Value",
"(",
"key",
")",
"\n",
"}"
] | // Value returns a value from the context for the given key | [
"Value",
"returns",
"a",
"value",
"from",
"the",
"context",
"for",
"the",
"given",
"key"
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/context.go#L19-L26 |
61 | markbates/grift | grift/context.go | Set | func (c *Context) Set(key string, val interface{}) {
c.moot.Lock()
defer c.moot.Unlock()
c.data[key] = val
} | go | func (c *Context) Set(key string, val interface{}) {
c.moot.Lock()
defer c.moot.Unlock()
c.data[key] = val
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"Set",
"(",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"c",
".",
"moot",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"moot",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"data",
"[",
"key",
"]",
"=",
"val",
"\n",
"}"
] | // Set a piece of data onto the Context. | [
"Set",
"a",
"piece",
"of",
"data",
"onto",
"the",
"Context",
"."
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/context.go#L29-L33 |
62 | markbates/grift | grift/context.go | NewContextWithContext | func NewContextWithContext(name string, ctx context.Context) *Context {
return &Context{
Context: ctx,
Name: name,
Args: []string{},
data: map[interface{}]interface{}{},
moot: &sync.Mutex{},
}
} | go | func NewContextWithContext(name string, ctx context.Context) *Context {
return &Context{
Context: ctx,
Name: name,
Args: []string{},
data: map[interface{}]interface{}{},
moot: &sync.Mutex{},
}
} | [
"func",
"NewContextWithContext",
"(",
"name",
"string",
",",
"ctx",
"context",
".",
"Context",
")",
"*",
"Context",
"{",
"return",
"&",
"Context",
"{",
"Context",
":",
"ctx",
",",
"Name",
":",
"name",
",",
"Args",
":",
"[",
"]",
"string",
"{",
"}",
",",
"data",
":",
"map",
"[",
"interface",
"{",
"}",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"moot",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n",
"}"
] | // NewContextWithContext builds and returns a new default Context given an existing context | [
"NewContextWithContext",
"builds",
"and",
"returns",
"a",
"new",
"default",
"Context",
"given",
"an",
"existing",
"context"
] | ce869fe62d84875913170d186f91a34667e4c732 | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/context.go#L41-L49 |
63 | aymerick/douceur | parser/parser.go | ParseStylesheet | func (parser *Parser) ParseStylesheet() (*css.Stylesheet, error) {
result := css.NewStylesheet()
// Parse BOM
if _, err := parser.parseBOM(); err != nil {
return result, err
}
// Parse list of rules
rules, err := parser.ParseRules()
if err != nil {
return result, err
}
result.Rules = rules
return result, nil
} | go | func (parser *Parser) ParseStylesheet() (*css.Stylesheet, error) {
result := css.NewStylesheet()
// Parse BOM
if _, err := parser.parseBOM(); err != nil {
return result, err
}
// Parse list of rules
rules, err := parser.ParseRules()
if err != nil {
return result, err
}
result.Rules = rules
return result, nil
} | [
"func",
"(",
"parser",
"*",
"Parser",
")",
"ParseStylesheet",
"(",
")",
"(",
"*",
"css",
".",
"Stylesheet",
",",
"error",
")",
"{",
"result",
":=",
"css",
".",
"NewStylesheet",
"(",
")",
"\n\n",
"// Parse BOM",
"if",
"_",
",",
"err",
":=",
"parser",
".",
"parseBOM",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"// Parse list of rules",
"rules",
",",
"err",
":=",
"parser",
".",
"ParseRules",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"result",
".",
"Rules",
"=",
"rules",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // ParseStylesheet parses a stylesheet | [
"ParseStylesheet",
"parses",
"a",
"stylesheet"
] | f9e29746e1161076eae141dd235f5d98b546ec3e | https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L55-L72 |
64 | aymerick/douceur | parser/parser.go | ParseRules | func (parser *Parser) ParseRules() ([]*css.Rule, error) {
result := []*css.Rule{}
inBlock := false
if parser.tokenChar("{") {
// parsing a block of rules
inBlock = true
parser.embedLevel++
parser.shiftToken()
}
for parser.tokenParsable() {
if parser.tokenIgnorable() {
parser.shiftToken()
} else if parser.tokenChar("}") {
if !inBlock {
errMsg := fmt.Sprintf("Unexpected } character: %s", parser.nextToken().String())
return result, errors.New(errMsg)
}
parser.shiftToken()
parser.embedLevel--
// finished
break
} else {
rule, err := parser.ParseRule()
if err != nil {
return result, err
}
rule.EmbedLevel = parser.embedLevel
result = append(result, rule)
}
}
return result, parser.err()
} | go | func (parser *Parser) ParseRules() ([]*css.Rule, error) {
result := []*css.Rule{}
inBlock := false
if parser.tokenChar("{") {
// parsing a block of rules
inBlock = true
parser.embedLevel++
parser.shiftToken()
}
for parser.tokenParsable() {
if parser.tokenIgnorable() {
parser.shiftToken()
} else if parser.tokenChar("}") {
if !inBlock {
errMsg := fmt.Sprintf("Unexpected } character: %s", parser.nextToken().String())
return result, errors.New(errMsg)
}
parser.shiftToken()
parser.embedLevel--
// finished
break
} else {
rule, err := parser.ParseRule()
if err != nil {
return result, err
}
rule.EmbedLevel = parser.embedLevel
result = append(result, rule)
}
}
return result, parser.err()
} | [
"func",
"(",
"parser",
"*",
"Parser",
")",
"ParseRules",
"(",
")",
"(",
"[",
"]",
"*",
"css",
".",
"Rule",
",",
"error",
")",
"{",
"result",
":=",
"[",
"]",
"*",
"css",
".",
"Rule",
"{",
"}",
"\n\n",
"inBlock",
":=",
"false",
"\n",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"// parsing a block of rules",
"inBlock",
"=",
"true",
"\n",
"parser",
".",
"embedLevel",
"++",
"\n\n",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"parser",
".",
"tokenParsable",
"(",
")",
"{",
"if",
"parser",
".",
"tokenIgnorable",
"(",
")",
"{",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"}",
"else",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"if",
"!",
"inBlock",
"{",
"errMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"parser",
".",
"nextToken",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"result",
",",
"errors",
".",
"New",
"(",
"errMsg",
")",
"\n",
"}",
"\n\n",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"parser",
".",
"embedLevel",
"--",
"\n\n",
"// finished",
"break",
"\n",
"}",
"else",
"{",
"rule",
",",
"err",
":=",
"parser",
".",
"ParseRule",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"rule",
".",
"EmbedLevel",
"=",
"parser",
".",
"embedLevel",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"rule",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"parser",
".",
"err",
"(",
")",
"\n",
"}"
] | // ParseRules parses a list of rules | [
"ParseRules",
"parses",
"a",
"list",
"of",
"rules"
] | f9e29746e1161076eae141dd235f5d98b546ec3e | https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L75-L113 |
65 | aymerick/douceur | parser/parser.go | ParseRule | func (parser *Parser) ParseRule() (*css.Rule, error) {
if parser.tokenAtKeyword() {
return parser.parseAtRule()
}
return parser.parseQualifiedRule()
} | go | func (parser *Parser) ParseRule() (*css.Rule, error) {
if parser.tokenAtKeyword() {
return parser.parseAtRule()
}
return parser.parseQualifiedRule()
} | [
"func",
"(",
"parser",
"*",
"Parser",
")",
"ParseRule",
"(",
")",
"(",
"*",
"css",
".",
"Rule",
",",
"error",
")",
"{",
"if",
"parser",
".",
"tokenAtKeyword",
"(",
")",
"{",
"return",
"parser",
".",
"parseAtRule",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"parser",
".",
"parseQualifiedRule",
"(",
")",
"\n",
"}"
] | // ParseRule parses a rule | [
"ParseRule",
"parses",
"a",
"rule"
] | f9e29746e1161076eae141dd235f5d98b546ec3e | https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L116-L122 |
66 | aymerick/douceur | parser/parser.go | ParseDeclarations | func (parser *Parser) ParseDeclarations() ([]*css.Declaration, error) {
result := []*css.Declaration{}
if parser.tokenChar("{") {
parser.shiftToken()
}
for parser.tokenParsable() {
if parser.tokenIgnorable() {
parser.shiftToken()
} else if parser.tokenChar("}") {
// end of block
parser.shiftToken()
break
} else {
declaration, err := parser.ParseDeclaration()
if err != nil {
return result, err
}
result = append(result, declaration)
}
}
return result, parser.err()
} | go | func (parser *Parser) ParseDeclarations() ([]*css.Declaration, error) {
result := []*css.Declaration{}
if parser.tokenChar("{") {
parser.shiftToken()
}
for parser.tokenParsable() {
if parser.tokenIgnorable() {
parser.shiftToken()
} else if parser.tokenChar("}") {
// end of block
parser.shiftToken()
break
} else {
declaration, err := parser.ParseDeclaration()
if err != nil {
return result, err
}
result = append(result, declaration)
}
}
return result, parser.err()
} | [
"func",
"(",
"parser",
"*",
"Parser",
")",
"ParseDeclarations",
"(",
")",
"(",
"[",
"]",
"*",
"css",
".",
"Declaration",
",",
"error",
")",
"{",
"result",
":=",
"[",
"]",
"*",
"css",
".",
"Declaration",
"{",
"}",
"\n\n",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"parser",
".",
"tokenParsable",
"(",
")",
"{",
"if",
"parser",
".",
"tokenIgnorable",
"(",
")",
"{",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"}",
"else",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"// end of block",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"break",
"\n",
"}",
"else",
"{",
"declaration",
",",
"err",
":=",
"parser",
".",
"ParseDeclaration",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"result",
"=",
"append",
"(",
"result",
",",
"declaration",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"parser",
".",
"err",
"(",
")",
"\n",
"}"
] | // ParseDeclarations parses a list of declarations | [
"ParseDeclarations",
"parses",
"a",
"list",
"of",
"declarations"
] | f9e29746e1161076eae141dd235f5d98b546ec3e | https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L125-L150 |
67 | aymerick/douceur | parser/parser.go | ParseDeclaration | func (parser *Parser) ParseDeclaration() (*css.Declaration, error) {
result := css.NewDeclaration()
curValue := ""
for parser.tokenParsable() {
if parser.tokenChar(":") {
result.Property = strings.TrimSpace(curValue)
curValue = ""
parser.shiftToken()
} else if parser.tokenChar(";") || parser.tokenChar("}") {
if result.Property == "" {
errMsg := fmt.Sprintf("Unexpected ; character: %s", parser.nextToken().String())
return result, errors.New(errMsg)
}
if importantRegexp.MatchString(curValue) {
result.Important = true
curValue = importantRegexp.ReplaceAllString(curValue, "")
}
result.Value = strings.TrimSpace(curValue)
if parser.tokenChar(";") {
parser.shiftToken()
}
// finished
break
} else {
token := parser.shiftToken()
curValue += token.Value
}
}
// log.Printf("[parsed] Declaration: %s", result.String())
return result, parser.err()
} | go | func (parser *Parser) ParseDeclaration() (*css.Declaration, error) {
result := css.NewDeclaration()
curValue := ""
for parser.tokenParsable() {
if parser.tokenChar(":") {
result.Property = strings.TrimSpace(curValue)
curValue = ""
parser.shiftToken()
} else if parser.tokenChar(";") || parser.tokenChar("}") {
if result.Property == "" {
errMsg := fmt.Sprintf("Unexpected ; character: %s", parser.nextToken().String())
return result, errors.New(errMsg)
}
if importantRegexp.MatchString(curValue) {
result.Important = true
curValue = importantRegexp.ReplaceAllString(curValue, "")
}
result.Value = strings.TrimSpace(curValue)
if parser.tokenChar(";") {
parser.shiftToken()
}
// finished
break
} else {
token := parser.shiftToken()
curValue += token.Value
}
}
// log.Printf("[parsed] Declaration: %s", result.String())
return result, parser.err()
} | [
"func",
"(",
"parser",
"*",
"Parser",
")",
"ParseDeclaration",
"(",
")",
"(",
"*",
"css",
".",
"Declaration",
",",
"error",
")",
"{",
"result",
":=",
"css",
".",
"NewDeclaration",
"(",
")",
"\n",
"curValue",
":=",
"\"",
"\"",
"\n\n",
"for",
"parser",
".",
"tokenParsable",
"(",
")",
"{",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"result",
".",
"Property",
"=",
"strings",
".",
"TrimSpace",
"(",
"curValue",
")",
"\n",
"curValue",
"=",
"\"",
"\"",
"\n\n",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"}",
"else",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"||",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"if",
"result",
".",
"Property",
"==",
"\"",
"\"",
"{",
"errMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"parser",
".",
"nextToken",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"result",
",",
"errors",
".",
"New",
"(",
"errMsg",
")",
"\n",
"}",
"\n\n",
"if",
"importantRegexp",
".",
"MatchString",
"(",
"curValue",
")",
"{",
"result",
".",
"Important",
"=",
"true",
"\n",
"curValue",
"=",
"importantRegexp",
".",
"ReplaceAllString",
"(",
"curValue",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"result",
".",
"Value",
"=",
"strings",
".",
"TrimSpace",
"(",
"curValue",
")",
"\n\n",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"}",
"\n\n",
"// finished",
"break",
"\n",
"}",
"else",
"{",
"token",
":=",
"parser",
".",
"shiftToken",
"(",
")",
"\n",
"curValue",
"+=",
"token",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n\n",
"// log.Printf(\"[parsed] Declaration: %s\", result.String())",
"return",
"result",
",",
"parser",
".",
"err",
"(",
")",
"\n",
"}"
] | // ParseDeclaration parses a declaration | [
"ParseDeclaration",
"parses",
"a",
"declaration"
] | f9e29746e1161076eae141dd235f5d98b546ec3e | https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L153-L191 |
68 | aymerick/douceur | parser/parser.go | parseAtRule | func (parser *Parser) parseAtRule() (*css.Rule, error) {
// parse rule name (eg: "@import")
token := parser.shiftToken()
result := css.NewRule(css.AtRule)
result.Name = token.Value
for parser.tokenParsable() {
if parser.tokenChar(";") {
parser.shiftToken()
// finished
break
} else if parser.tokenChar("{") {
if result.EmbedsRules() {
// parse rules block
rules, err := parser.ParseRules()
if err != nil {
return result, err
}
result.Rules = rules
} else {
// parse declarations block
declarations, err := parser.ParseDeclarations()
if err != nil {
return result, err
}
result.Declarations = declarations
}
// finished
break
} else {
// parse prelude
prelude, err := parser.parsePrelude()
if err != nil {
return result, err
}
result.Prelude = prelude
}
}
// log.Printf("[parsed] Rule: %s", result.String())
return result, parser.err()
} | go | func (parser *Parser) parseAtRule() (*css.Rule, error) {
// parse rule name (eg: "@import")
token := parser.shiftToken()
result := css.NewRule(css.AtRule)
result.Name = token.Value
for parser.tokenParsable() {
if parser.tokenChar(";") {
parser.shiftToken()
// finished
break
} else if parser.tokenChar("{") {
if result.EmbedsRules() {
// parse rules block
rules, err := parser.ParseRules()
if err != nil {
return result, err
}
result.Rules = rules
} else {
// parse declarations block
declarations, err := parser.ParseDeclarations()
if err != nil {
return result, err
}
result.Declarations = declarations
}
// finished
break
} else {
// parse prelude
prelude, err := parser.parsePrelude()
if err != nil {
return result, err
}
result.Prelude = prelude
}
}
// log.Printf("[parsed] Rule: %s", result.String())
return result, parser.err()
} | [
"func",
"(",
"parser",
"*",
"Parser",
")",
"parseAtRule",
"(",
")",
"(",
"*",
"css",
".",
"Rule",
",",
"error",
")",
"{",
"// parse rule name (eg: \"@import\")",
"token",
":=",
"parser",
".",
"shiftToken",
"(",
")",
"\n\n",
"result",
":=",
"css",
".",
"NewRule",
"(",
"css",
".",
"AtRule",
")",
"\n",
"result",
".",
"Name",
"=",
"token",
".",
"Value",
"\n\n",
"for",
"parser",
".",
"tokenParsable",
"(",
")",
"{",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"parser",
".",
"shiftToken",
"(",
")",
"\n\n",
"// finished",
"break",
"\n",
"}",
"else",
"if",
"parser",
".",
"tokenChar",
"(",
"\"",
"\"",
")",
"{",
"if",
"result",
".",
"EmbedsRules",
"(",
")",
"{",
"// parse rules block",
"rules",
",",
"err",
":=",
"parser",
".",
"ParseRules",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"result",
".",
"Rules",
"=",
"rules",
"\n",
"}",
"else",
"{",
"// parse declarations block",
"declarations",
",",
"err",
":=",
"parser",
".",
"ParseDeclarations",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"result",
".",
"Declarations",
"=",
"declarations",
"\n",
"}",
"\n\n",
"// finished",
"break",
"\n",
"}",
"else",
"{",
"// parse prelude",
"prelude",
",",
"err",
":=",
"parser",
".",
"parsePrelude",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n\n",
"result",
".",
"Prelude",
"=",
"prelude",
"\n",
"}",
"\n",
"}",
"\n\n",
"// log.Printf(\"[parsed] Rule: %s\", result.String())",
"return",
"result",
",",
"parser",
".",
"err",
"(",
")",
"\n",
"}"
] | // Parse an At Rule | [
"Parse",
"an",
"At",
"Rule"
] | f9e29746e1161076eae141dd235f5d98b546ec3e | https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/parser/parser.go#L194-L242 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 56