github.com/pingcap/tidb-lightning@v5.0.0-rc.0.20210428090220-84b649866577+incompatible/lightning/config/bytesize.go (about)

     1  // Copyright 2020 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package config
    15  
    16  import (
    17  	"encoding/json"
    18  
    19  	"github.com/docker/go-units"
    20  )
    21  
    22  // ByteSize is an alias of int64 which accepts human-friendly strings like
    23  // '10G' when read from TOML.
    24  type ByteSize int64
    25  
    26  // UnmarshalText implements encoding.TextUnmarshaler
    27  func (size *ByteSize) UnmarshalText(b []byte) error {
    28  	res, err := units.RAMInBytes(string(b))
    29  	if err != nil {
    30  		return err
    31  	}
    32  	*size = ByteSize(res)
    33  	return nil
    34  }
    35  
    36  // UnmarshalJSON implements json.Unmarshaler (for testing)
    37  func (size *ByteSize) UnmarshalJSON(b []byte) error {
    38  	var res int64
    39  	if err := json.Unmarshal(b, &res); err != nil {
    40  		return err
    41  	}
    42  	*size = ByteSize(res)
    43  	return nil
    44  }