github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/internal/version/parse.go (about)

     1  package version
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  
     7  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors"
     8  )
     9  
    10  type version struct {
    11  	Major  uint64
    12  	Minor  uint64
    13  	Patch  uint64
    14  	Suffix string
    15  }
    16  
    17  func (lhs version) Less(rhs version) bool {
    18  	if lhs.Major < rhs.Major {
    19  		return true
    20  	}
    21  	if lhs.Major > rhs.Major {
    22  		return false
    23  	}
    24  	if lhs.Minor < rhs.Minor {
    25  		return true
    26  	}
    27  	if lhs.Minor > rhs.Minor {
    28  		return false
    29  	}
    30  	if lhs.Patch < rhs.Patch {
    31  		return true
    32  	}
    33  	if lhs.Patch > rhs.Patch {
    34  		return false
    35  	}
    36  
    37  	return lhs.Suffix < rhs.Suffix
    38  }
    39  
    40  // Lt compare lhs and rhs as (lhs < rhs)
    41  func Lt(lhs, rhs string) bool {
    42  	v1, err := parse(lhs)
    43  	if err != nil {
    44  		return false
    45  	}
    46  	v2, err := parse(rhs)
    47  	if err != nil {
    48  		return false
    49  	}
    50  
    51  	return v1.Less(v2)
    52  }
    53  
    54  // Gte compare lhs and rhs as (lhs >= rhs)
    55  func Gte(lhs, rhs string) bool {
    56  	v1, err := parse(lhs)
    57  	if err != nil {
    58  		return false
    59  	}
    60  	v2, err := parse(rhs)
    61  	if err != nil {
    62  		return false
    63  	}
    64  	if v1.Less(v2) {
    65  		return false
    66  	}
    67  
    68  	return true
    69  }
    70  
    71  func parse(s string) (v version, err error) {
    72  	ss := strings.SplitN(s, "-", 2)
    73  	if len(ss) == 2 {
    74  		v.Suffix = ss[1]
    75  	}
    76  	sss := strings.SplitN(ss[0], ".", 3)
    77  	if len(sss) == 3 {
    78  		v.Patch, err = strconv.ParseUint(sss[2], 10, 64)
    79  		if err != nil {
    80  			return version{}, xerrors.WithStackTrace(err)
    81  		}
    82  	}
    83  	if len(sss) >= 2 {
    84  		v.Minor, err = strconv.ParseUint(sss[1], 10, 64)
    85  		if err != nil {
    86  			return version{}, xerrors.WithStackTrace(err)
    87  		}
    88  	}
    89  	if len(sss) >= 1 {
    90  		v.Major, err = strconv.ParseUint(sss[0], 10, 64)
    91  		if err != nil {
    92  			return version{}, xerrors.WithStackTrace(err)
    93  		}
    94  	}
    95  
    96  	return v, nil
    97  }