24
initialBias int32 = 72
31
func punyError(s string) error { return &labelError{s, "A3"} }
34
func decode(encoded string) (string, error) {
38
pos := 1 + strings.LastIndex(encoded, "-")
40
return "", punyError(encoded)
42
if pos == len(encoded) {
43
return encoded[:len(encoded)-1], nil
45
output := make([]rune, 0, len(encoded))
47
for _, r := range encoded[:pos-1] {
48
output = append(output, r)
51
i, n, bias := int32(0), initialN, initialBias
53
for pos < len(encoded) {
54
oldI, w := i, int32(1)
55
for k := base; ; k += base {
56
if pos == len(encoded) {
57
return "", punyError(encoded)
59
digit, ok := decodeDigit(encoded[pos])
61
return "", punyError(encoded)
64
i, overflow = madd(i, digit, w)
66
return "", punyError(encoded)
71
} else if k >= bias+tmax {
77
w, overflow = madd(0, w, base-t)
79
return "", punyError(encoded)
82
if len(output) >= 1024 {
83
return "", punyError(encoded)
85
x := int32(len(output) + 1)
86
bias = adapt(i-oldI, x, oldI == 0)
89
if n < 0 || n > utf8.MaxRune {
90
return "", punyError(encoded)
92
output = append(output, 0)
93
copy(output[i+1:], output[i:])
97
return string(output), nil
105
func encode(prefix, s string) (string, error) {
106
output := make([]byte, len(prefix), len(prefix)+1+2*len(s))
108
delta, n, bias := int32(0), initialN, initialBias
109
b, remaining := int32(0), int32(0)
110
for _, r := range s {
113
output = append(output, byte(r))
120
output = append(output, '-')
124
m := int32(0x7fffffff)
125
for _, r := range s {
130
delta, overflow = madd(delta, m-n, h+1)
132
return "", punyError(s)
135
for _, r := range s {
139
return "", punyError(s)
147
for k := base; ; k += base {
151
} else if k >= bias+tmax {
157
output = append(output, encodeDigit(t+(q-t)%(base-t)))
158
q = (q - t) / (base - t)
160
output = append(output, encodeDigit(q))
161
bias = adapt(delta, h+1, h == b)
169
return string(output), nil
173
func madd(a, b, c int32) (next int32, overflow bool) {
174
p := int64(b) * int64(c)
175
if p > math.MaxInt32-int64(a) {
178
return a + int32(p), false
181
func decodeDigit(x byte) (digit int32, ok bool) {
183
case '0' <= x && x <= '9':
184
return int32(x - ('0' - 26)), true
185
case 'A' <= x && x <= 'Z':
186
return int32(x - 'A'), true
187
case 'a' <= x && x <= 'z':
188
return int32(x - 'a'), true
193
func encodeDigit(digit int32) byte {
195
case 0 <= digit && digit < 26:
196
return byte(digit + 'a')
197
case 26 <= digit && digit < 36:
198
return byte(digit + ('0' - 26))
200
panic("idna: internal error in punycode encoding")
204
func adapt(delta, numPoints int32, firstTime bool) int32 {
210
delta += delta / numPoints
212
for delta > ((base-tmin)*tmax)/2 {
216
return k + (base-tmin+1)*delta/(delta+skew)