github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/cos/duration.go (about) 1 // Package cos provides common low-level types and utilities for all aistore projects. 2 /* 3 * Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. 4 */ 5 package cos 6 7 import ( 8 "strings" 9 "time" 10 11 jsoniter "github.com/json-iterator/go" 12 ) 13 14 // is used in cmn/config; is known to cmn/iter-fields parser 15 // (compare w/ size.go) 16 17 type Duration time.Duration 18 19 func (d Duration) D() time.Duration { return time.Duration(d) } 20 func (d Duration) MarshalJSON() ([]byte, error) { return jsoniter.Marshal(d.String()) } 21 22 func (d Duration) String() (s string) { 23 s = time.Duration(d).String() 24 // see related: https://github.com/golang/go/issues/39064 25 if strings.HasSuffix(s, "m0s") { 26 s = s[:len(s)-2] 27 } 28 return 29 } 30 31 func (d *Duration) UnmarshalJSON(b []byte) (err error) { 32 var ( 33 dur time.Duration 34 val string 35 ) 36 if err = jsoniter.Unmarshal(b, &val); err != nil { 37 return 38 } 39 dur, err = time.ParseDuration(val) 40 *d = Duration(dur) 41 return 42 }