"GOT", but the "O" is a cute, smiling pufferfish. Index | Thread | Search

From:
Theo Buehler <tb@theobuehler.org>
Subject:
Re: qsort(3) and comparing values via subtraction
To:
gameoftrees@openbsd.org
Date:
Sun, 1 May 2022 12:23:29 +0200

Download raw body.

Thread
On Sun, May 01, 2022 at 12:09:05PM +0200, Stefan Sperling wrote:
> Our qsort(3) manual page contains a warning regarding subtraction
> of values larger than int:
> 
> 	     size_t lena = strlen(*(const char **)a);
> 	     size_t lenb = strlen(*(const char **)b);
> 	     /*
> 	      * Do not subtract the lengths. The difference between values
> 	      * cannot be represented by an int.
> 	      */
> 	     return lena < lenb ? -1 : lena > lenb;
> 
> The patch below fixes our qsort comparison functions accordingly.
> 
> ok?

ok - I would leave out all the 'else ' as they don't add anything.

> 
> diff cf8f868e7c97644d885e9cc2a06debbe9eac72b0 a19717b80ae1a0fef4b5bee6be2e79029c2d7a23
> blob - 14aa4357200fc7ebcefeb1306ac93ca9c8d7fb54
> blob + 35b8999680c0033eb8b09e58d16b0df2a41b4ea5
> --- lib/pack_create.c
> +++ lib/pack_create.c
> @@ -162,8 +162,10 @@ delta_order_cmp(const void *pa, const void *pb)
>  	cmp = strcmp(a->path, b->path);
>  	if (cmp != 0)
>  		return cmp;
> -	if (a->mtime != b->mtime)
> -		return a->mtime - b->mtime;
> +	if (a->mtime < b->mtime)
> +		return -1;
> +	else if (a->mtime > b->mtime)
> +		return 1;
>  	return got_object_id_cmp(&a->id, &b->id);
>  }
>  
> @@ -1514,13 +1516,21 @@ write_order_cmp(const void *pa, const void *pb)
>  	b = *(struct got_pack_meta **)pb;
>  	ahd = (a->head == NULL) ? a : a->head;
>  	bhd = (b->head == NULL) ? b : b->head;
> -	if (ahd->mtime != bhd->mtime)
> -		return bhd->mtime - ahd->mtime;
> -	if (ahd != bhd)
> -		return (uintptr_t)bhd - (uintptr_t)ahd;
> +	if (bhd->mtime < ahd->mtime)
> +		return -1;
> +	else if (bhd->mtime > ahd->mtime)
> +		return 1;
> +	if (bhd < ahd)
> +		return -1;
> +	else if (bhd > ahd)
> +		return 1;
>  	if (a->nchain != b->nchain)
>  		return a->nchain - b->nchain;
> -	return a->mtime - b->mtime;
> +	if (a->mtime < b->mtime)
> +		return -1;
> +	else if (a->mtime > b->mtime)
> +		return 1;
> +	return got_object_id_cmp(&a->id, &b->id);
>  }
>  
>  static int
>