fmtutil.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // fmtutil.go — utilidades de formato ES compartidas (demo random walk y
  2. // WireGuard live): parseBytes/fmtBytes ("1,2 GB" ⇄ 1.2e9) y relTime
  3. // ("hace 38 s"). Port literal de demo.js:35-51 y wireguard.js:38-55.
  4. package adapters
  5. import (
  6. "fmt"
  7. "math"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. )
  12. var byteStrRe = regexp.MustCompile(`^([\d.,]+)\s*(B|KB|MB|GB|TB)$`)
  13. var unitMult = map[string]float64{"B": 1, "KB": 1e3, "MB": 1e6, "GB": 1e9, "TB": 1e12}
  14. // parseBytes parsea formato ES ("1,2 GB", "214 MB", "1,1 TB") a bytes.
  15. // Quita puntos de miles y convierte la coma decimal (demo.js:37-41).
  16. func parseBytes(str string) float64 {
  17. m := byteStrRe.FindStringSubmatch(strings.TrimSpace(str))
  18. if m == nil {
  19. return 0
  20. }
  21. num := strings.NewReplacer(".", "", ",", ".").Replace(m[1])
  22. v, err := strconv.ParseFloat(num, 64)
  23. if err != nil {
  24. return 0
  25. }
  26. return math.Round(v * unitMult[m[2]])
  27. }
  28. // fmtBytes formatea bytes al estilo ES del contrato (wireguard.js:38-46):
  29. // ≥1e12 → entero "N TB" o 1 decimal con coma; ≥1e9 → "N GB"; ≥1e6 → "N MB";
  30. // ≥1e3 → "N KB". La rama TB la pide el total 24h del WAN (issue #169).
  31. func fmtBytes(bytes float64) string {
  32. if bytes >= 1e12 {
  33. v := bytes / 1e12
  34. if v == math.Trunc(v) {
  35. return fmt.Sprintf("%d TB", int64(v))
  36. }
  37. return strings.Replace(strconv.FormatFloat(v, 'f', 1, 64), ".", ",", 1) + " TB"
  38. }
  39. if bytes >= 1e9 {
  40. v := bytes / 1e9
  41. if v == math.Trunc(v) {
  42. return fmt.Sprintf("%d GB", int64(v))
  43. }
  44. return strings.Replace(strconv.FormatFloat(v, 'f', 1, 64), ".", ",", 1) + " GB"
  45. }
  46. if bytes >= 1e6 {
  47. return fmt.Sprintf("%d MB", int64(math.Round(bytes/1e6)))
  48. }
  49. if bytes >= 1e3 {
  50. return fmt.Sprintf("%d KB", int64(math.Round(bytes/1e3)))
  51. }
  52. return fmt.Sprintf("%d B", int64(math.Round(bytes)))
  53. }
  54. // relTime: epoch seg → texto relativo ES (wireguard.js:49-55).
  55. func relTime(epochSec, nowSec int64) string {
  56. diff := nowSec - epochSec
  57. if diff < 0 {
  58. diff = 0
  59. }
  60. switch {
  61. case diff < 60:
  62. return fmt.Sprintf("hace %d s", diff)
  63. case diff < 3600:
  64. return fmt.Sprintf("hace %d min", diff/60)
  65. case diff < 86400:
  66. return fmt.Sprintf("hace %d h", diff/3600)
  67. default:
  68. return fmt.Sprintf("hace %d días", diff/86400)
  69. }
  70. }