github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/intsets/fast_str.go (about) 1 // Copyright 2020 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 intsets 12 13 import ( 14 "bytes" 15 "fmt" 16 ) 17 18 // String returns a list representation of elements. Sequential runs of positive 19 // numbers are shown as ranges. For example, for the set {0, 1, 2, 5, 6, 10}, 20 // the output is "(0-2,5,6,10)". 21 func (s Fast) String() string { 22 var buf bytes.Buffer 23 buf.WriteByte('(') 24 appendRange := func(start, end int) { 25 if buf.Len() > 1 { 26 buf.WriteByte(',') 27 } 28 if start == end { 29 fmt.Fprintf(&buf, "%d", start) 30 } else if start+1 == end { 31 fmt.Fprintf(&buf, "%d,%d", start, end) 32 } else { 33 fmt.Fprintf(&buf, "%d-%d", start, end) 34 } 35 } 36 rangeStart, rangeEnd := -1, -1 37 s.ForEach(func(i int) { 38 if i < 0 { 39 appendRange(i, i) 40 return 41 } 42 if rangeStart != -1 && rangeEnd == i-1 { 43 rangeEnd = i 44 } else { 45 if rangeStart != -1 { 46 appendRange(rangeStart, rangeEnd) 47 } 48 rangeStart, rangeEnd = i, i 49 } 50 }) 51 if rangeStart != -1 { 52 appendRange(rangeStart, rangeEnd) 53 } 54 buf.WriteByte(')') 55 return buf.String() 56 }