Debian Codegraph @

ansi/sixel/palette_sort.go

raw
1 // Copyright 2022 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 package sixel
6
7 import (
8 "math/bits"
9 )
10
11 const (
12 unknownHint sortedHint = iota
13 increasingHint
14 decreasingHint
15 )
16
17 type ordered interface {
18 ~int | ~int8 | ~int16 | ~int32 | ~int64 |
19 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
20 ~float32 | ~float64 |
21 ~string
22 }
23
24 // Compare returns
25 //
26 // -1 if x is less than y,
27 // 0 if x equals y,
28 // +1 if x is greater than y.
29 //
30 // For floating-point types, a NaN is considered less than any non-NaN,
31 // a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.
32 func compare[T ordered](x, y T) int {
33 xNaN := isNaN(x)
34 yNaN := isNaN(y)
35 if xNaN {
36 if yNaN {
37 return 0
38 }
39 return -1
40 }
41 if yNaN {
42 return +1
43 }
44 if x < y {
45 return -1
46 }
47 if x > y {
48 return +1
49 }
50 return 0
51 }
52
53 // isNaN reports whether x is a NaN without requiring the math package.
54 // This will always return false if T is not floating-point.
55 func isNaN[T ordered](x T) bool {
56 return x != x
57 }
58
59 func sortFunc[S ~[]E, E any](x S, cmp func(a, b E) int) {
60 n := len(x)
61 pdqsortCmpFunc(x, 0, n, bits.Len(uint(n)), cmp)
62 }
63
64 type sortedHint int // hint for pdqsort when choosing the pivot
65
66 // xorshift paper: https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf
67 type xorshift uint64
68
69 func (r *xorshift) Next() uint64 {
70 *r ^= *r << 13
71 *r ^= *r >> 7
72 *r ^= *r << 17
73 return uint64(*r)
74 }
75
76 func nextPowerOfTwo(length int) uint {
77 return 1 << bits.Len(uint(length)) //nolint:gosec
78 }
79
80 // insertionSortCmpFunc sorts data[a:b] using insertion sort.
81 func insertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
82 for i := a + 1; i < b; i++ {
83 for j := i; j > a && (cmp(data[j], data[j-1]) < 0); j-- {
84 data[j], data[j-1] = data[j-1], data[j]
85 }
86 }
87 }
88
89 // siftDownCmpFunc implements the heap property on data[lo:hi].
90 // first is an offset into the array where the root of the heap lies.
91 func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) {
92 root := lo
93 for {
94 child := 2*root + 1
95 if child >= hi {
96 break
97 }
98 if child+1 < hi && (cmp(data[first+child], data[first+child+1]) < 0) {
99 child++
100 }
101 if !(cmp(data[first+root], data[first+child]) < 0) { //nolint:staticcheck
102 return
103 }
104 data[first+root], data[first+child] = data[first+child], data[first+root]
105 root = child
106 }
107 }
108
109 func heapSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
110 first := a
111 lo := 0
112 hi := b - a
113
114 // Build heap with greatest element at top.
115 for i := (hi - 1) / 2; i >= 0; i-- {
116 siftDownCmpFunc(data, i, hi, first, cmp)
117 }
118
119 // Pop elements, largest first, into end of data.
120 for i := hi - 1; i >= 0; i-- {
121 data[first], data[first+i] = data[first+i], data[first]
122 siftDownCmpFunc(data, lo, i, first, cmp)
123 }
124 }
125
126 // pdqsortCmpFunc sorts data[a:b].
127 // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort.
128 // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf
129 // C++ implementation: https://github.com/orlp/pdqsort
130 // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/
131 // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort.
132 func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) {
133 const maxInsertion = 12
134
135 var (
136 wasBalanced = true // whether the last partitioning was reasonably balanced
137 wasPartitioned = true // whether the slice was already partitioned
138 )
139
140 for {
141 length := b - a
142
143 if length <= maxInsertion {
144 insertionSortCmpFunc(data, a, b, cmp)
145 return
146 }
147
148 // Fall back to heapsort if too many bad choices were made.
149 if limit == 0 {
150 heapSortCmpFunc(data, a, b, cmp)
151 return
152 }
153
154 // If the last partitioning was imbalanced, we need to breaking patterns.
155 if !wasBalanced {
156 breakPatternsCmpFunc(data, a, b)
157 limit--
158 }
159
160 pivot, hint := choosePivotCmpFunc(data, a, b, cmp)
161 if hint == decreasingHint {
162 reverseRangeCmpFunc(data, a, b)
163 // The chosen pivot was pivot-a elements after the start of the array.
164 // After reversing it is pivot-a elements before the end of the array.
165 // The idea came from Rust's implementation.
166 pivot = (b - 1) - (pivot - a)
167 hint = increasingHint
168 }
169
170 // The slice is likely already sorted.
171 if wasBalanced && wasPartitioned && hint == increasingHint {
172 if partialInsertionSortCmpFunc(data, a, b, cmp) {
173 return
174 }
175 }
176
177 // Probably the slice contains many duplicate elements, partition the slice into
178 // elements equal to and elements greater than the pivot.
179 if a > 0 && !(cmp(data[a-1], data[pivot]) < 0) { //nolint:staticcheck
180 mid := partitionEqualCmpFunc(data, a, b, pivot, cmp)
181 a = mid
182 continue
183 }
184
185 mid, alreadyPartitioned := partitionCmpFunc(data, a, b, pivot, cmp)
186 wasPartitioned = alreadyPartitioned
187
188 leftLen, rightLen := mid-a, b-mid
189 balanceThreshold := length / 8
190 if leftLen < rightLen {
191 wasBalanced = leftLen >= balanceThreshold
192 pdqsortCmpFunc(data, a, mid, limit, cmp)
193 a = mid + 1
194 } else {
195 wasBalanced = rightLen >= balanceThreshold
196 pdqsortCmpFunc(data, mid+1, b, limit, cmp)
197 b = mid
198 }
199 }
200 }
201
202 // partitionCmpFunc does one quicksort partition.
203 // Let p = data[pivot]
204 // Moves elements in data[a:b] around, so that data[i]<p and data[j]>=p for i<newpivot and j>newpivot.
205 // On return, data[newpivot] = p.
206 func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int, alreadyPartitioned bool) {
207 data[a], data[pivot] = data[pivot], data[a]
208 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
209
210 for i <= j && (cmp(data[i], data[a]) < 0) {
211 i++
212 }
213 for i <= j && !(cmp(data[j], data[a]) < 0) { //nolint:staticcheck
214 j--
215 }
216 if i > j {
217 data[j], data[a] = data[a], data[j]
218 return j, true
219 }
220 data[i], data[j] = data[j], data[i]
221 i++
222 j--
223
224 for {
225 for i <= j && (cmp(data[i], data[a]) < 0) {
226 i++
227 }
228 for i <= j && !(cmp(data[j], data[a]) < 0) { //nolint:staticcheck
229 j--
230 }
231 if i > j {
232 break
233 }
234 data[i], data[j] = data[j], data[i]
235 i++
236 j--
237 }
238 data[j], data[a] = data[a], data[j]
239 return j, false
240 }
241
242 // partitionEqualCmpFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot].
243 // It assumed that data[a:b] does not contain elements smaller than the data[pivot].
244 func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int) {
245 data[a], data[pivot] = data[pivot], data[a]
246 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
247
248 for {
249 for i <= j && !(cmp(data[a], data[i]) < 0) { //nolint:staticcheck
250 i++
251 }
252 for i <= j && (cmp(data[a], data[j]) < 0) {
253 j--
254 }
255 if i > j {
256 break
257 }
258 data[i], data[j] = data[j], data[i]
259 i++
260 j--
261 }
262 return i
263 }
264
265 // partialInsertionSortCmpFunc partially sorts a slice, returns true if the slice is sorted at the end.
266 func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) bool {
267 const (
268 maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted
269 shortestShifting = 50 // don't shift any elements on short arrays
270 )
271 i := a + 1
272 for range maxSteps {
273 for i < b && !(cmp(data[i], data[i-1]) < 0) { //nolint:staticcheck
274 i++
275 }
276
277 if i == b {
278 return true
279 }
280
281 if b-a < shortestShifting {
282 return false
283 }
284
285 data[i], data[i-1] = data[i-1], data[i]
286
287 // Shift the smaller one to the left.
288 if i-a >= 2 {
289 for j := i - 1; j >= 1; j-- {
290 if !(cmp(data[j], data[j-1]) < 0) { //nolint:staticcheck
291 break
292 }
293 data[j], data[j-1] = data[j-1], data[j]
294 }
295 }
296 // Shift the greater one to the right.
297 if b-i >= 2 {
298 for j := i + 1; j < b; j++ {
299 if !(cmp(data[j], data[j-1]) < 0) { //nolint:staticcheck
300 break
301 }
302 data[j], data[j-1] = data[j-1], data[j]
303 }
304 }
305 }
306 return false
307 }
308
309 // breakPatternsCmpFunc scatters some elements around in an attempt to break some patterns
310 // that might cause imbalanced partitions in quicksort.
311 func breakPatternsCmpFunc[E any](data []E, a, b int) {
312 length := b - a
313 if length >= 8 {
314 random := xorshift(length)
315 modulus := nextPowerOfTwo(length)
316
317 for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ {
318 other := int(uint(random.Next()) & (modulus - 1)) //nolint:gosec
319 if other >= length {
320 other -= length
321 }
322 data[idx], data[a+other] = data[a+other], data[idx]
323 }
324 }
325 }
326
327 // choosePivotCmpFunc chooses a pivot in data[a:b].
328 //
329 // [0,8): chooses a static pivot.
330 // [8,shortestNinther): uses the simple median-of-three method.
331 // [shortestNinther,∞): uses the Tukey ninther method.
332 func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot int, hint sortedHint) {
333 const (
334 shortestNinther = 50
335 maxSwaps = 4 * 3
336 )
337
338 l := b - a
339
340 var (
341 swaps int
342 i = a + l/4*1
343 j = a + l/4*2
344 k = a + l/4*3
345 )
346
347 if l >= 8 {
348 if l >= shortestNinther {
349 // Tukey ninther method, the idea came from Rust's implementation.
350 i = medianAdjacentCmpFunc(data, i, &swaps, cmp)
351 j = medianAdjacentCmpFunc(data, j, &swaps, cmp)
352 k = medianAdjacentCmpFunc(data, k, &swaps, cmp)
353 }
354 // Find the median among i, j, k and stores it into j.
355 j = medianCmpFunc(data, i, j, k, &swaps, cmp)
356 }
357
358 switch swaps {
359 case 0:
360 return j, increasingHint
361 case maxSwaps:
362 return j, decreasingHint
363 default:
364 return j, unknownHint
365 }
366 }
367
368 // order2CmpFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a.
369 func order2CmpFunc[E any](data []E, a, b int, swaps *int, cmp func(a, b E) int) (int, int) {
370 if cmp(data[b], data[a]) < 0 {
371 *swaps++
372 return b, a
373 }
374 return a, b
375 }
376
377 // medianCmpFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c.
378 func medianCmpFunc[E any](data []E, a, b, c int, swaps *int, cmp func(a, b E) int) int {
379 a, b = order2CmpFunc(data, a, b, swaps, cmp)
380 b, _ = order2CmpFunc(data, b, c, swaps, cmp)
381 _, b = order2CmpFunc(data, a, b, swaps, cmp)
382 return b
383 }
384
385 // medianAdjacentCmpFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a.
386 func medianAdjacentCmpFunc[E any](data []E, a int, swaps *int, cmp func(a, b E) int) int {
387 return medianCmpFunc(data, a-1, a, a+1, swaps, cmp)
388 }
389
390 func reverseRangeCmpFunc[E any](data []E, a, b int) {
391 i := a
392 j := b - 1
393 for i < j {
394 data[i], data[j] = data[j], data[i]
395 i++
396 j--
397 }
398 }