units.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package formatter
  14. import (
  15. "github.com/docker/go-units"
  16. )
  17. // MemBytes is a type for human readable memory bytes (like 128M, 2g, etc)
  18. type MemBytes int64
  19. // String returns the string format of the human readable memory bytes
  20. func (m *MemBytes) String() string {
  21. // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not.
  22. // We return "0" in case value is 0 here so that the default value is hidden.
  23. // (Sometimes "default 0 B" is actually misleading)
  24. if m.Value() != 0 {
  25. return units.BytesSize(float64(m.Value()))
  26. }
  27. return "0"
  28. }
  29. // Set sets the value of the MemBytes by passing a string
  30. func (m *MemBytes) Set(value string) error {
  31. val, err := units.RAMInBytes(value)
  32. *m = MemBytes(val)
  33. return err
  34. }
  35. // Type returns the type
  36. func (m *MemBytes) Type() string {
  37. return "bytes"
  38. }
  39. // Value returns the value in int64
  40. func (m *MemBytes) Value() int64 {
  41. return int64(*m)
  42. }