types.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "errors"
  17. "strconv"
  18. "strings"
  19. )
  20. const (
  21. MB = 1024 * 1024
  22. KB = 1024
  23. )
  24. type BandwithQuantity struct {
  25. s string // MB or KB
  26. i int64 // bytes
  27. }
  28. func NewBandwithQuantity(s string) (BandwithQuantity, error) {
  29. q := BandwithQuantity{}
  30. err := q.UnmarshalString(s)
  31. if err != nil {
  32. return q, err
  33. }
  34. return q, nil
  35. }
  36. func (q *BandwithQuantity) Equal(u *BandwithQuantity) bool {
  37. if q == nil && u == nil {
  38. return true
  39. }
  40. if q != nil && u != nil {
  41. return q.i == u.i
  42. }
  43. return false
  44. }
  45. func (q *BandwithQuantity) String() string {
  46. return q.s
  47. }
  48. func (q *BandwithQuantity) UnmarshalString(s string) error {
  49. q.s = strings.TrimSpace(s)
  50. if q.s == "" {
  51. return nil
  52. }
  53. var (
  54. base int64
  55. f float64
  56. err error
  57. )
  58. if strings.HasSuffix(s, "MB") {
  59. base = MB
  60. s = strings.TrimSuffix(s, "MB")
  61. f, err = strconv.ParseFloat(s, 64)
  62. if err != nil {
  63. return err
  64. }
  65. } else if strings.HasSuffix(s, "KB") {
  66. base = KB
  67. s = strings.TrimSuffix(s, "KB")
  68. f, err = strconv.ParseFloat(s, 64)
  69. if err != nil {
  70. return err
  71. }
  72. } else {
  73. return errors.New("unit not support")
  74. }
  75. q.i = int64(f * float64(base))
  76. return nil
  77. }
  78. func (q *BandwithQuantity) UnmarshalJSON(b []byte) error {
  79. return q.UnmarshalString(string(b))
  80. }
  81. func (q *BandwithQuantity) MarshalJSON() ([]byte, error) {
  82. return []byte(q.s), nil
  83. }
  84. func (q *BandwithQuantity) Bytes() int64 {
  85. return q.i
  86. }