您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 

77 行
2.4 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ptypes
  5. import (
  6. "errors"
  7. "fmt"
  8. "time"
  9. durationpb "github.com/golang/protobuf/ptypes/duration"
  10. )
  11. // Range of google.protobuf.Duration as specified in duration.proto.
  12. // This is about 10,000 years in seconds.
  13. const (
  14. maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
  15. minSeconds = -maxSeconds
  16. )
  17. // Duration converts a durationpb.Duration to a time.Duration.
  18. // Duration returns an error if dur is invalid or overflows a time.Duration.
  19. //
  20. // Deprecated: Call the dur.AsDuration and dur.CheckValid methods instead.
  21. func Duration(dur *durationpb.Duration) (time.Duration, error) {
  22. if err := validateDuration(dur); err != nil {
  23. return 0, err
  24. }
  25. d := time.Duration(dur.Seconds) * time.Second
  26. if int64(d/time.Second) != dur.Seconds {
  27. return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
  28. }
  29. if dur.Nanos != 0 {
  30. d += time.Duration(dur.Nanos) * time.Nanosecond
  31. if (d < 0) != (dur.Nanos < 0) {
  32. return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
  33. }
  34. }
  35. return d, nil
  36. }
  37. // DurationProto converts a time.Duration to a durationpb.Duration.
  38. //
  39. // Deprecated: Call the durationpb.New function instead.
  40. func DurationProto(d time.Duration) *durationpb.Duration {
  41. nanos := d.Nanoseconds()
  42. secs := nanos / 1e9
  43. nanos -= secs * 1e9
  44. return &durationpb.Duration{
  45. Seconds: int64(secs),
  46. Nanos: int32(nanos),
  47. }
  48. }
  49. // validateDuration determines whether the durationpb.Duration is valid
  50. // according to the definition in google/protobuf/duration.proto.
  51. // A valid durpb.Duration may still be too large to fit into a time.Duration
  52. // Note that the range of durationpb.Duration is about 10,000 years,
  53. // while the range of time.Duration is about 290 years.
  54. func validateDuration(dur *durationpb.Duration) error {
  55. if dur == nil {
  56. return errors.New("duration: nil Duration")
  57. }
  58. if dur.Seconds < minSeconds || dur.Seconds > maxSeconds {
  59. return fmt.Errorf("duration: %v: seconds out of range", dur)
  60. }
  61. if dur.Nanos <= -1e9 || dur.Nanos >= 1e9 {
  62. return fmt.Errorf("duration: %v: nanos out of range", dur)
  63. }
  64. // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
  65. if (dur.Seconds < 0 && dur.Nanos > 0) || (dur.Seconds > 0 && dur.Nanos < 0) {
  66. return fmt.Errorf("duration: %v: seconds and nanos have different signs", dur)
  67. }
  68. return nil
  69. }