freebsd-dev/lib/libc/stdlib/l64a.c
Ed Schouten 3005a8755a Let l64a() properly null terminate its result.
Though the buffer used by l64a() is initialized with null bytes,
repetetive calls may end up having trailing garbage of previous
invocations because we don't end up terminating the string.

Instead of importing NetBSD's fix, use this opportunity to simplify this
function dramatically, for example by just storing the Base64 character
set in a string. There is also no need to do the bitmasking, as we can
just use the proper integer type from <stdint.h>.

MFC after:	1 month
Differential Revision:	https://reviews.freebsd.org/D6511
2016-05-26 20:55:15 +00:00

45 lines
726 B
C

/*
* Written by J.T. Conklin <jtc@NetBSD.org>.
* Public domain.
*/
#if 0
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: l64a.c,v 1.13 2003/07/26 19:24:54 salo Exp $");
#endif /* not lint */
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <stdint.h>
#include <stdlib.h>
char *
l64a(long value)
{
static char buf[7];
(void)l64a_r(value, buf, sizeof(buf));
return (buf);
}
int
l64a_r(long value, char *buffer, int buflen)
{
static const char chars[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
uint32_t v;
v = value;
while (buflen-- > 0) {
if (v == 0) {
*buffer = '\0';
return (0);
}
*buffer++ = chars[v & 0x3f];
v >>= 6;
}
return (-1);
}