github.com/klaytn/klaytn@v1.12.1/common/format.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2016 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from common/format.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package common 22 23 import ( 24 "fmt" 25 "regexp" 26 "strings" 27 "time" 28 ) 29 30 // PrettyDuration is a pretty printed version of a time.Duration value that cuts 31 // the unnecessary precision off from the formatted textual representation. 32 type PrettyDuration time.Duration 33 34 var prettyDurationRe = regexp.MustCompile(`\.[0-9]+`) 35 36 // String implements the Stringer interface, allowing pretty printing of duration 37 // values rounded to three decimals. 38 func (d PrettyDuration) String() string { 39 label := fmt.Sprintf("%v", time.Duration(d)) 40 if match := prettyDurationRe.FindString(label); len(match) > 4 { 41 label = strings.Replace(label, match, match[:4], 1) 42 } 43 return label 44 } 45 46 // PrettyAge is a pretty printed version of a time.Duration value that rounds 47 // the values up to a single most significant unit, days/weeks/years included. 48 type PrettyAge time.Time 49 50 // ageUnits is a list of units the age pretty printing uses. 51 var ageUnits = []struct { 52 Size time.Duration 53 Symbol string 54 }{ 55 {12 * 30 * 24 * time.Hour, "y"}, 56 {30 * 24 * time.Hour, "mo"}, 57 {7 * 24 * time.Hour, "w"}, 58 {24 * time.Hour, "d"}, 59 {time.Hour, "h"}, 60 {time.Minute, "m"}, 61 {time.Second, "s"}, 62 {time.Millisecond, "ms"}, 63 } 64 65 // String implements the Stringer interface, allowing pretty printing of duration 66 // values rounded to the most significant time unit. 67 func (t PrettyAge) String() string { 68 // Calculate the time difference and handle the 0 cornercase 69 diff := time.Since(time.Time(t)) 70 if diff < time.Second { 71 return "0" 72 } 73 // Accumulate a precision of 3 components before returning 74 result, prec := "", 0 75 76 for _, unit := range ageUnits { 77 if diff > unit.Size { 78 result = fmt.Sprintf("%s%d%s", result, diff/unit.Size, unit.Symbol) 79 diff %= unit.Size 80 81 if prec += 1; prec >= 3 { 82 break 83 } 84 } 85 } 86 return result 87 }