gitee.com/gricks/utils@v1.0.8/misc.go (about)

     1  package utils
     2  
     3  import (
     4  	"crypto/md5"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"time"
     9  )
    10  
    11  type JsonTime time.Time
    12  
    13  func (this JsonTime) MarshalJSON() ([]byte, error) {
    14  	b := make([]byte, 0, 24)
    15  	b = append(b, '"')
    16  	b = time.Time(this).AppendFormat(b, "2006-01-02 15:04:05")
    17  	b = append(b, '"')
    18  	return b, nil
    19  }
    20  
    21  func (this *JsonTime) UnmarshalJSON(b []byte) error {
    22  	t, err := time.ParseInLocation(`"2006-01-02 15:04:05"`, string(b), time.Local)
    23  	*this = JsonTime(t)
    24  	return err
    25  }
    26  
    27  func (this JsonTime) String() string {
    28  	return time.Time(this).Format("2006-01-02 15:04:05")
    29  }
    30  
    31  ///////////////////////////////////////////////////////////////
    32  
    33  var bunits = [...]string{"", "Ki", "Mi", "Gi", "Ti"}
    34  
    35  func ShortenByte(bytes int) string {
    36  	i := 0
    37  	for ; bytes > 1024 && i < 4; i++ {
    38  		bytes /= 1024
    39  	}
    40  	return fmt.Sprintf("%d%sB", bytes, bunits[i])
    41  }
    42  
    43  ///////////////////////////////////////////////////////////////
    44  
    45  func MinInt(a, b int) int {
    46  	if a < b {
    47  		return a
    48  	}
    49  	return b
    50  }
    51  
    52  func MaxInt(a, b int) int {
    53  	if a > b {
    54  		return a
    55  	}
    56  	return b
    57  }
    58  
    59  func MinInt32(a, b int32) int32 {
    60  	if a < b {
    61  		return a
    62  	}
    63  	return b
    64  }
    65  
    66  func MaxInt32(a, b int32) int32 {
    67  	if a > b {
    68  		return a
    69  	}
    70  	return b
    71  }
    72  
    73  ///////////////////////////////////////////////////////////////
    74  // Convert Excel column name to number
    75  func Column2Number(s string) int {
    76  	v := 0
    77  	carry := 1
    78  	for i := len(s) - 1; i >= 0; i-- {
    79  		v += int(s[i]-'A'+1) * carry
    80  		carry *= 26
    81  	}
    82  	return v
    83  }
    84  
    85  // Convert Excel number name to column
    86  func Number2Column(i int) string {
    87  	s := [20]byte{} // string with 20 byte is realy a huge number
    88  	l := 0
    89  	i--
    90  	for i >= 0 {
    91  		s[l] = byte(i%26) + 'A'
    92  		l++
    93  		i = ((i - i%26) / 26) - 1
    94  	}
    95  	for k := 0; k < l/2; k++ {
    96  		s[k], s[l-1-k] = s[l-1-k], s[k]
    97  	}
    98  	return string(s[:l])
    99  }
   100  
   101  // Filehash return file md5 sum
   102  func Filehash(p string) (string, error) {
   103  	f, err := os.Open(p)
   104  	if err != nil {
   105  		return "", err
   106  	}
   107  	defer f.Close()
   108  
   109  	h := md5.New()
   110  	_, err = io.Copy(h, f)
   111  	if err != nil {
   112  		return "", err
   113  	}
   114  	return Byte2Hex(h.Sum(nil)), nil
   115  }