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. }
  32. return o.Default, len(o.Default) > 0
  33. }
  34. func (o *fieldOptionsWithContext) optional() bool {
  35. return o != nil && o.Optional
  36. }
  37. func (o *fieldOptionsWithContext) options() []string {
  38. if o == nil {
  39. return nil
  40. }
  41. return o.Options
  42. }
  43. func (o *fieldOptions) optionalDep() string {
  44. if o == nil {
  45. return ""
  46. }
  47. return o.OptionalDep
  48. }
  49. func (o *fieldOptions) toOptionsWithContext(key string, m Valuer, fullName string) (
  50. *fieldOptionsWithContext, error) {
  51. var optional bool
  52. if o.optional() {
  53. dep := o.optionalDep()
  54. if len(dep) == 0 {
  55. optional = true
  56. } else if dep[0] == notSymbol {
  57. dep = dep[1:]
  58. if len(dep) == 0 {
  59. return nil, fmt.Errorf("wrong optional value for %q in %q", key, fullName)
  60. }
  61. _, baseOn := m.Value(dep)
  62. _, selfOn := m.Value(key)
  63. if baseOn == selfOn {
  64. return nil, fmt.Errorf("set value for either %q or %q in %q", dep, key, fullName)
  65. }
  66. optional = baseOn
  67. } else {
  68. _, baseOn := m.Value(dep)
  69. _, selfOn := m.Value(key)
  70. if baseOn != selfOn {
  71. return nil, fmt.Errorf("values for %q and %q should be both provided or both not in %q",
  72. dep, key, fullName)
  73. }
  74. optional = !baseOn
  75. }
  76. }
  77. if o.fieldOptionsWithContext.Optional == optional {
  78. return &o.fieldOptionsWithContext, nil
  79. }
  80. return &fieldOptionsWithContext{
  81. FromString: o.FromString,
  82. Optional: optional,
  83. Options: o.Options,
  84. Default: o.Default,
  85. }, nil
  86. }