size.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (C) 2017 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "fmt"
  9. "strconv"
  10. "strings"
  11. )
  12. type Size struct {
  13. Value float64 `json:"value" xml:",chardata"`
  14. Unit string `json:"unit" xml:"unit,attr"`
  15. }
  16. func ParseSize(s string) (Size, error) {
  17. s = strings.TrimSpace(s)
  18. if len(s) == 0 {
  19. return Size{}, nil
  20. }
  21. var num, unit string
  22. for i := 0; i < len(s) && (s[i] >= '0' && s[i] <= '9' || s[i] == '.' || s[i] == ','); i++ {
  23. num = s[:i+1]
  24. }
  25. var i = len(num)
  26. for i < len(s) && s[i] == ' ' {
  27. i++
  28. }
  29. unit = s[i:]
  30. val, err := strconv.ParseFloat(num, 64)
  31. if err != nil {
  32. return Size{}, err
  33. }
  34. return Size{val, unit}, nil
  35. }
  36. func (s Size) BaseValue() float64 {
  37. unitPrefix := s.Unit
  38. if len(unitPrefix) > 1 {
  39. unitPrefix = unitPrefix[:1]
  40. }
  41. mult := 1.0
  42. switch unitPrefix {
  43. case "k", "K":
  44. mult = 1000
  45. case "m", "M":
  46. mult = 1000 * 1000
  47. case "g", "G":
  48. mult = 1000 * 1000 * 1000
  49. case "t", "T":
  50. mult = 1000 * 1000 * 1000 * 1000
  51. }
  52. return s.Value * mult
  53. }
  54. func (s Size) Percentage() bool {
  55. return strings.Contains(s.Unit, "%")
  56. }
  57. func (s Size) String() string {
  58. return fmt.Sprintf("%v %s", s.Value, s.Unit)
  59. }
  60. func (Size) ParseDefault(s string) (interface{}, error) {
  61. return ParseSize(s)
  62. }