fieldoptions.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package mapping
  2. import "fmt"
  3. const notSymbol = '!'
  4. type (
  5. // use context and OptionalDep option to determine the value of Optional
  6. // nothing to do with context.Context
  7. fieldOptionsWithContext struct {
  8. Inherit bool
  9. FromString bool
  10. Optional bool
  11. Options []string
  12. Default string
  13. Range *numberRange
  14. }
  15. fieldOptions struct {
  16. fieldOptionsWithContext
  17. OptionalDep string
  18. }
  19. numberRange struct {
  20. left float64
  21. leftInclude bool
  22. right float64
  23. rightInclude bool
  24. }
  25. )
  26. func (o *fieldOptionsWithContext) fromString() bool {
  27. return o != nil && o.FromString
  28. }
  29. func (o *fieldOptionsWithContext) getDefault() (string, bool) {
  30. if o == nil {
  31. return "", false
  32. }
  33. return o.Default, len(o.Default) > 0
  34. }
  35. func (o *fieldOptionsWithContext) inherit() bool {
  36. return o != nil && o.Inherit
  37. }
  38. func (o *fieldOptionsWithContext) optional() bool {
  39. return o != nil && o.Optional
  40. }
  41. func (o *fieldOptionsWithContext) options() []string {
  42. if o == nil {
  43. return nil
  44. }
  45. return o.Options
  46. }
  47. func (o *fieldOptions) optionalDep() string {
  48. if o == nil {
  49. return ""
  50. }
  51. return o.OptionalDep
  52. }
  53. func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName string) (
  54. *fieldOptionsWithContext, error) {
  55. var optional bool
  56. if o.optional() {
  57. dep := o.optionalDep()
  58. if len(dep) == 0 {
  59. optional = true
  60. } else if dep[0] == notSymbol {
  61. dep = dep[1:]
  62. if len(dep) == 0 {
  63. return nil, fmt.Errorf("wrong optional value for %q in %q", key, fullName)
  64. }
  65. _, baseOn := m.Value(dep)
  66. _, selfOn := m.Value(key)
  67. if baseOn == selfOn {
  68. return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName)
  69. }
  70. optional = baseOn
  71. } else {
  72. _, baseOn := m.Value(dep)
  73. _, selfOn := m.Value(key)
  74. if baseOn != selfOn {
  75. return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q",
  76. dep, key, fullName)
  77. }
  78. optional = !baseOn
  79. }
  80. }
  81. if o.fieldOptionsWithContext.Optional == optional {
  82. return &o.fieldOptionsWithContext, nil
  83. }
  84. return &fieldOptionsWithContext{
  85. FromString: o.FromString,
  86. Optional: optional,
  87. Options: o.Options,
  88. Default: o.Default,
  89. }, nil
  90. }