github.com/cloudfoundry/cli@v7.1.0+incompatible/types/null_bytesize_in_mb.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  	"strconv"
     6  
     7  	"code.cloudfoundry.org/bytefmt"
     8  )
     9  
    10  // NullByteSizeInMb represents size in a byte format in megabytes.
    11  type NullByteSizeInMb struct {
    12  	IsSet bool
    13  
    14  	// Value is a size in MB
    15  	Value uint64
    16  }
    17  
    18  func (b NullByteSizeInMb) String() string {
    19  	if !b.IsSet {
    20  		return ""
    21  	}
    22  
    23  	return bytefmt.ByteSize(b.Value * bytefmt.MEGABYTE)
    24  }
    25  
    26  func (b *NullByteSizeInMb) ParseStringValue(value string) error {
    27  	if value == "" {
    28  		b.IsSet = false
    29  		b.Value = 0
    30  		return nil
    31  	}
    32  
    33  	byteSize, fmtErr := bytefmt.ToMegabytes(value)
    34  	if fmtErr != nil {
    35  		return fmtErr
    36  	}
    37  
    38  	b.IsSet = true
    39  	b.Value = byteSize
    40  
    41  	return nil
    42  }
    43  
    44  // ParseUint64Value is used to parse a user provided *uint64 argument.
    45  func (b *NullByteSizeInMb) ParseUint64Value(val *uint64) {
    46  	if val == nil {
    47  		b.IsSet = false
    48  		b.Value = 0
    49  		return
    50  	}
    51  
    52  	b.Value = *val
    53  	b.IsSet = true
    54  }
    55  
    56  func (b *NullByteSizeInMb) UnmarshalJSON(rawJSON []byte) error {
    57  	if len(rawJSON) == 0 {
    58  		b.Value = 0
    59  		b.IsSet = false
    60  		return nil
    61  	}
    62  
    63  	var value json.Number
    64  	err := json.Unmarshal(rawJSON, &value)
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	if jsonNumberIsUninitialized(value) {
    70  		b.Value = 0
    71  		b.IsSet = false
    72  		return nil
    73  	}
    74  
    75  	valueInt, err := strconv.ParseUint(value.String(), 10, 64)
    76  	if err != nil {
    77  		return err
    78  	}
    79  
    80  	b.Value = valueInt
    81  	b.IsSet = true
    82  
    83  	return nil
    84  }
    85  
    86  func jsonNumberIsUninitialized(value json.Number) bool {
    87  	return value.String() == ""
    88  }