Path: blob/main/vendor/golang.org/x/text/encoding/htmlindex/htmlindex.go
2893 views
// Copyright 2015 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34//go:generate go run gen.go56// Package htmlindex maps character set encoding names to Encodings as7// recommended by the W3C for use in HTML 5. See http://www.w3.org/TR/encoding.8package htmlindex910// TODO: perhaps have a "bare" version of the index (used by this package) that11// is not pre-loaded with all encodings. Global variables in encodings prevent12// the linker from being able to purge unneeded tables. This means that13// referencing all encodings, as this package does for the default index, links14// in all encodings unconditionally.15//16// This issue can be solved by either solving the linking issue (see17// https://github.com/golang/go/issues/6330) or refactoring the encoding tables18// (e.g. moving the tables to internal packages that do not use global19// variables).2021// TODO: allow canonicalizing names2223import (24"errors"25"strings"26"sync"2728"golang.org/x/text/encoding"29"golang.org/x/text/encoding/internal/identifier"30"golang.org/x/text/language"31)3233var (34errInvalidName = errors.New("htmlindex: invalid encoding name")35errUnknown = errors.New("htmlindex: unknown Encoding")36errUnsupported = errors.New("htmlindex: this encoding is not supported")37)3839var (40matcherOnce sync.Once41matcher language.Matcher42)4344// LanguageDefault returns the canonical name of the default encoding for a45// given language.46func LanguageDefault(tag language.Tag) string {47matcherOnce.Do(func() {48tags := []language.Tag{}49for _, t := range strings.Split(locales, " ") {50tags = append(tags, language.MustParse(t))51}52matcher = language.NewMatcher(tags, language.PreferSameScript(true))53})54_, i, _ := matcher.Match(tag)55return canonical[localeMap[i]] // Default is Windows-1252.56}5758// Get returns an Encoding for one of the names listed in59// http://www.w3.org/TR/encoding using the Default Index. Matching is case-60// insensitive.61func Get(name string) (encoding.Encoding, error) {62x, ok := nameMap[strings.ToLower(strings.TrimSpace(name))]63if !ok {64return nil, errInvalidName65}66return encodings[x], nil67}6869// Name reports the canonical name of the given Encoding. It will return70// an error if e is not associated with a supported encoding scheme.71func Name(e encoding.Encoding) (string, error) {72id, ok := e.(identifier.Interface)73if !ok {74return "", errUnknown75}76mib, _ := id.ID()77if mib == 0 {78return "", errUnknown79}80v, ok := mibMap[mib]81if !ok {82return "", errUnsupported83}84return canonical[v], nil85}868788