#include "cache.h"
#include "refs.h"
#include "string-list.h"
#include "utf8.h"
int starts_with(const char *str, const char *prefix)
{
for (; ; str++, prefix++)
if (!*prefix)
return 1;
else if (*str != *prefix)
return 0;
}
int istarts_with(const char *str, const char *prefix)
{
for (; ; str++, prefix++)
if (!*prefix)
return 1;
else if (tolower(*str) != tolower(*prefix))
return 0;
}
int skip_to_optional_arg_default(const char *str, const char *prefix,
const char **arg, const char *def)
{
const char *p;
if (!skip_prefix(str, prefix, &p))
return 0;
if (!*p) {
if (arg)
*arg = def;
return 1;
}
if (*p != '=')
return 0;
if (arg)
*arg = p + 1;
return 1;
}
/*
* Used as the default ->buf value, so that people can always assume
* buf is non NULL and ->buf is NUL terminated even for a freshly
* initialized strbuf.
*/
char strbuf_slopbuf[1];
void strbuf_init(struct strbuf *sb, size_t hint)
{
struct strbuf blank = STRBUF_INIT;
memcpy(sb, &blank, sizeof(*sb));
if (hint)
strbuf_grow(sb, hint);
}
void strbuf_release(struct strbuf *sb)
{
if (sb->alloc) {
free(sb->buf);
strbuf_init(sb, 0);
}
}
char *strbuf_detach(struct strbuf *sb, size_t *sz)
{
char *res;
strbuf_grow(sb, 0);
res = sb->buf;
if (sz)
*sz = sb->len;
strbuf_init(sb, 0);
return res;
}
void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
{
strbuf_release(sb);
sb->buf = buf;
sb->len = len;
sb->alloc = alloc;
strbuf_grow(sb, 0);
sb->buf[sb->len] = '\0';
}
void strbuf_grow(struct strbuf *sb, size_t extra)
{
int new_buf = !sb->alloc;
if (unsigned_add_overflows(extra, 1) ||
unsigned_add_overflows(sb->len, extra + 1))
die("you want to use way too much memory");
if (new_buf)
sb->buf = NULL;
ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
if (new_buf)
sb->buf[0] = '\0';
}
void strbuf_trim(struct strbuf *sb)
{
strbuf_rtrim(sb);
strbuf_ltrim(sb);
}
void strbuf_rtrim(struct strbuf *sb)
{
while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
sb->len--;
sb->buf[sb->len] = '\0';
}
void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
{
while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))
sb->len--;
sb->buf[sb->len] = '\0';
}
void strbuf_trim_trailing_newline(struct strbuf *sb)
{
if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {
if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')
--sb->len;
sb->buf[sb->len] = '\0';
}
}
void strbuf_ltrim(struct strbuf *sb)
{
char *b = sb->buf;
while (sb->len > 0 && isspace(*b)) {
b++;
sb->len--;
}
memmove(sb->buf, b, sb->len);
sb->buf[sb->len] = '\0';
}
int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
{
char *out;
size_t len;
if (same_encoding(from, to))
return 0;
out = reencode_string_len(sb->buf, sb->len, to, from, &len);
if (!out)
return -1;
strbuf_attach(sb, out, len, len);
return 0;
}
void strbuf_tolower(struct strbuf *sb)
{
char *p = sb->buf, *end = sb->buf + sb->len;
for (; p < end; p++)
*p = tolower(*p);
}
struct strbuf **strbuf_split_buf(const char *str, size_t slen,
int terminator, int max)
{
|