From: Omar Polo Subject: Re: provide functions to parse/serialize different hashes To: Christian Weisgerber Cc: gameoftrees@openbsd.org Date: Thu, 23 Feb 2023 20:17:36 +0100 On 2023/02/23 20:12:15 +0100, Christian Weisgerber wrote: > Omar Polo: > > > +static char * > > +digest_to_str(const uint8_t *digest, int len, char *buf) > > { > > char *p = buf; > > char hex[3]; > > int i; > > > > - if (size < SHA1_DIGEST_STRING_LENGTH) > > - return NULL; > > - > > - for (i = 0; i < SHA1_DIGEST_LENGTH; i++) { > > + for (i = 0; i < len; i++) { > > snprintf(hex, sizeof(hex), "%.2x", digest[i]); > > p[0] = hex[0]; > > p[1] = hex[1]; > > Calling snprintf() 20 or soon 32 times to format a hash seems > excessive. How about doing this the very old-fashioned way? Agreed, and fwiw I like it a lot, thanks! OK with me > diff /home/naddy/got > commit - 87a3ab84d3eb87b790e3d34aeec2c344a8d7375b > path + /home/naddy/got > blob - 51a9a0ca1ab1e8d6bc5e9f6722d0595f2a3b5fe7 > file + lib/hash.c > --- lib/hash.c > +++ lib/hash.c > @@ -71,17 +71,15 @@ digest_to_str(const uint8_t *digest, int len, char *bu > static char * > digest_to_str(const uint8_t *digest, int len, char *buf) > { > + const char hex[] = "0123456789abcdef"; > char *p = buf; > - char hex[3]; > int i; > > for (i = 0; i < len; i++) { > - snprintf(hex, sizeof(hex), "%.2x", digest[i]); > - p[0] = hex[0]; > - p[1] = hex[1]; > - p += 2; > + *p++ = hex[digest[i] >> 4]; > + *p++ = hex[digest[i] & 0xf]; > } > - p[0] = '\0'; > + *p = '\0'; > > return buf; > }