compact.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package compact defines a compact representation of language tags.
  5. //
  6. // Common language tags (at least all for which locale information is defined
  7. // in CLDR) are assigned a unique index. Each Tag is associated with such an
  8. // ID for selecting language-related resources (such as translations) as well
  9. // as one for selecting regional defaults (currency, number formatting, etc.)
  10. //
  11. // It may want to export this functionality at some point, but at this point
  12. // this is only available for use within x/text.
  13. package compact // import "golang.org/x/text/internal/language/compact"
  14. import (
  15. "sort"
  16. "strings"
  17. "golang.org/x/text/internal/language"
  18. )
  19. // ID is an integer identifying a single tag.
  20. type ID uint16
  21. func getCoreIndex(t language.Tag) (id ID, ok bool) {
  22. cci, ok := language.GetCompactCore(t)
  23. if !ok {
  24. return 0, false
  25. }
  26. i := sort.Search(len(coreTags), func(i int) bool {
  27. return cci <= coreTags[i]
  28. })
  29. if i == len(coreTags) || coreTags[i] != cci {
  30. return 0, false
  31. }
  32. return ID(i), true
  33. }
  34. // Parent returns the ID of the parent or the root ID if id is already the root.
  35. func (id ID) Parent() ID {
  36. return parents[id]
  37. }
  38. // Tag converts id to an internal language Tag.
  39. func (id ID) Tag() language.Tag {
  40. if int(id) >= len(coreTags) {
  41. return specialTags[int(id)-len(coreTags)]
  42. }
  43. return coreTags[id].Tag()
  44. }
  45. var specialTags []language.Tag
  46. func init() {
  47. tags := strings.Split(specialTagsStr, " ")
  48. specialTags = make([]language.Tag, len(tags))
  49. for i, t := range tags {
  50. specialTags[i] = language.MustParse(t)
  51. }
  52. }