encode_duration.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. *
  3. * Copyright 2020 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpcutil
  19. import (
  20. "strconv"
  21. "time"
  22. )
  23. const maxTimeoutValue int64 = 100000000 - 1
  24. // div does integer division and round-up the result. Note that this is
  25. // equivalent to (d+r-1)/r but has less chance to overflow.
  26. func div(d, r time.Duration) int64 {
  27. if d%r > 0 {
  28. return int64(d/r + 1)
  29. }
  30. return int64(d / r)
  31. }
  32. // EncodeDuration encodes the duration to the format grpc-timeout header
  33. // accepts.
  34. //
  35. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
  36. func EncodeDuration(t time.Duration) string {
  37. // TODO: This is simplistic and not bandwidth efficient. Improve it.
  38. if t <= 0 {
  39. return "0n"
  40. }
  41. if d := div(t, time.Nanosecond); d <= maxTimeoutValue {
  42. return strconv.FormatInt(d, 10) + "n"
  43. }
  44. if d := div(t, time.Microsecond); d <= maxTimeoutValue {
  45. return strconv.FormatInt(d, 10) + "u"
  46. }
  47. if d := div(t, time.Millisecond); d <= maxTimeoutValue {
  48. return strconv.FormatInt(d, 10) + "m"
  49. }
  50. if d := div(t, time.Second); d <= maxTimeoutValue {
  51. return strconv.FormatInt(d, 10) + "S"
  52. }
  53. if d := div(t, time.Minute); d <= maxTimeoutValue {
  54. return strconv.FormatInt(d, 10) + "M"
  55. }
  56. // Note that maxTimeoutValue * time.Hour > MaxInt64.
  57. return strconv.FormatInt(div(t, time.Hour), 10) + "H"
  58. }