github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/types/null_int.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  // NullInt is a wrapper around integer values that can be null or an integer.
    10  // Use IsSet to check if the value is provided, instead of checking against 0.
    11  type NullInt struct {
    12  	IsSet bool
    13  	Value int
    14  }
    15  
    16  // ParseStringValue is used to parse a user provided flag argument.
    17  func (n *NullInt) ParseStringValue(val string) error {
    18  	if val == "" {
    19  		return nil
    20  	}
    21  
    22  	intVal, err := strconv.Atoi(val)
    23  	if err != nil {
    24  		return err
    25  	}
    26  
    27  	n.Value = intVal
    28  	n.IsSet = true
    29  
    30  	return nil
    31  }
    32  
    33  // IsValidValue returns an error if the input value is not an integer.
    34  func (n *NullInt) IsValidValue(val string) error {
    35  	_, err := strconv.Atoi(val)
    36  	return err
    37  }
    38  
    39  // ParseIntValue is used to parse a user provided *int argument.
    40  func (n *NullInt) ParseIntValue(val *int) {
    41  	if val == nil {
    42  		n.IsSet = false
    43  		n.Value = 0
    44  		return
    45  	}
    46  
    47  	n.Value = *val
    48  	n.IsSet = true
    49  }
    50  
    51  func (n *NullInt) UnmarshalFlag(val string) error {
    52  	return n.ParseStringValue(val)
    53  }
    54  
    55  func (n *NullInt) UnmarshalJSON(rawJSON []byte) error {
    56  	var value json.Number
    57  	err := json.Unmarshal(rawJSON, &value)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	if value.String() == "" {
    63  		n.Value = 0
    64  		n.IsSet = false
    65  		return nil
    66  	}
    67  
    68  	valueInt, err := strconv.Atoi(value.String())
    69  	if err != nil {
    70  		return err
    71  	}
    72  
    73  	n.Value = valueInt
    74  	n.IsSet = true
    75  
    76  	return nil
    77  }
    78  
    79  func (n NullInt) MarshalJSON() ([]byte, error) {
    80  	if n.IsSet {
    81  		return []byte(fmt.Sprint(n.Value)), nil
    82  	}
    83  	return []byte("null"), nil
    84  }