code.vegaprotocol.io/vega@v0.79.0/core/netparams/values.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package netparams
    17  
    18  import (
    19  	"bytes"
    20  	"context"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"reflect"
    25  	"strconv"
    26  	"strings"
    27  	"time"
    28  
    29  	"code.vegaprotocol.io/vega/libs/num"
    30  )
    31  
    32  type baseValue struct{}
    33  
    34  func (b *baseValue) ToDecimal() (num.Decimal, error) {
    35  	return num.DecimalZero(), errors.New("not a decimal value")
    36  }
    37  
    38  func (b *baseValue) ToInt() (int64, error) {
    39  	return 0, errors.New("not an int value")
    40  }
    41  
    42  func (b *baseValue) ToUint() (*num.Uint, error) {
    43  	return num.UintZero(), errors.New("not an uint value")
    44  }
    45  
    46  func (b *baseValue) ToBool() (bool, error) {
    47  	return false, errors.New("not a bool value")
    48  }
    49  
    50  func (b *baseValue) ToDuration() (time.Duration, error) {
    51  	return 0, errors.New("not a time.Duration value")
    52  }
    53  
    54  func (b *baseValue) ToString() (string, error) {
    55  	return "", errors.New("not a string value")
    56  }
    57  
    58  func (b *baseValue) ToJSONStruct(v Reset) error {
    59  	return errors.New("not a JSON value")
    60  }
    61  
    62  type DecimalRule func(num.Decimal) error
    63  
    64  type Decimal struct {
    65  	*baseValue
    66  	value   num.Decimal
    67  	rawval  string
    68  	rules   []DecimalRule
    69  	mutable bool
    70  }
    71  
    72  func NewDecimal(rules ...DecimalRule) *Decimal {
    73  	return &Decimal{
    74  		baseValue: &baseValue{},
    75  		rules:     rules,
    76  	}
    77  }
    78  
    79  func (f *Decimal) GetDispatch() func(context.Context, interface{}) error {
    80  	return func(ctx context.Context, rawfn interface{}) error {
    81  		// there can't be errors here, as all dispatcher
    82  		// should have been check earlier when being register
    83  		fn := rawfn.(func(context.Context, num.Decimal) error)
    84  		return fn(ctx, f.value)
    85  	}
    86  }
    87  
    88  func (f *Decimal) CheckDispatch(fn interface{}) error {
    89  	if _, ok := fn.(func(context.Context, num.Decimal) error); !ok {
    90  		return errors.New("invalid type, expected func(context.Context, num.Decimal) error")
    91  	}
    92  	return nil
    93  }
    94  
    95  func (f *Decimal) AddRules(fns ...interface{}) error {
    96  	for _, fn := range fns {
    97  		// asset they have the right type
    98  		v, ok := fn.(DecimalRule)
    99  		if !ok {
   100  			return errors.New("floats require DecimalRule functions")
   101  		}
   102  		f.rules = append(f.rules, v)
   103  	}
   104  
   105  	return nil
   106  }
   107  
   108  func (f *Decimal) ToDecimal() (num.Decimal, error) {
   109  	return f.value, nil
   110  }
   111  
   112  func (f *Decimal) Validate(value string) error {
   113  	valf, err := num.DecimalFromString(value)
   114  	if err != nil {
   115  		return err
   116  	}
   117  
   118  	if !f.mutable {
   119  		return errors.New("value is not mutable")
   120  	}
   121  
   122  	for _, fn := range f.rules {
   123  		if newerr := fn(valf); newerr != nil {
   124  			if err != nil {
   125  				err = fmt.Errorf("%v, %w", err, newerr)
   126  			} else {
   127  				err = newerr
   128  			}
   129  		}
   130  	}
   131  
   132  	return err
   133  }
   134  
   135  func (f *Decimal) UpdateOptionalValidation(value string, validate bool) error {
   136  	if !f.mutable {
   137  		return errors.New("value is not mutable")
   138  	}
   139  	valf, err := num.DecimalFromString(value)
   140  	if err != nil {
   141  		return err
   142  	}
   143  
   144  	if validate {
   145  		if err := f.Validate(value); err != nil {
   146  			return err
   147  		}
   148  	}
   149  
   150  	f.rawval = value
   151  	f.value = valf
   152  	return nil
   153  }
   154  
   155  func (f *Decimal) Update(value string) error {
   156  	return f.UpdateOptionalValidation(value, true)
   157  }
   158  
   159  func (f *Decimal) Mutable(b bool) *Decimal {
   160  	f.mutable = b
   161  	return f
   162  }
   163  
   164  func (f *Decimal) MustUpdate(value string) *Decimal {
   165  	if err := f.Update(value); err != nil {
   166  		panic(err)
   167  	}
   168  	return f
   169  }
   170  
   171  func (f *Decimal) String() string {
   172  	return f.rawval
   173  }
   174  
   175  func DecimalGTE(f num.Decimal) func(num.Decimal) error {
   176  	return func(val num.Decimal) error {
   177  		if val.GreaterThanOrEqual(f) {
   178  			return nil
   179  		}
   180  		return fmt.Errorf("expect >= %v got %v", f, val)
   181  	}
   182  }
   183  
   184  func DecimalDependentLT(otherName string, other *Decimal) func(num.Decimal) error {
   185  	return func(val num.Decimal) error {
   186  		if val.LessThan(other.value) {
   187  			return nil
   188  		}
   189  		return fmt.Errorf("expect < %v (%s) got %v", other.value, otherName, val)
   190  	}
   191  }
   192  
   193  func DecimalDependentLTE(otherName string, other *Decimal) func(num.Decimal) error {
   194  	return func(val num.Decimal) error {
   195  		if val.LessThanOrEqual(other.value) {
   196  			return nil
   197  		}
   198  		return fmt.Errorf("expect <= %v (%s) got %v", other.value, otherName, val)
   199  	}
   200  }
   201  
   202  func DecimalGT(f num.Decimal) func(num.Decimal) error {
   203  	return func(val num.Decimal) error {
   204  		if val.GreaterThan(f) {
   205  			return nil
   206  		}
   207  		return fmt.Errorf("expect > %v got %v", f, val)
   208  	}
   209  }
   210  
   211  func DecimalLTE(f num.Decimal) func(num.Decimal) error {
   212  	return func(val num.Decimal) error {
   213  		if val.LessThanOrEqual(f) {
   214  			return nil
   215  		}
   216  		return fmt.Errorf("expect <= %v got %v", f, val)
   217  	}
   218  }
   219  
   220  func DecimalLT(f num.Decimal) func(num.Decimal) error {
   221  	return func(val num.Decimal) error {
   222  		if val.LessThan(f) {
   223  			return nil
   224  		}
   225  		return fmt.Errorf("expect < %v got %v", f, val)
   226  	}
   227  }
   228  
   229  type IntRule func(int64) error
   230  
   231  type Int struct {
   232  	*baseValue
   233  	value   int64
   234  	rawval  string
   235  	rules   []IntRule
   236  	mutable bool
   237  }
   238  
   239  func NewInt(rules ...IntRule) *Int {
   240  	return &Int{
   241  		baseValue: &baseValue{},
   242  		rules:     rules,
   243  	}
   244  }
   245  
   246  func (i *Int) GetDispatch() func(context.Context, interface{}) error {
   247  	return func(ctx context.Context, rawfn interface{}) error {
   248  		// there can't be errors here, as all dispatcher
   249  		// should have been check earlier when being register
   250  		fn := rawfn.(func(context.Context, int64) error)
   251  		return fn(ctx, i.value)
   252  	}
   253  }
   254  
   255  func (i *Int) CheckDispatch(fn interface{}) error {
   256  	if _, ok := fn.(func(context.Context, int64) error); !ok {
   257  		return errors.New("invalid type, expected func(context.Context, int64) error")
   258  	}
   259  	return nil
   260  }
   261  
   262  func (i *Int) AddRules(fns ...interface{}) error {
   263  	for _, fn := range fns {
   264  		// asset they have the right type
   265  		v, ok := fn.(IntRule)
   266  		if !ok {
   267  			return errors.New("ints require IntRule functions")
   268  		}
   269  		i.rules = append(i.rules, v)
   270  	}
   271  
   272  	return nil
   273  }
   274  
   275  func (i *Int) ToInt() (int64, error) {
   276  	return i.value, nil
   277  }
   278  
   279  func (i *Int) Validate(value string) error {
   280  	vali, err := strconv.ParseInt(value, 10, 64)
   281  	if err != nil {
   282  		return err
   283  	}
   284  
   285  	if !i.mutable {
   286  		return errors.New("value is not mutable")
   287  	}
   288  
   289  	for _, fn := range i.rules {
   290  		if newerr := fn(vali); newerr != nil {
   291  			if err != nil {
   292  				err = fmt.Errorf("%v, %w", err, newerr)
   293  			} else {
   294  				err = newerr
   295  			}
   296  		}
   297  	}
   298  	return err
   299  }
   300  
   301  func (i *Int) UpdateOptionalValidation(value string, validate bool) error {
   302  	if !i.mutable {
   303  		return errors.New("value is not mutable")
   304  	}
   305  	vali, err := strconv.ParseInt(value, 10, 64)
   306  	if err != nil {
   307  		return err
   308  	}
   309  
   310  	if validate {
   311  		if err := i.Validate(value); err != nil {
   312  			return err
   313  		}
   314  	}
   315  
   316  	i.rawval = value
   317  	i.value = vali
   318  
   319  	return nil
   320  }
   321  
   322  func (i *Int) Update(value string) error {
   323  	return i.UpdateOptionalValidation(value, true)
   324  }
   325  
   326  func (i *Int) Mutable(b bool) *Int {
   327  	i.mutable = b
   328  	return i
   329  }
   330  
   331  func (i *Int) MustUpdate(value string) *Int {
   332  	if err := i.Update(value); err != nil {
   333  		panic(err)
   334  	}
   335  	return i
   336  }
   337  
   338  func (i *Int) String() string {
   339  	return i.rawval
   340  }
   341  
   342  func IntGTE(i int64) func(int64) error {
   343  	return func(val int64) error {
   344  		if val >= i {
   345  			return nil
   346  		}
   347  		return fmt.Errorf("expect >= %v got %v", i, val)
   348  	}
   349  }
   350  
   351  func IntGT(i int64) func(int64) error {
   352  	return func(val int64) error {
   353  		if val > i {
   354  			return nil
   355  		}
   356  		return fmt.Errorf("expect > %v got %v", i, val)
   357  	}
   358  }
   359  
   360  func IntLTE(i int64) func(int64) error {
   361  	return func(val int64) error {
   362  		if val <= i {
   363  			return nil
   364  		}
   365  		return fmt.Errorf("expect <= %v got %v", i, val)
   366  	}
   367  }
   368  
   369  func IntLT(i int64) func(int64) error {
   370  	return func(val int64) error {
   371  		if val < i {
   372  			return nil
   373  		}
   374  		return fmt.Errorf("expect < %v got %v", i, val)
   375  	}
   376  }
   377  
   378  type TimeRule func(time.Time) error
   379  
   380  type Time struct {
   381  	*baseValue
   382  	value   time.Time
   383  	rawval  string
   384  	rules   []TimeRule
   385  	mutable bool
   386  }
   387  
   388  func NewTime(rules ...TimeRule) *Time {
   389  	return &Time{
   390  		baseValue: &baseValue{},
   391  		rules:     rules,
   392  	}
   393  }
   394  
   395  func (t *Time) GetDispatch() func(context.Context, interface{}) error {
   396  	return func(ctx context.Context, rawfn interface{}) error {
   397  		// there can't be errors here, as all dispatcher
   398  		// should have been check earlier when being register
   399  		fn := rawfn.(func(context.Context, time.Time) error)
   400  		return fn(ctx, t.value)
   401  	}
   402  }
   403  
   404  func (t *Time) CheckDispatch(fn interface{}) error {
   405  	if _, ok := fn.(func(context.Context, time.Time) error); !ok {
   406  		return errors.New("invalid type, expected func(context.Context, time.Time) error")
   407  	}
   408  	return nil
   409  }
   410  
   411  func (t *Time) AddRules(fns ...interface{}) error {
   412  	for _, fn := range fns {
   413  		// asset they have the right type
   414  		v, ok := fn.(TimeRule)
   415  		if !ok {
   416  			return errors.New("times require TimeRule functions")
   417  		}
   418  		t.rules = append(t.rules, v)
   419  	}
   420  
   421  	return nil
   422  }
   423  
   424  func (t *Time) ToTime() (time.Time, error) {
   425  	return t.value, nil
   426  }
   427  
   428  func (t *Time) Validate(value string) error {
   429  	if !t.mutable {
   430  		return errors.New("value is not mutable")
   431  	}
   432  	pVal, err := parseTime(value)
   433  	if err != nil {
   434  		return err
   435  	}
   436  	tVal := *pVal
   437  	for _, fn := range t.rules {
   438  		if newerr := fn(tVal); newerr != nil {
   439  			if err != nil {
   440  				err = fmt.Errorf("%v, %w", err, newerr)
   441  			} else {
   442  				err = newerr
   443  			}
   444  		}
   445  	}
   446  	return err
   447  }
   448  
   449  func (t *Time) Update(value string) error {
   450  	if !t.mutable {
   451  		return errors.New("value is not mutable")
   452  	}
   453  	pVal, err := parseTime(value)
   454  	if err != nil {
   455  		return err
   456  	}
   457  	tVal := *pVal
   458  	for _, fn := range t.rules {
   459  		if newerr := fn(tVal); newerr != nil {
   460  			if err != nil {
   461  				err = fmt.Errorf("%v, %w", err, newerr)
   462  			} else {
   463  				err = newerr
   464  			}
   465  		}
   466  	}
   467  
   468  	if err == nil {
   469  		t.rawval = value
   470  		t.value = tVal
   471  	}
   472  	return nil
   473  }
   474  
   475  func (t *Time) Mutable(b bool) *Time {
   476  	t.mutable = b
   477  	return t
   478  }
   479  
   480  func (t *Time) MustUpdate(value string) *Time {
   481  	if err := t.Update(value); err != nil {
   482  		panic(err)
   483  	}
   484  	return t
   485  }
   486  
   487  func (t *Time) String() string {
   488  	return t.rawval
   489  }
   490  
   491  func TimeNonZero() func(time.Time) error {
   492  	return func(val time.Time) error {
   493  		if !val.IsZero() {
   494  			return nil
   495  		}
   496  		return fmt.Errorf("expect non-zero time")
   497  	}
   498  }
   499  
   500  func parseTime(v string) (*time.Time, error) {
   501  	if v == "never" {
   502  		return &time.Time{}, nil
   503  	}
   504  	formats := []string{
   505  		time.RFC3339,
   506  		"2006-01-02",
   507  	}
   508  	for _, f := range formats {
   509  		if tVal, err := time.Parse(f, v); err == nil {
   510  			return &tVal, nil
   511  		}
   512  	}
   513  	// last attempt -> timestamp
   514  	i, err := strconv.ParseInt(v, 10, 64)
   515  	if err != nil {
   516  		return nil, err
   517  	}
   518  	t := time.Unix(i, 0)
   519  	return &t, nil
   520  }
   521  
   522  type DurationRule func(time.Duration) error
   523  
   524  type Duration struct {
   525  	*baseValue
   526  	value   time.Duration
   527  	rawval  string
   528  	rules   []DurationRule
   529  	mutable bool
   530  }
   531  
   532  func NewDuration(rules ...DurationRule) *Duration {
   533  	return &Duration{
   534  		baseValue: &baseValue{},
   535  		rules:     rules,
   536  	}
   537  }
   538  
   539  func (d *Duration) GetDispatch() func(context.Context, interface{}) error {
   540  	return func(ctx context.Context, rawfn interface{}) error {
   541  		// there can't be errors here, as all dispatcher
   542  		// should have been check earlier when being register
   543  		fn := rawfn.(func(context.Context, time.Duration) error)
   544  		return fn(ctx, d.value)
   545  	}
   546  }
   547  
   548  func (d *Duration) CheckDispatch(fn interface{}) error {
   549  	if _, ok := fn.(func(context.Context, time.Duration) error); !ok {
   550  		return errors.New("invalid type, expected func(context.Context, time.Duration) error")
   551  	}
   552  	return nil
   553  }
   554  
   555  func (d *Duration) AddRules(fns ...interface{}) error {
   556  	for _, fn := range fns {
   557  		// asset they have the right type
   558  		v, ok := fn.(DurationRule)
   559  		if !ok {
   560  			return errors.New("durations require DurationRule functions")
   561  		}
   562  		d.rules = append(d.rules, v)
   563  	}
   564  
   565  	return nil
   566  }
   567  
   568  func (d *Duration) ToDuration() (time.Duration, error) {
   569  	return d.value, nil
   570  }
   571  
   572  func (d *Duration) Validate(value string) error {
   573  	vali, err := time.ParseDuration(value)
   574  	if err != nil {
   575  		return err
   576  	}
   577  
   578  	if !d.mutable {
   579  		return errors.New("value is not mutable")
   580  	}
   581  
   582  	for _, fn := range d.rules {
   583  		if newerr := fn(vali); newerr != nil {
   584  			if err != nil {
   585  				err = fmt.Errorf("%v, %w", err, newerr)
   586  			} else {
   587  				err = newerr
   588  			}
   589  		}
   590  	}
   591  	return err
   592  }
   593  
   594  func (d *Duration) Update(value string) error {
   595  	return d.UpdateOptionalValidation(value, true)
   596  }
   597  
   598  func (d *Duration) UpdateOptionalValidation(value string, validate bool) error {
   599  	if !d.mutable {
   600  		return errors.New("value is not mutable")
   601  	}
   602  	vali, err := time.ParseDuration(value)
   603  	if err != nil {
   604  		return err
   605  	}
   606  
   607  	if validate {
   608  		if err := d.Validate(value); err != nil {
   609  			return err
   610  		}
   611  	}
   612  
   613  	d.rawval = value
   614  	d.value = vali
   615  	return nil
   616  }
   617  
   618  func (d *Duration) Mutable(b bool) *Duration {
   619  	d.mutable = b
   620  	return d
   621  }
   622  
   623  func (d *Duration) MustUpdate(value string) *Duration {
   624  	if err := d.Update(value); err != nil {
   625  		panic(err)
   626  	}
   627  	return d
   628  }
   629  
   630  func (d *Duration) String() string {
   631  	return d.rawval
   632  }
   633  
   634  func DurationDependentGT(otherName string, other *Duration) DurationRule {
   635  	return func(val time.Duration) error {
   636  		if val > other.value {
   637  			return nil
   638  		}
   639  		return fmt.Errorf("expect > %v (%s) got %v", other.value, otherName, val)
   640  	}
   641  }
   642  
   643  func DurationDependentGTE(otherName string, other *Duration) DurationRule {
   644  	return func(val time.Duration) error {
   645  		if val >= other.value {
   646  			return nil
   647  		}
   648  		return fmt.Errorf("expect >= %v (%s) got %v", other.value, otherName, val)
   649  	}
   650  }
   651  
   652  func DurationDependentLT(otherName string, other *Duration) DurationRule {
   653  	return func(val time.Duration) error {
   654  		if val < other.value {
   655  			return nil
   656  		}
   657  		return fmt.Errorf("expect < %v (%s) got %v", other.value, otherName, val)
   658  	}
   659  }
   660  
   661  func DurationDependentLTE(otherName string, other *Duration) DurationRule {
   662  	return func(val time.Duration) error {
   663  		if val <= other.value {
   664  			return nil
   665  		}
   666  		return fmt.Errorf("expect <= %v (%s) got %v", other.value, otherName, val)
   667  	}
   668  }
   669  
   670  func DurationGTE(i time.Duration) func(time.Duration) error {
   671  	return func(val time.Duration) error {
   672  		if val >= i {
   673  			return nil
   674  		}
   675  		return fmt.Errorf("expect >= %v got %v", i, val)
   676  	}
   677  }
   678  
   679  func DurationGT(i time.Duration) func(time.Duration) error {
   680  	return func(val time.Duration) error {
   681  		if val > i {
   682  			return nil
   683  		}
   684  		return fmt.Errorf("expect > %v got %v", i, val)
   685  	}
   686  }
   687  
   688  func DurationLTE(i time.Duration) func(time.Duration) error {
   689  	return func(val time.Duration) error {
   690  		if val <= i {
   691  			return nil
   692  		}
   693  		return fmt.Errorf("expect <= %v got %v", i, val)
   694  	}
   695  }
   696  
   697  func DurationLT(i time.Duration) func(time.Duration) error {
   698  	return func(val time.Duration) error {
   699  		if val < i {
   700  			return nil
   701  		}
   702  		return fmt.Errorf("expect < %v got %v", i, val)
   703  	}
   704  }
   705  
   706  type JSONRule func(interface{}, interface{}) error
   707  
   708  type JSON struct {
   709  	*baseValue
   710  	value   Reset
   711  	ty      reflect.Type
   712  	rawval  string
   713  	rules   []JSONRule
   714  	mutable bool
   715  }
   716  
   717  func NewJSON(val Reset, rules ...JSONRule) *JSON {
   718  	if val == nil {
   719  		panic("JSON values requires non nil pointers")
   720  	}
   721  	ty := reflect.TypeOf(val)
   722  	if ty.Kind() != reflect.Ptr {
   723  		panic("JSON values requires pointers")
   724  	}
   725  	return &JSON{
   726  		baseValue: &baseValue{},
   727  		rules:     rules,
   728  		ty:        ty,
   729  		value:     val,
   730  	}
   731  }
   732  
   733  func (j *JSON) ToJSONStruct(v Reset) error {
   734  	if v == nil {
   735  		return errors.New("nil interface{}")
   736  	}
   737  	// just make sure types are compatible
   738  	if !reflect.TypeOf(v).AssignableTo(j.ty) {
   739  		return errors.New("incompatible type")
   740  	}
   741  
   742  	return json.Unmarshal([]byte(j.rawval), v)
   743  }
   744  
   745  func (j *JSON) GetDispatch() func(context.Context, interface{}) error {
   746  	return func(ctx context.Context, rawfn interface{}) error {
   747  		// there can't be errors here, as all dispatcher
   748  		// should have been check earlier when being register
   749  		fn := rawfn.(func(context.Context, interface{}) error)
   750  
   751  		// reset the proto struct before unmarshalling the JSON into it
   752  		j.value.Reset()
   753  
   754  		json.Unmarshal([]byte(j.rawval), j.value)
   755  		return fn(ctx, j.value)
   756  	}
   757  }
   758  
   759  func (j *JSON) CheckDispatch(fn interface{}) error {
   760  	if _, ok := fn.(func(context.Context, interface{}) error); !ok {
   761  		return errors.New("invalid type, expected func(context.Context, interface{}) error")
   762  	}
   763  	return nil
   764  }
   765  
   766  func (j *JSON) AddRules(fns ...interface{}) error {
   767  	for _, fn := range fns {
   768  		// asset they have the right type
   769  		v, ok := fn.(JSONRule)
   770  		if !ok {
   771  			return errors.New("JSONs require JSONRule functions")
   772  		}
   773  		j.rules = append(j.rules, v)
   774  	}
   775  
   776  	return nil
   777  }
   778  
   779  func (j *JSON) validateValue(value []byte) error {
   780  	j.value.Reset()
   781  	d := json.NewDecoder(bytes.NewReader(value))
   782  	d.DisallowUnknownFields()
   783  	return d.Decode(j.value)
   784  }
   785  
   786  func (j *JSON) Validate(value string) error {
   787  	err := j.validateValue([]byte(value))
   788  	if err != nil {
   789  		return fmt.Errorf("unable to unmarshal value, %w", err)
   790  	}
   791  
   792  	if !j.mutable {
   793  		return errors.New("value is not mutable")
   794  	}
   795  
   796  	for _, fn := range j.rules {
   797  		if newerr := fn(j.value, j.rawval); newerr != nil {
   798  			if err != nil {
   799  				err = fmt.Errorf("%v, %w", err, newerr)
   800  			} else {
   801  				err = newerr
   802  			}
   803  		}
   804  	}
   805  
   806  	return err
   807  }
   808  
   809  func (j *JSON) UpdateOptionalValidation(value string, validate bool) error {
   810  	if !j.mutable {
   811  		return errors.New("value is not mutable")
   812  	}
   813  	if validate {
   814  		if err := j.Validate(value); err != nil {
   815  			return err
   816  		}
   817  	}
   818  
   819  	j.rawval = value
   820  	return nil
   821  }
   822  
   823  func (j *JSON) Update(value string) error {
   824  	return j.UpdateOptionalValidation(value, true)
   825  }
   826  
   827  func (j *JSON) Mutable(b bool) *JSON {
   828  	j.mutable = b
   829  	return j
   830  }
   831  
   832  func (j *JSON) MustUpdate(value string) *JSON {
   833  	if err := j.Update(value); err != nil {
   834  		panic(err)
   835  	}
   836  	return j
   837  }
   838  
   839  func (j *JSON) String() string {
   840  	return j.rawval
   841  }
   842  
   843  type StringRule func(string) error
   844  
   845  type String struct {
   846  	*baseValue
   847  	rawval  string
   848  	rules   []StringRule
   849  	mutable bool
   850  }
   851  
   852  func NewString(rules ...StringRule) *String {
   853  	return &String{
   854  		baseValue: &baseValue{},
   855  		rules:     rules,
   856  	}
   857  }
   858  
   859  func (s *String) GetDispatch() func(context.Context, interface{}) error {
   860  	return func(ctx context.Context, rawfn interface{}) error {
   861  		// there can't be errors here, as all dispatcher
   862  		// should have been check earlier when being register
   863  		fn := rawfn.(func(context.Context, string) error)
   864  		return fn(ctx, s.rawval)
   865  	}
   866  }
   867  
   868  func (s *String) CheckDispatch(fn interface{}) error {
   869  	if _, ok := fn.(func(context.Context, string) error); !ok {
   870  		return errors.New("invalid type, expected func(context.Context, string) error")
   871  	}
   872  	return nil
   873  }
   874  
   875  func (s *String) AddRules(fns ...interface{}) error {
   876  	for _, fn := range fns {
   877  		// asset they have the right type
   878  		v, ok := fn.(StringRule)
   879  		if !ok {
   880  			return errors.New("strings require StringRule functions")
   881  		}
   882  		s.rules = append(s.rules, v)
   883  	}
   884  
   885  	return nil
   886  }
   887  
   888  func (s *String) ToString() (string, error) {
   889  	return s.rawval, nil
   890  }
   891  
   892  func (s *String) Validate(value string) error {
   893  	if !s.mutable {
   894  		return errors.New("value is not mutable")
   895  	}
   896  
   897  	var err error
   898  	for _, fn := range s.rules {
   899  		if newerr := fn(value); newerr != nil {
   900  			if err != nil {
   901  				err = fmt.Errorf("%v, %w", err, newerr)
   902  			} else {
   903  				err = newerr
   904  			}
   905  		}
   906  	}
   907  
   908  	return err
   909  }
   910  
   911  func (s *String) UpdateOptionalValidation(value string, validate bool) error {
   912  	if !s.mutable {
   913  		return errors.New("value is not mutable")
   914  	}
   915  
   916  	if validate {
   917  		if err := s.Validate(value); err != nil {
   918  			return err
   919  		}
   920  	}
   921  
   922  	s.rawval = value
   923  	return nil
   924  }
   925  
   926  func (s *String) Update(value string) error {
   927  	return s.UpdateOptionalValidation(value, true)
   928  }
   929  
   930  func (s *String) Mutable(b bool) *String {
   931  	s.mutable = b
   932  	return s
   933  }
   934  
   935  func (s *String) MustUpdate(value string) *String {
   936  	if err := s.Update(value); err != nil {
   937  		panic(err)
   938  	}
   939  	return s
   940  }
   941  
   942  func (s *String) String() string {
   943  	return s.rawval
   944  }
   945  
   946  type UintRule func(*num.Uint) error
   947  
   948  type Uint struct {
   949  	*baseValue
   950  	value   *num.Uint
   951  	rawval  string
   952  	rules   []UintRule
   953  	mutable bool
   954  }
   955  
   956  func NewUint(rules ...UintRule) *Uint {
   957  	return &Uint{
   958  		baseValue: &baseValue{},
   959  		rules:     rules,
   960  		value:     num.UintZero(),
   961  	}
   962  }
   963  
   964  func (i *Uint) GetDispatch() func(context.Context, interface{}) error {
   965  	return func(ctx context.Context, rawfn interface{}) error {
   966  		// there can't be errors here, as all dispatcher
   967  		// should have been check earlier when being register
   968  		fn := rawfn.(func(context.Context, *num.Uint) error)
   969  		return fn(ctx, i.value.Clone())
   970  	}
   971  }
   972  
   973  func (i *Uint) CheckDispatch(fn interface{}) error {
   974  	if _, ok := fn.(func(context.Context, *num.Uint) error); !ok {
   975  		return errors.New("invalid type, expected func(context.Context, *num.Uint) error")
   976  	}
   977  	return nil
   978  }
   979  
   980  func (i *Uint) AddRules(fns ...interface{}) error {
   981  	for _, fn := range fns {
   982  		// asset they have the right type
   983  		v, ok := fn.(UintRule)
   984  		if !ok {
   985  			return errors.New("ints require BigUintRule functions")
   986  		}
   987  		i.rules = append(i.rules, v)
   988  	}
   989  
   990  	return nil
   991  }
   992  
   993  func (i *Uint) ToUint() (*num.Uint, error) {
   994  	return i.value.Clone(), nil
   995  }
   996  
   997  func (i *Uint) Validate(value string) error {
   998  	if strings.HasPrefix(strings.TrimLeft(value, " "), "-") {
   999  		return errors.New("invalid uint")
  1000  	}
  1001  
  1002  	val, overflow := num.UintFromString(value, 10)
  1003  	if overflow {
  1004  		return errors.New("invalid uint")
  1005  	}
  1006  
  1007  	if !i.mutable {
  1008  		return errors.New("value is not mutable")
  1009  	}
  1010  
  1011  	var err error
  1012  	for _, fn := range i.rules {
  1013  		if newerr := fn(val.Clone()); newerr != nil {
  1014  			if err != nil {
  1015  				err = fmt.Errorf("%v, %w", err, newerr)
  1016  			} else {
  1017  				err = newerr
  1018  			}
  1019  		}
  1020  	}
  1021  	return err
  1022  }
  1023  
  1024  func (i *Uint) UpdateOptionalValidation(value string, validate bool) error {
  1025  	if !i.mutable {
  1026  		return errors.New("value is not mutable")
  1027  	}
  1028  	if strings.HasPrefix(strings.TrimLeft(value, " "), "-") {
  1029  		return errors.New("invalid uint")
  1030  	}
  1031  
  1032  	val, overflow := num.UintFromString(value, 10)
  1033  	if overflow {
  1034  		return errors.New("invalid uint")
  1035  	}
  1036  
  1037  	if validate {
  1038  		if err := i.Validate(value); err != nil {
  1039  			return err
  1040  		}
  1041  	}
  1042  
  1043  	i.rawval = value
  1044  	i.value = val
  1045  
  1046  	return nil
  1047  }
  1048  
  1049  func (i *Uint) Update(value string) error {
  1050  	return i.UpdateOptionalValidation(value, true)
  1051  }
  1052  
  1053  func (i *Uint) Mutable(b bool) *Uint {
  1054  	i.mutable = b
  1055  	return i
  1056  }
  1057  
  1058  func (i *Uint) MustUpdate(value string) *Uint {
  1059  	if err := i.Update(value); err != nil {
  1060  		panic(err)
  1061  	}
  1062  	return i
  1063  }
  1064  
  1065  func (i *Uint) String() string {
  1066  	return i.rawval
  1067  }
  1068  
  1069  func UintGTE(i *num.Uint) func(*num.Uint) error {
  1070  	icopy := i.Clone()
  1071  	return func(val *num.Uint) error {
  1072  		if val.GTE(icopy) {
  1073  			return nil
  1074  		}
  1075  		return fmt.Errorf("expect >= %v got %v", i, val)
  1076  	}
  1077  }
  1078  
  1079  // ensure that the value is >= the other value x factor.
  1080  func UintDependentGTE(otherName string, other *Uint, factor num.Decimal) UintRule {
  1081  	return func(val *num.Uint) error {
  1082  		lowerBound, _ := num.UintFromDecimal(other.value.ToDecimal().Mul(factor))
  1083  		if val.GTE(lowerBound) {
  1084  			return nil
  1085  		}
  1086  		return fmt.Errorf("expect >= %v (%s * %s) got %v", lowerBound, otherName, factor.String(), val)
  1087  	}
  1088  }
  1089  
  1090  // ensure that the value is <= the other value x factor.
  1091  func UintDependentLTE(otherName string, other *Uint, factor num.Decimal) UintRule {
  1092  	return func(val *num.Uint) error {
  1093  		upperBound, _ := num.UintFromDecimal(other.value.ToDecimal().Mul(factor))
  1094  		if val.LTE(upperBound) {
  1095  			return nil
  1096  		}
  1097  		return fmt.Errorf("expect <= %v (%s * %s) got %v", upperBound, otherName, factor.String(), val)
  1098  	}
  1099  }
  1100  
  1101  func UintGT(i *num.Uint) func(*num.Uint) error {
  1102  	icopy := i.Clone()
  1103  	return func(val *num.Uint) error {
  1104  		if val.GT(icopy) {
  1105  			return nil
  1106  		}
  1107  		return fmt.Errorf("expect > %v got %v", i, val)
  1108  	}
  1109  }
  1110  
  1111  func UintLTE(i *num.Uint) func(*num.Uint) error {
  1112  	icopy := i.Clone()
  1113  	return func(val *num.Uint) error {
  1114  		if val.LTE(icopy) {
  1115  			return nil
  1116  		}
  1117  		return fmt.Errorf("expect <= %v got %v", i, val)
  1118  	}
  1119  }
  1120  
  1121  func UintLT(i *num.Uint) func(*num.Uint) error {
  1122  	icopy := i.Clone()
  1123  	return func(val *num.Uint) error {
  1124  		if val.LT(icopy) {
  1125  			return nil
  1126  		}
  1127  		return fmt.Errorf("expect < %v got %v", i, val)
  1128  	}
  1129  }