fieldoptions.go 2.1 KB

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