qs22j: handle cases with (0 or 1) elements to sort

avoid undefined behaviour and return early
if we only have 1 element we can skip all the crap since we dont need to sort anyways
This commit is contained in:
Alug committed 2025-09-28 22:51:25 +02:00
1 parent 66d163a10b
commit 0f2efd0487
2 files changed
+12 -5

No files matched your search

+1 -1
View File
@@ -4211,7 +4211,7 @@ static int CompareVisSprites(const void *p1, const void *p2)
fdiff = spr2->tz - spr1->tz; // this order seems correct when checking with apitrace. Back to front.
if (fabsf(fdiff) < 1.0E-36f)
return spr1->dispoffset - spr2->dispoffset;// smallest dispoffset first if sprites are at (almost) same location.
return spr1->dispoffset - spr2->dispoffset; // smallest dispoffset first if sprites are at (almost) same location.
else if (fdiff > 0)
return 1;
else
+11 -4
View File
@@ -18,6 +18,7 @@
#include <stdint.h>
#include "qs22j.h"
#include "doomdef.h"
#define INSORTTHRESH 5 // if n < this use insertion sort
// MUST be >= 2
@@ -85,9 +86,14 @@ static inline char *med3(char *a, char *b, char *c, int (*compar)(const void *,
(COMP(b, c) > 0 ? b : COMP(a, c) > 0 ? c : a);
}
void qs22j(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
void qs22j(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
{
// we have nothing to sort
if (UNLIKELY(nmemb <= 1))
{
return;
}
char *stack[2*8*sizeof(size_t)], **sp = stack; // stack and stack pointer
char *left = base; // set up char * base pointer
char *limit = left + nmemb * size; // pointer past end of array
@@ -114,7 +120,7 @@ void qs22j(void *base, size_t nmemb, size_t size,
vecswapf = swapwords;
if (size == sizeof(pref_typ))
swap_type = 0;
}
}
else if ((size % sizeof(DWORD)) == 0)
{
swapf = vecswapf = swapdwords;
@@ -123,6 +129,7 @@ void qs22j(void *base, size_t nmemb, size_t size,
{
swapf = vecswapf = swapwords;
}
for (;;)
{
nmemb = (limit - left) / size;
@@ -133,7 +140,7 @@ void qs22j(void *base, size_t nmemb, size_t size,
goto pop;
if (nmemb >= INSORTTHRESH) // otherwise use insertion sort
{
{
char *right = limit - size;
// best so far? fewer compares, a few more swaps
char *p = left + (nmemb / 2) * size;