github.com/searKing/golang/go@v1.2.74/bytes/bytes.go (about)

     1  package bytes
     2  
     3  import (
     4  	"bytes"
     5  )
     6  
     7  // Truncate shrinks s's len to n at most
     8  func Truncate(s []byte, n int) []byte {
     9  	if n < 0 {
    10  		n = 0
    11  	}
    12  	if len(s) <= n {
    13  		return s
    14  	}
    15  	return s[:n]
    16  }
    17  
    18  // PadLeft returns s padded to length n, padded left with repeated pad
    19  // return s directly if pad is empty
    20  // padding s with {{pad}} and spaces(less than len(pad)) as a prefix, as [pad]...[pad][space]...[space][s]
    21  func PadLeft(s []byte, pad []byte, n int) []byte {
    22  	if len(pad) == 0 {
    23  		return s
    24  	}
    25  
    26  	pc, sc := ComputePad(s, pad, n)
    27  
    28  	return append(bytes.Repeat(pad, pc), append(bytes.Repeat([]byte(" "), sc), s...)...)
    29  }
    30  
    31  // PadRight returns s padded to length n, padded right with repeated pad
    32  // return s directly if pad is empty
    33  // padding s with {{pad}} and spaces(less than len(pad))  as a suffix, as [s][space]...[space][pad]...[pad]
    34  func PadRight(s []byte, pad []byte, n int) []byte {
    35  	if len(pad) == 0 {
    36  		return s
    37  	}
    38  	pc, sc := ComputePad(s, pad, n)
    39  
    40  	return append(append(s, bytes.Repeat([]byte(" "), sc)...), bytes.Repeat(pad, pc)...)
    41  }
    42  
    43  // ComputePad returns pad's count and space's count(less than len(pad)) will be need to pad s to len n
    44  // padCount = (n-len(s))/len(pad)
    45  // spaceCount = (n-len(s))%len(pad)
    46  func ComputePad(s []byte, pad []byte, n int) (padCount, spaceCount int) {
    47  	if len(pad) == 0 {
    48  		return 0, 0
    49  	}
    50  
    51  	c := n - len(s)
    52  	if c < 0 {
    53  		c = 0
    54  	}
    55  
    56  	padCount = c / len(pad)
    57  
    58  	spaceCount = c % len(pad)
    59  	return padCount, spaceCount
    60  }
    61  
    62  // Reverse returns bytes in reverse order.
    63  func Reverse(s []byte) []byte {
    64  	var b bytes.Buffer
    65  	b.Grow(len(s))
    66  	for i := len(s) - 1; i >= 0; i-- {
    67  		b.WriteByte(s[i])
    68  	}
    69  	return b.Bytes()
    70  }