open-vault/vendor/golang.org/x/net/idna/idna.go

69 lines
1.8 KiB
Go
Raw Normal View History

2017-01-27 01:16:19 +00:00
// Copyright 2012 The Go Authors. All rights reserved.
2016-09-30 13:50:46 +00:00
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2017-01-27 01:16:19 +00:00
// Package idna implements IDNA2008 (Internationalized Domain Names for
// Applications), defined in RFC 5890, RFC 5891, RFC 5892, RFC 5893 and
// RFC 5894.
2016-09-30 13:50:46 +00:00
package idna // import "golang.org/x/net/idna"
import (
"strings"
"unicode/utf8"
2017-01-13 14:06:34 +00:00
)
2016-09-30 13:50:46 +00:00
2017-01-27 01:16:19 +00:00
// TODO(nigeltao): specify when errors occur. For example, is ToASCII(".") or
// ToASCII("foo\x00") an error? See also http://www.unicode.org/faq/idn.html#11
// acePrefix is the ASCII Compatible Encoding prefix.
const acePrefix = "xn--"
2016-09-30 13:50:46 +00:00
// ToASCII converts a domain or domain label to its ASCII form. For example,
// ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
2017-01-27 01:16:19 +00:00
// ToASCII("golang") is "golang".
2016-09-30 13:50:46 +00:00
func ToASCII(s string) (string, error) {
2017-01-27 01:16:19 +00:00
if ascii(s) {
return s, nil
}
labels := strings.Split(s, ".")
for i, label := range labels {
if !ascii(label) {
a, err := encode(acePrefix, label)
if err != nil {
return "", err
}
labels[i] = a
}
2016-09-30 13:50:46 +00:00
}
2017-01-27 01:16:19 +00:00
return strings.Join(labels, "."), nil
2017-01-13 14:06:34 +00:00
}
// ToUnicode converts a domain or domain label to its Unicode form. For example,
// ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
2017-01-27 01:16:19 +00:00
// ToUnicode("golang") is "golang".
func ToUnicode(s string) (string, error) {
if !strings.Contains(s, acePrefix) {
return s, nil
2017-01-13 14:06:34 +00:00
}
2017-01-27 01:16:19 +00:00
labels := strings.Split(s, ".")
for i, label := range labels {
2016-09-30 13:50:46 +00:00
if strings.HasPrefix(label, acePrefix) {
2017-01-27 01:16:19 +00:00
u, err := decode(label[len(acePrefix):])
if err != nil {
return "", err
2016-09-30 13:50:46 +00:00
}
2017-01-27 01:16:19 +00:00
labels[i] = u
2016-09-30 13:50:46 +00:00
}
}
2017-01-27 01:16:19 +00:00
return strings.Join(labels, "."), nil
2016-09-30 13:50:46 +00:00
}
func ascii(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] >= utf8.RuneSelf {
return false
}
}
return true
}