You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

87 lines
2.1 KiB

  1. // Copyright 2017 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 cldrtree
  5. import (
  6. "reflect"
  7. "golang.org/x/text/unicode/cldr"
  8. )
  9. // An Option configures an Index.
  10. type Option func(*options)
  11. type options struct {
  12. parent *Index
  13. name string
  14. alias *cldr.Common
  15. sharedType *typeInfo
  16. sharedEnums *enum
  17. }
  18. func (o *options) fill(opt []Option) {
  19. for _, f := range opt {
  20. f(o)
  21. }
  22. }
  23. // aliasOpt sets an alias from the given node, if the node defines one.
  24. func (o *options) setAlias(n Element) {
  25. if n != nil && !reflect.ValueOf(n).IsNil() {
  26. o.alias = n.GetCommon()
  27. }
  28. }
  29. // Enum defines a enumeration type. The resulting option may be passed for the
  30. // construction of multiple Indexes, which they will share the same enum values.
  31. // Calling Gen on a Builder will generate the Enum for the given name. The
  32. // optional values fix the values for the given identifier to the argument
  33. // position (starting at 0). Other values may still be added and will be
  34. // assigned to subsequent values.
  35. func Enum(name string, value ...string) Option {
  36. return EnumFunc(name, nil, value...)
  37. }
  38. // EnumFunc is like Enum but also takes a function that allows rewriting keys.
  39. func EnumFunc(name string, rename func(string) string, value ...string) Option {
  40. enum := &enum{name: name, rename: rename, keyMap: map[string]enumIndex{}}
  41. for _, e := range value {
  42. enum.lookup(e)
  43. }
  44. return func(o *options) {
  45. found := false
  46. for _, e := range o.parent.meta.b.enums {
  47. if e.name == enum.name {
  48. found = true
  49. break
  50. }
  51. }
  52. if !found {
  53. o.parent.meta.b.enums = append(o.parent.meta.b.enums, enum)
  54. }
  55. o.sharedEnums = enum
  56. }
  57. }
  58. // SharedType returns an option which causes all Indexes to which this option is
  59. // passed to have the same type.
  60. func SharedType() Option {
  61. info := &typeInfo{}
  62. return func(o *options) { o.sharedType = info }
  63. }
  64. func useSharedType() Option {
  65. return func(o *options) {
  66. sub := o.parent.meta.typeInfo.keyTypeInfo
  67. if sub == nil {
  68. sub = &typeInfo{}
  69. o.parent.meta.typeInfo.keyTypeInfo = sub
  70. }
  71. o.sharedType = sub
  72. }
  73. }