github.com/kjk/siser@v0.0.0-20220410204903-1b1e84ea1397/util.go (about)

     1  package siser
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  )
     7  
     8  func fmtArgs(args ...interface{}) string {
     9  	if len(args) == 0 {
    10  		return ""
    11  	}
    12  	format := args[0].(string)
    13  	if len(args) == 1 {
    14  		return format
    15  	}
    16  	return fmt.Sprintf(format, args[1:]...)
    17  }
    18  
    19  func panicWithMsg(defaultMsg string, args ...interface{}) {
    20  	s := fmtArgs(args...)
    21  	if s == "" {
    22  		s = defaultMsg
    23  	}
    24  	panic(s)
    25  }
    26  
    27  func panicIfErr(err error, args ...interface{}) {
    28  	if err == nil {
    29  		return
    30  	}
    31  	panicWithMsg(err.Error(), args...)
    32  }
    33  
    34  func panicIf(cond bool, args ...interface{}) {
    35  	if !cond {
    36  		return
    37  	}
    38  	panicWithMsg("fatalIf: condition failed", args...)
    39  }
    40  
    41  // intStrLen calculates how long n would be when converted to a string
    42  // i.e. equivalent of len(strconv.Itoa(n)) but faster
    43  // Note: not used
    44  func intStrLen(n int) int {
    45  	l := 1 // count the last digit here
    46  	if n < 0 {
    47  		n = -n
    48  		l = 2
    49  	}
    50  	for n > 9 {
    51  		l++
    52  		n = n / 10
    53  	}
    54  	return l
    55  }
    56  
    57  func serializableOnLine(s string) bool {
    58  	n := len(s)
    59  	for i := 0; i < n; i++ {
    60  		b := s[i]
    61  		if b < 32 || b > 127 {
    62  			return false
    63  		}
    64  	}
    65  	return true
    66  }
    67  
    68  // TimeToUnixMillisecond converts t into Unix epoch time in milliseconds.
    69  // That's because seconds is not enough precision and nanoseconds is too much.
    70  func TimeToUnixMillisecond(t time.Time) int64 {
    71  	n := t.UnixNano()
    72  	return n / 1e6
    73  }
    74  
    75  // TimeFromUnixMillisecond returns time from Unix epoch time in milliseconds.
    76  func TimeFromUnixMillisecond(unixMs int64) time.Time {
    77  	nano := unixMs * 1e6
    78  	return time.Unix(0, nano)
    79  }