github.com/pingcap/tidb/parser@v0.0.0-20231013125129-93a834a6bf8d/duration/duration.go (about)

     1  // Copyright 2023 PingCAP, Inc.
     2  //
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // Package duration provides a customized duration, which supports unit 'd', 'h' and 'm'
    15  package duration
    16  
    17  import (
    18  	"strconv"
    19  	"time"
    20  	"unicode"
    21  
    22  	"github.com/pingcap/errors"
    23  )
    24  
    25  func readFloat(s string) (float64, string, error) {
    26  	numbers := ""
    27  	for pos, ch := range s {
    28  		if !unicode.IsDigit(ch) && ch != '.' {
    29  			numbers = s[:pos]
    30  			break
    31  		}
    32  	}
    33  	if len(numbers) > 0 {
    34  		i, err := strconv.ParseFloat(numbers, 64)
    35  		if err != nil {
    36  			return 0, s, err
    37  		}
    38  		return i, s[len(numbers):], nil
    39  	}
    40  	return 0, s, errors.New("fail to read an integer")
    41  }
    42  
    43  // ParseDuration parses the duration which contains 'd', 'h' and 'm'
    44  func ParseDuration(s string) (time.Duration, error) {
    45  	duration := time.Duration(0)
    46  
    47  	if s == "0" {
    48  		return 0, nil
    49  	}
    50  
    51  	var err error
    52  	var i float64
    53  	for len(s) > 0 {
    54  		i, s, err = readFloat(s)
    55  		if err != nil {
    56  			return 0, err
    57  		}
    58  		switch s[0] {
    59  		case 'd':
    60  			duration += time.Duration(i * float64(time.Hour*24))
    61  		case 'h':
    62  			duration += time.Duration(i * float64(time.Hour))
    63  		case 'm':
    64  			duration += time.Duration(i * float64(time.Minute))
    65  		default:
    66  			return 0, errors.Errorf("unknown unit %c", s[0])
    67  		}
    68  
    69  		s = s[1:]
    70  	}
    71  
    72  	return duration, nil
    73  }