github.com/jenspinney/cli@v6.42.1-0.20190207184520-7450c600020e+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  	var value json.Number
    58  	err := json.Unmarshal(rawJSON, &value)
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	if value.String() == "" {
    64  		b.Value = 0
    65  		b.IsSet = false
    66  		return nil
    67  	}
    68  
    69  	valueInt, err := strconv.ParseUint(value.String(), 10, 64)
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	b.Value = valueInt
    75  	b.IsSet = true
    76  
    77  	return nil
    78  }