Skip to content

Commit

Permalink
Use a C++ string for StringBuf internally
Browse files Browse the repository at this point in the history
Eventually we'll want to just replace the whole thing with native
strings, but it's used in several places so changing is fairly invasive.

The "proper" way to do stripTrailingBlanksStringBuf() in modern C++
would be using lambdas and whatnot, for now settling for something
that is easy to understand from a C background.
  • Loading branch information
pmatilai committed May 16, 2024
1 parent f555b7d commit e8b944e
Showing 1 changed file with 13 additions and 46 deletions.
59 changes: 13 additions & 46 deletions build/misc.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
*/
#include "system.h"

#include <string>
#include <algorithm>

#include <ctype.h>
#include <stdlib.h>
#include <rpm/rpmstring.h>
Expand All @@ -12,72 +15,36 @@
#define BUF_CHUNK 1024

struct StringBufRec {
char *buf;
char *tail; /* Points to first "free" char */
int allocated;
int free;
std::string buf;
};

StringBuf newStringBuf(void)
{
StringBuf sb = (StringBuf)xmalloc(sizeof(*sb));

sb->free = sb->allocated = BUF_CHUNK;
sb->buf = (char *)xcalloc(sb->allocated, sizeof(*sb->buf));
sb->buf[0] = '\0';
sb->tail = sb->buf;

return sb;
return new StringBufRec {};
}

StringBuf freeStringBuf(StringBuf sb)
{
if (sb) {
sb->buf = _free(sb->buf);
sb = _free(sb);
}
return sb;
delete sb;
return NULL;
}

void stripTrailingBlanksStringBuf(StringBuf sb)
{
while (sb->free != sb->allocated) {
if (! risspace(*(sb->tail - 1)))
break;
sb->free++;
sb->tail--;
}
sb->tail[0] = '\0';
while (!sb->buf.empty() && risspace(sb->buf.back()))
sb->buf.erase(sb->buf.size() - 1);
}

const char * getStringBuf(StringBuf sb)
{
return (sb != NULL) ? sb->buf : NULL;
return (sb != NULL) ? sb->buf.c_str() : NULL;
}

void appendStringBufAux(StringBuf sb, const char *s, int nl)
{
int l;

l = strlen(s);
/* If free == l there is no room for NULL terminator! */
while ((l + nl + 1) > sb->free) {
sb->allocated += BUF_CHUNK;
sb->free += BUF_CHUNK;
sb->buf = xrealloc(sb->buf, sb->allocated);
sb->tail = sb->buf + (sb->allocated - sb->free);
}

/* FIX: shrug */
strcpy(sb->tail, s);
sb->tail += l;
sb->free -= l;
if (nl) {
sb->tail[0] = '\n';
sb->tail[1] = '\0';
sb->tail++;
sb->free--;
}
sb->buf += s;
if (nl)
sb->buf += '\n';
}

int parseUnsignedNum(const char * line, uint32_t * res)
Expand Down

0 comments on commit e8b944e

Please sign in to comment.