vitess.io/vitess@v0.16.2/go/protoutil/duration.go (about)

     1  /*
     2  Copyright 2021 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package protoutil
    18  
    19  import (
    20  	"fmt"
    21  	"time"
    22  
    23  	"vitess.io/vitess/go/vt/proto/vttime"
    24  )
    25  
    26  // DurationFromProto converts a durationpb type to a time.Duration. It returns a
    27  // three-tuple of (dgo, ok, err) where dgo is the go time.Duration, ok indicates
    28  // whether the proto value was set, and err is set on failure to convert the
    29  // proto value.
    30  func DurationFromProto(dpb *vttime.Duration) (time.Duration, bool, error) {
    31  	if dpb == nil {
    32  		return 0, false, nil
    33  	}
    34  
    35  	d := time.Duration(dpb.Seconds) * time.Second
    36  	if int64(d/time.Second) != dpb.Seconds {
    37  		return 0, true, fmt.Errorf("duration: %v is out of range for time.Duration", dpb)
    38  	}
    39  	if dpb.Nanos != 0 {
    40  		d += time.Duration(dpb.Nanos) * time.Nanosecond
    41  		if (d < 0) != (dpb.Nanos < 0) {
    42  			return 0, true, fmt.Errorf("duration: %v is out of range for time.Duration", dpb)
    43  		}
    44  	}
    45  	return d, true, nil
    46  }
    47  
    48  // DurationToProto converts a time.Duration to a durpb.Duration.
    49  func DurationToProto(d time.Duration) *vttime.Duration {
    50  	nanos := d.Nanoseconds()
    51  	secs := nanos / 1e9
    52  	nanos -= secs * 1e9
    53  	return &vttime.Duration{
    54  		Seconds: secs,
    55  		Nanos:   int32(nanos),
    56  	}
    57  }