Skip to content

Commit

Permalink
Add fmt to mstring.
Browse files Browse the repository at this point in the history
  • Loading branch information
gijsbers committed May 7, 2024
1 parent dfb6fec commit 67df1d4
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/mstring.cc
Original file line number Diff line number Diff line change
Expand Up @@ -357,4 +357,56 @@ mstring mstring::match(const char* regex, const char* flags) const {
return mstring(data() + pos.rm_so, size_t(pos.rm_eo - pos.rm_so));
}

#include <errno.h>
#include <stdarg.h>

void mstring::fmt(const char* fmt, ...) {
const int en = errno;
va_list ap;
va_start(ap, fmt);
size_t len = strlen(fmt);
for (const char* s = fmt; *s; ++s) {
if (*s == '%' && s[1]) {
s++;
if (*s == 's') {
len += strlen(va_arg(ap, const char *));
}
if (*s == 'm') {
len += strlen(strerror(en));
}
}
}
va_end(ap);
MStringRef ref(len);
va_start(ap, fmt);
int i = 0;
for (const char* s = fmt; *s; ++s) {
if (*s == '%' && s[1]) {
s++;
if (*s == 's') {
const char* arg = va_arg(ap, const char *);
for (int k = 0; arg[k]; ++k)
ref[i++] = arg[k];
}
if (*s == 'm') {
const char* arg = strerror(en);
for (int k = 0; arg[k]; ++k)
ref[i++] = arg[k];
}
if (*s == '%') {
ref[i++] = '%';
}
} else {
ref[i++] = *s;
}
}
ref[i] = '\0';
va_end(ap);
release();
fRef = ref;
fOffset = 0;
fCount = i;
acquire();
}

// vim: set sw=4 ts=4 et:
1 change: 1 addition & 0 deletions src/mstring.h
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ class mstring {

operator const char *() { return c_str(); }
const char* c_str();
void fmt(const char* fmt, ...);
};

inline bool operator==(const char* s, const mstring& c) { return c == s; }
Expand Down
9 changes: 9 additions & 0 deletions src/strtest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <unistd.h>
#include <sys/types.h>
#include <fnmatch.h>
#include <errno.h>

char const *ApplicationName = "strtest";
static const char source[] = __FILE__;
Expand Down Expand Up @@ -256,6 +257,14 @@ static void test_mstring()
expect(u, "#fffff");
u = mstring("f#ffffff").match("#f{5}");
expect(u, "#fffff");

u.fmt("abc %s ghi", "def");
expect(u, "abc def ghi");
u.fmt("%s %s %s", "abc", "def", "ghi");
expect(u, "abc def ghi");
errno = EFAULT;
u.fmt("%m");
expect(u, strerror(errno));
}

static void test_upath()
Expand Down

0 comments on commit 67df1d4

Please sign in to comment.