summaryrefslogtreecommitdiff
path: root/src/oid.c
diff options
context:
space:
mode:
authorRussell Belfer <rb@github.com>2013-05-17 16:40:00 -0700
committerRussell Belfer <rb@github.com>2013-05-17 16:40:00 -0700
commit660d59caa9cd6260fbc980e7da15f806d6d53083 (patch)
tree0d889913876122f8c33371e5234b59c07f489d13 /src/oid.c
parentc2d282cfd88ffba7693113786bd2209a5d38b964 (diff)
downloadlibgit2-660d59caa9cd6260fbc980e7da15f806d6d53083.tar.gz
Add git_oid_nfmt - a flexible OID formatter
I frequently want to the the first N digits of an OID formatted as a string and I'd like it to be efficient. This function makes that easy and I could rewrite the OID formatters in terms of it.
Diffstat (limited to 'src/oid.c')
-rw-r--r--src/oid.c46
1 files changed, 27 insertions, 19 deletions
diff --git a/src/oid.c b/src/oid.c
index e74640c57..a64bd3b0a 100644
--- a/src/oid.c
+++ b/src/oid.c
@@ -68,12 +68,31 @@ GIT_INLINE(char) *fmt_one(char *str, unsigned int val)
return str;
}
-void git_oid_fmt(char *str, const git_oid *oid)
+void git_oid_nfmt(char *str, size_t n, const git_oid *oid)
{
- size_t i;
+ size_t i, max_i;
+
+ if (!oid) {
+ memset(str, 0, n);
+ return;
+ }
+ if (n > GIT_OID_HEXSZ) {
+ memset(&str[GIT_OID_HEXSZ], 0, n - GIT_OID_HEXSZ);
+ n = GIT_OID_HEXSZ;
+ }
+
+ max_i = n / 2;
- for (i = 0; i < sizeof(oid->id); i++)
+ for (i = 0; i < max_i; i++)
str = fmt_one(str, oid->id[i]);
+
+ if (n & 1)
+ *str++ = to_hex[oid->id[i] >> 4];
+}
+
+void git_oid_fmt(char *str, const git_oid *oid)
+{
+ git_oid_nfmt(str, GIT_OID_HEXSZ, oid);
}
void git_oid_pathfmt(char *str, const git_oid *oid)
@@ -91,31 +110,20 @@ char *git_oid_allocfmt(const git_oid *oid)
char *str = git__malloc(GIT_OID_HEXSZ + 1);
if (!str)
return NULL;
- git_oid_fmt(str, oid);
- str[GIT_OID_HEXSZ] = '\0';
+ git_oid_nfmt(str, GIT_OID_HEXSZ + 1, oid);
return str;
}
char *git_oid_tostr(char *out, size_t n, const git_oid *oid)
{
- char str[GIT_OID_HEXSZ];
-
if (!out || n == 0)
return "";
- n--; /* allow room for terminating NUL */
-
- if (oid == NULL)
- n = 0;
-
- if (n > 0) {
- git_oid_fmt(str, oid);
- if (n > GIT_OID_HEXSZ)
- n = GIT_OID_HEXSZ;
- memcpy(out, str, n);
- }
+ if (n > GIT_OID_HEXSZ + 1)
+ n = GIT_OID_HEXSZ + 1;
- out[n] = '\0';
+ git_oid_nfmt(out, n - 1, oid); /* allow room for terminating NUL */
+ out[n - 1] = '\0';
return out;
}