types.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright 2019 fatedier, fatedier@gmail.com
  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. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package config
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "strconv"
  19. "strings"
  20. )
  21. const (
  22. MB = 1024 * 1024
  23. KB = 1024
  24. )
  25. type BandwidthQuantity struct {
  26. s string // MB or KB
  27. i int64 // bytes
  28. }
  29. func NewBandwidthQuantity(s string) (BandwidthQuantity, error) {
  30. q := BandwidthQuantity{}
  31. err := q.UnmarshalString(s)
  32. if err != nil {
  33. return q, err
  34. }
  35. return q, nil
  36. }
  37. func (q *BandwidthQuantity) Equal(u *BandwidthQuantity) bool {
  38. if q == nil && u == nil {
  39. return true
  40. }
  41. if q != nil && u != nil {
  42. return q.i == u.i
  43. }
  44. return false
  45. }
  46. func (q *BandwidthQuantity) String() string {
  47. return q.s
  48. }
  49. func (q *BandwidthQuantity) UnmarshalString(s string) error {
  50. s = strings.TrimSpace(s)
  51. if s == "" {
  52. return nil
  53. }
  54. var (
  55. base int64
  56. f float64
  57. err error
  58. )
  59. if strings.HasSuffix(s, "MB") {
  60. base = MB
  61. fstr := strings.TrimSuffix(s, "MB")
  62. f, err = strconv.ParseFloat(fstr, 64)
  63. if err != nil {
  64. return err
  65. }
  66. } else if strings.HasSuffix(s, "KB") {
  67. base = KB
  68. fstr := strings.TrimSuffix(s, "KB")
  69. f, err = strconv.ParseFloat(fstr, 64)
  70. if err != nil {
  71. return err
  72. }
  73. } else {
  74. return errors.New("unit not support")
  75. }
  76. q.s = s
  77. q.i = int64(f * float64(base))
  78. return nil
  79. }
  80. func (q *BandwidthQuantity) UnmarshalJSON(b []byte) error {
  81. if len(b) == 4 && string(b) == "null" {
  82. return nil
  83. }
  84. var str string
  85. err := json.Unmarshal(b, &str)
  86. if err != nil {
  87. return err
  88. }
  89. return q.UnmarshalString(str)
  90. }
  91. func (q *BandwidthQuantity) MarshalJSON() ([]byte, error) {
  92. return []byte("\"" + q.s + "\""), nil
  93. }
  94. func (q *BandwidthQuantity) Bytes() int64 {
  95. return q.i
  96. }