github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+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  // ParseIntValue is used to parse a user provided *int argument.
    34  func (n *NullInt) ParseIntValue(val *int) {
    35  	if val == nil {
    36  		n.IsSet = false
    37  		n.Value = 0
    38  		return
    39  	}
    40  
    41  	n.Value = *val
    42  	n.IsSet = true
    43  }
    44  
    45  func (n *NullInt) UnmarshalJSON(rawJSON []byte) error {
    46  	var value json.Number
    47  	err := json.Unmarshal(rawJSON, &value)
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	if value.String() == "" {
    53  		n.Value = 0
    54  		n.IsSet = false
    55  		return nil
    56  	}
    57  
    58  	valueInt, err := strconv.Atoi(value.String())
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	n.Value = valueInt
    64  	n.IsSet = true
    65  
    66  	return nil
    67  }
    68  
    69  func (n NullInt) MarshalJSON() ([]byte, error) {
    70  	if n.IsSet {
    71  		return []byte(fmt.Sprint(n.Value)), nil
    72  	}
    73  	return []byte("null"), nil
    74  }