-
Notifications
You must be signed in to change notification settings - Fork 30
/
misc.go
95 lines (80 loc) · 2.07 KB
/
misc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package common
import (
"fmt"
"strconv"
"strings"
)
const tokenUnit = 10000000000.0
// Balance represents an amount of tokens.
type Balance int64
// ToToken converts the Balance to ZCN tokens.
func (b Balance) ToToken() float64 {
return float64(b) / tokenUnit
}
// ToBalance converts ZCN tokens to Balance.
func ToBalance(tok float64) Balance {
return Balance(tok * tokenUnit)
}
// String implements fmt.Stringer interface.
func (b Balance) String() string {
return strconv.FormatFloat(b.ToToken(), 'f', -1, 64)
}
// A Key represents an identifier. It can be a pool ID, client ID, smart
// contract address, etc.
type Key string
// A Size represents a size in bytes.
type Size int64
func byteCountIEC(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
// String implements fmt.Stringer interface
func (s Size) String() string {
return byteCountIEC(int64(s))
}
// WhoPays for file downloading.
type WhoPays int
// possible variants
const (
WhoPaysOwner WhoPays = iota // 0, file owner pays
WhoPays3rdParty // 1, 3rd party user pays
)
// String implements fmt.Stringer interface.
func (wp WhoPays) String() string {
switch wp {
case WhoPays3rdParty:
return "3rd_party"
case WhoPaysOwner:
return "owner"
}
return fmt.Sprintf("WhoPays(%d)", int(wp))
}
// Validate the WhoPays value.
func (wp WhoPays) Validate() (err error) {
switch wp {
case WhoPays3rdParty, WhoPaysOwner:
return // ok
}
return fmt.Errorf("unknown WhoPays value: %d", int(wp))
}
// Parse given string and set the WhoPays by it. Or return parsing error.
// The given string should be as result of the String method (case insensitive).
func (wp *WhoPays) Parse(val string) (err error) {
switch strings.ToLower(val) {
case "owner":
(*wp) = WhoPaysOwner
case "3rd_party":
(*wp) = WhoPays3rdParty
default:
err = fmt.Errorf("empty or unknown 'who_pays' value: %q", val)
}
return
}