github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/strutil/util.go (about) 1 // Copyright 2022 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package strutil 12 13 import ( 14 "fmt" 15 "strconv" 16 "strings" 17 ) 18 19 // AppendInt appends the decimal form of x to b and returns the result. 20 // If the decimal form is shorter than width, the result is padded with leading 0's. 21 // If the decimal is longer than width, returns formatted decimal without 22 // any truncation. 23 func AppendInt(b []byte, x int, width int) []byte { 24 if x < 0 { 25 width-- 26 x = -x 27 b = append(b, '-') 28 } 29 30 var scratch [16]byte 31 xb := strconv.AppendInt(scratch[:0], int64(x), 10) 32 33 // Add 0-padding. 34 for w := len(xb); w < width; w++ { 35 b = append(b, '0') 36 } 37 return append(b, xb...) 38 } 39 40 // JoinIDs joins a slice of any ids into a comma separated string. Each ID could 41 // be prefixed with a string (e.g. n1, n2, n3 to represent nodes). 42 func JoinIDs[T ~int | ~int32 | ~int64](prefix string, ids []T) string { 43 idNames := make([]string, 0, len(ids)) 44 for _, id := range ids { 45 idNames = append(idNames, fmt.Sprintf("%s%d", prefix, id)) 46 } 47 return strings.Join(idNames, ", ") 48 }