...

Source file src/internal/bytealg/compare_generic.go

Documentation: internal/bytealg

     1  // Copyright 2018 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  
     5  //go:build !386 && !amd64 && !s390x && !arm && !arm64 && !loong64 && !ppc64 && !ppc64le && !mips && !mipsle && !wasm && !mips64 && !mips64le && !riscv64
     6  
     7  package bytealg
     8  
     9  import _ "unsafe" // for go:linkname
    10  
    11  func Compare(a, b []byte) int {
    12  	l := len(a)
    13  	if len(b) < l {
    14  		l = len(b)
    15  	}
    16  	if l == 0 || &a[0] == &b[0] {
    17  		goto samebytes
    18  	}
    19  	for i := 0; i < l; i++ {
    20  		c1, c2 := a[i], b[i]
    21  		if c1 < c2 {
    22  			return -1
    23  		}
    24  		if c1 > c2 {
    25  			return +1
    26  		}
    27  	}
    28  samebytes:
    29  	if len(a) < len(b) {
    30  		return -1
    31  	}
    32  	if len(a) > len(b) {
    33  		return +1
    34  	}
    35  	return 0
    36  }
    37  
    38  func CompareString(a, b string) int {
    39  	return runtime_cmpstring(a, b)
    40  }
    41  
    42  // runtime.cmpstring calls are emitted by the compiler.
    43  //
    44  // runtime.cmpstring should be an internal detail,
    45  // but widely used packages access it using linkname.
    46  // Notable members of the hall of shame include:
    47  //   - gitee.com/zhaochuninhefei/gmgo
    48  //   - github.com/bytedance/gopkg
    49  //   - github.com/songzhibin97/gkit
    50  //
    51  // Do not remove or change the type signature.
    52  // See go.dev/issue/67401.
    53  //
    54  //go:linkname runtime_cmpstring runtime.cmpstring
    55  func runtime_cmpstring(a, b string) int {
    56  	l := len(a)
    57  	if len(b) < l {
    58  		l = len(b)
    59  	}
    60  	for i := 0; i < l; i++ {
    61  		c1, c2 := a[i], b[i]
    62  		if c1 < c2 {
    63  			return -1
    64  		}
    65  		if c1 > c2 {
    66  			return +1
    67  		}
    68  	}
    69  	if len(a) < len(b) {
    70  		return -1
    71  	}
    72  	if len(a) > len(b) {
    73  		return +1
    74  	}
    75  	return 0
    76  }
    77  

View as plain text