mirror of
https://github.com/servalproject/serval-dna.git
synced 2025-01-29 15:43:56 +00:00
Add strbuf_tohex() primitive
This commit is contained in:
parent
3b44bb6e58
commit
6bb0d93d85
18
strbuf.c
18
strbuf.c
@ -69,6 +69,24 @@ strbuf strbuf_puts(strbuf sb, const char *text)
|
||||
return sb;
|
||||
}
|
||||
|
||||
strbuf strbuf_tohex(strbuf sb, const unsigned char *data, size_t len)
|
||||
{
|
||||
static char hexdigit[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
|
||||
char *p = sb->current;
|
||||
sb->current += len * 2;
|
||||
if (sb->start) {
|
||||
char *e = sb->current < sb->end ? sb->current : sb->end;
|
||||
// The following loop could overwrite the '\0' at *sp->end.
|
||||
for (; p < e; ++data) {
|
||||
*p++ = hexdigit[*data >> 4];
|
||||
*p++ = hexdigit[*data & 0xf];
|
||||
}
|
||||
// This will restore the '\0' at *sp->end if it was overwritten.
|
||||
*e = '\0';
|
||||
}
|
||||
return sb;
|
||||
}
|
||||
|
||||
strbuf strbuf_putc(strbuf sb, char ch)
|
||||
{
|
||||
if (sb->start && sb->current < sb->end) {
|
||||
|
17
strbuf.h
17
strbuf.h
@ -254,6 +254,23 @@ strbuf strbuf_ncat(strbuf sb, const char *text, size_t len);
|
||||
strbuf strbuf_puts(strbuf sb, const char *text);
|
||||
|
||||
|
||||
/** Append binary data strbuf, in uppercase hexadecimal format, truncating if
|
||||
* necessary to avoid buffer overrun. Return a pointer to the strbuf.
|
||||
*
|
||||
* After these operations:
|
||||
* n = strbuf_len(sb);
|
||||
* c = strbuf_count(sb);
|
||||
* strbuf_tohex(data, len);
|
||||
* the following invariants hold:
|
||||
* strbuf_count(sb) == c + len * 2
|
||||
* strbuf_len(sb) >= n
|
||||
* strbuf_len(sb) <= n + len * 2
|
||||
*
|
||||
* @author Andrew Bettison <andrew@servalproject.com>
|
||||
*/
|
||||
strbuf strbuf_tohex(strbuf sb, const unsigned char *data, size_t len);
|
||||
|
||||
|
||||
/** Append a single character to the strbuf if there is space, and place a
|
||||
* terminating nul after it. Return a pointer to the strbuf so that
|
||||
* concatenations can be chained in a single line.
|
||||
|
Loading…
x
Reference in New Issue
Block a user