Implement fmt.Stringer for atomic types (#76)

Add safe `String()` methods for atomic types that replicate the same
behavior as `fmt.Sprintf("%v", x.Load())` without the allocations.

As with json.Marshaler/Unmarshaler, we've omitted the `atomic.Value`
type for now.

Resolves #50
This commit is contained in:
Abhinav Gupta
2020-05-14 16:26:08 -07:00
committed by GitHub
parent 982a2dde23
commit ddc304d531
13 changed files with 143 additions and 0 deletions

View File

@@ -129,6 +129,7 @@ package atomic
import (
"encoding/json"
"strconv"
"sync/atomic"
)
@@ -204,4 +205,14 @@ func (i *{{ .Name }}) UnmarshalJSON(b []byte) error {
i.Store(v)
return nil
}
// String encodes the wrapped value as a string.
func (i *{{ .Name }}) String() string {
v := i.Load()
{{ if .Unsigned -}}
return strconv.FormatUint(uint64(v), 10)
{{- else -}}
return strconv.FormatInt(int64(v), 10)
{{- end }}
}
`))