repository_name
stringlengths 5
54
| func_path_in_repository
stringlengths 4
155
| func_name
stringlengths 1
118
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 1
value | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 21
188k
| func_documentation_string
stringlengths 4
26.3k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|
go-gl/mathgl | mgl64/matrix.go | Mul | func (m1 Mat4x2) Mul(c float64) Mat4x2 {
return Mat4x2{m1[0] * c, m1[1] * c, m1[2] * c, m1[3] * c, m1[4] * c, m1[5] * c, m1[6] * c, m1[7] * c}
} | go | func (m1 Mat4x2) Mul(c float64) Mat4x2 {
return Mat4x2{m1[0] * c, m1[1] * c, m1[2] * c, m1[3] * c, m1[4] * c, m1[5] * c, m1[6] * c, m1[7] * c}
} | [
"func",
"(",
"m1",
"Mat4x2",
")",
"Mul",
"(",
"c",
"float64",
")",
"Mat4x2",
"{",
"return",
"Mat4x2",
"{",
"m1",
"[",
"0",
"]",
"*",
"c",
",",
"m1",
"[",
"1",
"]",
"*",
"c",
",",
"m1",
"[",
"2",
"]",
"*",
"c",
",",
"m1",
"[",
"3",
"]",
"*",
"c",
",",
"m1",
"[",
"4",
"]",
"*",
"c",
",",
"m1",
"[",
"5",
"]",
"*",
"c",
",",
"m1",
"[",
"6",
"]",
"*",
"c",
",",
"m1",
"[",
"7",
"]",
"*",
"c",
"}",
"\n",
"}"
] | // Mul performs a scalar multiplcation of the matrix. This is equivalent to iterating
// over every element of the matrix and multiply it by c. | [
"Mul",
"performs",
"a",
"scalar",
"multiplcation",
"of",
"the",
"matrix",
".",
"This",
"is",
"equivalent",
"to",
"iterating",
"over",
"every",
"element",
"of",
"the",
"matrix",
"and",
"multiply",
"it",
"by",
"c",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L1591-L1593 |
go-gl/mathgl | mgl64/matrix.go | At | func (m Mat4x2) At(row, col int) float64 {
return m[col*4+row]
} | go | func (m Mat4x2) At(row, col int) float64 {
return m[col*4+row]
} | [
"func",
"(",
"m",
"Mat4x2",
")",
"At",
"(",
"row",
",",
"col",
"int",
")",
"float64",
"{",
"return",
"m",
"[",
"col",
"*",
"4",
"+",
"row",
"]",
"\n",
"}"
] | // At returns the matrix element at the given row and column.
// This is equivalent to mat[col * numRow + row] where numRow is constant
// (E.G. for a Mat3x2 it's equal to 3)
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// At(5,0) will work just like At(1,1). Or it may panic if it's out of bounds. | [
"At",
"returns",
"the",
"matrix",
"element",
"at",
"the",
"given",
"row",
"and",
"column",
".",
"This",
"is",
"equivalent",
"to",
"mat",
"[",
"col",
"*",
"numRow",
"+",
"row",
"]",
"where",
"numRow",
"is",
"constant",
"(",
"E",
".",
"G",
".",
"for",
"a",
"Mat3x2",
"it",
"s",
"equal",
"to",
"3",
")",
"This",
"method",
"is",
"garbage",
"-",
"in",
"garbage",
"-",
"out",
".",
"For",
"instance",
"on",
"a",
"Mat4",
"asking",
"for",
"At",
"(",
"5",
"0",
")",
"will",
"work",
"just",
"like",
"At",
"(",
"1",
"1",
")",
".",
"Or",
"it",
"may",
"panic",
"if",
"it",
"s",
"out",
"of",
"bounds",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L1722-L1724 |
go-gl/mathgl | mgl64/matrix.go | Set | func (m *Mat4x2) Set(row, col int, value float64) {
m[col*4+row] = value
} | go | func (m *Mat4x2) Set(row, col int, value float64) {
m[col*4+row] = value
} | [
"func",
"(",
"m",
"*",
"Mat4x2",
")",
"Set",
"(",
"row",
",",
"col",
"int",
",",
"value",
"float64",
")",
"{",
"m",
"[",
"col",
"*",
"4",
"+",
"row",
"]",
"=",
"value",
"\n",
"}"
] | // Set sets the corresponding matrix element at the given row and column.
// This has a pointer receiver because it mutates the matrix.
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// Set(5,0,val) will work just like Set(1,1,val). Or it may panic if it's out of bounds. | [
"Set",
"sets",
"the",
"corresponding",
"matrix",
"element",
"at",
"the",
"given",
"row",
"and",
"column",
".",
"This",
"has",
"a",
"pointer",
"receiver",
"because",
"it",
"mutates",
"the",
"matrix",
".",
"This",
"method",
"is",
"garbage",
"-",
"in",
"garbage",
"-",
"out",
".",
"For",
"instance",
"on",
"a",
"Mat4",
"asking",
"for",
"Set",
"(",
"5",
"0",
"val",
")",
"will",
"work",
"just",
"like",
"Set",
"(",
"1",
"1",
"val",
")",
".",
"Or",
"it",
"may",
"panic",
"if",
"it",
"s",
"out",
"of",
"bounds",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L1731-L1733 |
go-gl/mathgl | mgl64/matrix.go | Mul | func (m1 Mat4x3) Mul(c float64) Mat4x3 {
return Mat4x3{m1[0] * c, m1[1] * c, m1[2] * c, m1[3] * c, m1[4] * c, m1[5] * c, m1[6] * c, m1[7] * c, m1[8] * c, m1[9] * c, m1[10] * c, m1[11] * c}
} | go | func (m1 Mat4x3) Mul(c float64) Mat4x3 {
return Mat4x3{m1[0] * c, m1[1] * c, m1[2] * c, m1[3] * c, m1[4] * c, m1[5] * c, m1[6] * c, m1[7] * c, m1[8] * c, m1[9] * c, m1[10] * c, m1[11] * c}
} | [
"func",
"(",
"m1",
"Mat4x3",
")",
"Mul",
"(",
"c",
"float64",
")",
"Mat4x3",
"{",
"return",
"Mat4x3",
"{",
"m1",
"[",
"0",
"]",
"*",
"c",
",",
"m1",
"[",
"1",
"]",
"*",
"c",
",",
"m1",
"[",
"2",
"]",
"*",
"c",
",",
"m1",
"[",
"3",
"]",
"*",
"c",
",",
"m1",
"[",
"4",
"]",
"*",
"c",
",",
"m1",
"[",
"5",
"]",
"*",
"c",
",",
"m1",
"[",
"6",
"]",
"*",
"c",
",",
"m1",
"[",
"7",
"]",
"*",
"c",
",",
"m1",
"[",
"8",
"]",
"*",
"c",
",",
"m1",
"[",
"9",
"]",
"*",
"c",
",",
"m1",
"[",
"10",
"]",
"*",
"c",
",",
"m1",
"[",
"11",
"]",
"*",
"c",
"}",
"\n",
"}"
] | // Mul performs a scalar multiplcation of the matrix. This is equivalent to iterating
// over every element of the matrix and multiply it by c. | [
"Mul",
"performs",
"a",
"scalar",
"multiplcation",
"of",
"the",
"matrix",
".",
"This",
"is",
"equivalent",
"to",
"iterating",
"over",
"every",
"element",
"of",
"the",
"matrix",
"and",
"multiply",
"it",
"by",
"c",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L1829-L1831 |
go-gl/mathgl | mgl64/matrix.go | At | func (m Mat4x3) At(row, col int) float64 {
return m[col*4+row]
} | go | func (m Mat4x3) At(row, col int) float64 {
return m[col*4+row]
} | [
"func",
"(",
"m",
"Mat4x3",
")",
"At",
"(",
"row",
",",
"col",
"int",
")",
"float64",
"{",
"return",
"m",
"[",
"col",
"*",
"4",
"+",
"row",
"]",
"\n",
"}"
] | // At returns the matrix element at the given row and column.
// This is equivalent to mat[col * numRow + row] where numRow is constant
// (E.G. for a Mat3x2 it's equal to 3)
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// At(5,0) will work just like At(1,1). Or it may panic if it's out of bounds. | [
"At",
"returns",
"the",
"matrix",
"element",
"at",
"the",
"given",
"row",
"and",
"column",
".",
"This",
"is",
"equivalent",
"to",
"mat",
"[",
"col",
"*",
"numRow",
"+",
"row",
"]",
"where",
"numRow",
"is",
"constant",
"(",
"E",
".",
"G",
".",
"for",
"a",
"Mat3x2",
"it",
"s",
"equal",
"to",
"3",
")",
"This",
"method",
"is",
"garbage",
"-",
"in",
"garbage",
"-",
"out",
".",
"For",
"instance",
"on",
"a",
"Mat4",
"asking",
"for",
"At",
"(",
"5",
"0",
")",
"will",
"work",
"just",
"like",
"At",
"(",
"1",
"1",
")",
".",
"Or",
"it",
"may",
"panic",
"if",
"it",
"s",
"out",
"of",
"bounds",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L1960-L1962 |
go-gl/mathgl | mgl64/matrix.go | Set | func (m *Mat4x3) Set(row, col int, value float64) {
m[col*4+row] = value
} | go | func (m *Mat4x3) Set(row, col int, value float64) {
m[col*4+row] = value
} | [
"func",
"(",
"m",
"*",
"Mat4x3",
")",
"Set",
"(",
"row",
",",
"col",
"int",
",",
"value",
"float64",
")",
"{",
"m",
"[",
"col",
"*",
"4",
"+",
"row",
"]",
"=",
"value",
"\n",
"}"
] | // Set sets the corresponding matrix element at the given row and column.
// This has a pointer receiver because it mutates the matrix.
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// Set(5,0,val) will work just like Set(1,1,val). Or it may panic if it's out of bounds. | [
"Set",
"sets",
"the",
"corresponding",
"matrix",
"element",
"at",
"the",
"given",
"row",
"and",
"column",
".",
"This",
"has",
"a",
"pointer",
"receiver",
"because",
"it",
"mutates",
"the",
"matrix",
".",
"This",
"method",
"is",
"garbage",
"-",
"in",
"garbage",
"-",
"out",
".",
"For",
"instance",
"on",
"a",
"Mat4",
"asking",
"for",
"Set",
"(",
"5",
"0",
"val",
")",
"will",
"work",
"just",
"like",
"Set",
"(",
"1",
"1",
"val",
")",
".",
"Or",
"it",
"may",
"panic",
"if",
"it",
"s",
"out",
"of",
"bounds",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L1969-L1971 |
go-gl/mathgl | mgl64/matrix.go | Mul | func (m1 Mat4) Mul(c float64) Mat4 {
return Mat4{m1[0] * c, m1[1] * c, m1[2] * c, m1[3] * c, m1[4] * c, m1[5] * c, m1[6] * c, m1[7] * c, m1[8] * c, m1[9] * c, m1[10] * c, m1[11] * c, m1[12] * c, m1[13] * c, m1[14] * c, m1[15] * c}
} | go | func (m1 Mat4) Mul(c float64) Mat4 {
return Mat4{m1[0] * c, m1[1] * c, m1[2] * c, m1[3] * c, m1[4] * c, m1[5] * c, m1[6] * c, m1[7] * c, m1[8] * c, m1[9] * c, m1[10] * c, m1[11] * c, m1[12] * c, m1[13] * c, m1[14] * c, m1[15] * c}
} | [
"func",
"(",
"m1",
"Mat4",
")",
"Mul",
"(",
"c",
"float64",
")",
"Mat4",
"{",
"return",
"Mat4",
"{",
"m1",
"[",
"0",
"]",
"*",
"c",
",",
"m1",
"[",
"1",
"]",
"*",
"c",
",",
"m1",
"[",
"2",
"]",
"*",
"c",
",",
"m1",
"[",
"3",
"]",
"*",
"c",
",",
"m1",
"[",
"4",
"]",
"*",
"c",
",",
"m1",
"[",
"5",
"]",
"*",
"c",
",",
"m1",
"[",
"6",
"]",
"*",
"c",
",",
"m1",
"[",
"7",
"]",
"*",
"c",
",",
"m1",
"[",
"8",
"]",
"*",
"c",
",",
"m1",
"[",
"9",
"]",
"*",
"c",
",",
"m1",
"[",
"10",
"]",
"*",
"c",
",",
"m1",
"[",
"11",
"]",
"*",
"c",
",",
"m1",
"[",
"12",
"]",
"*",
"c",
",",
"m1",
"[",
"13",
"]",
"*",
"c",
",",
"m1",
"[",
"14",
"]",
"*",
"c",
",",
"m1",
"[",
"15",
"]",
"*",
"c",
"}",
"\n",
"}"
] | // Mul performs a scalar multiplcation of the matrix. This is equivalent to iterating
// over every element of the matrix and multiply it by c. | [
"Mul",
"performs",
"a",
"scalar",
"multiplcation",
"of",
"the",
"matrix",
".",
"This",
"is",
"equivalent",
"to",
"iterating",
"over",
"every",
"element",
"of",
"the",
"matrix",
"and",
"multiply",
"it",
"by",
"c",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L2091-L2093 |
go-gl/mathgl | mgl64/matrix.go | Det | func (m Mat4) Det() float64 {
return m[0]*m[5]*m[10]*m[15] - m[0]*m[5]*m[11]*m[14] - m[0]*m[6]*m[9]*m[15] + m[0]*m[6]*m[11]*m[13] + m[0]*m[7]*m[9]*m[14] - m[0]*m[7]*m[10]*m[13] - m[1]*m[4]*m[10]*m[15] + m[1]*m[4]*m[11]*m[14] + m[1]*m[6]*m[8]*m[15] - m[1]*m[6]*m[11]*m[12] - m[1]*m[7]*m[8]*m[14] + m[1]*m[7]*m[10]*m[12] + m[2]*m[4]*m[9]*m[15] - m[2]*m[4]*m[11]*m[13] - m[2]*m[5]*m[8]*m[15] + m[2]*m[5]*m[11]*m[12] + m[2]*m[7]*m[8]*m[13] - m[2]*m[7]*m[9]*m[12] - m[3]*m[4]*m[9]*m[14] + m[3]*m[4]*m[10]*m[13] + m[3]*m[5]*m[8]*m[14] - m[3]*m[5]*m[10]*m[12] - m[3]*m[6]*m[8]*m[13] + m[3]*m[6]*m[9]*m[12]
} | go | func (m Mat4) Det() float64 {
return m[0]*m[5]*m[10]*m[15] - m[0]*m[5]*m[11]*m[14] - m[0]*m[6]*m[9]*m[15] + m[0]*m[6]*m[11]*m[13] + m[0]*m[7]*m[9]*m[14] - m[0]*m[7]*m[10]*m[13] - m[1]*m[4]*m[10]*m[15] + m[1]*m[4]*m[11]*m[14] + m[1]*m[6]*m[8]*m[15] - m[1]*m[6]*m[11]*m[12] - m[1]*m[7]*m[8]*m[14] + m[1]*m[7]*m[10]*m[12] + m[2]*m[4]*m[9]*m[15] - m[2]*m[4]*m[11]*m[13] - m[2]*m[5]*m[8]*m[15] + m[2]*m[5]*m[11]*m[12] + m[2]*m[7]*m[8]*m[13] - m[2]*m[7]*m[9]*m[12] - m[3]*m[4]*m[9]*m[14] + m[3]*m[4]*m[10]*m[13] + m[3]*m[5]*m[8]*m[14] - m[3]*m[5]*m[10]*m[12] - m[3]*m[6]*m[8]*m[13] + m[3]*m[6]*m[9]*m[12]
} | [
"func",
"(",
"m",
"Mat4",
")",
"Det",
"(",
")",
"float64",
"{",
"return",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"12",
"]",
"\n",
"}"
] | // Det returns the determinant of a matrix. It is a measure of a square matrix's
// singularity and invertability, among other things. In this library, the
// determinant is hard coded based on pre-computed cofactor expansion, and uses
// no loops. Of course, the addition and multiplication must still be done. | [
"Det",
"returns",
"the",
"determinant",
"of",
"a",
"matrix",
".",
"It",
"is",
"a",
"measure",
"of",
"a",
"square",
"matrix",
"s",
"singularity",
"and",
"invertability",
"among",
"other",
"things",
".",
"In",
"this",
"library",
"the",
"determinant",
"is",
"hard",
"coded",
"based",
"on",
"pre",
"-",
"computed",
"cofactor",
"expansion",
"and",
"uses",
"no",
"loops",
".",
"Of",
"course",
"the",
"addition",
"and",
"multiplication",
"must",
"still",
"be",
"done",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L2186-L2188 |
go-gl/mathgl | mgl64/matrix.go | Inv | func (m Mat4) Inv() Mat4 {
det := m.Det()
if FloatEqual(det, float64(0.0)) {
return Mat4{}
}
retMat := Mat4{
-m[7]*m[10]*m[13] + m[6]*m[11]*m[13] + m[7]*m[9]*m[14] - m[5]*m[11]*m[14] - m[6]*m[9]*m[15] + m[5]*m[10]*m[15],
m[3]*m[10]*m[13] - m[2]*m[11]*m[13] - m[3]*m[9]*m[14] + m[1]*m[11]*m[14] + m[2]*m[9]*m[15] - m[1]*m[10]*m[15],
-m[3]*m[6]*m[13] + m[2]*m[7]*m[13] + m[3]*m[5]*m[14] - m[1]*m[7]*m[14] - m[2]*m[5]*m[15] + m[1]*m[6]*m[15],
m[3]*m[6]*m[9] - m[2]*m[7]*m[9] - m[3]*m[5]*m[10] + m[1]*m[7]*m[10] + m[2]*m[5]*m[11] - m[1]*m[6]*m[11],
m[7]*m[10]*m[12] - m[6]*m[11]*m[12] - m[7]*m[8]*m[14] + m[4]*m[11]*m[14] + m[6]*m[8]*m[15] - m[4]*m[10]*m[15],
-m[3]*m[10]*m[12] + m[2]*m[11]*m[12] + m[3]*m[8]*m[14] - m[0]*m[11]*m[14] - m[2]*m[8]*m[15] + m[0]*m[10]*m[15],
m[3]*m[6]*m[12] - m[2]*m[7]*m[12] - m[3]*m[4]*m[14] + m[0]*m[7]*m[14] + m[2]*m[4]*m[15] - m[0]*m[6]*m[15],
-m[3]*m[6]*m[8] + m[2]*m[7]*m[8] + m[3]*m[4]*m[10] - m[0]*m[7]*m[10] - m[2]*m[4]*m[11] + m[0]*m[6]*m[11],
-m[7]*m[9]*m[12] + m[5]*m[11]*m[12] + m[7]*m[8]*m[13] - m[4]*m[11]*m[13] - m[5]*m[8]*m[15] + m[4]*m[9]*m[15],
m[3]*m[9]*m[12] - m[1]*m[11]*m[12] - m[3]*m[8]*m[13] + m[0]*m[11]*m[13] + m[1]*m[8]*m[15] - m[0]*m[9]*m[15],
-m[3]*m[5]*m[12] + m[1]*m[7]*m[12] + m[3]*m[4]*m[13] - m[0]*m[7]*m[13] - m[1]*m[4]*m[15] + m[0]*m[5]*m[15],
m[3]*m[5]*m[8] - m[1]*m[7]*m[8] - m[3]*m[4]*m[9] + m[0]*m[7]*m[9] + m[1]*m[4]*m[11] - m[0]*m[5]*m[11],
m[6]*m[9]*m[12] - m[5]*m[10]*m[12] - m[6]*m[8]*m[13] + m[4]*m[10]*m[13] + m[5]*m[8]*m[14] - m[4]*m[9]*m[14],
-m[2]*m[9]*m[12] + m[1]*m[10]*m[12] + m[2]*m[8]*m[13] - m[0]*m[10]*m[13] - m[1]*m[8]*m[14] + m[0]*m[9]*m[14],
m[2]*m[5]*m[12] - m[1]*m[6]*m[12] - m[2]*m[4]*m[13] + m[0]*m[6]*m[13] + m[1]*m[4]*m[14] - m[0]*m[5]*m[14],
-m[2]*m[5]*m[8] + m[1]*m[6]*m[8] + m[2]*m[4]*m[9] - m[0]*m[6]*m[9] - m[1]*m[4]*m[10] + m[0]*m[5]*m[10],
}
return retMat.Mul(1 / det)
} | go | func (m Mat4) Inv() Mat4 {
det := m.Det()
if FloatEqual(det, float64(0.0)) {
return Mat4{}
}
retMat := Mat4{
-m[7]*m[10]*m[13] + m[6]*m[11]*m[13] + m[7]*m[9]*m[14] - m[5]*m[11]*m[14] - m[6]*m[9]*m[15] + m[5]*m[10]*m[15],
m[3]*m[10]*m[13] - m[2]*m[11]*m[13] - m[3]*m[9]*m[14] + m[1]*m[11]*m[14] + m[2]*m[9]*m[15] - m[1]*m[10]*m[15],
-m[3]*m[6]*m[13] + m[2]*m[7]*m[13] + m[3]*m[5]*m[14] - m[1]*m[7]*m[14] - m[2]*m[5]*m[15] + m[1]*m[6]*m[15],
m[3]*m[6]*m[9] - m[2]*m[7]*m[9] - m[3]*m[5]*m[10] + m[1]*m[7]*m[10] + m[2]*m[5]*m[11] - m[1]*m[6]*m[11],
m[7]*m[10]*m[12] - m[6]*m[11]*m[12] - m[7]*m[8]*m[14] + m[4]*m[11]*m[14] + m[6]*m[8]*m[15] - m[4]*m[10]*m[15],
-m[3]*m[10]*m[12] + m[2]*m[11]*m[12] + m[3]*m[8]*m[14] - m[0]*m[11]*m[14] - m[2]*m[8]*m[15] + m[0]*m[10]*m[15],
m[3]*m[6]*m[12] - m[2]*m[7]*m[12] - m[3]*m[4]*m[14] + m[0]*m[7]*m[14] + m[2]*m[4]*m[15] - m[0]*m[6]*m[15],
-m[3]*m[6]*m[8] + m[2]*m[7]*m[8] + m[3]*m[4]*m[10] - m[0]*m[7]*m[10] - m[2]*m[4]*m[11] + m[0]*m[6]*m[11],
-m[7]*m[9]*m[12] + m[5]*m[11]*m[12] + m[7]*m[8]*m[13] - m[4]*m[11]*m[13] - m[5]*m[8]*m[15] + m[4]*m[9]*m[15],
m[3]*m[9]*m[12] - m[1]*m[11]*m[12] - m[3]*m[8]*m[13] + m[0]*m[11]*m[13] + m[1]*m[8]*m[15] - m[0]*m[9]*m[15],
-m[3]*m[5]*m[12] + m[1]*m[7]*m[12] + m[3]*m[4]*m[13] - m[0]*m[7]*m[13] - m[1]*m[4]*m[15] + m[0]*m[5]*m[15],
m[3]*m[5]*m[8] - m[1]*m[7]*m[8] - m[3]*m[4]*m[9] + m[0]*m[7]*m[9] + m[1]*m[4]*m[11] - m[0]*m[5]*m[11],
m[6]*m[9]*m[12] - m[5]*m[10]*m[12] - m[6]*m[8]*m[13] + m[4]*m[10]*m[13] + m[5]*m[8]*m[14] - m[4]*m[9]*m[14],
-m[2]*m[9]*m[12] + m[1]*m[10]*m[12] + m[2]*m[8]*m[13] - m[0]*m[10]*m[13] - m[1]*m[8]*m[14] + m[0]*m[9]*m[14],
m[2]*m[5]*m[12] - m[1]*m[6]*m[12] - m[2]*m[4]*m[13] + m[0]*m[6]*m[13] + m[1]*m[4]*m[14] - m[0]*m[5]*m[14],
-m[2]*m[5]*m[8] + m[1]*m[6]*m[8] + m[2]*m[4]*m[9] - m[0]*m[6]*m[9] - m[1]*m[4]*m[10] + m[0]*m[5]*m[10],
}
return retMat.Mul(1 / det)
} | [
"func",
"(",
"m",
"Mat4",
")",
"Inv",
"(",
")",
"Mat4",
"{",
"det",
":=",
"m",
".",
"Det",
"(",
")",
"\n",
"if",
"FloatEqual",
"(",
"det",
",",
"float64",
"(",
"0.0",
")",
")",
"{",
"return",
"Mat4",
"{",
"}",
"\n",
"}",
"\n\n",
"retMat",
":=",
"Mat4",
"{",
"-",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"9",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"9",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"10",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"10",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"11",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"11",
"]",
",",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"8",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"8",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"10",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"10",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"11",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"11",
"]",
",",
"-",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"11",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"15",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"15",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"15",
"]",
",",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"8",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"8",
"]",
"-",
"m",
"[",
"3",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"9",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"7",
"]",
"*",
"m",
"[",
"9",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"11",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"11",
"]",
",",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"14",
"]",
",",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"12",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"10",
"]",
"*",
"m",
"[",
"13",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"8",
"]",
"*",
"m",
"[",
"14",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"9",
"]",
"*",
"m",
"[",
"14",
"]",
",",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"12",
"]",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"13",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"14",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"14",
"]",
",",
"-",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"8",
"]",
"+",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"8",
"]",
"+",
"m",
"[",
"2",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"9",
"]",
"-",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"6",
"]",
"*",
"m",
"[",
"9",
"]",
"-",
"m",
"[",
"1",
"]",
"*",
"m",
"[",
"4",
"]",
"*",
"m",
"[",
"10",
"]",
"+",
"m",
"[",
"0",
"]",
"*",
"m",
"[",
"5",
"]",
"*",
"m",
"[",
"10",
"]",
",",
"}",
"\n\n",
"return",
"retMat",
".",
"Mul",
"(",
"1",
"/",
"det",
")",
"\n",
"}"
] | // Inv computes the inverse of a square matrix. An inverse is a square matrix such that when multiplied by the
// original, yields the identity.
//
// M_inv * M = M * M_inv = I
//
// In this library, the math is precomputed, and uses no loops, though the multiplications, additions, determinant calculation, and scaling
// are still done. This can still be (relatively) expensive for a 4x4.
//
// This function checks the determinant to see if the matrix is invertible.
// If the determinant is 0.0, this function returns the zero matrix. However, due to floating point errors, it is
// entirely plausible to get a false positive or negative.
// In the future, an alternate function may be written which takes in a pre-computed determinant. | [
"Inv",
"computes",
"the",
"inverse",
"of",
"a",
"square",
"matrix",
".",
"An",
"inverse",
"is",
"a",
"square",
"matrix",
"such",
"that",
"when",
"multiplied",
"by",
"the",
"original",
"yields",
"the",
"identity",
".",
"M_inv",
"*",
"M",
"=",
"M",
"*",
"M_inv",
"=",
"I",
"In",
"this",
"library",
"the",
"math",
"is",
"precomputed",
"and",
"uses",
"no",
"loops",
"though",
"the",
"multiplications",
"additions",
"determinant",
"calculation",
"and",
"scaling",
"are",
"still",
"done",
".",
"This",
"can",
"still",
"be",
"(",
"relatively",
")",
"expensive",
"for",
"a",
"4x4",
".",
"This",
"function",
"checks",
"the",
"determinant",
"to",
"see",
"if",
"the",
"matrix",
"is",
"invertible",
".",
"If",
"the",
"determinant",
"is",
"0",
".",
"0",
"this",
"function",
"returns",
"the",
"zero",
"matrix",
".",
"However",
"due",
"to",
"floating",
"point",
"errors",
"it",
"is",
"entirely",
"plausible",
"to",
"get",
"a",
"false",
"positive",
"or",
"negative",
".",
"In",
"the",
"future",
"an",
"alternate",
"function",
"may",
"be",
"written",
"which",
"takes",
"in",
"a",
"pre",
"-",
"computed",
"determinant",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L2202-L2228 |
go-gl/mathgl | mgl64/matrix.go | At | func (m Mat4) At(row, col int) float64 {
return m[col*4+row]
} | go | func (m Mat4) At(row, col int) float64 {
return m[col*4+row]
} | [
"func",
"(",
"m",
"Mat4",
")",
"At",
"(",
"row",
",",
"col",
"int",
")",
"float64",
"{",
"return",
"m",
"[",
"col",
"*",
"4",
"+",
"row",
"]",
"\n",
"}"
] | // At returns the matrix element at the given row and column.
// This is equivalent to mat[col * numRow + row] where numRow is constant
// (E.G. for a Mat3x2 it's equal to 3)
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// At(5,0) will work just like At(1,1). Or it may panic if it's out of bounds. | [
"At",
"returns",
"the",
"matrix",
"element",
"at",
"the",
"given",
"row",
"and",
"column",
".",
"This",
"is",
"equivalent",
"to",
"mat",
"[",
"col",
"*",
"numRow",
"+",
"row",
"]",
"where",
"numRow",
"is",
"constant",
"(",
"E",
".",
"G",
".",
"for",
"a",
"Mat3x2",
"it",
"s",
"equal",
"to",
"3",
")",
"This",
"method",
"is",
"garbage",
"-",
"in",
"garbage",
"-",
"out",
".",
"For",
"instance",
"on",
"a",
"Mat4",
"asking",
"for",
"At",
"(",
"5",
"0",
")",
"will",
"work",
"just",
"like",
"At",
"(",
"1",
"1",
")",
".",
"Or",
"it",
"may",
"panic",
"if",
"it",
"s",
"out",
"of",
"bounds",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L2270-L2272 |
go-gl/mathgl | mgl64/matrix.go | Set | func (m *Mat4) Set(row, col int, value float64) {
m[col*4+row] = value
} | go | func (m *Mat4) Set(row, col int, value float64) {
m[col*4+row] = value
} | [
"func",
"(",
"m",
"*",
"Mat4",
")",
"Set",
"(",
"row",
",",
"col",
"int",
",",
"value",
"float64",
")",
"{",
"m",
"[",
"col",
"*",
"4",
"+",
"row",
"]",
"=",
"value",
"\n",
"}"
] | // Set sets the corresponding matrix element at the given row and column.
// This has a pointer receiver because it mutates the matrix.
//
// This method is garbage-in garbage-out. For instance, on a Mat4 asking for
// Set(5,0,val) will work just like Set(1,1,val). Or it may panic if it's out of bounds. | [
"Set",
"sets",
"the",
"corresponding",
"matrix",
"element",
"at",
"the",
"given",
"row",
"and",
"column",
".",
"This",
"has",
"a",
"pointer",
"receiver",
"because",
"it",
"mutates",
"the",
"matrix",
".",
"This",
"method",
"is",
"garbage",
"-",
"in",
"garbage",
"-",
"out",
".",
"For",
"instance",
"on",
"a",
"Mat4",
"asking",
"for",
"Set",
"(",
"5",
"0",
"val",
")",
"will",
"work",
"just",
"like",
"Set",
"(",
"1",
"1",
"val",
")",
".",
"Or",
"it",
"may",
"panic",
"if",
"it",
"s",
"out",
"of",
"bounds",
"."
] | train | https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl64/matrix.go#L2279-L2281 |
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"
] | train | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/file.go#L57-L62 |
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"
] | train | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/filesystem.go#L50-L70 |
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",
"."
] | train | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/generate.go#L129-L153 |
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",
"."
] | train | https://github.com/jessevdk/go-assets/blob/4f4301a06e153ff90e17793577ab6bf79f8dc5c5/generate.go#L170-L298 |
ttacon/libphonenumber | phonenumberutil.go | extractPossibleNumber | func extractPossibleNumber(number string) string {
if VALID_START_CHAR_PATTERN.MatchString(number) {
start := VALID_START_CHAR_PATTERN.FindIndex([]byte(number))[0]
number = number[start:]
// Remove trailing non-alpha non-numerical characters.
indices := UNWANTED_END_CHAR_PATTERN.FindIndex([]byte(number))
if len(indices) > 0 {
number = number[0:indices[0]]
}
// Check for extra numbers at the end.
indices = SECOND_NUMBER_START_PATTERN.FindIndex([]byte(number))
if len(indices) > 0 {
number = number[0:indices[0]]
}
return number
}
return ""
} | go | func extractPossibleNumber(number string) string {
if VALID_START_CHAR_PATTERN.MatchString(number) {
start := VALID_START_CHAR_PATTERN.FindIndex([]byte(number))[0]
number = number[start:]
// Remove trailing non-alpha non-numerical characters.
indices := UNWANTED_END_CHAR_PATTERN.FindIndex([]byte(number))
if len(indices) > 0 {
number = number[0:indices[0]]
}
// Check for extra numbers at the end.
indices = SECOND_NUMBER_START_PATTERN.FindIndex([]byte(number))
if len(indices) > 0 {
number = number[0:indices[0]]
}
return number
}
return ""
} | [
"func",
"extractPossibleNumber",
"(",
"number",
"string",
")",
"string",
"{",
"if",
"VALID_START_CHAR_PATTERN",
".",
"MatchString",
"(",
"number",
")",
"{",
"start",
":=",
"VALID_START_CHAR_PATTERN",
".",
"FindIndex",
"(",
"[",
"]",
"byte",
"(",
"number",
")",
")",
"[",
"0",
"]",
"\n",
"number",
"=",
"number",
"[",
"start",
":",
"]",
"\n",
"// Remove trailing non-alpha non-numerical characters.",
"indices",
":=",
"UNWANTED_END_CHAR_PATTERN",
".",
"FindIndex",
"(",
"[",
"]",
"byte",
"(",
"number",
")",
")",
"\n",
"if",
"len",
"(",
"indices",
")",
">",
"0",
"{",
"number",
"=",
"number",
"[",
"0",
":",
"indices",
"[",
"0",
"]",
"]",
"\n",
"}",
"\n",
"// Check for extra numbers at the end.",
"indices",
"=",
"SECOND_NUMBER_START_PATTERN",
".",
"FindIndex",
"(",
"[",
"]",
"byte",
"(",
"number",
")",
")",
"\n",
"if",
"len",
"(",
"indices",
")",
">",
"0",
"{",
"number",
"=",
"number",
"[",
"0",
":",
"indices",
"[",
"0",
"]",
"]",
"\n",
"}",
"\n",
"return",
"number",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Attempts to extract a possible number from the string passed in.
// This currently strips all leading characters that cannot be used to
// start a phone number. Characters that can be used to start a phone
// number are defined in the VALID_START_CHAR_PATTERN. If none of these
// characters are found in the number passed in, an empty string is
// returned. This function also attempts to strip off any alternative
// extensions or endings if two or more are present, such as in the case
// of: (530) 583-6985 x302/x2303. The second extension here makes this
// actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303.
// We remove the second extension so that the first number is parsed correctly. | [
"Attempts",
"to",
"extract",
"a",
"possible",
"number",
"from",
"the",
"string",
"passed",
"in",
".",
"This",
"currently",
"strips",
"all",
"leading",
"characters",
"that",
"cannot",
"be",
"used",
"to",
"start",
"a",
"phone",
"number",
".",
"Characters",
"that",
"can",
"be",
"used",
"to",
"start",
"a",
"phone",
"number",
"are",
"defined",
"in",
"the",
"VALID_START_CHAR_PATTERN",
".",
"If",
"none",
"of",
"these",
"characters",
"are",
"found",
"in",
"the",
"number",
"passed",
"in",
"an",
"empty",
"string",
"is",
"returned",
".",
"This",
"function",
"also",
"attempts",
"to",
"strip",
"off",
"any",
"alternative",
"extensions",
"or",
"endings",
"if",
"two",
"or",
"more",
"are",
"present",
"such",
"as",
"in",
"the",
"case",
"of",
":",
"(",
"530",
")",
"583",
"-",
"6985",
"x302",
"/",
"x2303",
".",
"The",
"second",
"extension",
"here",
"makes",
"this",
"actually",
"two",
"phone",
"numbers",
"(",
"530",
")",
"583",
"-",
"6985",
"x302",
"and",
"(",
"530",
")",
"583",
"-",
"6985",
"x2303",
".",
"We",
"remove",
"the",
"second",
"extension",
"so",
"that",
"the",
"first",
"number",
"is",
"parsed",
"correctly",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L699-L716 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L725-L730 |
ttacon/libphonenumber | phonenumberutil.go | normalize | func normalize(number string) string {
if VALID_ALPHA_PHONE_PATTERN.MatchString(number) {
return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true)
}
return NormalizeDigitsOnly(number)
} | go | func normalize(number string) string {
if VALID_ALPHA_PHONE_PATTERN.MatchString(number) {
return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true)
}
return NormalizeDigitsOnly(number)
} | [
"func",
"normalize",
"(",
"number",
"string",
")",
"string",
"{",
"if",
"VALID_ALPHA_PHONE_PATTERN",
".",
"MatchString",
"(",
"number",
")",
"{",
"return",
"normalizeHelper",
"(",
"number",
",",
"ALPHA_PHONE_MAPPINGS",
",",
"true",
")",
"\n",
"}",
"\n",
"return",
"NormalizeDigitsOnly",
"(",
"number",
")",
"\n",
"}"
] | // Normalizes a string of characters representing a phone number. This
// performs the following conversions:
// - Punctuation is stripped.
// - For ALPHA/VANITY numbers:
// - Letters are converted to their numeric representation on a telephone
// keypad. The keypad used here is the one defined in ITU Recommendation
// E.161. This is only done if there are 3 or more letters in the
// number, to lessen the risk that such letters are typos.
//
// - For other numbers:
// - Wide-ascii digits are converted to normal ASCII (European) digits.
// - Arabic-Indic numerals are converted to European numerals.
// - Spurious alpha characters are stripped. | [
"Normalizes",
"a",
"string",
"of",
"characters",
"representing",
"a",
"phone",
"number",
".",
"This",
"performs",
"the",
"following",
"conversions",
":",
"-",
"Punctuation",
"is",
"stripped",
".",
"-",
"For",
"ALPHA",
"/",
"VANITY",
"numbers",
":",
"-",
"Letters",
"are",
"converted",
"to",
"their",
"numeric",
"representation",
"on",
"a",
"telephone",
"keypad",
".",
"The",
"keypad",
"used",
"here",
"is",
"the",
"one",
"defined",
"in",
"ITU",
"Recommendation",
"E",
".",
"161",
".",
"This",
"is",
"only",
"done",
"if",
"there",
"are",
"3",
"or",
"more",
"letters",
"in",
"the",
"number",
"to",
"lessen",
"the",
"risk",
"that",
"such",
"letters",
"are",
"typos",
".",
"-",
"For",
"other",
"numbers",
":",
"-",
"Wide",
"-",
"ascii",
"digits",
"are",
"converted",
"to",
"normal",
"ASCII",
"(",
"European",
")",
"digits",
".",
"-",
"Arabic",
"-",
"Indic",
"numerals",
"are",
"converted",
"to",
"European",
"numerals",
".",
"-",
"Spurious",
"alpha",
"characters",
"are",
"stripped",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L745-L750 |
ttacon/libphonenumber | phonenumberutil.go | normalizeBytes | func normalizeBytes(number *builder.Builder) *builder.Builder {
normalizedNumber := normalize(number.String())
b := number.Bytes()
copy(b[0:len(normalizedNumber)], []byte(normalizedNumber))
return builder.NewBuilder(b)
} | go | func normalizeBytes(number *builder.Builder) *builder.Builder {
normalizedNumber := normalize(number.String())
b := number.Bytes()
copy(b[0:len(normalizedNumber)], []byte(normalizedNumber))
return builder.NewBuilder(b)
} | [
"func",
"normalizeBytes",
"(",
"number",
"*",
"builder",
".",
"Builder",
")",
"*",
"builder",
".",
"Builder",
"{",
"normalizedNumber",
":=",
"normalize",
"(",
"number",
".",
"String",
"(",
")",
")",
"\n",
"b",
":=",
"number",
".",
"Bytes",
"(",
")",
"\n",
"copy",
"(",
"b",
"[",
"0",
":",
"len",
"(",
"normalizedNumber",
")",
"]",
",",
"[",
"]",
"byte",
"(",
"normalizedNumber",
")",
")",
"\n",
"return",
"builder",
".",
"NewBuilder",
"(",
"b",
")",
"\n",
"}"
] | // Normalizes a string of characters representing a phone number. This is
// a wrapper for normalize(String number) but does in-place normalization
// of the StringBuilder provided. | [
"Normalizes",
"a",
"string",
"of",
"characters",
"representing",
"a",
"phone",
"number",
".",
"This",
"is",
"a",
"wrapper",
"for",
"normalize",
"(",
"String",
"number",
")",
"but",
"does",
"in",
"-",
"place",
"normalization",
"of",
"the",
"StringBuilder",
"provided",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L755-L760 |
ttacon/libphonenumber | phonenumberutil.go | GetLengthOfGeographicalAreaCode | func GetLengthOfGeographicalAreaCode(number *PhoneNumber) int {
metadata := getMetadataForRegion(GetRegionCodeForNumber(number))
if metadata == nil {
return 0
}
// If a country doesn't use a national prefix, and this number
// doesn't have an Italian leading zero, we assume it is a closed
// dialling plan with no area codes.
if len(metadata.GetNationalPrefix()) == 0 && !number.GetItalianLeadingZero() {
return 0
}
if !isNumberGeographical(number) {
return 0
}
return GetLengthOfNationalDestinationCode(number)
} | go | func GetLengthOfGeographicalAreaCode(number *PhoneNumber) int {
metadata := getMetadataForRegion(GetRegionCodeForNumber(number))
if metadata == nil {
return 0
}
// If a country doesn't use a national prefix, and this number
// doesn't have an Italian leading zero, we assume it is a closed
// dialling plan with no area codes.
if len(metadata.GetNationalPrefix()) == 0 && !number.GetItalianLeadingZero() {
return 0
}
if !isNumberGeographical(number) {
return 0
}
return GetLengthOfNationalDestinationCode(number)
} | [
"func",
"GetLengthOfGeographicalAreaCode",
"(",
"number",
"*",
"PhoneNumber",
")",
"int",
"{",
"metadata",
":=",
"getMetadataForRegion",
"(",
"GetRegionCodeForNumber",
"(",
"number",
")",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"// If a country doesn't use a national prefix, and this number",
"// doesn't have an Italian leading zero, we assume it is a closed",
"// dialling plan with no area codes.",
"if",
"len",
"(",
"metadata",
".",
"GetNationalPrefix",
"(",
")",
")",
"==",
"0",
"&&",
"!",
"number",
".",
"GetItalianLeadingZero",
"(",
")",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"if",
"!",
"isNumberGeographical",
"(",
"number",
")",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"return",
"GetLengthOfNationalDestinationCode",
"(",
"number",
")",
"\n",
"}"
] | // Gets the length of the geographical area code from the PhoneNumber
// object passed in, so that clients could use it to split a national
// significant number into geographical area code and subscriber number. It
// works in such a way that the resultant subscriber number should be
// diallable, at least on some devices. An example of how this could be used:
//
// number, err := Parse("16502530000", "US");
// // ... deal with err appropriately ...
// nationalSignificantNumber := GetNationalSignificantNumber(number);
// var areaCode, subscriberNumber;
//
// int areaCodeLength = GetLengthOfGeographicalAreaCode(number);
// if (areaCodeLength > 0) {
// areaCode = nationalSignificantNumber[0:areaCodeLength];
// subscriberNumber = nationalSignificantNumber[areaCodeLength:];
// } else {
// areaCode = "";
// subscriberNumber = nationalSignificantNumber;
// }
//
// N.B.: area code is a very ambiguous concept, so the I18N team generally
// recommends against using it for most purposes, but recommends using the
// more general national_number instead. Read the following carefully before
// deciding to use this method:
//
// - geographical area codes change over time, and this method honors those changes;
// therefore, it doesn't guarantee the stability of the result it produces.
// - subscriber numbers may not be diallable from all devices (notably mobile
// devices, which typically requires the full national_number to be dialled
// in most regions).
// - most non-geographical numbers have no area codes, including numbers from
// non-geographical entities
// - some geographical numbers have no area codes. | [
"Gets",
"the",
"length",
"of",
"the",
"geographical",
"area",
"code",
"from",
"the",
"PhoneNumber",
"object",
"passed",
"in",
"so",
"that",
"clients",
"could",
"use",
"it",
"to",
"split",
"a",
"national",
"significant",
"number",
"into",
"geographical",
"area",
"code",
"and",
"subscriber",
"number",
".",
"It",
"works",
"in",
"such",
"a",
"way",
"that",
"the",
"resultant",
"subscriber",
"number",
"should",
"be",
"diallable",
"at",
"least",
"on",
"some",
"devices",
".",
"An",
"example",
"of",
"how",
"this",
"could",
"be",
"used",
":",
"number",
"err",
":",
"=",
"Parse",
"(",
"16502530000",
"US",
")",
";",
"//",
"...",
"deal",
"with",
"err",
"appropriately",
"...",
"nationalSignificantNumber",
":",
"=",
"GetNationalSignificantNumber",
"(",
"number",
")",
";",
"var",
"areaCode",
"subscriberNumber",
";",
"int",
"areaCodeLength",
"=",
"GetLengthOfGeographicalAreaCode",
"(",
"number",
")",
";",
"if",
"(",
"areaCodeLength",
">",
"0",
")",
"{",
"areaCode",
"=",
"nationalSignificantNumber",
"[",
"0",
":",
"areaCodeLength",
"]",
";",
"subscriberNumber",
"=",
"nationalSignificantNumber",
"[",
"areaCodeLength",
":",
"]",
";",
"}",
"else",
"{",
"areaCode",
"=",
";",
"subscriberNumber",
"=",
"nationalSignificantNumber",
";",
"}",
"N",
".",
"B",
".",
":",
"area",
"code",
"is",
"a",
"very",
"ambiguous",
"concept",
"so",
"the",
"I18N",
"team",
"generally",
"recommends",
"against",
"using",
"it",
"for",
"most",
"purposes",
"but",
"recommends",
"using",
"the",
"more",
"general",
"national_number",
"instead",
".",
"Read",
"the",
"following",
"carefully",
"before",
"deciding",
"to",
"use",
"this",
"method",
":",
"-",
"geographical",
"area",
"codes",
"change",
"over",
"time",
"and",
"this",
"method",
"honors",
"those",
"changes",
";",
"therefore",
"it",
"doesn",
"t",
"guarantee",
"the",
"stability",
"of",
"the",
"result",
"it",
"produces",
".",
"-",
"subscriber",
"numbers",
"may",
"not",
"be",
"diallable",
"from",
"all",
"devices",
"(",
"notably",
"mobile",
"devices",
"which",
"typically",
"requires",
"the",
"full",
"national_number",
"to",
"be",
"dialled",
"in",
"most",
"regions",
")",
".",
"-",
"most",
"non",
"-",
"geographical",
"numbers",
"have",
"no",
"area",
"codes",
"including",
"numbers",
"from",
"non",
"-",
"geographical",
"entities",
"-",
"some",
"geographical",
"numbers",
"have",
"no",
"area",
"codes",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L868-L886 |
ttacon/libphonenumber | phonenumberutil.go | GetLengthOfNationalDestinationCode | func GetLengthOfNationalDestinationCode(number *PhoneNumber) int {
var copiedProto *PhoneNumber
if len(number.GetExtension()) > 0 {
// We don't want to alter the proto given to us, but we don't
// want to include the extension when we format it, so we copy
// it and clear the extension here.
copiedProto = &PhoneNumber{}
proto.Merge(copiedProto, number)
copiedProto.Extension = nil
} else {
copiedProto = number
}
nationalSignificantNumber := Format(copiedProto, INTERNATIONAL)
numberGroups := DIGITS_PATTERN.FindAllString(nationalSignificantNumber, -1)
// The pattern will start with "+COUNTRY_CODE " so the first group
// will always be the empty string (before the + symbol) and the
// second group will be the country calling code. The third group
// will be area code if it is not the last group.
if len(numberGroups) <= 3 {
return 0
}
if GetNumberType(number) == MOBILE {
// For example Argentinian mobile numbers, when formatted in
// the international format, are in the form of +54 9 NDC XXXX....
// As a result, we take the length of the third group (NDC) and
// add the length of the second group (which is the mobile token),
// which also forms part of the national significant number. This
// assumes that the mobile token is always formatted separately
// from the rest of the phone number.
mobileToken := GetCountryMobileToken(int(number.GetCountryCode()))
if mobileToken != "" {
return len(numberGroups[1]) + len(numberGroups[2])
}
}
return len(numberGroups[1])
} | go | func GetLengthOfNationalDestinationCode(number *PhoneNumber) int {
var copiedProto *PhoneNumber
if len(number.GetExtension()) > 0 {
// We don't want to alter the proto given to us, but we don't
// want to include the extension when we format it, so we copy
// it and clear the extension here.
copiedProto = &PhoneNumber{}
proto.Merge(copiedProto, number)
copiedProto.Extension = nil
} else {
copiedProto = number
}
nationalSignificantNumber := Format(copiedProto, INTERNATIONAL)
numberGroups := DIGITS_PATTERN.FindAllString(nationalSignificantNumber, -1)
// The pattern will start with "+COUNTRY_CODE " so the first group
// will always be the empty string (before the + symbol) and the
// second group will be the country calling code. The third group
// will be area code if it is not the last group.
if len(numberGroups) <= 3 {
return 0
}
if GetNumberType(number) == MOBILE {
// For example Argentinian mobile numbers, when formatted in
// the international format, are in the form of +54 9 NDC XXXX....
// As a result, we take the length of the third group (NDC) and
// add the length of the second group (which is the mobile token),
// which also forms part of the national significant number. This
// assumes that the mobile token is always formatted separately
// from the rest of the phone number.
mobileToken := GetCountryMobileToken(int(number.GetCountryCode()))
if mobileToken != "" {
return len(numberGroups[1]) + len(numberGroups[2])
}
}
return len(numberGroups[1])
} | [
"func",
"GetLengthOfNationalDestinationCode",
"(",
"number",
"*",
"PhoneNumber",
")",
"int",
"{",
"var",
"copiedProto",
"*",
"PhoneNumber",
"\n",
"if",
"len",
"(",
"number",
".",
"GetExtension",
"(",
")",
")",
">",
"0",
"{",
"// We don't want to alter the proto given to us, but we don't",
"// want to include the extension when we format it, so we copy",
"// it and clear the extension here.",
"copiedProto",
"=",
"&",
"PhoneNumber",
"{",
"}",
"\n",
"proto",
".",
"Merge",
"(",
"copiedProto",
",",
"number",
")",
"\n",
"copiedProto",
".",
"Extension",
"=",
"nil",
"\n",
"}",
"else",
"{",
"copiedProto",
"=",
"number",
"\n",
"}",
"\n\n",
"nationalSignificantNumber",
":=",
"Format",
"(",
"copiedProto",
",",
"INTERNATIONAL",
")",
"\n",
"numberGroups",
":=",
"DIGITS_PATTERN",
".",
"FindAllString",
"(",
"nationalSignificantNumber",
",",
"-",
"1",
")",
"\n",
"// The pattern will start with \"+COUNTRY_CODE \" so the first group",
"// will always be the empty string (before the + symbol) and the",
"// second group will be the country calling code. The third group",
"// will be area code if it is not the last group.",
"if",
"len",
"(",
"numberGroups",
")",
"<=",
"3",
"{",
"return",
"0",
"\n",
"}",
"\n",
"if",
"GetNumberType",
"(",
"number",
")",
"==",
"MOBILE",
"{",
"// For example Argentinian mobile numbers, when formatted in",
"// the international format, are in the form of +54 9 NDC XXXX....",
"// As a result, we take the length of the third group (NDC) and",
"// add the length of the second group (which is the mobile token),",
"// which also forms part of the national significant number. This",
"// assumes that the mobile token is always formatted separately",
"// from the rest of the phone number.",
"mobileToken",
":=",
"GetCountryMobileToken",
"(",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
")",
"\n",
"if",
"mobileToken",
"!=",
"\"",
"\"",
"{",
"return",
"len",
"(",
"numberGroups",
"[",
"1",
"]",
")",
"+",
"len",
"(",
"numberGroups",
"[",
"2",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"len",
"(",
"numberGroups",
"[",
"1",
"]",
")",
"\n",
"}"
] | // Gets the length of the national destination code (NDC) from the
// PhoneNumber object passed in, so that clients could use it to split a
// national significant number into NDC and subscriber number. The NDC of
// a phone number is normally the first group of digit(s) right after the
// country calling code when the number is formatted in the international
// format, if there is a subscriber number part that follows. An example
// of how this could be used:
//
// PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
// PhoneNumber number = phoneUtil.parse("18002530000", "US");
// String nationalSignificantNumber = phoneUtil.GetNationalSignificantNumber(number);
// String nationalDestinationCode;
// String subscriberNumber;
//
// int nationalDestinationCodeLength =
// phoneUtil.GetLengthOfNationalDestinationCode(number);
// if nationalDestinationCodeLength > 0 {
// nationalDestinationCode = nationalSignificantNumber.substring(0,
// nationalDestinationCodeLength);
// subscriberNumber = nationalSignificantNumber.substring(
// nationalDestinationCodeLength);
// } else {
// nationalDestinationCode = "";
// subscriberNumber = nationalSignificantNumber;
// }
//
// Refer to the unittests to see the difference between this function and
// GetLengthOfGeographicalAreaCode(). | [
"Gets",
"the",
"length",
"of",
"the",
"national",
"destination",
"code",
"(",
"NDC",
")",
"from",
"the",
"PhoneNumber",
"object",
"passed",
"in",
"so",
"that",
"clients",
"could",
"use",
"it",
"to",
"split",
"a",
"national",
"significant",
"number",
"into",
"NDC",
"and",
"subscriber",
"number",
".",
"The",
"NDC",
"of",
"a",
"phone",
"number",
"is",
"normally",
"the",
"first",
"group",
"of",
"digit",
"(",
"s",
")",
"right",
"after",
"the",
"country",
"calling",
"code",
"when",
"the",
"number",
"is",
"formatted",
"in",
"the",
"international",
"format",
"if",
"there",
"is",
"a",
"subscriber",
"number",
"part",
"that",
"follows",
".",
"An",
"example",
"of",
"how",
"this",
"could",
"be",
"used",
":",
"PhoneNumberUtil",
"phoneUtil",
"=",
"PhoneNumberUtil",
".",
"getInstance",
"()",
";",
"PhoneNumber",
"number",
"=",
"phoneUtil",
".",
"parse",
"(",
"18002530000",
"US",
")",
";",
"String",
"nationalSignificantNumber",
"=",
"phoneUtil",
".",
"GetNationalSignificantNumber",
"(",
"number",
")",
";",
"String",
"nationalDestinationCode",
";",
"String",
"subscriberNumber",
";",
"int",
"nationalDestinationCodeLength",
"=",
"phoneUtil",
".",
"GetLengthOfNationalDestinationCode",
"(",
"number",
")",
";",
"if",
"nationalDestinationCodeLength",
">",
"0",
"{",
"nationalDestinationCode",
"=",
"nationalSignificantNumber",
".",
"substring",
"(",
"0",
"nationalDestinationCodeLength",
")",
";",
"subscriberNumber",
"=",
"nationalSignificantNumber",
".",
"substring",
"(",
"nationalDestinationCodeLength",
")",
";",
"}",
"else",
"{",
"nationalDestinationCode",
"=",
";",
"subscriberNumber",
"=",
"nationalSignificantNumber",
";",
"}",
"Refer",
"to",
"the",
"unittests",
"to",
"see",
"the",
"difference",
"between",
"this",
"function",
"and",
"GetLengthOfGeographicalAreaCode",
"()",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L916-L952 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L958-L963 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L968-L983 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1012-L1018 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1021-L1024 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1042-L1058 |
ttacon/libphonenumber | phonenumberutil.go | FormatWithBuf | func FormatWithBuf(
number *PhoneNumber,
numberFormat PhoneNumberFormat,
formattedNumber *builder.Builder) {
// Clear the StringBuilder first.
formattedNumber.Reset()
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if numberFormat == E164 {
// Early exit for E164 case (even if the country calling code
// is invalid) since no formatting of the national number needs
// to be applied. Extensions are not formatted.
formattedNumber.WriteString(nationalSignificantNumber)
prefixNumberWithCountryCallingCode(
countryCallingCode,
E164,
formattedNumber)
return
} else if !hasValidCountryCallingCode(countryCallingCode) {
formattedNumber.WriteString(nationalSignificantNumber)
return
}
// 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 (which means that the region code cannot be ZZ and must
// be one of our supported region codes).
metadata := getMetadataForRegionOrCallingCode(
countryCallingCode, regionCode)
formattedNumber.WriteString(
formatNsn(nationalSignificantNumber, metadata, numberFormat))
maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber)
prefixNumberWithCountryCallingCode(
countryCallingCode, numberFormat, formattedNumber)
} | go | func FormatWithBuf(
number *PhoneNumber,
numberFormat PhoneNumberFormat,
formattedNumber *builder.Builder) {
// Clear the StringBuilder first.
formattedNumber.Reset()
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if numberFormat == E164 {
// Early exit for E164 case (even if the country calling code
// is invalid) since no formatting of the national number needs
// to be applied. Extensions are not formatted.
formattedNumber.WriteString(nationalSignificantNumber)
prefixNumberWithCountryCallingCode(
countryCallingCode,
E164,
formattedNumber)
return
} else if !hasValidCountryCallingCode(countryCallingCode) {
formattedNumber.WriteString(nationalSignificantNumber)
return
}
// 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 (which means that the region code cannot be ZZ and must
// be one of our supported region codes).
metadata := getMetadataForRegionOrCallingCode(
countryCallingCode, regionCode)
formattedNumber.WriteString(
formatNsn(nationalSignificantNumber, metadata, numberFormat))
maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber)
prefixNumberWithCountryCallingCode(
countryCallingCode, numberFormat, formattedNumber)
} | [
"func",
"FormatWithBuf",
"(",
"number",
"*",
"PhoneNumber",
",",
"numberFormat",
"PhoneNumberFormat",
",",
"formattedNumber",
"*",
"builder",
".",
"Builder",
")",
"{",
"// Clear the StringBuilder first.",
"formattedNumber",
".",
"Reset",
"(",
")",
"\n",
"countryCallingCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"nationalSignificantNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n\n",
"if",
"numberFormat",
"==",
"E164",
"{",
"// Early exit for E164 case (even if the country calling code",
"// is invalid) since no formatting of the national number needs",
"// to be applied. Extensions are not formatted.",
"formattedNumber",
".",
"WriteString",
"(",
"nationalSignificantNumber",
")",
"\n",
"prefixNumberWithCountryCallingCode",
"(",
"countryCallingCode",
",",
"E164",
",",
"formattedNumber",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCallingCode",
")",
"{",
"formattedNumber",
".",
"WriteString",
"(",
"nationalSignificantNumber",
")",
"\n",
"return",
"\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 (which means that the region code cannot be ZZ and must",
"// be one of our supported region codes).",
"metadata",
":=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCallingCode",
",",
"regionCode",
")",
"\n",
"formattedNumber",
".",
"WriteString",
"(",
"formatNsn",
"(",
"nationalSignificantNumber",
",",
"metadata",
",",
"numberFormat",
")",
")",
"\n",
"maybeAppendFormattedExtension",
"(",
"number",
",",
"metadata",
",",
"numberFormat",
",",
"formattedNumber",
")",
"\n",
"prefixNumberWithCountryCallingCode",
"(",
"countryCallingCode",
",",
"numberFormat",
",",
"formattedNumber",
")",
"\n",
"}"
] | // Same as Format(PhoneNumber, PhoneNumberFormat), but accepts a mutable
// StringBuilder as a parameter to decrease object creation when invoked
// many times. | [
"Same",
"as",
"Format",
"(",
"PhoneNumber",
"PhoneNumberFormat",
")",
"but",
"accepts",
"a",
"mutable",
"StringBuilder",
"as",
"a",
"parameter",
"to",
"decrease",
"object",
"creation",
"when",
"invoked",
"many",
"times",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1063-L1101 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1109-L1167 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1174-L1201 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1221-L1230 |
ttacon/libphonenumber | phonenumberutil.go | FormatNumberForMobileDialing | func FormatNumberForMobileDialing(
number *PhoneNumber,
regionCallingFrom string,
withFormatting bool) string {
countryCallingCode := int(number.GetCountryCode())
if !hasValidCountryCallingCode(countryCallingCode) {
return number.GetRawInput() // go impl defaults to ""
}
formattedNumber := ""
// Clear the extension, as that part cannot normally be dialed
// together with the main number.
var numberNoExt = &PhoneNumber{}
proto.Merge(numberNoExt, number)
numberNoExt.Extension = nil // can we assume this is safe? (no nil-pointer?)
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
numberType := GetNumberType(numberNoExt)
isValidNumber := numberType != UNKNOWN
if regionCallingFrom == regionCode {
isFixedLineOrMobile :=
numberType == FIXED_LINE ||
numberType == MOBILE ||
numberType == FIXED_LINE_OR_MOBILE
// Carrier codes may be needed in some countries. We handle this here.
if regionCode == "CO" && numberType == FIXED_LINE {
formattedNumber =
FormatNationalNumberWithCarrierCode(
numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX)
} else if regionCode == "BR" && isFixedLineOrMobile {
if numberNoExt.GetPreferredDomesticCarrierCode() != "" {
formattedNumber =
FormatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
} else {
// Brazilian fixed line and mobile numbers need to be dialed
// with a carrier code when called within Brazil. Without
// that, most of the carriers won't connect the call.
// Because of that, we return an empty string here.
formattedNumber = ""
}
} else if isValidNumber && regionCode == "HU" {
// The national format for HU numbers doesn't contain the
// national prefix, because that is how numbers are normally
// written down. However, the national prefix is obligatory when
// dialing from a mobile phone, except for short numbers. As a
// result, we add it back here
// if it is a valid regular length phone number.
formattedNumber =
GetNddPrefixForRegion(regionCode, true /* strip non-digits */) +
" " + Format(numberNoExt, NATIONAL)
} else if countryCallingCode == NANPA_COUNTRY_CODE {
// For NANPA countries, we output international format for
// numbers that can be dialed internationally, since that
// always works, except for numbers which might potentially be
// short numbers, which are always dialled in national format.
regionMetadata := getMetadataForRegion(regionCallingFrom)
if canBeInternationallyDialled(numberNoExt) &&
!isShorterThanPossibleNormalNumber(regionMetadata,
GetNationalSignificantNumber(numberNoExt)) {
formattedNumber = Format(numberNoExt, INTERNATIONAL)
} else {
formattedNumber = Format(numberNoExt, NATIONAL)
}
} else {
// For non-geographical countries, and Mexican and Chilean fixed
// line and mobile numbers, we output international format for
// numbers that can be dialed internationally as that always
// works.
// MX fixed line and mobile numbers should always be formatted
// in international format, even when dialed within MX. For
// national format to work, a carrier code needs to be used,
// and the correct carrier code depends on if the caller and
// callee are from the same local area. It is trickier to get
// that to work correctly than using international format, which
// is tested to work fine on all carriers. CL fixed line
// numbers need the national prefix when dialing in the national
// format, but don't have it when used for display. The reverse
// is true for mobile numbers. As a result, we output them in
// the international format to make it work.
if regionCode == REGION_CODE_FOR_NON_GEO_ENTITY ||
((regionCode == "MX" ||
regionCode == "CL") &&
isFixedLineOrMobile) &&
canBeInternationallyDialled(numberNoExt) {
formattedNumber = Format(numberNoExt, INTERNATIONAL)
} else {
formattedNumber = Format(numberNoExt, NATIONAL)
}
}
} else if isValidNumber && canBeInternationallyDialled(numberNoExt) {
// We assume that short numbers are not diallable from outside
// their region, so if a number is not a valid regular length
// phone number, we treat it as if it cannot be internationally
// dialled.
if withFormatting {
return Format(numberNoExt, INTERNATIONAL)
}
return Format(numberNoExt, E164)
}
if withFormatting {
return formattedNumber
}
return normalizeDiallableCharsOnly(formattedNumber)
} | go | func FormatNumberForMobileDialing(
number *PhoneNumber,
regionCallingFrom string,
withFormatting bool) string {
countryCallingCode := int(number.GetCountryCode())
if !hasValidCountryCallingCode(countryCallingCode) {
return number.GetRawInput() // go impl defaults to ""
}
formattedNumber := ""
// Clear the extension, as that part cannot normally be dialed
// together with the main number.
var numberNoExt = &PhoneNumber{}
proto.Merge(numberNoExt, number)
numberNoExt.Extension = nil // can we assume this is safe? (no nil-pointer?)
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
numberType := GetNumberType(numberNoExt)
isValidNumber := numberType != UNKNOWN
if regionCallingFrom == regionCode {
isFixedLineOrMobile :=
numberType == FIXED_LINE ||
numberType == MOBILE ||
numberType == FIXED_LINE_OR_MOBILE
// Carrier codes may be needed in some countries. We handle this here.
if regionCode == "CO" && numberType == FIXED_LINE {
formattedNumber =
FormatNationalNumberWithCarrierCode(
numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX)
} else if regionCode == "BR" && isFixedLineOrMobile {
if numberNoExt.GetPreferredDomesticCarrierCode() != "" {
formattedNumber =
FormatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
} else {
// Brazilian fixed line and mobile numbers need to be dialed
// with a carrier code when called within Brazil. Without
// that, most of the carriers won't connect the call.
// Because of that, we return an empty string here.
formattedNumber = ""
}
} else if isValidNumber && regionCode == "HU" {
// The national format for HU numbers doesn't contain the
// national prefix, because that is how numbers are normally
// written down. However, the national prefix is obligatory when
// dialing from a mobile phone, except for short numbers. As a
// result, we add it back here
// if it is a valid regular length phone number.
formattedNumber =
GetNddPrefixForRegion(regionCode, true /* strip non-digits */) +
" " + Format(numberNoExt, NATIONAL)
} else if countryCallingCode == NANPA_COUNTRY_CODE {
// For NANPA countries, we output international format for
// numbers that can be dialed internationally, since that
// always works, except for numbers which might potentially be
// short numbers, which are always dialled in national format.
regionMetadata := getMetadataForRegion(regionCallingFrom)
if canBeInternationallyDialled(numberNoExt) &&
!isShorterThanPossibleNormalNumber(regionMetadata,
GetNationalSignificantNumber(numberNoExt)) {
formattedNumber = Format(numberNoExt, INTERNATIONAL)
} else {
formattedNumber = Format(numberNoExt, NATIONAL)
}
} else {
// For non-geographical countries, and Mexican and Chilean fixed
// line and mobile numbers, we output international format for
// numbers that can be dialed internationally as that always
// works.
// MX fixed line and mobile numbers should always be formatted
// in international format, even when dialed within MX. For
// national format to work, a carrier code needs to be used,
// and the correct carrier code depends on if the caller and
// callee are from the same local area. It is trickier to get
// that to work correctly than using international format, which
// is tested to work fine on all carriers. CL fixed line
// numbers need the national prefix when dialing in the national
// format, but don't have it when used for display. The reverse
// is true for mobile numbers. As a result, we output them in
// the international format to make it work.
if regionCode == REGION_CODE_FOR_NON_GEO_ENTITY ||
((regionCode == "MX" ||
regionCode == "CL") &&
isFixedLineOrMobile) &&
canBeInternationallyDialled(numberNoExt) {
formattedNumber = Format(numberNoExt, INTERNATIONAL)
} else {
formattedNumber = Format(numberNoExt, NATIONAL)
}
}
} else if isValidNumber && canBeInternationallyDialled(numberNoExt) {
// We assume that short numbers are not diallable from outside
// their region, so if a number is not a valid regular length
// phone number, we treat it as if it cannot be internationally
// dialled.
if withFormatting {
return Format(numberNoExt, INTERNATIONAL)
}
return Format(numberNoExt, E164)
}
if withFormatting {
return formattedNumber
}
return normalizeDiallableCharsOnly(formattedNumber)
} | [
"func",
"FormatNumberForMobileDialing",
"(",
"number",
"*",
"PhoneNumber",
",",
"regionCallingFrom",
"string",
",",
"withFormatting",
"bool",
")",
"string",
"{",
"countryCallingCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCallingCode",
")",
"{",
"return",
"number",
".",
"GetRawInput",
"(",
")",
"// go impl defaults to \"\"",
"\n",
"}",
"\n\n",
"formattedNumber",
":=",
"\"",
"\"",
"\n",
"// Clear the extension, as that part cannot normally be dialed",
"// together with the main number.",
"var",
"numberNoExt",
"=",
"&",
"PhoneNumber",
"{",
"}",
"\n",
"proto",
".",
"Merge",
"(",
"numberNoExt",
",",
"number",
")",
"\n",
"numberNoExt",
".",
"Extension",
"=",
"nil",
"// can we assume this is safe? (no nil-pointer?)",
"\n",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCallingCode",
")",
"\n",
"numberType",
":=",
"GetNumberType",
"(",
"numberNoExt",
")",
"\n",
"isValidNumber",
":=",
"numberType",
"!=",
"UNKNOWN",
"\n",
"if",
"regionCallingFrom",
"==",
"regionCode",
"{",
"isFixedLineOrMobile",
":=",
"numberType",
"==",
"FIXED_LINE",
"||",
"numberType",
"==",
"MOBILE",
"||",
"numberType",
"==",
"FIXED_LINE_OR_MOBILE",
"\n",
"// Carrier codes may be needed in some countries. We handle this here.",
"if",
"regionCode",
"==",
"\"",
"\"",
"&&",
"numberType",
"==",
"FIXED_LINE",
"{",
"formattedNumber",
"=",
"FormatNationalNumberWithCarrierCode",
"(",
"numberNoExt",
",",
"COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX",
")",
"\n",
"}",
"else",
"if",
"regionCode",
"==",
"\"",
"\"",
"&&",
"isFixedLineOrMobile",
"{",
"if",
"numberNoExt",
".",
"GetPreferredDomesticCarrierCode",
"(",
")",
"!=",
"\"",
"\"",
"{",
"formattedNumber",
"=",
"FormatNationalNumberWithPreferredCarrierCode",
"(",
"numberNoExt",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"// Brazilian fixed line and mobile numbers need to be dialed",
"// with a carrier code when called within Brazil. Without",
"// that, most of the carriers won't connect the call.",
"// Because of that, we return an empty string here.",
"formattedNumber",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"else",
"if",
"isValidNumber",
"&&",
"regionCode",
"==",
"\"",
"\"",
"{",
"// The national format for HU numbers doesn't contain the",
"// national prefix, because that is how numbers are normally",
"// written down. However, the national prefix is obligatory when",
"// dialing from a mobile phone, except for short numbers. As a",
"// result, we add it back here",
"// if it is a valid regular length phone number.",
"formattedNumber",
"=",
"GetNddPrefixForRegion",
"(",
"regionCode",
",",
"true",
"/* strip non-digits */",
")",
"+",
"\"",
"\"",
"+",
"Format",
"(",
"numberNoExt",
",",
"NATIONAL",
")",
"\n",
"}",
"else",
"if",
"countryCallingCode",
"==",
"NANPA_COUNTRY_CODE",
"{",
"// For NANPA countries, we output international format for",
"// numbers that can be dialed internationally, since that",
"// always works, except for numbers which might potentially be",
"// short numbers, which are always dialled in national format.",
"regionMetadata",
":=",
"getMetadataForRegion",
"(",
"regionCallingFrom",
")",
"\n",
"if",
"canBeInternationallyDialled",
"(",
"numberNoExt",
")",
"&&",
"!",
"isShorterThanPossibleNormalNumber",
"(",
"regionMetadata",
",",
"GetNationalSignificantNumber",
"(",
"numberNoExt",
")",
")",
"{",
"formattedNumber",
"=",
"Format",
"(",
"numberNoExt",
",",
"INTERNATIONAL",
")",
"\n",
"}",
"else",
"{",
"formattedNumber",
"=",
"Format",
"(",
"numberNoExt",
",",
"NATIONAL",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// For non-geographical countries, and Mexican and Chilean fixed",
"// line and mobile numbers, we output international format for",
"// numbers that can be dialed internationally as that always",
"// works.",
"// MX fixed line and mobile numbers should always be formatted",
"// in international format, even when dialed within MX. For",
"// national format to work, a carrier code needs to be used,",
"// and the correct carrier code depends on if the caller and",
"// callee are from the same local area. It is trickier to get",
"// that to work correctly than using international format, which",
"// is tested to work fine on all carriers. CL fixed line",
"// numbers need the national prefix when dialing in the national",
"// format, but don't have it when used for display. The reverse",
"// is true for mobile numbers. As a result, we output them in",
"// the international format to make it work.",
"if",
"regionCode",
"==",
"REGION_CODE_FOR_NON_GEO_ENTITY",
"||",
"(",
"(",
"regionCode",
"==",
"\"",
"\"",
"||",
"regionCode",
"==",
"\"",
"\"",
")",
"&&",
"isFixedLineOrMobile",
")",
"&&",
"canBeInternationallyDialled",
"(",
"numberNoExt",
")",
"{",
"formattedNumber",
"=",
"Format",
"(",
"numberNoExt",
",",
"INTERNATIONAL",
")",
"\n",
"}",
"else",
"{",
"formattedNumber",
"=",
"Format",
"(",
"numberNoExt",
",",
"NATIONAL",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"isValidNumber",
"&&",
"canBeInternationallyDialled",
"(",
"numberNoExt",
")",
"{",
"// We assume that short numbers are not diallable from outside",
"// their region, so if a number is not a valid regular length",
"// phone number, we treat it as if it cannot be internationally",
"// dialled.",
"if",
"withFormatting",
"{",
"return",
"Format",
"(",
"numberNoExt",
",",
"INTERNATIONAL",
")",
"\n",
"}",
"\n",
"return",
"Format",
"(",
"numberNoExt",
",",
"E164",
")",
"\n",
"}",
"\n",
"if",
"withFormatting",
"{",
"return",
"formattedNumber",
"\n",
"}",
"\n",
"return",
"normalizeDiallableCharsOnly",
"(",
"formattedNumber",
")",
"\n",
"}"
] | // Returns a number formatted in such a way that it can be dialed from a
// mobile phone in a specific region. If the number cannot be reached from
// the region (e.g. some countries block toll-free numbers from being
// called outside of the country), the method returns an empty string. | [
"Returns",
"a",
"number",
"formatted",
"in",
"such",
"a",
"way",
"that",
"it",
"can",
"be",
"dialed",
"from",
"a",
"mobile",
"phone",
"in",
"a",
"specific",
"region",
".",
"If",
"the",
"number",
"cannot",
"be",
"reached",
"from",
"the",
"region",
"(",
"e",
".",
"g",
".",
"some",
"countries",
"block",
"toll",
"-",
"free",
"numbers",
"from",
"being",
"called",
"outside",
"of",
"the",
"country",
")",
"the",
"method",
"returns",
"an",
"empty",
"string",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1236-L1340 |
ttacon/libphonenumber | phonenumberutil.go | FormatOutOfCountryCallingNumber | func FormatOutOfCountryCallingNumber(
number *PhoneNumber,
regionCallingFrom string) string {
if !isValidRegionCode(regionCallingFrom) {
return Format(number, INTERNATIONAL)
}
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
if countryCallingCode == NANPA_COUNTRY_CODE {
if IsNANPACountry(regionCallingFrom) {
// For NANPA regions, return the national format for these
// regions but prefix it with the country calling code.
return strconv.Itoa(countryCallingCode) + " " + Format(number, NATIONAL)
}
} else if countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom) {
// If regions share a country calling code, the country calling
// code need not be dialled. This also applies when dialling
// within a region, so this if clause covers both these cases.
// Technically this is the case for dialling from La Reunion to
// other overseas departments of France (French Guiana, Martinique,
// Guadeloupe), but not vice versa - so we don't cover this edge
// case for now and for those cases return the version including
// country calling code.
// Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
return Format(number, NATIONAL)
}
// Metadata cannot be null because we checked 'isValidRegionCode()' above.
metadataForRegionCallingFrom := getMetadataForRegion(regionCallingFrom)
internationalPrefix := metadataForRegionCallingFrom.GetInternationalPrefix()
// For regions that have multiple international prefixes, the
// international format of the number is returned, unless there is
// a preferred international prefix.
internationalPrefixForFormatting := ""
metPref := metadataForRegionCallingFrom.GetPreferredInternationalPrefix()
if UNIQUE_INTERNATIONAL_PREFIX.MatchString(internationalPrefix) {
internationalPrefixForFormatting = internationalPrefix
} else if metPref != "" {
internationalPrefixForFormatting = metPref
}
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid.
metadataForRegion :=
getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNationalNumber :=
formatNsn(
nationalSignificantNumber, metadataForRegion, INTERNATIONAL)
formattedNumber := builder.NewBuilder([]byte(formattedNationalNumber))
maybeAppendFormattedExtension(number, metadataForRegion, INTERNATIONAL,
formattedNumber)
if len(internationalPrefixForFormatting) > 0 {
formattedBytes := formattedNumber.Bytes()
formattedBytes = append([]byte(" "), formattedBytes...)
// we know countryCallingCode is really an int32
intBuf := []byte{
byte(countryCallingCode >> 24),
byte(countryCallingCode >> 16),
byte(countryCallingCode >> 8),
byte(countryCallingCode),
}
formattedBytes = append(intBuf, formattedBytes...)
formattedBytes = append([]byte(" "), formattedBytes...)
formattedBytes = append(
[]byte(internationalPrefixForFormatting), formattedBytes...)
return string(formattedBytes)
} else {
prefixNumberWithCountryCallingCode(
countryCallingCode, INTERNATIONAL, formattedNumber)
}
return formattedNumber.String()
} | go | func FormatOutOfCountryCallingNumber(
number *PhoneNumber,
regionCallingFrom string) string {
if !isValidRegionCode(regionCallingFrom) {
return Format(number, INTERNATIONAL)
}
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
if countryCallingCode == NANPA_COUNTRY_CODE {
if IsNANPACountry(regionCallingFrom) {
// For NANPA regions, return the national format for these
// regions but prefix it with the country calling code.
return strconv.Itoa(countryCallingCode) + " " + Format(number, NATIONAL)
}
} else if countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom) {
// If regions share a country calling code, the country calling
// code need not be dialled. This also applies when dialling
// within a region, so this if clause covers both these cases.
// Technically this is the case for dialling from La Reunion to
// other overseas departments of France (French Guiana, Martinique,
// Guadeloupe), but not vice versa - so we don't cover this edge
// case for now and for those cases return the version including
// country calling code.
// Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
return Format(number, NATIONAL)
}
// Metadata cannot be null because we checked 'isValidRegionCode()' above.
metadataForRegionCallingFrom := getMetadataForRegion(regionCallingFrom)
internationalPrefix := metadataForRegionCallingFrom.GetInternationalPrefix()
// For regions that have multiple international prefixes, the
// international format of the number is returned, unless there is
// a preferred international prefix.
internationalPrefixForFormatting := ""
metPref := metadataForRegionCallingFrom.GetPreferredInternationalPrefix()
if UNIQUE_INTERNATIONAL_PREFIX.MatchString(internationalPrefix) {
internationalPrefixForFormatting = internationalPrefix
} else if metPref != "" {
internationalPrefixForFormatting = metPref
}
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid.
metadataForRegion :=
getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNationalNumber :=
formatNsn(
nationalSignificantNumber, metadataForRegion, INTERNATIONAL)
formattedNumber := builder.NewBuilder([]byte(formattedNationalNumber))
maybeAppendFormattedExtension(number, metadataForRegion, INTERNATIONAL,
formattedNumber)
if len(internationalPrefixForFormatting) > 0 {
formattedBytes := formattedNumber.Bytes()
formattedBytes = append([]byte(" "), formattedBytes...)
// we know countryCallingCode is really an int32
intBuf := []byte{
byte(countryCallingCode >> 24),
byte(countryCallingCode >> 16),
byte(countryCallingCode >> 8),
byte(countryCallingCode),
}
formattedBytes = append(intBuf, formattedBytes...)
formattedBytes = append([]byte(" "), formattedBytes...)
formattedBytes = append(
[]byte(internationalPrefixForFormatting), formattedBytes...)
return string(formattedBytes)
} else {
prefixNumberWithCountryCallingCode(
countryCallingCode, INTERNATIONAL, formattedNumber)
}
return formattedNumber.String()
} | [
"func",
"FormatOutOfCountryCallingNumber",
"(",
"number",
"*",
"PhoneNumber",
",",
"regionCallingFrom",
"string",
")",
"string",
"{",
"if",
"!",
"isValidRegionCode",
"(",
"regionCallingFrom",
")",
"{",
"return",
"Format",
"(",
"number",
",",
"INTERNATIONAL",
")",
"\n",
"}",
"\n",
"countryCallingCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"nationalSignificantNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCallingCode",
")",
"{",
"return",
"nationalSignificantNumber",
"\n",
"}",
"\n",
"if",
"countryCallingCode",
"==",
"NANPA_COUNTRY_CODE",
"{",
"if",
"IsNANPACountry",
"(",
"regionCallingFrom",
")",
"{",
"// For NANPA regions, return the national format for these",
"// regions but prefix it with the country calling code.",
"return",
"strconv",
".",
"Itoa",
"(",
"countryCallingCode",
")",
"+",
"\"",
"\"",
"+",
"Format",
"(",
"number",
",",
"NATIONAL",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"countryCallingCode",
"==",
"getCountryCodeForValidRegion",
"(",
"regionCallingFrom",
")",
"{",
"// If regions share a country calling code, the country calling",
"// code need not be dialled. This also applies when dialling",
"// within a region, so this if clause covers both these cases.",
"// Technically this is the case for dialling from La Reunion to",
"// other overseas departments of France (French Guiana, Martinique,",
"// Guadeloupe), but not vice versa - so we don't cover this edge",
"// case for now and for those cases return the version including",
"// country calling code.",
"// Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion",
"return",
"Format",
"(",
"number",
",",
"NATIONAL",
")",
"\n",
"}",
"\n",
"// Metadata cannot be null because we checked 'isValidRegionCode()' above.",
"metadataForRegionCallingFrom",
":=",
"getMetadataForRegion",
"(",
"regionCallingFrom",
")",
"\n",
"internationalPrefix",
":=",
"metadataForRegionCallingFrom",
".",
"GetInternationalPrefix",
"(",
")",
"\n\n",
"// For regions that have multiple international prefixes, the",
"// international format of the number is returned, unless there is",
"// a preferred international prefix.",
"internationalPrefixForFormatting",
":=",
"\"",
"\"",
"\n",
"metPref",
":=",
"metadataForRegionCallingFrom",
".",
"GetPreferredInternationalPrefix",
"(",
")",
"\n",
"if",
"UNIQUE_INTERNATIONAL_PREFIX",
".",
"MatchString",
"(",
"internationalPrefix",
")",
"{",
"internationalPrefixForFormatting",
"=",
"internationalPrefix",
"\n",
"}",
"else",
"if",
"metPref",
"!=",
"\"",
"\"",
"{",
"internationalPrefixForFormatting",
"=",
"metPref",
"\n",
"}",
"\n\n",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCallingCode",
")",
"\n",
"// Metadata cannot be null because the country calling code is valid.",
"metadataForRegion",
":=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCallingCode",
",",
"regionCode",
")",
"\n",
"formattedNationalNumber",
":=",
"formatNsn",
"(",
"nationalSignificantNumber",
",",
"metadataForRegion",
",",
"INTERNATIONAL",
")",
"\n",
"formattedNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"[",
"]",
"byte",
"(",
"formattedNationalNumber",
")",
")",
"\n",
"maybeAppendFormattedExtension",
"(",
"number",
",",
"metadataForRegion",
",",
"INTERNATIONAL",
",",
"formattedNumber",
")",
"\n",
"if",
"len",
"(",
"internationalPrefixForFormatting",
")",
">",
"0",
"{",
"formattedBytes",
":=",
"formattedNumber",
".",
"Bytes",
"(",
")",
"\n",
"formattedBytes",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"formattedBytes",
"...",
")",
"\n",
"// we know countryCallingCode is really an int32",
"intBuf",
":=",
"[",
"]",
"byte",
"{",
"byte",
"(",
"countryCallingCode",
">>",
"24",
")",
",",
"byte",
"(",
"countryCallingCode",
">>",
"16",
")",
",",
"byte",
"(",
"countryCallingCode",
">>",
"8",
")",
",",
"byte",
"(",
"countryCallingCode",
")",
",",
"}",
"\n",
"formattedBytes",
"=",
"append",
"(",
"intBuf",
",",
"formattedBytes",
"...",
")",
"\n",
"formattedBytes",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"formattedBytes",
"...",
")",
"\n",
"formattedBytes",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"internationalPrefixForFormatting",
")",
",",
"formattedBytes",
"...",
")",
"\n",
"return",
"string",
"(",
"formattedBytes",
")",
"\n",
"}",
"else",
"{",
"prefixNumberWithCountryCallingCode",
"(",
"countryCallingCode",
",",
"INTERNATIONAL",
",",
"formattedNumber",
")",
"\n",
"}",
"\n",
"return",
"formattedNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Formats a phone number for out-of-country dialing purposes. If no
// regionCallingFrom is supplied, we format the number in its
// INTERNATIONAL format. If the country calling code is the same as that
// of the region where the number is from, then NATIONAL formatting will
// be applied.
//
// If the number itself has a country calling code of zero or an otherwise
// invalid country calling code, then we return the number with no
// formatting applied.
//
// Note this function takes care of the case for calling inside of NANPA and
// between Russia and Kazakhstan (who share the same country calling code).
// In those cases, no international prefix is used. For regions which have
// multiple international prefixes, the number in its INTERNATIONAL format
// will be returned instead. | [
"Formats",
"a",
"phone",
"number",
"for",
"out",
"-",
"of",
"-",
"country",
"dialing",
"purposes",
".",
"If",
"no",
"regionCallingFrom",
"is",
"supplied",
"we",
"format",
"the",
"number",
"in",
"its",
"INTERNATIONAL",
"format",
".",
"If",
"the",
"country",
"calling",
"code",
"is",
"the",
"same",
"as",
"that",
"of",
"the",
"region",
"where",
"the",
"number",
"is",
"from",
"then",
"NATIONAL",
"formatting",
"will",
"be",
"applied",
".",
"If",
"the",
"number",
"itself",
"has",
"a",
"country",
"calling",
"code",
"of",
"zero",
"or",
"an",
"otherwise",
"invalid",
"country",
"calling",
"code",
"then",
"we",
"return",
"the",
"number",
"with",
"no",
"formatting",
"applied",
".",
"Note",
"this",
"function",
"takes",
"care",
"of",
"the",
"case",
"for",
"calling",
"inside",
"of",
"NANPA",
"and",
"between",
"Russia",
"and",
"Kazakhstan",
"(",
"who",
"share",
"the",
"same",
"country",
"calling",
"code",
")",
".",
"In",
"those",
"cases",
"no",
"international",
"prefix",
"is",
"used",
".",
"For",
"regions",
"which",
"have",
"multiple",
"international",
"prefixes",
"the",
"number",
"in",
"its",
"INTERNATIONAL",
"format",
"will",
"be",
"returned",
"instead",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1357-L1432 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1444-L1542 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1547-L1563 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1568-L1571 |
ttacon/libphonenumber | phonenumberutil.go | FormatOutOfCountryKeepingAlphaChars | func FormatOutOfCountryKeepingAlphaChars(
number *PhoneNumber,
regionCallingFrom string) string {
rawInput := number.GetRawInput()
// If there is no raw input, then we can't keep alpha characters
// because there aren't any. In this case, we return
// formatOutOfCountryCallingNumber.
if len(rawInput) == 0 {
return FormatOutOfCountryCallingNumber(number, regionCallingFrom)
}
countryCode := int(number.GetCountryCode())
if !hasValidCountryCallingCode(countryCode) {
return rawInput
}
// Strip any prefix such as country calling code, IDD, that was
// present. We do this by comparing the number in raw_input with
// the parsed number. To do this, first we normalize punctuation.
// We retain number grouping symbols such as " " only.
rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true)
// Now we trim everything before the first three digits in the
// parsed number. We choose three because all valid alpha numbers
// have 3 digits at the start - if it does not, then we don't trim
// anything at all. Similarly, if the national number was less than
// three digits, we don't trim anything at all.
nationalNumber := GetNationalSignificantNumber(number)
if len(nationalNumber) > 3 {
firstNationalNumberDigit := strings.Index(rawInput, nationalNumber[0:3])
if firstNationalNumberDigit > -1 {
rawInput = rawInput[firstNationalNumberDigit:]
}
}
metadataForRegionCallingFrom := getMetadataForRegion(regionCallingFrom)
if countryCode == NANPA_COUNTRY_CODE {
if IsNANPACountry(regionCallingFrom) {
return strconv.Itoa(countryCode) + " " + rawInput
}
} else if metadataForRegionCallingFrom != nil &&
countryCode == getCountryCodeForValidRegion(regionCallingFrom) {
formattingPattern :=
chooseFormattingPatternForNumber(
metadataForRegionCallingFrom.GetNumberFormat(),
nationalNumber)
if formattingPattern == nil {
// If no pattern above is matched, we format the original input.
return rawInput
}
var newFormat *NumberFormat
proto.Merge(newFormat, formattingPattern)
// The first group is the first group of digits that the user
// wrote together.
newFormat.Pattern = proto.String("(\\d+)(.*)")
// Here we just concatenate them back together after the national
// prefix has been fixed.
newFormat.Format = proto.String("$1$2")
// Now we format using this pattern instead of the default pattern,
// but with the national prefix prefixed if necessary. This will not
// work in the cases where the pattern (and not the leading digits)
// decide whether a national prefix needs to be used, since we
// have overridden the pattern to match anything, but that is not
// the case in the metadata to date.
return formatNsnUsingPattern(rawInput, newFormat, NATIONAL)
}
var internationalPrefixForFormatting = ""
// If an unsupported region-calling-from is entered, or a country
// with multiple international prefixes, the international format
// of the number is returned, unless there is a preferred international
// prefix.
if metadataForRegionCallingFrom != nil {
internationalPrefix := metadataForRegionCallingFrom.GetInternationalPrefix()
internationalPrefixForFormatting = internationalPrefix
if !UNIQUE_INTERNATIONAL_PREFIX.MatchString(internationalPrefix) {
internationalPrefixForFormatting =
metadataForRegionCallingFrom.GetPreferredInternationalPrefix()
}
}
var formattedNumber = builder.NewBuilder([]byte(rawInput))
regionCode := GetRegionCodeForCountryCode(countryCode)
// Metadata cannot be null because the country calling code is valid.
var metadataForRegion *PhoneMetadata = getMetadataForRegionOrCallingCode(countryCode, regionCode)
maybeAppendFormattedExtension(number, metadataForRegion,
INTERNATIONAL, formattedNumber)
if len(internationalPrefixForFormatting) > 0 {
formattedBytes := append([]byte(" "), formattedNumber.Bytes()...)
// we know countryCode is really an int32
intBuf := []byte{
byte(countryCode >> 24),
byte(countryCode >> 16),
byte(countryCode >> 8),
byte(countryCode),
}
formattedBytes = append(intBuf, formattedBytes...)
formattedBytes = append([]byte(" "), formattedBytes...)
formattedBytes = append(
[]byte(internationalPrefixForFormatting), formattedBytes...)
formattedNumber = builder.NewBuilder(formattedBytes)
} else {
// Invalid region entered as country-calling-from (so no metadata
// was found for it) or the region chosen has multiple international
// dialling prefixes.
prefixNumberWithCountryCallingCode(countryCode,
INTERNATIONAL,
formattedNumber)
}
return formattedNumber.String()
} | go | func FormatOutOfCountryKeepingAlphaChars(
number *PhoneNumber,
regionCallingFrom string) string {
rawInput := number.GetRawInput()
// If there is no raw input, then we can't keep alpha characters
// because there aren't any. In this case, we return
// formatOutOfCountryCallingNumber.
if len(rawInput) == 0 {
return FormatOutOfCountryCallingNumber(number, regionCallingFrom)
}
countryCode := int(number.GetCountryCode())
if !hasValidCountryCallingCode(countryCode) {
return rawInput
}
// Strip any prefix such as country calling code, IDD, that was
// present. We do this by comparing the number in raw_input with
// the parsed number. To do this, first we normalize punctuation.
// We retain number grouping symbols such as " " only.
rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true)
// Now we trim everything before the first three digits in the
// parsed number. We choose three because all valid alpha numbers
// have 3 digits at the start - if it does not, then we don't trim
// anything at all. Similarly, if the national number was less than
// three digits, we don't trim anything at all.
nationalNumber := GetNationalSignificantNumber(number)
if len(nationalNumber) > 3 {
firstNationalNumberDigit := strings.Index(rawInput, nationalNumber[0:3])
if firstNationalNumberDigit > -1 {
rawInput = rawInput[firstNationalNumberDigit:]
}
}
metadataForRegionCallingFrom := getMetadataForRegion(regionCallingFrom)
if countryCode == NANPA_COUNTRY_CODE {
if IsNANPACountry(regionCallingFrom) {
return strconv.Itoa(countryCode) + " " + rawInput
}
} else if metadataForRegionCallingFrom != nil &&
countryCode == getCountryCodeForValidRegion(regionCallingFrom) {
formattingPattern :=
chooseFormattingPatternForNumber(
metadataForRegionCallingFrom.GetNumberFormat(),
nationalNumber)
if formattingPattern == nil {
// If no pattern above is matched, we format the original input.
return rawInput
}
var newFormat *NumberFormat
proto.Merge(newFormat, formattingPattern)
// The first group is the first group of digits that the user
// wrote together.
newFormat.Pattern = proto.String("(\\d+)(.*)")
// Here we just concatenate them back together after the national
// prefix has been fixed.
newFormat.Format = proto.String("$1$2")
// Now we format using this pattern instead of the default pattern,
// but with the national prefix prefixed if necessary. This will not
// work in the cases where the pattern (and not the leading digits)
// decide whether a national prefix needs to be used, since we
// have overridden the pattern to match anything, but that is not
// the case in the metadata to date.
return formatNsnUsingPattern(rawInput, newFormat, NATIONAL)
}
var internationalPrefixForFormatting = ""
// If an unsupported region-calling-from is entered, or a country
// with multiple international prefixes, the international format
// of the number is returned, unless there is a preferred international
// prefix.
if metadataForRegionCallingFrom != nil {
internationalPrefix := metadataForRegionCallingFrom.GetInternationalPrefix()
internationalPrefixForFormatting = internationalPrefix
if !UNIQUE_INTERNATIONAL_PREFIX.MatchString(internationalPrefix) {
internationalPrefixForFormatting =
metadataForRegionCallingFrom.GetPreferredInternationalPrefix()
}
}
var formattedNumber = builder.NewBuilder([]byte(rawInput))
regionCode := GetRegionCodeForCountryCode(countryCode)
// Metadata cannot be null because the country calling code is valid.
var metadataForRegion *PhoneMetadata = getMetadataForRegionOrCallingCode(countryCode, regionCode)
maybeAppendFormattedExtension(number, metadataForRegion,
INTERNATIONAL, formattedNumber)
if len(internationalPrefixForFormatting) > 0 {
formattedBytes := append([]byte(" "), formattedNumber.Bytes()...)
// we know countryCode is really an int32
intBuf := []byte{
byte(countryCode >> 24),
byte(countryCode >> 16),
byte(countryCode >> 8),
byte(countryCode),
}
formattedBytes = append(intBuf, formattedBytes...)
formattedBytes = append([]byte(" "), formattedBytes...)
formattedBytes = append(
[]byte(internationalPrefixForFormatting), formattedBytes...)
formattedNumber = builder.NewBuilder(formattedBytes)
} else {
// Invalid region entered as country-calling-from (so no metadata
// was found for it) or the region chosen has multiple international
// dialling prefixes.
prefixNumberWithCountryCallingCode(countryCode,
INTERNATIONAL,
formattedNumber)
}
return formattedNumber.String()
} | [
"func",
"FormatOutOfCountryKeepingAlphaChars",
"(",
"number",
"*",
"PhoneNumber",
",",
"regionCallingFrom",
"string",
")",
"string",
"{",
"rawInput",
":=",
"number",
".",
"GetRawInput",
"(",
")",
"\n",
"// If there is no raw input, then we can't keep alpha characters",
"// because there aren't any. In this case, we return",
"// formatOutOfCountryCallingNumber.",
"if",
"len",
"(",
"rawInput",
")",
"==",
"0",
"{",
"return",
"FormatOutOfCountryCallingNumber",
"(",
"number",
",",
"regionCallingFrom",
")",
"\n",
"}",
"\n",
"countryCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCode",
")",
"{",
"return",
"rawInput",
"\n",
"}",
"\n",
"// Strip any prefix such as country calling code, IDD, that was",
"// present. We do this by comparing the number in raw_input with",
"// the parsed number. To do this, first we normalize punctuation.",
"// We retain number grouping symbols such as \" \" only.",
"rawInput",
"=",
"normalizeHelper",
"(",
"rawInput",
",",
"ALL_PLUS_NUMBER_GROUPING_SYMBOLS",
",",
"true",
")",
"\n",
"// Now we trim everything before the first three digits in the",
"// parsed number. We choose three because all valid alpha numbers",
"// have 3 digits at the start - if it does not, then we don't trim",
"// anything at all. Similarly, if the national number was less than",
"// three digits, we don't trim anything at all.",
"nationalNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"if",
"len",
"(",
"nationalNumber",
")",
">",
"3",
"{",
"firstNationalNumberDigit",
":=",
"strings",
".",
"Index",
"(",
"rawInput",
",",
"nationalNumber",
"[",
"0",
":",
"3",
"]",
")",
"\n",
"if",
"firstNationalNumberDigit",
">",
"-",
"1",
"{",
"rawInput",
"=",
"rawInput",
"[",
"firstNationalNumberDigit",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"metadataForRegionCallingFrom",
":=",
"getMetadataForRegion",
"(",
"regionCallingFrom",
")",
"\n",
"if",
"countryCode",
"==",
"NANPA_COUNTRY_CODE",
"{",
"if",
"IsNANPACountry",
"(",
"regionCallingFrom",
")",
"{",
"return",
"strconv",
".",
"Itoa",
"(",
"countryCode",
")",
"+",
"\"",
"\"",
"+",
"rawInput",
"\n",
"}",
"\n",
"}",
"else",
"if",
"metadataForRegionCallingFrom",
"!=",
"nil",
"&&",
"countryCode",
"==",
"getCountryCodeForValidRegion",
"(",
"regionCallingFrom",
")",
"{",
"formattingPattern",
":=",
"chooseFormattingPatternForNumber",
"(",
"metadataForRegionCallingFrom",
".",
"GetNumberFormat",
"(",
")",
",",
"nationalNumber",
")",
"\n",
"if",
"formattingPattern",
"==",
"nil",
"{",
"// If no pattern above is matched, we format the original input.",
"return",
"rawInput",
"\n",
"}",
"\n",
"var",
"newFormat",
"*",
"NumberFormat",
"\n",
"proto",
".",
"Merge",
"(",
"newFormat",
",",
"formattingPattern",
")",
"\n",
"// The first group is the first group of digits that the user",
"// wrote together.",
"newFormat",
".",
"Pattern",
"=",
"proto",
".",
"String",
"(",
"\"",
"\\\\",
"\"",
")",
"\n",
"// Here we just concatenate them back together after the national",
"// prefix has been fixed.",
"newFormat",
".",
"Format",
"=",
"proto",
".",
"String",
"(",
"\"",
"\"",
")",
"\n",
"// Now we format using this pattern instead of the default pattern,",
"// but with the national prefix prefixed if necessary. This will not",
"// work in the cases where the pattern (and not the leading digits)",
"// decide whether a national prefix needs to be used, since we",
"// have overridden the pattern to match anything, but that is not",
"// the case in the metadata to date.",
"return",
"formatNsnUsingPattern",
"(",
"rawInput",
",",
"newFormat",
",",
"NATIONAL",
")",
"\n",
"}",
"\n",
"var",
"internationalPrefixForFormatting",
"=",
"\"",
"\"",
"\n",
"// If an unsupported region-calling-from is entered, or a country",
"// with multiple international prefixes, the international format",
"// of the number is returned, unless there is a preferred international",
"// prefix.",
"if",
"metadataForRegionCallingFrom",
"!=",
"nil",
"{",
"internationalPrefix",
":=",
"metadataForRegionCallingFrom",
".",
"GetInternationalPrefix",
"(",
")",
"\n",
"internationalPrefixForFormatting",
"=",
"internationalPrefix",
"\n",
"if",
"!",
"UNIQUE_INTERNATIONAL_PREFIX",
".",
"MatchString",
"(",
"internationalPrefix",
")",
"{",
"internationalPrefixForFormatting",
"=",
"metadataForRegionCallingFrom",
".",
"GetPreferredInternationalPrefix",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"formattedNumber",
"=",
"builder",
".",
"NewBuilder",
"(",
"[",
"]",
"byte",
"(",
"rawInput",
")",
")",
"\n",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCode",
")",
"\n",
"// Metadata cannot be null because the country calling code is valid.",
"var",
"metadataForRegion",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCode",
",",
"regionCode",
")",
"\n",
"maybeAppendFormattedExtension",
"(",
"number",
",",
"metadataForRegion",
",",
"INTERNATIONAL",
",",
"formattedNumber",
")",
"\n",
"if",
"len",
"(",
"internationalPrefixForFormatting",
")",
">",
"0",
"{",
"formattedBytes",
":=",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"formattedNumber",
".",
"Bytes",
"(",
")",
"...",
")",
"\n",
"// we know countryCode is really an int32",
"intBuf",
":=",
"[",
"]",
"byte",
"{",
"byte",
"(",
"countryCode",
">>",
"24",
")",
",",
"byte",
"(",
"countryCode",
">>",
"16",
")",
",",
"byte",
"(",
"countryCode",
">>",
"8",
")",
",",
"byte",
"(",
"countryCode",
")",
",",
"}",
"\n",
"formattedBytes",
"=",
"append",
"(",
"intBuf",
",",
"formattedBytes",
"...",
")",
"\n",
"formattedBytes",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"formattedBytes",
"...",
")",
"\n",
"formattedBytes",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"internationalPrefixForFormatting",
")",
",",
"formattedBytes",
"...",
")",
"\n\n",
"formattedNumber",
"=",
"builder",
".",
"NewBuilder",
"(",
"formattedBytes",
")",
"\n",
"}",
"else",
"{",
"// Invalid region entered as country-calling-from (so no metadata",
"// was found for it) or the region chosen has multiple international",
"// dialling prefixes.",
"prefixNumberWithCountryCallingCode",
"(",
"countryCode",
",",
"INTERNATIONAL",
",",
"formattedNumber",
")",
"\n",
"}",
"\n",
"return",
"formattedNumber",
".",
"String",
"(",
")",
"\n",
"}"
] | // Formats a phone number for out-of-country dialing purposes.
//
// Note that in this version, if the number was entered originally using
// alpha characters and this version of the number is stored in raw_input,
// this representation of the number will be used rather than the digit
// representation. Grouping information, as specified by characters
// such as "-" and " ", will be retained.
//
// Caveats:
//
// - This will not produce good results if the country calling code is
// both present in the raw input _and_ is the start of the national
// number. This is not a problem in the regions which typically use
// alpha numbers.
// - This will also not produce good results if the raw input has any
// grouping information within the first three digits of the national
// number, and if the function needs to strip preceding digits/words
// in the raw input before these digits. Normally people group the
// first three digits together so this is not a huge problem - and will
// be fixed if it proves to be so. | [
"Formats",
"a",
"phone",
"number",
"for",
"out",
"-",
"of",
"-",
"country",
"dialing",
"purposes",
".",
"Note",
"that",
"in",
"this",
"version",
"if",
"the",
"number",
"was",
"entered",
"originally",
"using",
"alpha",
"characters",
"and",
"this",
"version",
"of",
"the",
"number",
"is",
"stored",
"in",
"raw_input",
"this",
"representation",
"of",
"the",
"number",
"will",
"be",
"used",
"rather",
"than",
"the",
"digit",
"representation",
".",
"Grouping",
"information",
"as",
"specified",
"by",
"characters",
"such",
"as",
"-",
"and",
"will",
"be",
"retained",
".",
"Caveats",
":",
"-",
"This",
"will",
"not",
"produce",
"good",
"results",
"if",
"the",
"country",
"calling",
"code",
"is",
"both",
"present",
"in",
"the",
"raw",
"input",
"_and_",
"is",
"the",
"start",
"of",
"the",
"national",
"number",
".",
"This",
"is",
"not",
"a",
"problem",
"in",
"the",
"regions",
"which",
"typically",
"use",
"alpha",
"numbers",
".",
"-",
"This",
"will",
"also",
"not",
"produce",
"good",
"results",
"if",
"the",
"raw",
"input",
"has",
"any",
"grouping",
"information",
"within",
"the",
"first",
"three",
"digits",
"of",
"the",
"national",
"number",
"and",
"if",
"the",
"function",
"needs",
"to",
"strip",
"preceding",
"digits",
"/",
"words",
"in",
"the",
"raw",
"input",
"before",
"these",
"digits",
".",
"Normally",
"people",
"group",
"the",
"first",
"three",
"digits",
"together",
"so",
"this",
"is",
"not",
"a",
"huge",
"problem",
"-",
"and",
"will",
"be",
"fixed",
"if",
"it",
"proves",
"to",
"be",
"so",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1607-L1713 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1718-L1733 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1736-L1766 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1769-L1772 |
ttacon/libphonenumber | phonenumberutil.go | formatNsnWithCarrier | func formatNsnWithCarrier(
number string,
metadata *PhoneMetadata,
numberFormat PhoneNumberFormat,
carrierCode string) string {
var intlNumberFormats []*NumberFormat = metadata.GetIntlNumberFormat()
// When the intlNumberFormats exists, we use that to format national
// number for the INTERNATIONAL format instead of using the
// numberDesc.numberFormats.
var availableFormats []*NumberFormat = metadata.GetIntlNumberFormat()
if len(intlNumberFormats) == 0 || numberFormat == NATIONAL {
availableFormats = metadata.GetNumberFormat()
}
var formattingPattern *NumberFormat = chooseFormattingPatternForNumber(
availableFormats, number)
if formattingPattern == nil {
return number
}
return formatNsnUsingPatternWithCarrier(
number, formattingPattern, numberFormat, carrierCode)
} | go | func formatNsnWithCarrier(
number string,
metadata *PhoneMetadata,
numberFormat PhoneNumberFormat,
carrierCode string) string {
var intlNumberFormats []*NumberFormat = metadata.GetIntlNumberFormat()
// When the intlNumberFormats exists, we use that to format national
// number for the INTERNATIONAL format instead of using the
// numberDesc.numberFormats.
var availableFormats []*NumberFormat = metadata.GetIntlNumberFormat()
if len(intlNumberFormats) == 0 || numberFormat == NATIONAL {
availableFormats = metadata.GetNumberFormat()
}
var formattingPattern *NumberFormat = chooseFormattingPatternForNumber(
availableFormats, number)
if formattingPattern == nil {
return number
}
return formatNsnUsingPatternWithCarrier(
number, formattingPattern, numberFormat, carrierCode)
} | [
"func",
"formatNsnWithCarrier",
"(",
"number",
"string",
",",
"metadata",
"*",
"PhoneMetadata",
",",
"numberFormat",
"PhoneNumberFormat",
",",
"carrierCode",
"string",
")",
"string",
"{",
"var",
"intlNumberFormats",
"[",
"]",
"*",
"NumberFormat",
"=",
"metadata",
".",
"GetIntlNumberFormat",
"(",
")",
"\n",
"// When the intlNumberFormats exists, we use that to format national",
"// number for the INTERNATIONAL format instead of using the",
"// numberDesc.numberFormats.",
"var",
"availableFormats",
"[",
"]",
"*",
"NumberFormat",
"=",
"metadata",
".",
"GetIntlNumberFormat",
"(",
")",
"\n",
"if",
"len",
"(",
"intlNumberFormats",
")",
"==",
"0",
"||",
"numberFormat",
"==",
"NATIONAL",
"{",
"availableFormats",
"=",
"metadata",
".",
"GetNumberFormat",
"(",
")",
"\n",
"}",
"\n",
"var",
"formattingPattern",
"*",
"NumberFormat",
"=",
"chooseFormattingPatternForNumber",
"(",
"availableFormats",
",",
"number",
")",
"\n",
"if",
"formattingPattern",
"==",
"nil",
"{",
"return",
"number",
"\n",
"}",
"\n",
"return",
"formatNsnUsingPatternWithCarrier",
"(",
"number",
",",
"formattingPattern",
",",
"numberFormat",
",",
"carrierCode",
")",
"\n",
"}"
] | // Note in some regions, the national number can be written in two
// completely different ways depending on whether it forms part of the
// NATIONAL format or INTERNATIONAL format. The numberFormat parameter
// here is used to specify which format to use for those cases. If a
// carrierCode is specified, this will be inserted into the formatted
// string to replace $CC. | [
"Note",
"in",
"some",
"regions",
"the",
"national",
"number",
"can",
"be",
"written",
"in",
"two",
"completely",
"different",
"ways",
"depending",
"on",
"whether",
"it",
"forms",
"part",
"of",
"the",
"NATIONAL",
"format",
"or",
"INTERNATIONAL",
"format",
".",
"The",
"numberFormat",
"parameter",
"here",
"is",
"used",
"to",
"specify",
"which",
"format",
"to",
"use",
"for",
"those",
"cases",
".",
"If",
"a",
"carrierCode",
"is",
"specified",
"this",
"will",
"be",
"inserted",
"into",
"the",
"formatted",
"string",
"to",
"replace",
"$CC",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1780-L1800 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1844-L1850 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1854-L1930 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1938-L1954 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1958-L1978 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L1982-L2002 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2037-L2046 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2106-L2112 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2154-L2157 |
ttacon/libphonenumber | phonenumberutil.go | IsValidNumberForRegion | func IsValidNumberForRegion(number *PhoneNumber, regionCode string) bool {
var countryCode int = int(number.GetCountryCode())
var metadata *PhoneMetadata = getMetadataForRegionOrCallingCode(
countryCode, regionCode)
if metadata == nil ||
(REGION_CODE_FOR_NON_GEO_ENTITY != regionCode &&
countryCode != getCountryCodeForValidRegion(regionCode)) {
// Either the region code was invalid, or the country calling
// code for this number does not match that of the region code.
return false
}
var generalNumDesc *PhoneNumberDesc = metadata.GetGeneralDesc()
var nationalSignificantNumber string = GetNationalSignificantNumber(number)
// For regions where we don't have metadata for PhoneNumberDesc, we
// treat any number passed in as a valid number if its national
// significant number is between the minimum and maximum lengths
// defined by ITU for a national significant number.
if len(generalNumDesc.GetNationalNumberPattern()) == 0 {
var numberLength int = len(nationalSignificantNumber)
return numberLength > MIN_LENGTH_FOR_NSN &&
numberLength <= MAX_LENGTH_FOR_NSN
}
return getNumberTypeHelper(nationalSignificantNumber, metadata) != UNKNOWN
} | go | func IsValidNumberForRegion(number *PhoneNumber, regionCode string) bool {
var countryCode int = int(number.GetCountryCode())
var metadata *PhoneMetadata = getMetadataForRegionOrCallingCode(
countryCode, regionCode)
if metadata == nil ||
(REGION_CODE_FOR_NON_GEO_ENTITY != regionCode &&
countryCode != getCountryCodeForValidRegion(regionCode)) {
// Either the region code was invalid, or the country calling
// code for this number does not match that of the region code.
return false
}
var generalNumDesc *PhoneNumberDesc = metadata.GetGeneralDesc()
var nationalSignificantNumber string = GetNationalSignificantNumber(number)
// For regions where we don't have metadata for PhoneNumberDesc, we
// treat any number passed in as a valid number if its national
// significant number is between the minimum and maximum lengths
// defined by ITU for a national significant number.
if len(generalNumDesc.GetNationalNumberPattern()) == 0 {
var numberLength int = len(nationalSignificantNumber)
return numberLength > MIN_LENGTH_FOR_NSN &&
numberLength <= MAX_LENGTH_FOR_NSN
}
return getNumberTypeHelper(nationalSignificantNumber, metadata) != UNKNOWN
} | [
"func",
"IsValidNumberForRegion",
"(",
"number",
"*",
"PhoneNumber",
",",
"regionCode",
"string",
")",
"bool",
"{",
"var",
"countryCode",
"int",
"=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"var",
"metadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCode",
",",
"regionCode",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"||",
"(",
"REGION_CODE_FOR_NON_GEO_ENTITY",
"!=",
"regionCode",
"&&",
"countryCode",
"!=",
"getCountryCodeForValidRegion",
"(",
"regionCode",
")",
")",
"{",
"// Either the region code was invalid, or the country calling",
"// code for this number does not match that of the region code.",
"return",
"false",
"\n",
"}",
"\n",
"var",
"generalNumDesc",
"*",
"PhoneNumberDesc",
"=",
"metadata",
".",
"GetGeneralDesc",
"(",
")",
"\n",
"var",
"nationalSignificantNumber",
"string",
"=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"// For regions where we don't have metadata for PhoneNumberDesc, we",
"// treat any number passed in as a valid number if its national",
"// significant number is between the minimum and maximum lengths",
"// defined by ITU for a national significant number.",
"if",
"len",
"(",
"generalNumDesc",
".",
"GetNationalNumberPattern",
"(",
")",
")",
"==",
"0",
"{",
"var",
"numberLength",
"int",
"=",
"len",
"(",
"nationalSignificantNumber",
")",
"\n",
"return",
"numberLength",
">",
"MIN_LENGTH_FOR_NSN",
"&&",
"numberLength",
"<=",
"MAX_LENGTH_FOR_NSN",
"\n",
"}",
"\n",
"return",
"getNumberTypeHelper",
"(",
"nationalSignificantNumber",
",",
"metadata",
")",
"!=",
"UNKNOWN",
"\n",
"}"
] | // Tests whether a phone number is valid for a certain region. Note this
// doesn't verify the number is actually in use, which is impossible to
// tell by just looking at a number itself. If the country calling code is
// not the same as the country calling code for the region, this immediately
// exits with false. After this, the specific number pattern rules for the
// region are examined. This is useful for determining for example whether
// a particular number is valid for Canada, rather than just a valid NANPA
// number.
// Warning: In most cases, you want to use IsValidNumber() instead. For
// example, this method will mark numbers from British Crown dependencies
// such as the Isle of Man as invalid for the region "GB" (United Kingdom),
// since it has its own region code, "IM", which may be undesirable. | [
"Tests",
"whether",
"a",
"phone",
"number",
"is",
"valid",
"for",
"a",
"certain",
"region",
".",
"Note",
"this",
"doesn",
"t",
"verify",
"the",
"number",
"is",
"actually",
"in",
"use",
"which",
"is",
"impossible",
"to",
"tell",
"by",
"just",
"looking",
"at",
"a",
"number",
"itself",
".",
"If",
"the",
"country",
"calling",
"code",
"is",
"not",
"the",
"same",
"as",
"the",
"country",
"calling",
"code",
"for",
"the",
"region",
"this",
"immediately",
"exits",
"with",
"false",
".",
"After",
"this",
"the",
"specific",
"number",
"pattern",
"rules",
"for",
"the",
"region",
"are",
"examined",
".",
"This",
"is",
"useful",
"for",
"determining",
"for",
"example",
"whether",
"a",
"particular",
"number",
"is",
"valid",
"for",
"Canada",
"rather",
"than",
"just",
"a",
"valid",
"NANPA",
"number",
".",
"Warning",
":",
"In",
"most",
"cases",
"you",
"want",
"to",
"use",
"IsValidNumber",
"()",
"instead",
".",
"For",
"example",
"this",
"method",
"will",
"mark",
"numbers",
"from",
"British",
"Crown",
"dependencies",
"such",
"as",
"the",
"Isle",
"of",
"Man",
"as",
"invalid",
"for",
"the",
"region",
"GB",
"(",
"United",
"Kingdom",
")",
"since",
"it",
"has",
"its",
"own",
"region",
"code",
"IM",
"which",
"may",
"be",
"undesirable",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2171-L2194 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2198-L2208 |
ttacon/libphonenumber | phonenumberutil.go | GetRegionCodeForCountryCode | func GetRegionCodeForCountryCode(countryCallingCode int) string {
var regionCodes []string = CountryCodeToRegion[countryCallingCode]
if len(regionCodes) == 0 {
return UNKNOWN_REGION
}
return regionCodes[0]
} | go | func GetRegionCodeForCountryCode(countryCallingCode int) string {
var regionCodes []string = CountryCodeToRegion[countryCallingCode]
if len(regionCodes) == 0 {
return UNKNOWN_REGION
}
return regionCodes[0]
} | [
"func",
"GetRegionCodeForCountryCode",
"(",
"countryCallingCode",
"int",
")",
"string",
"{",
"var",
"regionCodes",
"[",
"]",
"string",
"=",
"CountryCodeToRegion",
"[",
"countryCallingCode",
"]",
"\n",
"if",
"len",
"(",
"regionCodes",
")",
"==",
"0",
"{",
"return",
"UNKNOWN_REGION",
"\n",
"}",
"\n",
"return",
"regionCodes",
"[",
"0",
"]",
"\n",
"}"
] | // Returns the region code that matches the specific country calling code.
// In the case of no region code being found, ZZ will be returned. In the
// case of multiple regions, the one designated in the metadata as the
// "main" region for this calling code will be returned. If the
// countryCallingCode entered is valid but doesn't match a specific region
// (such as in the case of non-geographical calling codes like 800) the
// value "001" will be returned (corresponding to the value for World in
// the UN M.49 schema). | [
"Returns",
"the",
"region",
"code",
"that",
"matches",
"the",
"specific",
"country",
"calling",
"code",
".",
"In",
"the",
"case",
"of",
"no",
"region",
"code",
"being",
"found",
"ZZ",
"will",
"be",
"returned",
".",
"In",
"the",
"case",
"of",
"multiple",
"regions",
"the",
"one",
"designated",
"in",
"the",
"metadata",
"as",
"the",
"main",
"region",
"for",
"this",
"calling",
"code",
"will",
"be",
"returned",
".",
"If",
"the",
"countryCallingCode",
"entered",
"is",
"valid",
"but",
"doesn",
"t",
"match",
"a",
"specific",
"region",
"(",
"such",
"as",
"in",
"the",
"case",
"of",
"non",
"-",
"geographical",
"calling",
"codes",
"like",
"800",
")",
"the",
"value",
"001",
"will",
"be",
"returned",
"(",
"corresponding",
"to",
"the",
"value",
"for",
"World",
"in",
"the",
"UN",
"M",
".",
"49",
"schema",
")",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2245-L2251 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2274-L2277 |
ttacon/libphonenumber | phonenumberutil.go | GetNddPrefixForRegion | func GetNddPrefixForRegion(regionCode string, stripNonDigits bool) string {
var metadata *PhoneMetadata = getMetadataForRegion(regionCode)
if metadata == nil {
return ""
}
var nationalPrefix string = metadata.GetNationalPrefix()
// If no national prefix was found, we return an empty string.
if len(nationalPrefix) == 0 {
return ""
}
if stripNonDigits {
// Note: if any other non-numeric symbols are ever used in
// national prefixes, these would have to be removed here as well.
nationalPrefix = strings.Replace(nationalPrefix, "~", "", -1)
}
return nationalPrefix
} | go | func GetNddPrefixForRegion(regionCode string, stripNonDigits bool) string {
var metadata *PhoneMetadata = getMetadataForRegion(regionCode)
if metadata == nil {
return ""
}
var nationalPrefix string = metadata.GetNationalPrefix()
// If no national prefix was found, we return an empty string.
if len(nationalPrefix) == 0 {
return ""
}
if stripNonDigits {
// Note: if any other non-numeric symbols are ever used in
// national prefixes, these would have to be removed here as well.
nationalPrefix = strings.Replace(nationalPrefix, "~", "", -1)
}
return nationalPrefix
} | [
"func",
"GetNddPrefixForRegion",
"(",
"regionCode",
"string",
",",
"stripNonDigits",
"bool",
")",
"string",
"{",
"var",
"metadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegion",
"(",
"regionCode",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"var",
"nationalPrefix",
"string",
"=",
"metadata",
".",
"GetNationalPrefix",
"(",
")",
"\n",
"// If no national prefix was found, we return an empty string.",
"if",
"len",
"(",
"nationalPrefix",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"stripNonDigits",
"{",
"// Note: if any other non-numeric symbols are ever used in",
"// national prefixes, these would have to be removed here as well.",
"nationalPrefix",
"=",
"strings",
".",
"Replace",
"(",
"nationalPrefix",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"return",
"nationalPrefix",
"\n",
"}"
] | // Returns the national dialling prefix for a specific region. For example,
// this would be 1 for the United States, and 0 for New Zealand. Set
// stripNonDigits to true to strip symbols like "~" (which indicates a
// wait for a dialling tone) from the prefix returned. If no national prefix
// is present, we return null.
//
// Warning: Do not use this method for do-your-own formatting - for some
// regions, the national dialling prefix is used only for certain types
// of numbers. Use the library's formatting functions to prefix the
// national prefix when required. | [
"Returns",
"the",
"national",
"dialling",
"prefix",
"for",
"a",
"specific",
"region",
".",
"For",
"example",
"this",
"would",
"be",
"1",
"for",
"the",
"United",
"States",
"and",
"0",
"for",
"New",
"Zealand",
".",
"Set",
"stripNonDigits",
"to",
"true",
"to",
"strip",
"symbols",
"like",
"~",
"(",
"which",
"indicates",
"a",
"wait",
"for",
"a",
"dialling",
"tone",
")",
"from",
"the",
"prefix",
"returned",
".",
"If",
"no",
"national",
"prefix",
"is",
"present",
"we",
"return",
"null",
".",
"Warning",
":",
"Do",
"not",
"use",
"this",
"method",
"for",
"do",
"-",
"your",
"-",
"own",
"formatting",
"-",
"for",
"some",
"regions",
"the",
"national",
"dialling",
"prefix",
"is",
"used",
"only",
"for",
"certain",
"types",
"of",
"numbers",
".",
"Use",
"the",
"library",
"s",
"formatting",
"functions",
"to",
"prefix",
"the",
"national",
"prefix",
"when",
"required",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2289-L2305 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2317-L2323 |
ttacon/libphonenumber | phonenumberutil.go | IsAlphaNumber | func IsAlphaNumber(number string) bool {
if !isViablePhoneNumber(number) {
// Number is too short, or doesn't match the basic phone
// number pattern.
return false
}
strippedNumber := builder.NewBuilderString(number)
maybeStripExtension(strippedNumber)
return VALID_ALPHA_PHONE_PATTERN.MatchString(strippedNumber.String())
} | go | func IsAlphaNumber(number string) bool {
if !isViablePhoneNumber(number) {
// Number is too short, or doesn't match the basic phone
// number pattern.
return false
}
strippedNumber := builder.NewBuilderString(number)
maybeStripExtension(strippedNumber)
return VALID_ALPHA_PHONE_PATTERN.MatchString(strippedNumber.String())
} | [
"func",
"IsAlphaNumber",
"(",
"number",
"string",
")",
"bool",
"{",
"if",
"!",
"isViablePhoneNumber",
"(",
"number",
")",
"{",
"// Number is too short, or doesn't match the basic phone",
"// number pattern.",
"return",
"false",
"\n",
"}",
"\n",
"strippedNumber",
":=",
"builder",
".",
"NewBuilderString",
"(",
"number",
")",
"\n",
"maybeStripExtension",
"(",
"strippedNumber",
")",
"\n",
"return",
"VALID_ALPHA_PHONE_PATTERN",
".",
"MatchString",
"(",
"strippedNumber",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // Checks if the number is a valid vanity (alpha) number such as 800
// MICROSOFT. A valid vanity number will start with at least 3 digits and
// will have three or more alpha characters. This does not do
// region-specific checks - to work out if this number is actually valid
// for a region, it should be parsed and methods such as
// IsPossibleNumberWithReason() and IsValidNumber() should be used. | [
"Checks",
"if",
"the",
"number",
"is",
"a",
"valid",
"vanity",
"(",
"alpha",
")",
"number",
"such",
"as",
"800",
"MICROSOFT",
".",
"A",
"valid",
"vanity",
"number",
"will",
"start",
"with",
"at",
"least",
"3",
"digits",
"and",
"will",
"have",
"three",
"or",
"more",
"alpha",
"characters",
".",
"This",
"does",
"not",
"do",
"region",
"-",
"specific",
"checks",
"-",
"to",
"work",
"out",
"if",
"this",
"number",
"is",
"actually",
"valid",
"for",
"a",
"region",
"it",
"should",
"be",
"parsed",
"and",
"methods",
"such",
"as",
"IsPossibleNumberWithReason",
"()",
"and",
"IsValidNumber",
"()",
"should",
"be",
"used",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2331-L2340 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2370-L2381 |
ttacon/libphonenumber | phonenumberutil.go | IsPossibleNumberWithReason | func IsPossibleNumberWithReason(number *PhoneNumber) ValidationResult {
nationalNumber := GetNationalSignificantNumber(number)
countryCode := int(number.GetCountryCode())
// Note: For Russian Fed and NANPA numbers, we just use the rules
// from the default region (US or Russia) since the
// getRegionCodeForNumber will not work if the number is possible
// but not valid. This would need to be revisited if the possible
// number pattern ever differed between various regions within
// those plans.
if !hasValidCountryCallingCode(countryCode) {
return INVALID_COUNTRY_CODE
}
regionCode := GetRegionCodeForCountryCode(countryCode)
// Metadata cannot be null because the country calling code is valid.
var metadata *PhoneMetadata = getMetadataForRegionOrCallingCode(
countryCode, regionCode)
var generalNumDesc *PhoneNumberDesc = metadata.GetGeneralDesc()
// Handling case of numbers with no metadata.
if len(generalNumDesc.GetNationalNumberPattern()) == 0 {
numberLength := len(nationalNumber)
if numberLength < MIN_LENGTH_FOR_NSN {
return TOO_SHORT
} else if numberLength > MAX_LENGTH_FOR_NSN {
return TOO_LONG
} else {
return IS_POSSIBLE
}
}
pat, ok := readFromRegexCache(generalNumDesc.GetNationalNumberPattern())
if !ok {
patP := generalNumDesc.GetNationalNumberPattern()
pat = regexp.MustCompile(patP)
writeToRegexCache(patP, pat)
}
return testNumberLengthAgainstPattern(pat, nationalNumber)
} | go | func IsPossibleNumberWithReason(number *PhoneNumber) ValidationResult {
nationalNumber := GetNationalSignificantNumber(number)
countryCode := int(number.GetCountryCode())
// Note: For Russian Fed and NANPA numbers, we just use the rules
// from the default region (US or Russia) since the
// getRegionCodeForNumber will not work if the number is possible
// but not valid. This would need to be revisited if the possible
// number pattern ever differed between various regions within
// those plans.
if !hasValidCountryCallingCode(countryCode) {
return INVALID_COUNTRY_CODE
}
regionCode := GetRegionCodeForCountryCode(countryCode)
// Metadata cannot be null because the country calling code is valid.
var metadata *PhoneMetadata = getMetadataForRegionOrCallingCode(
countryCode, regionCode)
var generalNumDesc *PhoneNumberDesc = metadata.GetGeneralDesc()
// Handling case of numbers with no metadata.
if len(generalNumDesc.GetNationalNumberPattern()) == 0 {
numberLength := len(nationalNumber)
if numberLength < MIN_LENGTH_FOR_NSN {
return TOO_SHORT
} else if numberLength > MAX_LENGTH_FOR_NSN {
return TOO_LONG
} else {
return IS_POSSIBLE
}
}
pat, ok := readFromRegexCache(generalNumDesc.GetNationalNumberPattern())
if !ok {
patP := generalNumDesc.GetNationalNumberPattern()
pat = regexp.MustCompile(patP)
writeToRegexCache(patP, pat)
}
return testNumberLengthAgainstPattern(pat, nationalNumber)
} | [
"func",
"IsPossibleNumberWithReason",
"(",
"number",
"*",
"PhoneNumber",
")",
"ValidationResult",
"{",
"nationalNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"countryCode",
":=",
"int",
"(",
"number",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"// Note: For Russian Fed and NANPA numbers, we just use the rules",
"// from the default region (US or Russia) since the",
"// getRegionCodeForNumber will not work if the number is possible",
"// but not valid. This would need to be revisited if the possible",
"// number pattern ever differed between various regions within",
"// those plans.",
"if",
"!",
"hasValidCountryCallingCode",
"(",
"countryCode",
")",
"{",
"return",
"INVALID_COUNTRY_CODE",
"\n",
"}",
"\n",
"regionCode",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCode",
")",
"\n",
"// Metadata cannot be null because the country calling code is valid.",
"var",
"metadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCode",
",",
"regionCode",
")",
"\n",
"var",
"generalNumDesc",
"*",
"PhoneNumberDesc",
"=",
"metadata",
".",
"GetGeneralDesc",
"(",
")",
"\n",
"// Handling case of numbers with no metadata.",
"if",
"len",
"(",
"generalNumDesc",
".",
"GetNationalNumberPattern",
"(",
")",
")",
"==",
"0",
"{",
"numberLength",
":=",
"len",
"(",
"nationalNumber",
")",
"\n",
"if",
"numberLength",
"<",
"MIN_LENGTH_FOR_NSN",
"{",
"return",
"TOO_SHORT",
"\n",
"}",
"else",
"if",
"numberLength",
">",
"MAX_LENGTH_FOR_NSN",
"{",
"return",
"TOO_LONG",
"\n",
"}",
"else",
"{",
"return",
"IS_POSSIBLE",
"\n",
"}",
"\n",
"}",
"\n",
"pat",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"generalNumDesc",
".",
"GetNationalNumberPattern",
"(",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"patP",
":=",
"generalNumDesc",
".",
"GetNationalNumberPattern",
"(",
")",
"\n",
"pat",
"=",
"regexp",
".",
"MustCompile",
"(",
"patP",
")",
"\n",
"writeToRegexCache",
"(",
"patP",
",",
"pat",
")",
"\n",
"}",
"\n",
"return",
"testNumberLengthAgainstPattern",
"(",
"pat",
",",
"nationalNumber",
")",
"\n",
"}"
] | // Check whether a phone number is a possible number. It provides a more
// lenient check than IsValidNumber() in the following sense:
//
// - It only checks the length of phone numbers. In particular, it
// doesn't check starting digits of the number.
// - It doesn't attempt to figure out the type of the number, but uses
// general rules which applies to all types of phone numbers in a
// region. Therefore, it is much faster than isValidNumber.
// - For fixed line numbers, many regions have the concept of area code,
// which together with subscriber number constitute the national
// significant number. It is sometimes okay to dial the subscriber number
// only when dialing in the same area. This function will return true
// if the subscriber-number-only version is passed in. On the other hand,
// because isValidNumber validates using information on both starting
// digits (for fixed line numbers, that would most likely be area codes)
// and length (obviously includes the length of area codes for fixed
// line numbers), it will return false for the subscriber-number-only
// version. | [
"Check",
"whether",
"a",
"phone",
"number",
"is",
"a",
"possible",
"number",
".",
"It",
"provides",
"a",
"more",
"lenient",
"check",
"than",
"IsValidNumber",
"()",
"in",
"the",
"following",
"sense",
":",
"-",
"It",
"only",
"checks",
"the",
"length",
"of",
"phone",
"numbers",
".",
"In",
"particular",
"it",
"doesn",
"t",
"check",
"starting",
"digits",
"of",
"the",
"number",
".",
"-",
"It",
"doesn",
"t",
"attempt",
"to",
"figure",
"out",
"the",
"type",
"of",
"the",
"number",
"but",
"uses",
"general",
"rules",
"which",
"applies",
"to",
"all",
"types",
"of",
"phone",
"numbers",
"in",
"a",
"region",
".",
"Therefore",
"it",
"is",
"much",
"faster",
"than",
"isValidNumber",
".",
"-",
"For",
"fixed",
"line",
"numbers",
"many",
"regions",
"have",
"the",
"concept",
"of",
"area",
"code",
"which",
"together",
"with",
"subscriber",
"number",
"constitute",
"the",
"national",
"significant",
"number",
".",
"It",
"is",
"sometimes",
"okay",
"to",
"dial",
"the",
"subscriber",
"number",
"only",
"when",
"dialing",
"in",
"the",
"same",
"area",
".",
"This",
"function",
"will",
"return",
"true",
"if",
"the",
"subscriber",
"-",
"number",
"-",
"only",
"version",
"is",
"passed",
"in",
".",
"On",
"the",
"other",
"hand",
"because",
"isValidNumber",
"validates",
"using",
"information",
"on",
"both",
"starting",
"digits",
"(",
"for",
"fixed",
"line",
"numbers",
"that",
"would",
"most",
"likely",
"be",
"area",
"codes",
")",
"and",
"length",
"(",
"obviously",
"includes",
"the",
"length",
"of",
"area",
"codes",
"for",
"fixed",
"line",
"numbers",
")",
"it",
"will",
"return",
"false",
"for",
"the",
"subscriber",
"-",
"number",
"-",
"only",
"version",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2401-L2436 |
ttacon/libphonenumber | phonenumberutil.go | isPossibleNumberWithRegion | func isPossibleNumberWithRegion(number, regionDialingFrom string) bool {
num, err := Parse(number, regionDialingFrom)
if err != nil {
return false
}
return IsPossibleNumber(num)
} | go | func isPossibleNumberWithRegion(number, regionDialingFrom string) bool {
num, err := Parse(number, regionDialingFrom)
if err != nil {
return false
}
return IsPossibleNumber(num)
} | [
"func",
"isPossibleNumberWithRegion",
"(",
"number",
",",
"regionDialingFrom",
"string",
")",
"bool",
"{",
"num",
",",
"err",
":=",
"Parse",
"(",
"number",
",",
"regionDialingFrom",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"IsPossibleNumber",
"(",
"num",
")",
"\n",
"}"
] | // Check whether a phone number is a possible number given a number in the
// form of a string, and the region where the number could be dialed from.
// It provides a more lenient check than IsValidNumber(). See
// IsPossibleNumber(PhoneNumber) for details.
//
// This method first parses the number, then invokes
// IsPossibleNumber(PhoneNumber) with the resultant PhoneNumber object. | [
"Check",
"whether",
"a",
"phone",
"number",
"is",
"a",
"possible",
"number",
"given",
"a",
"number",
"in",
"the",
"form",
"of",
"a",
"string",
"and",
"the",
"region",
"where",
"the",
"number",
"could",
"be",
"dialed",
"from",
".",
"It",
"provides",
"a",
"more",
"lenient",
"check",
"than",
"IsValidNumber",
"()",
".",
"See",
"IsPossibleNumber",
"(",
"PhoneNumber",
")",
"for",
"details",
".",
"This",
"method",
"first",
"parses",
"the",
"number",
"then",
"invokes",
"IsPossibleNumber",
"(",
"PhoneNumber",
")",
"with",
"the",
"resultant",
"PhoneNumber",
"object",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2445-L2451 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2457-L2480 |
ttacon/libphonenumber | phonenumberutil.go | extractCountryCode | func extractCountryCode(fullNumber, nationalNumber *builder.Builder) int {
fullNumBytes := fullNumber.Bytes()
if len(fullNumBytes) == 0 || fullNumBytes[0] == '0' {
// Country codes do not begin with a '0'.
return 0
}
var (
potentialCountryCode int
numberLength = len(fullNumBytes)
)
for i := 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++ {
potentialCountryCode, _ = strconv.Atoi(string(fullNumBytes[0:i]))
if _, ok := CountryCodeToRegion[potentialCountryCode]; ok {
nationalNumber.Write(fullNumBytes[i:])
return potentialCountryCode
}
}
return 0
} | go | func extractCountryCode(fullNumber, nationalNumber *builder.Builder) int {
fullNumBytes := fullNumber.Bytes()
if len(fullNumBytes) == 0 || fullNumBytes[0] == '0' {
// Country codes do not begin with a '0'.
return 0
}
var (
potentialCountryCode int
numberLength = len(fullNumBytes)
)
for i := 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++ {
potentialCountryCode, _ = strconv.Atoi(string(fullNumBytes[0:i]))
if _, ok := CountryCodeToRegion[potentialCountryCode]; ok {
nationalNumber.Write(fullNumBytes[i:])
return potentialCountryCode
}
}
return 0
} | [
"func",
"extractCountryCode",
"(",
"fullNumber",
",",
"nationalNumber",
"*",
"builder",
".",
"Builder",
")",
"int",
"{",
"fullNumBytes",
":=",
"fullNumber",
".",
"Bytes",
"(",
")",
"\n",
"if",
"len",
"(",
"fullNumBytes",
")",
"==",
"0",
"||",
"fullNumBytes",
"[",
"0",
"]",
"==",
"'0'",
"{",
"// Country codes do not begin with a '0'.",
"return",
"0",
"\n",
"}",
"\n",
"var",
"(",
"potentialCountryCode",
"int",
"\n",
"numberLength",
"=",
"len",
"(",
"fullNumBytes",
")",
"\n",
")",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<=",
"MAX_LENGTH_COUNTRY_CODE",
"&&",
"i",
"<=",
"numberLength",
";",
"i",
"++",
"{",
"potentialCountryCode",
",",
"_",
"=",
"strconv",
".",
"Atoi",
"(",
"string",
"(",
"fullNumBytes",
"[",
"0",
":",
"i",
"]",
")",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"CountryCodeToRegion",
"[",
"potentialCountryCode",
"]",
";",
"ok",
"{",
"nationalNumber",
".",
"Write",
"(",
"fullNumBytes",
"[",
"i",
":",
"]",
")",
"\n",
"return",
"potentialCountryCode",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"0",
"\n",
"}"
] | // Gets an AsYouTypeFormatter for the specific region.
// TODO(ttacon): uncomment once we do asyoutypeformatter.go
//public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
// return new AsYouTypeFormatter(regionCode);
//}
// Extracts country calling code from fullNumber, returns it and places
// the remaining number in nationalNumber. It assumes that the leading plus
// sign or IDD has already been removed. Returns 0 if fullNumber doesn't
// start with a valid country calling code, and leaves nationalNumber
// unmodified. | [
"Gets",
"an",
"AsYouTypeFormatter",
"for",
"the",
"specific",
"region",
".",
"TODO",
"(",
"ttacon",
")",
":",
"uncomment",
"once",
"we",
"do",
"asyoutypeformatter",
".",
"go",
"public",
"AsYouTypeFormatter",
"getAsYouTypeFormatter",
"(",
"String",
"regionCode",
")",
"{",
"return",
"new",
"AsYouTypeFormatter",
"(",
"regionCode",
")",
";",
"}",
"Extracts",
"country",
"calling",
"code",
"from",
"fullNumber",
"returns",
"it",
"and",
"places",
"the",
"remaining",
"number",
"in",
"nationalNumber",
".",
"It",
"assumes",
"that",
"the",
"leading",
"plus",
"sign",
"or",
"IDD",
"has",
"already",
"been",
"removed",
".",
"Returns",
"0",
"if",
"fullNumber",
"doesn",
"t",
"start",
"with",
"a",
"valid",
"country",
"calling",
"code",
"and",
"leaves",
"nationalNumber",
"unmodified",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2493-L2511 |
ttacon/libphonenumber | phonenumberutil.go | maybeExtractCountryCode | func maybeExtractCountryCode(
number string,
defaultRegionMetadata *PhoneMetadata,
nationalNumber *builder.Builder,
keepRawInput bool,
phoneNumber *PhoneNumber) (int, error) {
if len(number) == 0 {
return 0, nil
}
fullNumber := builder.NewBuilderString(number)
// Set the default prefix to be something that will never match.
possibleCountryIddPrefix := "NonMatch"
if defaultRegionMetadata != nil {
possibleCountryIddPrefix = defaultRegionMetadata.GetInternationalPrefix()
}
countryCodeSource :=
maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix)
if keepRawInput {
phoneNumber.CountryCodeSource = &countryCodeSource
}
if countryCodeSource != PhoneNumber_FROM_DEFAULT_COUNTRY {
if len(fullNumber.String()) <= MIN_LENGTH_FOR_NSN {
return 0, ErrTooShortAfterIDD
}
potentialCountryCode := extractCountryCode(fullNumber, nationalNumber)
if potentialCountryCode != 0 {
phoneNumber.CountryCode = proto.Int(potentialCountryCode)
return potentialCountryCode, nil
}
// If this fails, they must be using a strange country calling code
// that we don't recognize, or that doesn't exist.
return 0, ErrInvalidCountryCode
} else if defaultRegionMetadata != nil {
// Check to see if the number starts with the country calling code
// for the default region. If so, we remove the country calling
// code, and do some checks on the validity of the number before
// and after.
defaultCountryCode := int(defaultRegionMetadata.GetCountryCode())
defaultCountryCodeString := strconv.Itoa(defaultCountryCode)
normalizedNumber := fullNumber.String()
if strings.HasPrefix(normalizedNumber, defaultCountryCodeString) {
var (
potentialNationalNumber = builder.NewBuilderString(
normalizedNumber[len(defaultCountryCodeString):])
generalDesc = defaultRegionMetadata.GetGeneralDesc()
patP = `^(?:` + generalDesc.GetNationalNumberPattern() + `)$` // Strictly match
validNumberPattern, ok = readFromRegexCache(patP)
)
if !ok {
validNumberPattern = regexp.MustCompile(patP)
writeToRegexCache(patP, validNumberPattern)
}
maybeStripNationalPrefixAndCarrierCode(
potentialNationalNumber,
defaultRegionMetadata,
builder.NewBuilder(nil) /* Don't need the carrier code */)
nationalNumberPattern, ok := readFromRegexCache(generalDesc.GetNationalNumberPattern())
if !ok {
pat := generalDesc.GetNationalNumberPattern()
nationalNumberPattern = regexp.MustCompile(pat)
writeToRegexCache(pat, nationalNumberPattern)
}
// If the number was not valid before but is valid now, or
// if it was too long before, we consider the number with
// the country calling code stripped to be a better result and
// keep that instead.
if (!validNumberPattern.MatchString(fullNumber.String()) &&
validNumberPattern.MatchString(potentialNationalNumber.String())) ||
testNumberLengthAgainstPattern(
nationalNumberPattern, fullNumber.String()) == TOO_LONG {
nationalNumber.Write(potentialNationalNumber.Bytes())
if keepRawInput {
val := PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN
phoneNumber.CountryCodeSource = &val
}
phoneNumber.CountryCode = proto.Int(defaultCountryCode)
return defaultCountryCode, nil
}
}
}
// No country calling code present.
phoneNumber.CountryCode = proto.Int(0)
return 0, nil
} | go | func maybeExtractCountryCode(
number string,
defaultRegionMetadata *PhoneMetadata,
nationalNumber *builder.Builder,
keepRawInput bool,
phoneNumber *PhoneNumber) (int, error) {
if len(number) == 0 {
return 0, nil
}
fullNumber := builder.NewBuilderString(number)
// Set the default prefix to be something that will never match.
possibleCountryIddPrefix := "NonMatch"
if defaultRegionMetadata != nil {
possibleCountryIddPrefix = defaultRegionMetadata.GetInternationalPrefix()
}
countryCodeSource :=
maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix)
if keepRawInput {
phoneNumber.CountryCodeSource = &countryCodeSource
}
if countryCodeSource != PhoneNumber_FROM_DEFAULT_COUNTRY {
if len(fullNumber.String()) <= MIN_LENGTH_FOR_NSN {
return 0, ErrTooShortAfterIDD
}
potentialCountryCode := extractCountryCode(fullNumber, nationalNumber)
if potentialCountryCode != 0 {
phoneNumber.CountryCode = proto.Int(potentialCountryCode)
return potentialCountryCode, nil
}
// If this fails, they must be using a strange country calling code
// that we don't recognize, or that doesn't exist.
return 0, ErrInvalidCountryCode
} else if defaultRegionMetadata != nil {
// Check to see if the number starts with the country calling code
// for the default region. If so, we remove the country calling
// code, and do some checks on the validity of the number before
// and after.
defaultCountryCode := int(defaultRegionMetadata.GetCountryCode())
defaultCountryCodeString := strconv.Itoa(defaultCountryCode)
normalizedNumber := fullNumber.String()
if strings.HasPrefix(normalizedNumber, defaultCountryCodeString) {
var (
potentialNationalNumber = builder.NewBuilderString(
normalizedNumber[len(defaultCountryCodeString):])
generalDesc = defaultRegionMetadata.GetGeneralDesc()
patP = `^(?:` + generalDesc.GetNationalNumberPattern() + `)$` // Strictly match
validNumberPattern, ok = readFromRegexCache(patP)
)
if !ok {
validNumberPattern = regexp.MustCompile(patP)
writeToRegexCache(patP, validNumberPattern)
}
maybeStripNationalPrefixAndCarrierCode(
potentialNationalNumber,
defaultRegionMetadata,
builder.NewBuilder(nil) /* Don't need the carrier code */)
nationalNumberPattern, ok := readFromRegexCache(generalDesc.GetNationalNumberPattern())
if !ok {
pat := generalDesc.GetNationalNumberPattern()
nationalNumberPattern = regexp.MustCompile(pat)
writeToRegexCache(pat, nationalNumberPattern)
}
// If the number was not valid before but is valid now, or
// if it was too long before, we consider the number with
// the country calling code stripped to be a better result and
// keep that instead.
if (!validNumberPattern.MatchString(fullNumber.String()) &&
validNumberPattern.MatchString(potentialNationalNumber.String())) ||
testNumberLengthAgainstPattern(
nationalNumberPattern, fullNumber.String()) == TOO_LONG {
nationalNumber.Write(potentialNationalNumber.Bytes())
if keepRawInput {
val := PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN
phoneNumber.CountryCodeSource = &val
}
phoneNumber.CountryCode = proto.Int(defaultCountryCode)
return defaultCountryCode, nil
}
}
}
// No country calling code present.
phoneNumber.CountryCode = proto.Int(0)
return 0, nil
} | [
"func",
"maybeExtractCountryCode",
"(",
"number",
"string",
",",
"defaultRegionMetadata",
"*",
"PhoneMetadata",
",",
"nationalNumber",
"*",
"builder",
".",
"Builder",
",",
"keepRawInput",
"bool",
",",
"phoneNumber",
"*",
"PhoneNumber",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"len",
"(",
"number",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"fullNumber",
":=",
"builder",
".",
"NewBuilderString",
"(",
"number",
")",
"\n",
"// Set the default prefix to be something that will never match.",
"possibleCountryIddPrefix",
":=",
"\"",
"\"",
"\n",
"if",
"defaultRegionMetadata",
"!=",
"nil",
"{",
"possibleCountryIddPrefix",
"=",
"defaultRegionMetadata",
".",
"GetInternationalPrefix",
"(",
")",
"\n",
"}",
"\n\n",
"countryCodeSource",
":=",
"maybeStripInternationalPrefixAndNormalize",
"(",
"fullNumber",
",",
"possibleCountryIddPrefix",
")",
"\n",
"if",
"keepRawInput",
"{",
"phoneNumber",
".",
"CountryCodeSource",
"=",
"&",
"countryCodeSource",
"\n",
"}",
"\n",
"if",
"countryCodeSource",
"!=",
"PhoneNumber_FROM_DEFAULT_COUNTRY",
"{",
"if",
"len",
"(",
"fullNumber",
".",
"String",
"(",
")",
")",
"<=",
"MIN_LENGTH_FOR_NSN",
"{",
"return",
"0",
",",
"ErrTooShortAfterIDD",
"\n",
"}",
"\n",
"potentialCountryCode",
":=",
"extractCountryCode",
"(",
"fullNumber",
",",
"nationalNumber",
")",
"\n",
"if",
"potentialCountryCode",
"!=",
"0",
"{",
"phoneNumber",
".",
"CountryCode",
"=",
"proto",
".",
"Int",
"(",
"potentialCountryCode",
")",
"\n",
"return",
"potentialCountryCode",
",",
"nil",
"\n",
"}",
"\n\n",
"// If this fails, they must be using a strange country calling code",
"// that we don't recognize, or that doesn't exist.",
"return",
"0",
",",
"ErrInvalidCountryCode",
"\n",
"}",
"else",
"if",
"defaultRegionMetadata",
"!=",
"nil",
"{",
"// Check to see if the number starts with the country calling code",
"// for the default region. If so, we remove the country calling",
"// code, and do some checks on the validity of the number before",
"// and after.",
"defaultCountryCode",
":=",
"int",
"(",
"defaultRegionMetadata",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"defaultCountryCodeString",
":=",
"strconv",
".",
"Itoa",
"(",
"defaultCountryCode",
")",
"\n",
"normalizedNumber",
":=",
"fullNumber",
".",
"String",
"(",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"normalizedNumber",
",",
"defaultCountryCodeString",
")",
"{",
"var",
"(",
"potentialNationalNumber",
"=",
"builder",
".",
"NewBuilderString",
"(",
"normalizedNumber",
"[",
"len",
"(",
"defaultCountryCodeString",
")",
":",
"]",
")",
"\n",
"generalDesc",
"=",
"defaultRegionMetadata",
".",
"GetGeneralDesc",
"(",
")",
"\n",
"patP",
"=",
"`^(?:`",
"+",
"generalDesc",
".",
"GetNationalNumberPattern",
"(",
")",
"+",
"`)$`",
"// Strictly match",
"\n",
"validNumberPattern",
",",
"ok",
"=",
"readFromRegexCache",
"(",
"patP",
")",
"\n",
")",
"\n",
"if",
"!",
"ok",
"{",
"validNumberPattern",
"=",
"regexp",
".",
"MustCompile",
"(",
"patP",
")",
"\n",
"writeToRegexCache",
"(",
"patP",
",",
"validNumberPattern",
")",
"\n",
"}",
"\n",
"maybeStripNationalPrefixAndCarrierCode",
"(",
"potentialNationalNumber",
",",
"defaultRegionMetadata",
",",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"/* Don't need the carrier code */",
")",
"\n",
"nationalNumberPattern",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"generalDesc",
".",
"GetNationalNumberPattern",
"(",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"pat",
":=",
"generalDesc",
".",
"GetNationalNumberPattern",
"(",
")",
"\n",
"nationalNumberPattern",
"=",
"regexp",
".",
"MustCompile",
"(",
"pat",
")",
"\n",
"writeToRegexCache",
"(",
"pat",
",",
"nationalNumberPattern",
")",
"\n",
"}",
"\n",
"// If the number was not valid before but is valid now, or",
"// if it was too long before, we consider the number with",
"// the country calling code stripped to be a better result and",
"// keep that instead.",
"if",
"(",
"!",
"validNumberPattern",
".",
"MatchString",
"(",
"fullNumber",
".",
"String",
"(",
")",
")",
"&&",
"validNumberPattern",
".",
"MatchString",
"(",
"potentialNationalNumber",
".",
"String",
"(",
")",
")",
")",
"||",
"testNumberLengthAgainstPattern",
"(",
"nationalNumberPattern",
",",
"fullNumber",
".",
"String",
"(",
")",
")",
"==",
"TOO_LONG",
"{",
"nationalNumber",
".",
"Write",
"(",
"potentialNationalNumber",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"keepRawInput",
"{",
"val",
":=",
"PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN",
"\n",
"phoneNumber",
".",
"CountryCodeSource",
"=",
"&",
"val",
"\n",
"}",
"\n",
"phoneNumber",
".",
"CountryCode",
"=",
"proto",
".",
"Int",
"(",
"defaultCountryCode",
")",
"\n",
"return",
"defaultCountryCode",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// No country calling code present.",
"phoneNumber",
".",
"CountryCode",
"=",
"proto",
".",
"Int",
"(",
"0",
")",
"\n",
"return",
"0",
",",
"nil",
"\n",
"}"
] | // Tries to extract a country calling code from a number. This method will
// return zero if no country calling code is considered to be present.
// Country calling codes are extracted in the following ways:
//
// - by stripping the international dialing prefix of the region the
// person is dialing from, if this is present in the number, and looking
// at the next digits
// - by stripping the '+' sign if present and then looking at the next digits
// - by comparing the start of the number and the country calling code of
// the default region. If the number is not considered possible for the
// numbering plan of the default region initially, but starts with the
// country calling code of this region, validation will be reattempted
// after stripping this country calling code. If this number is considered a
// possible number, then the first digits will be considered the country
// calling code and removed as such.
//
// It will throw a NumberParseException if the number starts with a '+' but
// the country calling code supplied after this does not match that of any
// known region. | [
"Tries",
"to",
"extract",
"a",
"country",
"calling",
"code",
"from",
"a",
"number",
".",
"This",
"method",
"will",
"return",
"zero",
"if",
"no",
"country",
"calling",
"code",
"is",
"considered",
"to",
"be",
"present",
".",
"Country",
"calling",
"codes",
"are",
"extracted",
"in",
"the",
"following",
"ways",
":",
"-",
"by",
"stripping",
"the",
"international",
"dialing",
"prefix",
"of",
"the",
"region",
"the",
"person",
"is",
"dialing",
"from",
"if",
"this",
"is",
"present",
"in",
"the",
"number",
"and",
"looking",
"at",
"the",
"next",
"digits",
"-",
"by",
"stripping",
"the",
"+",
"sign",
"if",
"present",
"and",
"then",
"looking",
"at",
"the",
"next",
"digits",
"-",
"by",
"comparing",
"the",
"start",
"of",
"the",
"number",
"and",
"the",
"country",
"calling",
"code",
"of",
"the",
"default",
"region",
".",
"If",
"the",
"number",
"is",
"not",
"considered",
"possible",
"for",
"the",
"numbering",
"plan",
"of",
"the",
"default",
"region",
"initially",
"but",
"starts",
"with",
"the",
"country",
"calling",
"code",
"of",
"this",
"region",
"validation",
"will",
"be",
"reattempted",
"after",
"stripping",
"this",
"country",
"calling",
"code",
".",
"If",
"this",
"number",
"is",
"considered",
"a",
"possible",
"number",
"then",
"the",
"first",
"digits",
"will",
"be",
"considered",
"the",
"country",
"calling",
"code",
"and",
"removed",
"as",
"such",
".",
"It",
"will",
"throw",
"a",
"NumberParseException",
"if",
"the",
"number",
"starts",
"with",
"a",
"+",
"but",
"the",
"country",
"calling",
"code",
"supplied",
"after",
"this",
"does",
"not",
"match",
"that",
"of",
"any",
"known",
"region",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2535-L2621 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2625-L2644 |
ttacon/libphonenumber | phonenumberutil.go | maybeStripInternationalPrefixAndNormalize | func maybeStripInternationalPrefixAndNormalize(
number *builder.Builder,
possibleIddPrefix string) PhoneNumber_CountryCodeSource {
numBytes := number.Bytes()
if len(numBytes) == 0 {
return PhoneNumber_FROM_DEFAULT_COUNTRY
}
// Check to see if the number begins with one or more plus signs.
ind := PLUS_CHARS_PATTERN.FindIndex(numBytes) // Return is an int pair [start,end]
if len(ind) > 0 && ind[0] == 0 { // Strictly match from string start
number.ResetWith(numBytes[ind[1]:])
// Can now normalize the rest of the number since we've consumed
// the "+" sign at the start.
number.ResetWithString(normalize(number.String()))
return PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN
}
// Attempt to parse the first digits as an international prefix.
iddPattern, ok := readFromRegexCache(possibleIddPrefix)
if !ok {
pat := possibleIddPrefix
iddPattern = regexp.MustCompile(pat)
writeToRegexCache(pat, iddPattern)
}
number.ResetWithString(normalize(string(numBytes)))
if parsePrefixAsIdd(iddPattern, number) {
return PhoneNumber_FROM_NUMBER_WITH_IDD
}
return PhoneNumber_FROM_DEFAULT_COUNTRY
} | go | func maybeStripInternationalPrefixAndNormalize(
number *builder.Builder,
possibleIddPrefix string) PhoneNumber_CountryCodeSource {
numBytes := number.Bytes()
if len(numBytes) == 0 {
return PhoneNumber_FROM_DEFAULT_COUNTRY
}
// Check to see if the number begins with one or more plus signs.
ind := PLUS_CHARS_PATTERN.FindIndex(numBytes) // Return is an int pair [start,end]
if len(ind) > 0 && ind[0] == 0 { // Strictly match from string start
number.ResetWith(numBytes[ind[1]:])
// Can now normalize the rest of the number since we've consumed
// the "+" sign at the start.
number.ResetWithString(normalize(number.String()))
return PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN
}
// Attempt to parse the first digits as an international prefix.
iddPattern, ok := readFromRegexCache(possibleIddPrefix)
if !ok {
pat := possibleIddPrefix
iddPattern = regexp.MustCompile(pat)
writeToRegexCache(pat, iddPattern)
}
number.ResetWithString(normalize(string(numBytes)))
if parsePrefixAsIdd(iddPattern, number) {
return PhoneNumber_FROM_NUMBER_WITH_IDD
}
return PhoneNumber_FROM_DEFAULT_COUNTRY
} | [
"func",
"maybeStripInternationalPrefixAndNormalize",
"(",
"number",
"*",
"builder",
".",
"Builder",
",",
"possibleIddPrefix",
"string",
")",
"PhoneNumber_CountryCodeSource",
"{",
"numBytes",
":=",
"number",
".",
"Bytes",
"(",
")",
"\n",
"if",
"len",
"(",
"numBytes",
")",
"==",
"0",
"{",
"return",
"PhoneNumber_FROM_DEFAULT_COUNTRY",
"\n",
"}",
"\n",
"// Check to see if the number begins with one or more plus signs.",
"ind",
":=",
"PLUS_CHARS_PATTERN",
".",
"FindIndex",
"(",
"numBytes",
")",
"// Return is an int pair [start,end]",
"\n",
"if",
"len",
"(",
"ind",
")",
">",
"0",
"&&",
"ind",
"[",
"0",
"]",
"==",
"0",
"{",
"// Strictly match from string start",
"number",
".",
"ResetWith",
"(",
"numBytes",
"[",
"ind",
"[",
"1",
"]",
":",
"]",
")",
"\n",
"// Can now normalize the rest of the number since we've consumed",
"// the \"+\" sign at the start.",
"number",
".",
"ResetWithString",
"(",
"normalize",
"(",
"number",
".",
"String",
"(",
")",
")",
")",
"\n",
"return",
"PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN",
"\n",
"}",
"\n\n",
"// Attempt to parse the first digits as an international prefix.",
"iddPattern",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"possibleIddPrefix",
")",
"\n",
"if",
"!",
"ok",
"{",
"pat",
":=",
"possibleIddPrefix",
"\n",
"iddPattern",
"=",
"regexp",
".",
"MustCompile",
"(",
"pat",
")",
"\n",
"writeToRegexCache",
"(",
"pat",
",",
"iddPattern",
")",
"\n",
"}",
"\n",
"number",
".",
"ResetWithString",
"(",
"normalize",
"(",
"string",
"(",
"numBytes",
")",
")",
")",
"\n",
"if",
"parsePrefixAsIdd",
"(",
"iddPattern",
",",
"number",
")",
"{",
"return",
"PhoneNumber_FROM_NUMBER_WITH_IDD",
"\n",
"}",
"\n",
"return",
"PhoneNumber_FROM_DEFAULT_COUNTRY",
"\n",
"}"
] | // Strips any international prefix (such as +, 00, 011) present in the
// number provided, normalizes the resulting number, and indicates if
// an international prefix was present. | [
"Strips",
"any",
"international",
"prefix",
"(",
"such",
"as",
"+",
"00",
"011",
")",
"present",
"in",
"the",
"number",
"provided",
"normalizes",
"the",
"resulting",
"number",
"and",
"indicates",
"if",
"an",
"international",
"prefix",
"was",
"present",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2649-L2679 |
ttacon/libphonenumber | phonenumberutil.go | maybeStripNationalPrefixAndCarrierCode | func maybeStripNationalPrefixAndCarrierCode(
number *builder.Builder,
metadata *PhoneMetadata,
carrierCode *builder.Builder) bool {
numberLength := len(number.String())
possibleNationalPrefix := metadata.GetNationalPrefixForParsing()
if numberLength == 0 || len(possibleNationalPrefix) == 0 {
// Early return for numbers of zero length.
return false
}
possibleNationalPrefix = "^(?:" + possibleNationalPrefix + ")" // Strictly match from string start
// Attempt to parse the first digits as a national prefix.
prefixMatcher, ok := readFromRegexCache(possibleNationalPrefix)
if !ok {
pat := possibleNationalPrefix
prefixMatcher = regexp.MustCompile(pat)
writeToRegexCache(pat, prefixMatcher)
}
if prefixMatcher.MatchString(number.String()) {
natRulePattern := "^(?:" + metadata.GetGeneralDesc().GetNationalNumberPattern() + ")$" // Strictly match
nationalNumberRule, ok :=
readFromRegexCache(natRulePattern)
if !ok {
nationalNumberRule = regexp.MustCompile(natRulePattern)
writeToRegexCache(natRulePattern, nationalNumberRule)
}
// Check if the original number is viable.
isViableOriginalNumber := nationalNumberRule.Match(number.Bytes())
// prefixMatcher.group(numOfGroups) == null implies nothing was
// captured by the capturing groups in possibleNationalPrefix;
// therefore, no transformation is necessary, and we just
// remove the national prefix.
groups := prefixMatcher.FindSubmatchIndex(number.Bytes())
numOfGroups := len(groups)/2 - 1 // groups is a list of index pairs, idx0,idx1 defines the whole match, idx2+ submatches.
// Subtract one to ignore group(0) in count
transformRule := metadata.GetNationalPrefixTransformRule()
if len(transformRule) == 0 || groups[numOfGroups*2] < 0 { // Negative idx means subgroup did not match
// If the original number was viable, and the resultant number
// is not, we return.
if isViableOriginalNumber &&
!nationalNumberRule.MatchString(
number.String()[groups[1]:]) { // groups[1] == last match idx
return false
}
if len(carrierCode.Bytes()) != 0 &&
numOfGroups > 0 &&
groups[numOfGroups*2] > 0 { // Negative idx means subgroup did not match
carrierCode.Write(number.Bytes()[groups[numOfGroups*2]:groups[numOfGroups*2+1]])
}
number.ResetWith(number.Bytes()[groups[1]:])
return true
} else {
// Check that the resultant number is still viable. If not,
// return. Check this by copying the string buffer and
// making the transformation on the copy first.
numString := number.String()
transformedNumBytes := []byte(prefixMatcher.ReplaceAllString(numString, transformRule))
if isViableOriginalNumber &&
!nationalNumberRule.Match(transformedNumBytes) {
return false
}
if len(carrierCode.Bytes()) != 0 && numOfGroups > 1 && groups[2] != -1 { // Check group(1) got a submatch
carrC := numString[groups[2]:groups[3]] // group(1) idxs
carrierCode.WriteString(carrC)
}
number.ResetWith(transformedNumBytes)
return true
}
}
return false
} | go | func maybeStripNationalPrefixAndCarrierCode(
number *builder.Builder,
metadata *PhoneMetadata,
carrierCode *builder.Builder) bool {
numberLength := len(number.String())
possibleNationalPrefix := metadata.GetNationalPrefixForParsing()
if numberLength == 0 || len(possibleNationalPrefix) == 0 {
// Early return for numbers of zero length.
return false
}
possibleNationalPrefix = "^(?:" + possibleNationalPrefix + ")" // Strictly match from string start
// Attempt to parse the first digits as a national prefix.
prefixMatcher, ok := readFromRegexCache(possibleNationalPrefix)
if !ok {
pat := possibleNationalPrefix
prefixMatcher = regexp.MustCompile(pat)
writeToRegexCache(pat, prefixMatcher)
}
if prefixMatcher.MatchString(number.String()) {
natRulePattern := "^(?:" + metadata.GetGeneralDesc().GetNationalNumberPattern() + ")$" // Strictly match
nationalNumberRule, ok :=
readFromRegexCache(natRulePattern)
if !ok {
nationalNumberRule = regexp.MustCompile(natRulePattern)
writeToRegexCache(natRulePattern, nationalNumberRule)
}
// Check if the original number is viable.
isViableOriginalNumber := nationalNumberRule.Match(number.Bytes())
// prefixMatcher.group(numOfGroups) == null implies nothing was
// captured by the capturing groups in possibleNationalPrefix;
// therefore, no transformation is necessary, and we just
// remove the national prefix.
groups := prefixMatcher.FindSubmatchIndex(number.Bytes())
numOfGroups := len(groups)/2 - 1 // groups is a list of index pairs, idx0,idx1 defines the whole match, idx2+ submatches.
// Subtract one to ignore group(0) in count
transformRule := metadata.GetNationalPrefixTransformRule()
if len(transformRule) == 0 || groups[numOfGroups*2] < 0 { // Negative idx means subgroup did not match
// If the original number was viable, and the resultant number
// is not, we return.
if isViableOriginalNumber &&
!nationalNumberRule.MatchString(
number.String()[groups[1]:]) { // groups[1] == last match idx
return false
}
if len(carrierCode.Bytes()) != 0 &&
numOfGroups > 0 &&
groups[numOfGroups*2] > 0 { // Negative idx means subgroup did not match
carrierCode.Write(number.Bytes()[groups[numOfGroups*2]:groups[numOfGroups*2+1]])
}
number.ResetWith(number.Bytes()[groups[1]:])
return true
} else {
// Check that the resultant number is still viable. If not,
// return. Check this by copying the string buffer and
// making the transformation on the copy first.
numString := number.String()
transformedNumBytes := []byte(prefixMatcher.ReplaceAllString(numString, transformRule))
if isViableOriginalNumber &&
!nationalNumberRule.Match(transformedNumBytes) {
return false
}
if len(carrierCode.Bytes()) != 0 && numOfGroups > 1 && groups[2] != -1 { // Check group(1) got a submatch
carrC := numString[groups[2]:groups[3]] // group(1) idxs
carrierCode.WriteString(carrC)
}
number.ResetWith(transformedNumBytes)
return true
}
}
return false
} | [
"func",
"maybeStripNationalPrefixAndCarrierCode",
"(",
"number",
"*",
"builder",
".",
"Builder",
",",
"metadata",
"*",
"PhoneMetadata",
",",
"carrierCode",
"*",
"builder",
".",
"Builder",
")",
"bool",
"{",
"numberLength",
":=",
"len",
"(",
"number",
".",
"String",
"(",
")",
")",
"\n",
"possibleNationalPrefix",
":=",
"metadata",
".",
"GetNationalPrefixForParsing",
"(",
")",
"\n",
"if",
"numberLength",
"==",
"0",
"||",
"len",
"(",
"possibleNationalPrefix",
")",
"==",
"0",
"{",
"// Early return for numbers of zero length.",
"return",
"false",
"\n",
"}",
"\n",
"possibleNationalPrefix",
"=",
"\"",
"\"",
"+",
"possibleNationalPrefix",
"+",
"\"",
"\"",
"// Strictly match from string start",
"\n",
"// Attempt to parse the first digits as a national prefix.",
"prefixMatcher",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"possibleNationalPrefix",
")",
"\n",
"if",
"!",
"ok",
"{",
"pat",
":=",
"possibleNationalPrefix",
"\n",
"prefixMatcher",
"=",
"regexp",
".",
"MustCompile",
"(",
"pat",
")",
"\n",
"writeToRegexCache",
"(",
"pat",
",",
"prefixMatcher",
")",
"\n",
"}",
"\n",
"if",
"prefixMatcher",
".",
"MatchString",
"(",
"number",
".",
"String",
"(",
")",
")",
"{",
"natRulePattern",
":=",
"\"",
"\"",
"+",
"metadata",
".",
"GetGeneralDesc",
"(",
")",
".",
"GetNationalNumberPattern",
"(",
")",
"+",
"\"",
"\"",
"// Strictly match",
"\n",
"nationalNumberRule",
",",
"ok",
":=",
"readFromRegexCache",
"(",
"natRulePattern",
")",
"\n",
"if",
"!",
"ok",
"{",
"nationalNumberRule",
"=",
"regexp",
".",
"MustCompile",
"(",
"natRulePattern",
")",
"\n",
"writeToRegexCache",
"(",
"natRulePattern",
",",
"nationalNumberRule",
")",
"\n",
"}",
"\n",
"// Check if the original number is viable.",
"isViableOriginalNumber",
":=",
"nationalNumberRule",
".",
"Match",
"(",
"number",
".",
"Bytes",
"(",
")",
")",
"\n",
"// prefixMatcher.group(numOfGroups) == null implies nothing was",
"// captured by the capturing groups in possibleNationalPrefix;",
"// therefore, no transformation is necessary, and we just",
"// remove the national prefix.",
"groups",
":=",
"prefixMatcher",
".",
"FindSubmatchIndex",
"(",
"number",
".",
"Bytes",
"(",
")",
")",
"\n",
"numOfGroups",
":=",
"len",
"(",
"groups",
")",
"/",
"2",
"-",
"1",
"// groups is a list of index pairs, idx0,idx1 defines the whole match, idx2+ submatches.",
"\n",
"// Subtract one to ignore group(0) in count",
"transformRule",
":=",
"metadata",
".",
"GetNationalPrefixTransformRule",
"(",
")",
"\n",
"if",
"len",
"(",
"transformRule",
")",
"==",
"0",
"||",
"groups",
"[",
"numOfGroups",
"*",
"2",
"]",
"<",
"0",
"{",
"// Negative idx means subgroup did not match",
"// If the original number was viable, and the resultant number",
"// is not, we return.",
"if",
"isViableOriginalNumber",
"&&",
"!",
"nationalNumberRule",
".",
"MatchString",
"(",
"number",
".",
"String",
"(",
")",
"[",
"groups",
"[",
"1",
"]",
":",
"]",
")",
"{",
"// groups[1] == last match idx",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"carrierCode",
".",
"Bytes",
"(",
")",
")",
"!=",
"0",
"&&",
"numOfGroups",
">",
"0",
"&&",
"groups",
"[",
"numOfGroups",
"*",
"2",
"]",
">",
"0",
"{",
"// Negative idx means subgroup did not match",
"carrierCode",
".",
"Write",
"(",
"number",
".",
"Bytes",
"(",
")",
"[",
"groups",
"[",
"numOfGroups",
"*",
"2",
"]",
":",
"groups",
"[",
"numOfGroups",
"*",
"2",
"+",
"1",
"]",
"]",
")",
"\n",
"}",
"\n",
"number",
".",
"ResetWith",
"(",
"number",
".",
"Bytes",
"(",
")",
"[",
"groups",
"[",
"1",
"]",
":",
"]",
")",
"\n",
"return",
"true",
"\n",
"}",
"else",
"{",
"// Check that the resultant number is still viable. If not,",
"// return. Check this by copying the string buffer and",
"// making the transformation on the copy first.",
"numString",
":=",
"number",
".",
"String",
"(",
")",
"\n",
"transformedNumBytes",
":=",
"[",
"]",
"byte",
"(",
"prefixMatcher",
".",
"ReplaceAllString",
"(",
"numString",
",",
"transformRule",
")",
")",
"\n",
"if",
"isViableOriginalNumber",
"&&",
"!",
"nationalNumberRule",
".",
"Match",
"(",
"transformedNumBytes",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"carrierCode",
".",
"Bytes",
"(",
")",
")",
"!=",
"0",
"&&",
"numOfGroups",
">",
"1",
"&&",
"groups",
"[",
"2",
"]",
"!=",
"-",
"1",
"{",
"// Check group(1) got a submatch",
"carrC",
":=",
"numString",
"[",
"groups",
"[",
"2",
"]",
":",
"groups",
"[",
"3",
"]",
"]",
"// group(1) idxs",
"\n",
"carrierCode",
".",
"WriteString",
"(",
"carrC",
")",
"\n",
"}",
"\n",
"number",
".",
"ResetWith",
"(",
"transformedNumBytes",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Strips any national prefix (such as 0, 1) present in the number provided.
// @VisibleForTesting | [
"Strips",
"any",
"national",
"prefix",
"(",
"such",
"as",
"0",
"1",
")",
"present",
"in",
"the",
"number",
"provided",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2683-L2754 |
ttacon/libphonenumber | phonenumberutil.go | maybeStripExtension | func maybeStripExtension(number *builder.Builder) string {
// If we find a potential extension, and the number preceding this is
// a viable number, we assume it is an extension.
numStr := number.String()
ind := EXTN_PATTERN.FindStringIndex(numStr)
if len(ind) > 0 && isViablePhoneNumber(numStr[0:ind[0]]) {
// The numbers are captured into groups in the regular expression.
for _, extensionGroup := range EXTN_PATTERN.FindAllStringIndex(numStr, -1) {
if len(extensionGroup) == 0 {
continue
}
// We go through the capturing groups until we find one
// that captured some digits. If none did, then we will
// return the empty string.
extension := numStr[extensionGroup[0]:extensionGroup[1]]
number.ResetWithString(numStr[0:ind[0]])
return extension
}
}
return ""
} | go | func maybeStripExtension(number *builder.Builder) string {
// If we find a potential extension, and the number preceding this is
// a viable number, we assume it is an extension.
numStr := number.String()
ind := EXTN_PATTERN.FindStringIndex(numStr)
if len(ind) > 0 && isViablePhoneNumber(numStr[0:ind[0]]) {
// The numbers are captured into groups in the regular expression.
for _, extensionGroup := range EXTN_PATTERN.FindAllStringIndex(numStr, -1) {
if len(extensionGroup) == 0 {
continue
}
// We go through the capturing groups until we find one
// that captured some digits. If none did, then we will
// return the empty string.
extension := numStr[extensionGroup[0]:extensionGroup[1]]
number.ResetWithString(numStr[0:ind[0]])
return extension
}
}
return ""
} | [
"func",
"maybeStripExtension",
"(",
"number",
"*",
"builder",
".",
"Builder",
")",
"string",
"{",
"// If we find a potential extension, and the number preceding this is",
"// a viable number, we assume it is an extension.",
"numStr",
":=",
"number",
".",
"String",
"(",
")",
"\n",
"ind",
":=",
"EXTN_PATTERN",
".",
"FindStringIndex",
"(",
"numStr",
")",
"\n",
"if",
"len",
"(",
"ind",
")",
">",
"0",
"&&",
"isViablePhoneNumber",
"(",
"numStr",
"[",
"0",
":",
"ind",
"[",
"0",
"]",
"]",
")",
"{",
"// The numbers are captured into groups in the regular expression.",
"for",
"_",
",",
"extensionGroup",
":=",
"range",
"EXTN_PATTERN",
".",
"FindAllStringIndex",
"(",
"numStr",
",",
"-",
"1",
")",
"{",
"if",
"len",
"(",
"extensionGroup",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"// We go through the capturing groups until we find one",
"// that captured some digits. If none did, then we will",
"// return the empty string.",
"extension",
":=",
"numStr",
"[",
"extensionGroup",
"[",
"0",
"]",
":",
"extensionGroup",
"[",
"1",
"]",
"]",
"\n",
"number",
".",
"ResetWithString",
"(",
"numStr",
"[",
"0",
":",
"ind",
"[",
"0",
"]",
"]",
")",
"\n",
"return",
"extension",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Strips any extension (as in, the part of the number dialled after the
// call is connected, usually indicated with extn, ext, x or similar) from
// the end of the number, and returns it.
// @VisibleForTesting | [
"Strips",
"any",
"extension",
"(",
"as",
"in",
"the",
"part",
"of",
"the",
"number",
"dialled",
"after",
"the",
"call",
"is",
"connected",
"usually",
"indicated",
"with",
"extn",
"ext",
"x",
"or",
"similar",
")",
"from",
"the",
"end",
"of",
"the",
"number",
"and",
"returns",
"it",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2760-L2780 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2786-L2795 |
ttacon/libphonenumber | phonenumberutil.go | Parse | func Parse(numberToParse, defaultRegion string) (*PhoneNumber, error) {
var phoneNumber *PhoneNumber = &PhoneNumber{}
err := ParseToNumber(numberToParse, defaultRegion, phoneNumber)
return phoneNumber, err
} | go | func Parse(numberToParse, defaultRegion string) (*PhoneNumber, error) {
var phoneNumber *PhoneNumber = &PhoneNumber{}
err := ParseToNumber(numberToParse, defaultRegion, phoneNumber)
return phoneNumber, err
} | [
"func",
"Parse",
"(",
"numberToParse",
",",
"defaultRegion",
"string",
")",
"(",
"*",
"PhoneNumber",
",",
"error",
")",
"{",
"var",
"phoneNumber",
"*",
"PhoneNumber",
"=",
"&",
"PhoneNumber",
"{",
"}",
"\n",
"err",
":=",
"ParseToNumber",
"(",
"numberToParse",
",",
"defaultRegion",
",",
"phoneNumber",
")",
"\n",
"return",
"phoneNumber",
",",
"err",
"\n",
"}"
] | // Parses a string and returns it in proto buffer format. This method will
// throw a NumberParseException if the number is not considered to be a
// possible number. Note that validation of whether the number is actually
// a valid number for a particular region is not performed. This can be
// done separately with IsValidNumber(). | [
"Parses",
"a",
"string",
"and",
"returns",
"it",
"in",
"proto",
"buffer",
"format",
".",
"This",
"method",
"will",
"throw",
"a",
"NumberParseException",
"if",
"the",
"number",
"is",
"not",
"considered",
"to",
"be",
"a",
"possible",
"number",
".",
"Note",
"that",
"validation",
"of",
"whether",
"the",
"number",
"is",
"actually",
"a",
"valid",
"number",
"for",
"a",
"particular",
"region",
"is",
"not",
"performed",
".",
"This",
"can",
"be",
"done",
"separately",
"with",
"IsValidNumber",
"()",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2802-L2806 |
ttacon/libphonenumber | phonenumberutil.go | ParseToNumber | func ParseToNumber(numberToParse, defaultRegion string, phoneNumber *PhoneNumber) error {
return parseHelper(numberToParse, defaultRegion, false, true, phoneNumber)
} | go | func ParseToNumber(numberToParse, defaultRegion string, phoneNumber *PhoneNumber) error {
return parseHelper(numberToParse, defaultRegion, false, true, phoneNumber)
} | [
"func",
"ParseToNumber",
"(",
"numberToParse",
",",
"defaultRegion",
"string",
",",
"phoneNumber",
"*",
"PhoneNumber",
")",
"error",
"{",
"return",
"parseHelper",
"(",
"numberToParse",
",",
"defaultRegion",
",",
"false",
",",
"true",
",",
"phoneNumber",
")",
"\n",
"}"
] | // Same as Parse(string, string), but accepts mutable PhoneNumber as a
// parameter to decrease object creation when invoked many times. | [
"Same",
"as",
"Parse",
"(",
"string",
"string",
")",
"but",
"accepts",
"mutable",
"PhoneNumber",
"as",
"a",
"parameter",
"to",
"decrease",
"object",
"creation",
"when",
"invoked",
"many",
"times",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2810-L2812 |
ttacon/libphonenumber | phonenumberutil.go | ParseAndKeepRawInput | func ParseAndKeepRawInput(
numberToParse, defaultRegion string) (*PhoneNumber, error) {
var phoneNumber *PhoneNumber = &PhoneNumber{}
return phoneNumber, ParseAndKeepRawInputToNumber(
numberToParse, defaultRegion, phoneNumber)
} | go | func ParseAndKeepRawInput(
numberToParse, defaultRegion string) (*PhoneNumber, error) {
var phoneNumber *PhoneNumber = &PhoneNumber{}
return phoneNumber, ParseAndKeepRawInputToNumber(
numberToParse, defaultRegion, phoneNumber)
} | [
"func",
"ParseAndKeepRawInput",
"(",
"numberToParse",
",",
"defaultRegion",
"string",
")",
"(",
"*",
"PhoneNumber",
",",
"error",
")",
"{",
"var",
"phoneNumber",
"*",
"PhoneNumber",
"=",
"&",
"PhoneNumber",
"{",
"}",
"\n",
"return",
"phoneNumber",
",",
"ParseAndKeepRawInputToNumber",
"(",
"numberToParse",
",",
"defaultRegion",
",",
"phoneNumber",
")",
"\n",
"}"
] | // Parses a string and returns it in proto buffer format. This method
// differs from Parse() in that it always populates the raw_input field of
// the protocol buffer with numberToParse as well as the country_code_source
// field. | [
"Parses",
"a",
"string",
"and",
"returns",
"it",
"in",
"proto",
"buffer",
"format",
".",
"This",
"method",
"differs",
"from",
"Parse",
"()",
"in",
"that",
"it",
"always",
"populates",
"the",
"raw_input",
"field",
"of",
"the",
"protocol",
"buffer",
"with",
"numberToParse",
"as",
"well",
"as",
"the",
"country_code_source",
"field",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2818-L2823 |
ttacon/libphonenumber | phonenumberutil.go | ParseAndKeepRawInputToNumber | func ParseAndKeepRawInputToNumber(
numberToParse, defaultRegion string,
phoneNumber *PhoneNumber) error {
return parseHelper(numberToParse, defaultRegion, true, true, phoneNumber)
} | go | func ParseAndKeepRawInputToNumber(
numberToParse, defaultRegion string,
phoneNumber *PhoneNumber) error {
return parseHelper(numberToParse, defaultRegion, true, true, phoneNumber)
} | [
"func",
"ParseAndKeepRawInputToNumber",
"(",
"numberToParse",
",",
"defaultRegion",
"string",
",",
"phoneNumber",
"*",
"PhoneNumber",
")",
"error",
"{",
"return",
"parseHelper",
"(",
"numberToParse",
",",
"defaultRegion",
",",
"true",
",",
"true",
",",
"phoneNumber",
")",
"\n",
"}"
] | // Same as ParseAndKeepRawInput(String, String), but accepts a mutable
// PhoneNumber as a parameter to decrease object creation when invoked many
// times. | [
"Same",
"as",
"ParseAndKeepRawInput",
"(",
"String",
"String",
")",
"but",
"accepts",
"a",
"mutable",
"PhoneNumber",
"as",
"a",
"parameter",
"to",
"decrease",
"object",
"creation",
"when",
"invoked",
"many",
"times",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2828-L2832 |
ttacon/libphonenumber | phonenumberutil.go | setItalianLeadingZerosForPhoneNumber | func setItalianLeadingZerosForPhoneNumber(
nationalNum string, phoneNumber *PhoneNumber) {
if len(nationalNum) < 2 || nationalNum[0] != '0' {
return
}
phoneNumber.ItalianLeadingZero = proto.Bool(true)
numLeadZeros := 1
// Note that if the national number is all "0"s, the last "0"
// is not counted as a leading zero.
for numLeadZeros < len(nationalNum)-1 && nationalNum[numLeadZeros] == '0' {
numLeadZeros++
}
if numLeadZeros != 1 {
phoneNumber.NumberOfLeadingZeros = proto.Int(numLeadZeros)
}
} | go | func setItalianLeadingZerosForPhoneNumber(
nationalNum string, phoneNumber *PhoneNumber) {
if len(nationalNum) < 2 || nationalNum[0] != '0' {
return
}
phoneNumber.ItalianLeadingZero = proto.Bool(true)
numLeadZeros := 1
// Note that if the national number is all "0"s, the last "0"
// is not counted as a leading zero.
for numLeadZeros < len(nationalNum)-1 && nationalNum[numLeadZeros] == '0' {
numLeadZeros++
}
if numLeadZeros != 1 {
phoneNumber.NumberOfLeadingZeros = proto.Int(numLeadZeros)
}
} | [
"func",
"setItalianLeadingZerosForPhoneNumber",
"(",
"nationalNum",
"string",
",",
"phoneNumber",
"*",
"PhoneNumber",
")",
"{",
"if",
"len",
"(",
"nationalNum",
")",
"<",
"2",
"||",
"nationalNum",
"[",
"0",
"]",
"!=",
"'0'",
"{",
"return",
"\n",
"}",
"\n\n",
"phoneNumber",
".",
"ItalianLeadingZero",
"=",
"proto",
".",
"Bool",
"(",
"true",
")",
"\n",
"numLeadZeros",
":=",
"1",
"\n",
"// Note that if the national number is all \"0\"s, the last \"0\"",
"// is not counted as a leading zero.",
"for",
"numLeadZeros",
"<",
"len",
"(",
"nationalNum",
")",
"-",
"1",
"&&",
"nationalNum",
"[",
"numLeadZeros",
"]",
"==",
"'0'",
"{",
"numLeadZeros",
"++",
"\n",
"}",
"\n",
"if",
"numLeadZeros",
"!=",
"1",
"{",
"phoneNumber",
".",
"NumberOfLeadingZeros",
"=",
"proto",
".",
"Int",
"(",
"numLeadZeros",
")",
"\n",
"}",
"\n",
"}"
] | // Returns an iterable over all PhoneNumberMatch PhoneNumberMatches in text.
// This is a shortcut for findNumbers(CharSequence, String, Leniency, long)
// getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
//public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
// return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
//}
// Returns an iterable over all PhoneNumberMatch PhoneNumberMatches in text.
//public Iterable<PhoneNumberMatch> findNumbers(
// final CharSequence text, final String defaultRegion, final Leniency leniency,
// final long maxTries) {
//
// return new Iterable<PhoneNumberMatch>() {
// public Iterator<PhoneNumberMatch> iterator() {
// return new PhoneNumberMatcher(
// PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
// }
// };
// }
// A helper function to set the values related to leading zeros in a
// PhoneNumber. | [
"Returns",
"an",
"iterable",
"over",
"all",
"PhoneNumberMatch",
"PhoneNumberMatches",
"in",
"text",
".",
"This",
"is",
"a",
"shortcut",
"for",
"findNumbers",
"(",
"CharSequence",
"String",
"Leniency",
"long",
")",
"getMatcher",
"(",
"text",
"defaultRegion",
"Leniency",
".",
"VALID",
"Long",
".",
"MAX_VALUE",
")",
"}",
".",
"public",
"Iterable<PhoneNumberMatch",
">",
"findNumbers",
"(",
"CharSequence",
"text",
"String",
"defaultRegion",
")",
"{",
"return",
"findNumbers",
"(",
"text",
"defaultRegion",
"Leniency",
".",
"VALID",
"Long",
".",
"MAX_VALUE",
")",
";",
"}",
"Returns",
"an",
"iterable",
"over",
"all",
"PhoneNumberMatch",
"PhoneNumberMatches",
"in",
"text",
".",
"public",
"Iterable<PhoneNumberMatch",
">",
"findNumbers",
"(",
"final",
"CharSequence",
"text",
"final",
"String",
"defaultRegion",
"final",
"Leniency",
"leniency",
"final",
"long",
"maxTries",
")",
"{",
"return",
"new",
"Iterable<PhoneNumberMatch",
">",
"()",
"{",
"public",
"Iterator<PhoneNumberMatch",
">",
"iterator",
"()",
"{",
"return",
"new",
"PhoneNumberMatcher",
"(",
"PhoneNumberUtil",
".",
"this",
"text",
"defaultRegion",
"leniency",
"maxTries",
")",
";",
"}",
"}",
";",
"}",
"A",
"helper",
"function",
"to",
"set",
"the",
"values",
"related",
"to",
"leading",
"zeros",
"in",
"a",
"PhoneNumber",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2856-L2872 |
ttacon/libphonenumber | phonenumberutil.go | parseHelper | func parseHelper(
numberToParse, defaultRegion string,
keepRawInput, checkRegion bool,
phoneNumber *PhoneNumber) error {
if len(numberToParse) == 0 {
return ErrNotANumber
} else if len(numberToParse) > MAX_INPUT_STRING_LENGTH {
return ErrNumTooLong
}
nationalNumber := builder.NewBuilder(nil)
buildNationalNumberForParsing(numberToParse, nationalNumber)
if !isViablePhoneNumber(nationalNumber.String()) {
return ErrNotANumber
}
// Check the region supplied is valid, or that the extracted number
// starts with some sort of + sign so the number's region can be determined.
if checkRegion &&
!checkRegionForParsing(nationalNumber.String(), defaultRegion) {
return ErrInvalidCountryCode
}
if keepRawInput {
phoneNumber.RawInput = proto.String(numberToParse)
}
// Attempt to parse extension first, since it doesn't require
// region-specific data and we want to have the non-normalised
// number here.
extension := maybeStripExtension(nationalNumber)
if len(extension) > 0 {
phoneNumber.Extension = proto.String(extension)
}
var regionMetadata *PhoneMetadata = getMetadataForRegion(defaultRegion)
// Check to see if the number is given in international format so we
// know whether this number is from the default region or not.
normalizedNationalNumber := builder.NewBuilder(nil)
// TODO: This method should really just take in the string buffer that
// has already been created, and just remove the prefix, rather than
// taking in a string and then outputting a string buffer.
countryCode, err := maybeExtractCountryCode(
nationalNumber.String(), regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber)
if err != nil {
// There might be a plus at the beginning
inds := PLUS_CHARS_PATTERN.FindStringIndex(nationalNumber.String())
if err == ErrInvalidCountryCode && len(inds) > 0 {
// Strip the plus-char, and try again.
countryCode, err = maybeExtractCountryCode(
nationalNumber.String()[inds[1]:], regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber)
if err != nil {
return err
} else if countryCode == 0 {
return ErrInvalidCountryCode
}
} else {
return err
}
}
if countryCode != 0 {
phoneNumberRegion := GetRegionCodeForCountryCode(countryCode)
if phoneNumberRegion != defaultRegion {
// Metadata cannot be null because the country calling
// code is valid.
regionMetadata = getMetadataForRegionOrCallingCode(
countryCode, phoneNumberRegion)
}
} else {
// If no extracted country calling code, use the region supplied
// instead. The national number is just the normalized version of
// the number we were given to parse.
normalizedNationalNumber.WriteString(normalize(nationalNumber.String()))
if len(defaultRegion) != 0 {
countryCode = int(regionMetadata.GetCountryCode())
phoneNumber.CountryCode = proto.Int(countryCode)
} else if keepRawInput {
phoneNumber.CountryCodeSource = nil
}
}
if len(normalizedNationalNumber.String()) < MIN_LENGTH_FOR_NSN {
return ErrTooShortNSN
}
if regionMetadata != nil {
carrierCode := builder.NewBuilder(nil)
bufferCopy := make([]byte, normalizedNationalNumber.Len())
copy(bufferCopy, normalizedNationalNumber.Bytes())
potentialNationalNumber := builder.NewBuilder(bufferCopy)
maybeStripNationalPrefixAndCarrierCode(
potentialNationalNumber, regionMetadata, carrierCode)
// We require that the NSN remaining after stripping the national
// prefix and carrier code be of a possible length for the region.
// Otherwise, we don't do the stripping, since the original number
// could be a valid short number.
if !isShorterThanPossibleNormalNumber(
regionMetadata, potentialNationalNumber.String()) {
normalizedNationalNumber = potentialNationalNumber
if keepRawInput {
phoneNumber.PreferredDomesticCarrierCode =
proto.String(carrierCode.String())
}
}
}
lengthOfNationalNumber := len(normalizedNationalNumber.String())
if lengthOfNationalNumber < MIN_LENGTH_FOR_NSN {
return ErrTooShortNSN
}
if lengthOfNationalNumber > MAX_LENGTH_FOR_NSN {
return ErrNumTooLong
}
setItalianLeadingZerosForPhoneNumber(
normalizedNationalNumber.String(), phoneNumber)
val, _ := strconv.ParseUint(normalizedNationalNumber.String(), 10, 64)
phoneNumber.NationalNumber = proto.Uint64(val)
return nil
} | go | func parseHelper(
numberToParse, defaultRegion string,
keepRawInput, checkRegion bool,
phoneNumber *PhoneNumber) error {
if len(numberToParse) == 0 {
return ErrNotANumber
} else if len(numberToParse) > MAX_INPUT_STRING_LENGTH {
return ErrNumTooLong
}
nationalNumber := builder.NewBuilder(nil)
buildNationalNumberForParsing(numberToParse, nationalNumber)
if !isViablePhoneNumber(nationalNumber.String()) {
return ErrNotANumber
}
// Check the region supplied is valid, or that the extracted number
// starts with some sort of + sign so the number's region can be determined.
if checkRegion &&
!checkRegionForParsing(nationalNumber.String(), defaultRegion) {
return ErrInvalidCountryCode
}
if keepRawInput {
phoneNumber.RawInput = proto.String(numberToParse)
}
// Attempt to parse extension first, since it doesn't require
// region-specific data and we want to have the non-normalised
// number here.
extension := maybeStripExtension(nationalNumber)
if len(extension) > 0 {
phoneNumber.Extension = proto.String(extension)
}
var regionMetadata *PhoneMetadata = getMetadataForRegion(defaultRegion)
// Check to see if the number is given in international format so we
// know whether this number is from the default region or not.
normalizedNationalNumber := builder.NewBuilder(nil)
// TODO: This method should really just take in the string buffer that
// has already been created, and just remove the prefix, rather than
// taking in a string and then outputting a string buffer.
countryCode, err := maybeExtractCountryCode(
nationalNumber.String(), regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber)
if err != nil {
// There might be a plus at the beginning
inds := PLUS_CHARS_PATTERN.FindStringIndex(nationalNumber.String())
if err == ErrInvalidCountryCode && len(inds) > 0 {
// Strip the plus-char, and try again.
countryCode, err = maybeExtractCountryCode(
nationalNumber.String()[inds[1]:], regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber)
if err != nil {
return err
} else if countryCode == 0 {
return ErrInvalidCountryCode
}
} else {
return err
}
}
if countryCode != 0 {
phoneNumberRegion := GetRegionCodeForCountryCode(countryCode)
if phoneNumberRegion != defaultRegion {
// Metadata cannot be null because the country calling
// code is valid.
regionMetadata = getMetadataForRegionOrCallingCode(
countryCode, phoneNumberRegion)
}
} else {
// If no extracted country calling code, use the region supplied
// instead. The national number is just the normalized version of
// the number we were given to parse.
normalizedNationalNumber.WriteString(normalize(nationalNumber.String()))
if len(defaultRegion) != 0 {
countryCode = int(regionMetadata.GetCountryCode())
phoneNumber.CountryCode = proto.Int(countryCode)
} else if keepRawInput {
phoneNumber.CountryCodeSource = nil
}
}
if len(normalizedNationalNumber.String()) < MIN_LENGTH_FOR_NSN {
return ErrTooShortNSN
}
if regionMetadata != nil {
carrierCode := builder.NewBuilder(nil)
bufferCopy := make([]byte, normalizedNationalNumber.Len())
copy(bufferCopy, normalizedNationalNumber.Bytes())
potentialNationalNumber := builder.NewBuilder(bufferCopy)
maybeStripNationalPrefixAndCarrierCode(
potentialNationalNumber, regionMetadata, carrierCode)
// We require that the NSN remaining after stripping the national
// prefix and carrier code be of a possible length for the region.
// Otherwise, we don't do the stripping, since the original number
// could be a valid short number.
if !isShorterThanPossibleNormalNumber(
regionMetadata, potentialNationalNumber.String()) {
normalizedNationalNumber = potentialNationalNumber
if keepRawInput {
phoneNumber.PreferredDomesticCarrierCode =
proto.String(carrierCode.String())
}
}
}
lengthOfNationalNumber := len(normalizedNationalNumber.String())
if lengthOfNationalNumber < MIN_LENGTH_FOR_NSN {
return ErrTooShortNSN
}
if lengthOfNationalNumber > MAX_LENGTH_FOR_NSN {
return ErrNumTooLong
}
setItalianLeadingZerosForPhoneNumber(
normalizedNationalNumber.String(), phoneNumber)
val, _ := strconv.ParseUint(normalizedNationalNumber.String(), 10, 64)
phoneNumber.NationalNumber = proto.Uint64(val)
return nil
} | [
"func",
"parseHelper",
"(",
"numberToParse",
",",
"defaultRegion",
"string",
",",
"keepRawInput",
",",
"checkRegion",
"bool",
",",
"phoneNumber",
"*",
"PhoneNumber",
")",
"error",
"{",
"if",
"len",
"(",
"numberToParse",
")",
"==",
"0",
"{",
"return",
"ErrNotANumber",
"\n",
"}",
"else",
"if",
"len",
"(",
"numberToParse",
")",
">",
"MAX_INPUT_STRING_LENGTH",
"{",
"return",
"ErrNumTooLong",
"\n",
"}",
"\n\n",
"nationalNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"buildNationalNumberForParsing",
"(",
"numberToParse",
",",
"nationalNumber",
")",
"\n\n",
"if",
"!",
"isViablePhoneNumber",
"(",
"nationalNumber",
".",
"String",
"(",
")",
")",
"{",
"return",
"ErrNotANumber",
"\n",
"}",
"\n\n",
"// Check the region supplied is valid, or that the extracted number",
"// starts with some sort of + sign so the number's region can be determined.",
"if",
"checkRegion",
"&&",
"!",
"checkRegionForParsing",
"(",
"nationalNumber",
".",
"String",
"(",
")",
",",
"defaultRegion",
")",
"{",
"return",
"ErrInvalidCountryCode",
"\n",
"}",
"\n\n",
"if",
"keepRawInput",
"{",
"phoneNumber",
".",
"RawInput",
"=",
"proto",
".",
"String",
"(",
"numberToParse",
")",
"\n",
"}",
"\n",
"// Attempt to parse extension first, since it doesn't require",
"// region-specific data and we want to have the non-normalised",
"// number here.",
"extension",
":=",
"maybeStripExtension",
"(",
"nationalNumber",
")",
"\n",
"if",
"len",
"(",
"extension",
")",
">",
"0",
"{",
"phoneNumber",
".",
"Extension",
"=",
"proto",
".",
"String",
"(",
"extension",
")",
"\n",
"}",
"\n",
"var",
"regionMetadata",
"*",
"PhoneMetadata",
"=",
"getMetadataForRegion",
"(",
"defaultRegion",
")",
"\n",
"// Check to see if the number is given in international format so we",
"// know whether this number is from the default region or not.",
"normalizedNationalNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"// TODO: This method should really just take in the string buffer that",
"// has already been created, and just remove the prefix, rather than",
"// taking in a string and then outputting a string buffer.",
"countryCode",
",",
"err",
":=",
"maybeExtractCountryCode",
"(",
"nationalNumber",
".",
"String",
"(",
")",
",",
"regionMetadata",
",",
"normalizedNationalNumber",
",",
"keepRawInput",
",",
"phoneNumber",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// There might be a plus at the beginning",
"inds",
":=",
"PLUS_CHARS_PATTERN",
".",
"FindStringIndex",
"(",
"nationalNumber",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"ErrInvalidCountryCode",
"&&",
"len",
"(",
"inds",
")",
">",
"0",
"{",
"// Strip the plus-char, and try again.",
"countryCode",
",",
"err",
"=",
"maybeExtractCountryCode",
"(",
"nationalNumber",
".",
"String",
"(",
")",
"[",
"inds",
"[",
"1",
"]",
":",
"]",
",",
"regionMetadata",
",",
"normalizedNationalNumber",
",",
"keepRawInput",
",",
"phoneNumber",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"countryCode",
"==",
"0",
"{",
"return",
"ErrInvalidCountryCode",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"countryCode",
"!=",
"0",
"{",
"phoneNumberRegion",
":=",
"GetRegionCodeForCountryCode",
"(",
"countryCode",
")",
"\n",
"if",
"phoneNumberRegion",
"!=",
"defaultRegion",
"{",
"// Metadata cannot be null because the country calling",
"// code is valid.",
"regionMetadata",
"=",
"getMetadataForRegionOrCallingCode",
"(",
"countryCode",
",",
"phoneNumberRegion",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// If no extracted country calling code, use the region supplied",
"// instead. The national number is just the normalized version of",
"// the number we were given to parse.",
"normalizedNationalNumber",
".",
"WriteString",
"(",
"normalize",
"(",
"nationalNumber",
".",
"String",
"(",
")",
")",
")",
"\n",
"if",
"len",
"(",
"defaultRegion",
")",
"!=",
"0",
"{",
"countryCode",
"=",
"int",
"(",
"regionMetadata",
".",
"GetCountryCode",
"(",
")",
")",
"\n",
"phoneNumber",
".",
"CountryCode",
"=",
"proto",
".",
"Int",
"(",
"countryCode",
")",
"\n",
"}",
"else",
"if",
"keepRawInput",
"{",
"phoneNumber",
".",
"CountryCodeSource",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"normalizedNationalNumber",
".",
"String",
"(",
")",
")",
"<",
"MIN_LENGTH_FOR_NSN",
"{",
"return",
"ErrTooShortNSN",
"\n",
"}",
"\n\n",
"if",
"regionMetadata",
"!=",
"nil",
"{",
"carrierCode",
":=",
"builder",
".",
"NewBuilder",
"(",
"nil",
")",
"\n",
"bufferCopy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"normalizedNationalNumber",
".",
"Len",
"(",
")",
")",
"\n",
"copy",
"(",
"bufferCopy",
",",
"normalizedNationalNumber",
".",
"Bytes",
"(",
")",
")",
"\n",
"potentialNationalNumber",
":=",
"builder",
".",
"NewBuilder",
"(",
"bufferCopy",
")",
"\n",
"maybeStripNationalPrefixAndCarrierCode",
"(",
"potentialNationalNumber",
",",
"regionMetadata",
",",
"carrierCode",
")",
"\n",
"// We require that the NSN remaining after stripping the national",
"// prefix and carrier code be of a possible length for the region.",
"// Otherwise, we don't do the stripping, since the original number",
"// could be a valid short number.",
"if",
"!",
"isShorterThanPossibleNormalNumber",
"(",
"regionMetadata",
",",
"potentialNationalNumber",
".",
"String",
"(",
")",
")",
"{",
"normalizedNationalNumber",
"=",
"potentialNationalNumber",
"\n",
"if",
"keepRawInput",
"{",
"phoneNumber",
".",
"PreferredDomesticCarrierCode",
"=",
"proto",
".",
"String",
"(",
"carrierCode",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"lengthOfNationalNumber",
":=",
"len",
"(",
"normalizedNationalNumber",
".",
"String",
"(",
")",
")",
"\n",
"if",
"lengthOfNationalNumber",
"<",
"MIN_LENGTH_FOR_NSN",
"{",
"return",
"ErrTooShortNSN",
"\n",
"}",
"\n",
"if",
"lengthOfNationalNumber",
">",
"MAX_LENGTH_FOR_NSN",
"{",
"return",
"ErrNumTooLong",
"\n",
"}",
"\n",
"setItalianLeadingZerosForPhoneNumber",
"(",
"normalizedNationalNumber",
".",
"String",
"(",
")",
",",
"phoneNumber",
")",
"\n",
"val",
",",
"_",
":=",
"strconv",
".",
"ParseUint",
"(",
"normalizedNationalNumber",
".",
"String",
"(",
")",
",",
"10",
",",
"64",
")",
"\n",
"phoneNumber",
".",
"NationalNumber",
"=",
"proto",
".",
"Uint64",
"(",
"val",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Parses a string and fills up the phoneNumber. This method is the same
// as the public Parse() method, with the exception that it allows the
// default region to be null, for use by IsNumberMatch(). checkRegion should
// be set to false if it is permitted for the default region to be null or
// unknown ("ZZ"). | [
"Parses",
"a",
"string",
"and",
"fills",
"up",
"the",
"phoneNumber",
".",
"This",
"method",
"is",
"the",
"same",
"as",
"the",
"public",
"Parse",
"()",
"method",
"with",
"the",
"exception",
"that",
"it",
"allows",
"the",
"default",
"region",
"to",
"be",
"null",
"for",
"use",
"by",
"IsNumberMatch",
"()",
".",
"checkRegion",
"should",
"be",
"set",
"to",
"false",
"if",
"it",
"is",
"permitted",
"for",
"the",
"default",
"region",
"to",
"be",
"null",
"or",
"unknown",
"(",
"ZZ",
")",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L2885-L3002 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3009-L3063 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3078-L3143 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3147-L3157 |
ttacon/libphonenumber | phonenumberutil.go | IsNumberMatch | func IsNumberMatch(firstNumber, secondNumber string) MatchType {
firstNumberAsProto, err := Parse(firstNumber, UNKNOWN_REGION)
if err == nil {
return isNumberMatchWithOneNumber(firstNumberAsProto, secondNumber)
} else if err != ErrInvalidCountryCode {
return NOT_A_NUMBER
}
secondNumberAsProto, err := Parse(secondNumber, UNKNOWN_REGION)
if err == nil {
return isNumberMatchWithOneNumber(secondNumberAsProto, firstNumber)
} else if err != ErrInvalidCountryCode {
return NOT_A_NUMBER
}
var firstNumberProto, secondNumberProto *PhoneNumber
err = parseHelper(firstNumber, "", false, false, firstNumberProto)
if err != nil {
return NOT_A_NUMBER
}
err = parseHelper(secondNumber, "", false, false, secondNumberProto)
if err != nil {
return NOT_A_NUMBER
}
return isNumberMatchWithNumbers(firstNumberProto, secondNumberProto)
} | go | func IsNumberMatch(firstNumber, secondNumber string) MatchType {
firstNumberAsProto, err := Parse(firstNumber, UNKNOWN_REGION)
if err == nil {
return isNumberMatchWithOneNumber(firstNumberAsProto, secondNumber)
} else if err != ErrInvalidCountryCode {
return NOT_A_NUMBER
}
secondNumberAsProto, err := Parse(secondNumber, UNKNOWN_REGION)
if err == nil {
return isNumberMatchWithOneNumber(secondNumberAsProto, firstNumber)
} else if err != ErrInvalidCountryCode {
return NOT_A_NUMBER
}
var firstNumberProto, secondNumberProto *PhoneNumber
err = parseHelper(firstNumber, "", false, false, firstNumberProto)
if err != nil {
return NOT_A_NUMBER
}
err = parseHelper(secondNumber, "", false, false, secondNumberProto)
if err != nil {
return NOT_A_NUMBER
}
return isNumberMatchWithNumbers(firstNumberProto, secondNumberProto)
} | [
"func",
"IsNumberMatch",
"(",
"firstNumber",
",",
"secondNumber",
"string",
")",
"MatchType",
"{",
"firstNumberAsProto",
",",
"err",
":=",
"Parse",
"(",
"firstNumber",
",",
"UNKNOWN_REGION",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"isNumberMatchWithOneNumber",
"(",
"firstNumberAsProto",
",",
"secondNumber",
")",
"\n",
"}",
"else",
"if",
"err",
"!=",
"ErrInvalidCountryCode",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n\n",
"secondNumberAsProto",
",",
"err",
":=",
"Parse",
"(",
"secondNumber",
",",
"UNKNOWN_REGION",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"isNumberMatchWithOneNumber",
"(",
"secondNumberAsProto",
",",
"firstNumber",
")",
"\n",
"}",
"else",
"if",
"err",
"!=",
"ErrInvalidCountryCode",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n\n",
"var",
"firstNumberProto",
",",
"secondNumberProto",
"*",
"PhoneNumber",
"\n",
"err",
"=",
"parseHelper",
"(",
"firstNumber",
",",
"\"",
"\"",
",",
"false",
",",
"false",
",",
"firstNumberProto",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n",
"err",
"=",
"parseHelper",
"(",
"secondNumber",
",",
"\"",
"\"",
",",
"false",
",",
"false",
",",
"secondNumberProto",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n",
"return",
"isNumberMatchWithNumbers",
"(",
"firstNumberProto",
",",
"secondNumberProto",
")",
"\n",
"}"
] | // Takes two phone numbers as strings and compares them for equality. This is
// a convenience wrapper for IsNumberMatch(PhoneNumber, PhoneNumber). No
// default region is known. | [
"Takes",
"two",
"phone",
"numbers",
"as",
"strings",
"and",
"compares",
"them",
"for",
"equality",
".",
"This",
"is",
"a",
"convenience",
"wrapper",
"for",
"IsNumberMatch",
"(",
"PhoneNumber",
"PhoneNumber",
")",
".",
"No",
"default",
"region",
"is",
"known",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3162-L3187 |
ttacon/libphonenumber | phonenumberutil.go | isNumberMatchWithOneNumber | func isNumberMatchWithOneNumber(
firstNumber *PhoneNumber, secondNumber string) MatchType {
// First see if the second number has an implicit country calling
// code, by attempting to parse it.
secondNumberAsProto, err := Parse(secondNumber, UNKNOWN_REGION)
if err == nil {
return isNumberMatchWithNumbers(firstNumber, secondNumberAsProto)
}
if err != ErrInvalidCountryCode {
return NOT_A_NUMBER
}
// The second number has no country calling code. EXACT_MATCH is no
// longer possible. We parse it as if the region was the same as that
// for the first number, and if EXACT_MATCH is returned, we replace
// this with NSN_MATCH.
firstNumberRegion := GetRegionCodeForCountryCode(int(firstNumber.GetCountryCode()))
if firstNumberRegion != UNKNOWN_REGION {
secondNumberWithFirstNumberRegion, err :=
Parse(secondNumber, firstNumberRegion)
if err != nil {
return NOT_A_NUMBER
}
match := isNumberMatchWithNumbers(
firstNumber, secondNumberWithFirstNumberRegion)
if match == EXACT_MATCH {
return NSN_MATCH
}
return match
} else {
// If the first number didn't have a valid country calling
// code, then we parse the second number without one as well.
var secondNumberProto *PhoneNumber
err := parseHelper(secondNumber, "", false, false, secondNumberProto)
if err != nil {
return NOT_A_NUMBER
}
return isNumberMatchWithNumbers(firstNumber, secondNumberProto)
}
} | go | func isNumberMatchWithOneNumber(
firstNumber *PhoneNumber, secondNumber string) MatchType {
// First see if the second number has an implicit country calling
// code, by attempting to parse it.
secondNumberAsProto, err := Parse(secondNumber, UNKNOWN_REGION)
if err == nil {
return isNumberMatchWithNumbers(firstNumber, secondNumberAsProto)
}
if err != ErrInvalidCountryCode {
return NOT_A_NUMBER
}
// The second number has no country calling code. EXACT_MATCH is no
// longer possible. We parse it as if the region was the same as that
// for the first number, and if EXACT_MATCH is returned, we replace
// this with NSN_MATCH.
firstNumberRegion := GetRegionCodeForCountryCode(int(firstNumber.GetCountryCode()))
if firstNumberRegion != UNKNOWN_REGION {
secondNumberWithFirstNumberRegion, err :=
Parse(secondNumber, firstNumberRegion)
if err != nil {
return NOT_A_NUMBER
}
match := isNumberMatchWithNumbers(
firstNumber, secondNumberWithFirstNumberRegion)
if match == EXACT_MATCH {
return NSN_MATCH
}
return match
} else {
// If the first number didn't have a valid country calling
// code, then we parse the second number without one as well.
var secondNumberProto *PhoneNumber
err := parseHelper(secondNumber, "", false, false, secondNumberProto)
if err != nil {
return NOT_A_NUMBER
}
return isNumberMatchWithNumbers(firstNumber, secondNumberProto)
}
} | [
"func",
"isNumberMatchWithOneNumber",
"(",
"firstNumber",
"*",
"PhoneNumber",
",",
"secondNumber",
"string",
")",
"MatchType",
"{",
"// First see if the second number has an implicit country calling",
"// code, by attempting to parse it.",
"secondNumberAsProto",
",",
"err",
":=",
"Parse",
"(",
"secondNumber",
",",
"UNKNOWN_REGION",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"isNumberMatchWithNumbers",
"(",
"firstNumber",
",",
"secondNumberAsProto",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"ErrInvalidCountryCode",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n",
"// The second number has no country calling code. EXACT_MATCH is no",
"// longer possible. We parse it as if the region was the same as that",
"// for the first number, and if EXACT_MATCH is returned, we replace",
"// this with NSN_MATCH.",
"firstNumberRegion",
":=",
"GetRegionCodeForCountryCode",
"(",
"int",
"(",
"firstNumber",
".",
"GetCountryCode",
"(",
")",
")",
")",
"\n\n",
"if",
"firstNumberRegion",
"!=",
"UNKNOWN_REGION",
"{",
"secondNumberWithFirstNumberRegion",
",",
"err",
":=",
"Parse",
"(",
"secondNumber",
",",
"firstNumberRegion",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n",
"match",
":=",
"isNumberMatchWithNumbers",
"(",
"firstNumber",
",",
"secondNumberWithFirstNumberRegion",
")",
"\n",
"if",
"match",
"==",
"EXACT_MATCH",
"{",
"return",
"NSN_MATCH",
"\n",
"}",
"\n",
"return",
"match",
"\n",
"}",
"else",
"{",
"// If the first number didn't have a valid country calling",
"// code, then we parse the second number without one as well.",
"var",
"secondNumberProto",
"*",
"PhoneNumber",
"\n",
"err",
":=",
"parseHelper",
"(",
"secondNumber",
",",
"\"",
"\"",
",",
"false",
",",
"false",
",",
"secondNumberProto",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NOT_A_NUMBER",
"\n",
"}",
"\n",
"return",
"isNumberMatchWithNumbers",
"(",
"firstNumber",
",",
"secondNumberProto",
")",
"\n",
"}",
"\n",
"}"
] | // Takes two phone numbers and compares them for equality. This is a
// convenience wrapper for IsNumberMatch(PhoneNumber, PhoneNumber). No
// default region is known. | [
"Takes",
"two",
"phone",
"numbers",
"and",
"compares",
"them",
"for",
"equality",
".",
"This",
"is",
"a",
"convenience",
"wrapper",
"for",
"IsNumberMatch",
"(",
"PhoneNumber",
"PhoneNumber",
")",
".",
"No",
"default",
"region",
"is",
"known",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3192-L3231 |
ttacon/libphonenumber | phonenumberutil.go | canBeInternationallyDialled | func canBeInternationallyDialled(number *PhoneNumber) bool {
metadata := getMetadataForRegion(GetRegionCodeForNumber(number))
if metadata == nil {
// Note numbers belonging to non-geographical entities
// (e.g. +800 numbers) are always internationally diallable,
// and will be caught here.
return true
}
nationalSignificantNumber := GetNationalSignificantNumber(number)
return !isNumberMatchingDesc(
nationalSignificantNumber, metadata.GetNoInternationalDialling())
} | go | func canBeInternationallyDialled(number *PhoneNumber) bool {
metadata := getMetadataForRegion(GetRegionCodeForNumber(number))
if metadata == nil {
// Note numbers belonging to non-geographical entities
// (e.g. +800 numbers) are always internationally diallable,
// and will be caught here.
return true
}
nationalSignificantNumber := GetNationalSignificantNumber(number)
return !isNumberMatchingDesc(
nationalSignificantNumber, metadata.GetNoInternationalDialling())
} | [
"func",
"canBeInternationallyDialled",
"(",
"number",
"*",
"PhoneNumber",
")",
"bool",
"{",
"metadata",
":=",
"getMetadataForRegion",
"(",
"GetRegionCodeForNumber",
"(",
"number",
")",
")",
"\n",
"if",
"metadata",
"==",
"nil",
"{",
"// Note numbers belonging to non-geographical entities",
"// (e.g. +800 numbers) are always internationally diallable,",
"// and will be caught here.",
"return",
"true",
"\n",
"}",
"\n",
"nationalSignificantNumber",
":=",
"GetNationalSignificantNumber",
"(",
"number",
")",
"\n",
"return",
"!",
"isNumberMatchingDesc",
"(",
"nationalSignificantNumber",
",",
"metadata",
".",
"GetNoInternationalDialling",
"(",
")",
")",
"\n",
"}"
] | // Returns true if the number can be dialled from outside the region, or
// unknown. If the number can only be dialled from within the region,
// returns false. Does not check the number is a valid number. Note that,
// at the moment, this method does not handle short numbers.
// TODO: Make this method public when we have enough metadata to make it worthwhile. | [
"Returns",
"true",
"if",
"the",
"number",
"can",
"be",
"dialled",
"from",
"outside",
"the",
"region",
"or",
"unknown",
".",
"If",
"the",
"number",
"can",
"only",
"be",
"dialled",
"from",
"within",
"the",
"region",
"returns",
"false",
".",
"Does",
"not",
"check",
"the",
"number",
"is",
"a",
"valid",
"number",
".",
"Note",
"that",
"at",
"the",
"moment",
"this",
"method",
"does",
"not",
"handle",
"short",
"numbers",
".",
"TODO",
":",
"Make",
"this",
"method",
"public",
"when",
"we",
"have",
"enough",
"metadata",
"to",
"make",
"it",
"worthwhile",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3238-L3249 |
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",
"."
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/phonenumberutil.go#L3254-L3260 |
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"
] | train | https://github.com/ttacon/libphonenumber/blob/23ddf903e8f8800d2857645eb155ffbe15cd02ee/countryCodeToTimeZones.go#L2253-L2264 |
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",
"."
] | train | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/decode.go#L57-L67 |
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",
"."
] | train | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/decode.go#L72-L112 |
hajimehoshi/go-mp3 | decode.go | NewDecoder | func NewDecoder(r io.Reader) (*Decoder, error) {
s := &source{
reader: r,
}
d := &Decoder{
source: s,
length: invalidLength,
}
if err := s.skipTags(); err != nil {
return nil, err
}
// TODO: Is readFrame here really needed?
if err := d.readFrame(); err != nil {
return nil, err
}
d.sampleRate = d.frame.SamplingFrequency()
if err := d.ensureFrameStartsAndLength(); err != nil {
return nil, err
}
return d, nil
} | go | func NewDecoder(r io.Reader) (*Decoder, error) {
s := &source{
reader: r,
}
d := &Decoder{
source: s,
length: invalidLength,
}
if err := s.skipTags(); err != nil {
return nil, err
}
// TODO: Is readFrame here really needed?
if err := d.readFrame(); err != nil {
return nil, err
}
d.sampleRate = d.frame.SamplingFrequency()
if err := d.ensureFrameStartsAndLength(); err != nil {
return nil, err
}
return d, nil
} | [
"func",
"NewDecoder",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Decoder",
",",
"error",
")",
"{",
"s",
":=",
"&",
"source",
"{",
"reader",
":",
"r",
",",
"}",
"\n",
"d",
":=",
"&",
"Decoder",
"{",
"source",
":",
"s",
",",
"length",
":",
"invalidLength",
",",
"}",
"\n\n",
"if",
"err",
":=",
"s",
".",
"skipTags",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// TODO: Is readFrame here really needed?",
"if",
"err",
":=",
"d",
".",
"readFrame",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"d",
".",
"sampleRate",
"=",
"d",
".",
"frame",
".",
"SamplingFrequency",
"(",
")",
"\n\n",
"if",
"err",
":=",
"d",
".",
"ensureFrameStartsAndLength",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"d",
",",
"nil",
"\n",
"}"
] | // NewDecoder decodes the given io.Reader and returns a decoded stream.
//
// The stream is always formatted as 16bit (little endian) 2 channels
// even if the source is single channel MP3.
// Thus, a sample always consists of 4 bytes. | [
"NewDecoder",
"decodes",
"the",
"given",
"io",
".",
"Reader",
"and",
"returns",
"a",
"decoded",
"stream",
".",
"The",
"stream",
"is",
"always",
"formatted",
"as",
"16bit",
"(",
"little",
"endian",
")",
"2",
"channels",
"even",
"if",
"the",
"source",
"is",
"single",
"channel",
"MP3",
".",
"Thus",
"a",
"sample",
"always",
"consists",
"of",
"4",
"bytes",
"."
] | train | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/decode.go#L189-L212 |
hajimehoshi/go-mp3 | internal/frameheader/frameheader.go | UseMSStereo | func (f FrameHeader) UseMSStereo() bool {
if f.Mode() != consts.ModeJointStereo {
return false
}
return f.modeExtension()&0x2 != 0
} | go | func (f FrameHeader) UseMSStereo() bool {
if f.Mode() != consts.ModeJointStereo {
return false
}
return f.modeExtension()&0x2 != 0
} | [
"func",
"(",
"f",
"FrameHeader",
")",
"UseMSStereo",
"(",
")",
"bool",
"{",
"if",
"f",
".",
"Mode",
"(",
")",
"!=",
"consts",
".",
"ModeJointStereo",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"f",
".",
"modeExtension",
"(",
")",
"&",
"0x2",
"!=",
"0",
"\n",
"}"
] | // UseMSStereo returns a boolean value indicating whether the frame uses middle/side stereo. | [
"UseMSStereo",
"returns",
"a",
"boolean",
"value",
"indicating",
"whether",
"the",
"frame",
"uses",
"middle",
"/",
"side",
"stereo",
"."
] | train | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/internal/frameheader/frameheader.go#L74-L79 |
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",
"."
] | train | https://github.com/hajimehoshi/go-mp3/blob/14af46a99b16fe1e285e22e032579d8b075c71f4/internal/frameheader/frameheader.go#L105-L126 |
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",
"."
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L19-L29 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L32-L36 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L53-L59 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L62-L67 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L94-L97 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L113-L122 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/cuckoofilter.go#L125-L144 |
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"
] | train | https://github.com/seiflotfy/cuckoofilter/blob/764cb5258d9bcd276f2f809e74cfa206d8e8e054/util.go#L18-L24 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L24-L32 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L51-L70 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L74-L80 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L85-L98 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L102-L111 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L116-L124 |
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",
"."
] | train | https://github.com/markbates/grift/blob/ce869fe62d84875913170d186f91a34667e4c732/grift/grift.go#L128-L145 |